Search in sources :

Example 1 with APIOperationsDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.

the class GraphQLSchemaDefinition method extractGraphQLOperationList.

/**
 * Extract GraphQL Operations from given schema.
 *
 * @param typeRegistry graphQL Schema Type Registry
 * @param type operation type string
 * @return the arrayList of APIOperationsDTO
 */
public List<URITemplate> extractGraphQLOperationList(TypeDefinitionRegistry typeRegistry, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        Optional<SchemaDefinition> schemaDefinition = typeRegistry.schemaDefinition();
        if (schemaDefinition.isPresent()) {
            List<OperationTypeDefinition> operationTypeList = schemaDefinition.get().getOperationTypeDefinitions();
            for (OperationTypeDefinition operationTypeDefinition : operationTypeList) {
                if (entry.getValue().getName().equalsIgnoreCase(operationTypeDefinition.getTypeName().getName())) {
                    if (type == null) {
                        addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
                    } else if (type.equals(operationTypeDefinition.getName().toUpperCase())) {
                        addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
                    }
                }
            }
        } else {
            if (entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_QUERY) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_MUTATION) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_SUBSCRIPTION)) {
                if (type == null) {
                    addOperations(entry, entry.getKey(), operationArray);
                } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                    addOperations(entry, entry.getKey(), operationArray);
                }
            }
        }
    }
    return operationArray;
}
Also used : SchemaDefinition(graphql.language.SchemaDefinition) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OperationTypeDefinition(graphql.language.OperationTypeDefinition) OperationTypeDefinition(graphql.language.OperationTypeDefinition) ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) TypeDefinition(graphql.language.TypeDefinition)

Example 2 with APIOperationsDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method setOperationPoliciesToOperationsDTO.

/**
 * Reads the operationPolicies from the API object passed in, and sets them back to the API Operations DTO
 *
 * @param api               API object
 * @param apiOperationsDTO  List of API Operations DTO
 */
private static void setOperationPoliciesToOperationsDTO(API api, List<APIOperationsDTO> apiOperationsDTO) {
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    Map<String, URITemplate> uriTemplateMap = new HashMap<>();
    for (URITemplate uriTemplate : uriTemplates) {
        String key = uriTemplate.getUriTemplate() + ":" + uriTemplate.getHTTPVerb();
        uriTemplateMap.put(key, uriTemplate);
    }
    for (APIOperationsDTO operationsDTO : apiOperationsDTO) {
        String key = operationsDTO.getTarget() + ":" + operationsDTO.getVerb();
        List<OperationPolicy> operationPolicies = uriTemplateMap.get(key).getOperationPolicies();
        if (!operationPolicies.isEmpty()) {
            operationsDTO.setOperationPolicies(OperationPolicyMappingUtil.fromOperationPolicyListToDTO(operationPolicies));
        }
    }
}
Also used : HashMap(java.util.HashMap) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO)

Example 3 with APIOperationsDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 4 with APIOperationsDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.

the class ImportUtils method checkAPIProductResourcesValid.

/**
 * This method checks whether the resources in the API Product are valid.
 *
 * @param path          Location of the extracted folder of the API Product
 * @param currentUser   The current logged in user
 * @param apiProvider   API provider
 * @param apiProductDto API Product DTO
 * @param preserveProvider
 * @param organization
 * @throws IOException            If there is an error while reading an API file
 * @throws APIManagementException If failed to get the API Provider of an API,
 *                                or failed when checking the existence of an API
 */
private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider, String organization) throws IOException, APIManagementException {
    // Get dependent APIs in the API Product
    List<ProductAPIDTO> apis = apiProductDto.getApis();
    String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
    File apisDirectory = new File(apisDirectoryPath);
    File[] apisDirectoryListing = apisDirectory.listFiles();
    if (apisDirectoryListing != null) {
        for (File apiDirectory : apisDirectoryListing) {
            String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
            JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser, ImportExportConstants.TYPE_API);
            APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class);
            String apiName = apiDto.getName();
            String apiVersion = apiDto.getVersion();
            String swaggerContent = loadSwaggerFile(apiDirectoryPath);
            APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
            Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent);
            for (ProductAPIDTO apiFromProduct : apis) {
                if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils.equals(apiFromProduct.getVersion(), apiVersion)) {
                    List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources(apiFromProduct.getOperations(), apiUriTemplates);
                    // dependent APIs inside the directory) check whether those are already inside APIM
                    if (!invalidApiOperations.isEmpty()) {
                        // Get the provider of the API if the API is in current user's tenant domain.
                        API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
                        invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates());
                    }
                    // inside the APIM
                    if (!invalidApiOperations.isEmpty()) {
                        throw new APIMgtResourceNotFoundException("Cannot find API resources for some API Product resources.");
                    }
                }
            }
        }
    }
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) JsonElement(com.google.gson.JsonElement) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) File(java.io.File)

Example 5 with APIOperationsDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.

the class PublisherCommonUtils method extractGraphQLOperationList.

/**
 * Extract GraphQL Operations from given schema.
 *
 * @param schema graphQL Schema
 * @return the arrayList of APIOperationsDTOextractGraphQLOperationList
 */
public static List<APIOperationsDTO> extractGraphQLOperationList(String schema) {
    List<APIOperationsDTO> operationArray = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) || entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION) || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
            for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
                APIOperationsDTO operation = new APIOperationsDTO();
                operation.setVerb(entry.getKey());
                operation.setTarget(fieldDef.getName());
                operationArray.add(operation);
            }
        }
    }
    return operationArray;
}
Also used : ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) FieldDefinition(graphql.language.FieldDefinition) ArrayList(java.util.ArrayList) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaParser(graphql.schema.idl.SchemaParser) ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) TypeDefinition(graphql.language.TypeDefinition) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

APIOperationsDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO)19 ArrayList (java.util.ArrayList)15 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)15 HashMap (java.util.HashMap)9 Scope (org.wso2.carbon.apimgt.api.model.Scope)7 JSONObject (org.json.simple.JSONObject)6 Tier (org.wso2.carbon.apimgt.api.model.Tier)6 CORSConfiguration (org.wso2.carbon.apimgt.api.model.CORSConfiguration)4 APICorsConfigurationDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO)4 APIInfoAdditionalPropertiesDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO)4 Timestamp (java.sql.Timestamp)3 Date (java.util.Date)3 LinkedHashSet (java.util.LinkedHashSet)3 Map (java.util.Map)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 APICategory (org.wso2.carbon.apimgt.api.model.APICategory)3 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)3 ProductAPIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO)3 JsonObject (com.google.gson.JsonObject)2 ObjectTypeDefinition (graphql.language.ObjectTypeDefinition)2