Search in sources :

Example 61 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate 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 62 with URITemplate

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

the class TemplateBuilderUtil method createAPIGatewayDTOtoPublishAPI.

private static GatewayAPIDTO createAPIGatewayDTOtoPublishAPI(Environment environment, API api, APITemplateBuilder builder, String tenantDomain, String extractedPath, APIDTO apidto, List<ClientCertificateDTO> clientCertificatesDTOList) throws APIManagementException, APITemplateException, XMLStreamException {
    GatewayAPIDTO gatewayAPIDTO = new GatewayAPIDTO();
    gatewayAPIDTO.setName(api.getId().getName());
    gatewayAPIDTO.setVersion(api.getId().getVersion());
    gatewayAPIDTO.setProvider(api.getId().getProviderName());
    gatewayAPIDTO.setApiId(api.getUUID());
    gatewayAPIDTO.setTenantDomain(tenantDomain);
    gatewayAPIDTO.setKeyManagers(api.getKeyManagers());
    String definition;
    boolean isGraphQLSubscriptionAPI = false;
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        // Build schema with additional info
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID() + "_graphQL", gatewayAPIDTO.getLocalEntriesToBeRemove()));
        GatewayContentDTO graphqlLocalEntry = new GatewayContentDTO();
        graphqlLocalEntry.setName(api.getUUID() + "_graphQL");
        graphqlLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "_graphQL" + "\">" + "<![CDATA[" + api.getGraphQLSchema() + "]]>" + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(graphqlLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
        gatewayAPIDTO.setGraphQLSchema(api.getGraphQLSchema());
        Set<URITemplate> uriTemplates = new HashSet<>();
        URITemplate template = new URITemplate();
        template.setAuthType("Any");
        template.setHTTPVerb("POST");
        template.setHttpVerbs("POST");
        template.setUriTemplate("/*");
        uriTemplates.add(template);
        api.setUriTemplates(uriTemplates);
        GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
        if (graphql.isSubscriptionAvailable(api.getGraphQLSchema())) {
            isGraphQLSubscriptionAPI = true;
            // if subscriptions are available add new URI template with wild card resource without http verb.
            template = new URITemplate();
            template.setUriTemplate("/*");
            uriTemplates.add(template);
            api.setUriTemplates(uriTemplates);
            api.setEndpointConfig(populateSubscriptionEndpointConfig(api.getEndpointConfig()));
            addGqlWebSocketTopicMappings(api);
        }
    } else if (api.getType() != null && (APIConstants.APITransportType.HTTP.toString().equals(api.getType()) || APIConstants.API_TYPE_SOAP.equals(api.getType()) || APIConstants.API_TYPE_SOAPTOREST.equals(api.getType()))) {
        definition = api.getSwaggerDefinition();
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        GatewayContentDTO apiLocalEntry = new GatewayContentDTO();
        apiLocalEntry.setName(api.getUUID());
        apiLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(apiLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
    } else if (api.getType() != null && (APIConstants.APITransportType.WS.toString().equals(api.getType()) || APIConstants.APITransportType.SSE.toString().equals(api.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(api.getType()))) {
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        definition = api.getAsyncApiDefinition();
        GatewayContentDTO apiLocalEntry = new GatewayContentDTO();
        apiLocalEntry.setName(api.getUUID());
        apiLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(apiLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
    }
    if ((APIConstants.GATEWAY_ENV_TYPE_PRODUCTION.equals(environment.getType()) && !APIUtil.isProductionEndpointsExists(api.getEndpointConfig())) || (APIConstants.GATEWAY_ENV_TYPE_SANDBOX.equals(environment.getType()) && !APIUtil.isSandboxEndpointsExists(api.getEndpointConfig()))) {
        if (log.isDebugEnabled()) {
            log.debug("Not adding API to environment " + environment.getName() + " since its endpoint URL " + "cannot be found");
        }
        return null;
    }
    GatewayUtils.setCustomSequencesToBeRemoved(api, gatewayAPIDTO);
    setAPIFaultSequencesToBeAdded(api, gatewayAPIDTO, extractedPath, apidto);
    setCustomSequencesToBeAdded(api, gatewayAPIDTO, extractedPath, apidto);
    setClientCertificatesToBeAdded(tenantDomain, gatewayAPIDTO, clientCertificatesDTOList);
    boolean isWsApi = APIConstants.APITransportType.WS.toString().equals(api.getType());
    if (isWsApi) {
        addWebsocketTopicMappings(api, apidto);
    }
    // Add the API
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        String prototypeScriptAPI = builder.getConfigStringForPrototypeScriptAPI(environment);
        gatewayAPIDTO.setApiDefinition(prototypeScriptAPI);
    } else if (APIConstants.IMPLEMENTATION_TYPE_ENDPOINT.equalsIgnoreCase(api.getImplementation())) {
        String apiConfig = builder.getConfigStringForTemplate(environment);
        gatewayAPIDTO.setApiDefinition(apiConfig);
        org.json.JSONObject endpointConfig = new org.json.JSONObject(api.getEndpointConfig());
        if (!endpointConfig.get(APIConstants.API_ENDPOINT_CONFIG_PROTOCOL_TYPE).equals(APIConstants.ENDPOINT_TYPE_AWSLAMBDA)) {
            if (!isWsApi) {
                addEndpoints(api, builder, gatewayAPIDTO);
            }
            if (isWsApi || isGraphQLSubscriptionAPI) {
                addWebSocketResourceEndpoints(api, builder, gatewayAPIDTO);
            }
        }
    }
    setSecureVaultPropertyToBeAdded(null, api, gatewayAPIDTO);
    return gatewayAPIDTO;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) JSONObject(org.json.simple.JSONObject) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO) HashSet(java.util.HashSet)

Example 63 with URITemplate

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

the class TemplateBuilderUtil method retrieveGatewayAPIDto.

public static GatewayAPIDTO retrieveGatewayAPIDto(API api, Environment environment, String tenantDomain, APIDTO apidto, String extractedFolderPath, APIDefinitionValidationResponse apiDefinitionValidationResponse) throws APIManagementException, XMLStreamException, APITemplateException, CertificateManagementException {
    if (apiDefinitionValidationResponse.isValid()) {
        APIDefinition parser = apiDefinitionValidationResponse.getParser();
        String definition = apiDefinitionValidationResponse.getJsonContent();
        if (parser != null) {
            Set<URITemplate> uriTemplates = parser.getURITemplates(definition);
            for (URITemplate uriTemplate : uriTemplates) {
                for (URITemplate template : api.getUriTemplates()) {
                    if (template.getHTTPVerb().equalsIgnoreCase(uriTemplate.getHTTPVerb()) && template.getUriTemplate().equals(uriTemplate.getUriTemplate())) {
                        template.setMediationScript(uriTemplate.getMediationScript());
                        template.setMediationScripts(uriTemplate.getHTTPVerb(), uriTemplate.getMediationScript());
                        template.setAmznResourceName(uriTemplate.getAmznResourceName());
                        template.setAmznResourceTimeout(uriTemplate.getAmznResourceTimeout());
                        break;
                    }
                }
            }
        }
    }
    return retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath);
}
Also used : APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 64 with URITemplate

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

the class TemplateBuilderUtil method retrieveOperationPolicySequenceForProducts.

private static GatewayContentDTO retrieveOperationPolicySequenceForProducts(APIProduct apiProduct, API api, String extractedLocation, String flow) throws APIManagementException {
    Set<URITemplate> applicableURITemplates = new HashSet<>();
    for (APIProductResource productResource : apiProduct.getProductResources()) {
        if (productResource.getApiIdentifier().equals(api.getId())) {
            applicableURITemplates.add(productResource.getUriTemplate());
        }
    }
    String policySequence = null;
    APIProductIdentifier apiProductIdentifier = apiProduct.getId();
    String seqExt = APIUtil.getSequenceExtensionName(apiProductIdentifier.getName(), apiProductIdentifier.getVersion()).concat("--").concat(api.getUuid()).concat(SynapsePolicyAggregator.getSequenceExtensionFlow(flow));
    try {
        policySequence = SynapsePolicyAggregator.generatePolicySequenceForUriTemplateSet(applicableURITemplates, seqExt, flow, extractedLocation);
    } catch (IOException e) {
        throw new APIManagementException(e);
    }
    GatewayContentDTO operationPolicySequenceContentDto = new GatewayContentDTO();
    if (StringUtils.isNotEmpty(policySequence)) {
        try {
            OMElement omElement = APIUtil.buildOMElement(new ByteArrayInputStream(policySequence.getBytes()));
            if (omElement != null) {
                if (omElement.getAttribute(new QName("name")) != null) {
                    omElement.getAttribute(new QName("name")).setAttributeValue(seqExt);
                }
                operationPolicySequenceContentDto.setName(seqExt);
                operationPolicySequenceContentDto.setContent(APIUtil.convertOMtoString(omElement));
                for (APIProductResource productResource : apiProduct.getProductResources()) {
                    if (productResource.getApiIdentifier().equals(api.getId())) {
                        switch(flow) {
                            case APIConstants.OPERATION_SEQUENCE_TYPE_REQUEST:
                                productResource.setInSequenceName(seqExt);
                                break;
                            case APIConstants.OPERATION_SEQUENCE_TYPE_RESPONSE:
                                productResource.setOutSequenceName(seqExt);
                                break;
                            case APIConstants.OPERATION_SEQUENCE_TYPE_FAULT:
                                productResource.setFaultSequenceName(seqExt);
                                break;
                        }
                    }
                }
                return operationPolicySequenceContentDto;
            }
        } catch (Exception e) {
            throw new APIManagementException(e);
        }
    }
    return null;
}
Also used : QName(javax.xml.namespace.QName) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) ByteArrayInputStream(java.io.ByteArrayInputStream) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO) HashSet(java.util.HashSet)

Example 65 with URITemplate

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

the class RestApiUtil method getAdminAPIAppResourceMapping.

/**
 * This is static method to return URI Templates map of API Admin REST API.
 * This content need to load only one time and keep it in memory as content will not change
 * during runtime.
 *
 * @return URITemplate set associated with API Manager Admin REST API
 */
public static Set<URITemplate> getAdminAPIAppResourceMapping(String version) {
    API api = new API(new APIIdentifier(RestApiConstants.REST_API_PROVIDER, RestApiConstants.REST_API_ADMIN_CONTEXT, RestApiConstants.REST_API_ADMIN_VERSION_0));
    if (adminAPIResourceMappings != null) {
        return adminAPIResourceMappings;
    } else {
        try {
            String definition;
            if (RestApiConstants.REST_API_ADMIN_VERSION_0.equals(version)) {
                definition = IOUtils.toString(RestApiUtil.class.getResourceAsStream("/admin-api.json"), "UTF-8");
            } else {
                definition = IOUtils.toString(RestApiUtil.class.getResourceAsStream("/admin-api.yaml"), "UTF-8");
            }
            APIDefinition oasParser = OASParserUtil.getOASParser(definition);
            // Get URL templates from swagger content we created
            adminAPIResourceMappings = oasParser.getURITemplates(definition);
        } catch (APIManagementException e) {
            log.error("Error while reading resource mappings for API: " + api.getId().getApiName(), e);
        } catch (IOException e) {
            log.error("Error while reading the swagger definition for API: " + api.getId().getApiName(), e);
        }
        return adminAPIResourceMappings;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) IOException(java.io.IOException)

Aggregations

URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)122 HashMap (java.util.HashMap)71 ArrayList (java.util.ArrayList)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)42 Scope (org.wso2.carbon.apimgt.api.model.Scope)41 API (org.wso2.carbon.apimgt.api.model.API)38 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 HashSet (java.util.HashSet)36 LinkedHashSet (java.util.LinkedHashSet)28 PreparedStatement (java.sql.PreparedStatement)25 ResultSet (java.sql.ResultSet)23 API (org.wso2.carbon.apimgt.core.models.API)22 Map (java.util.Map)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 Connection (java.sql.Connection)20 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)20 LinkedHashMap (java.util.LinkedHashMap)19 List (java.util.List)19 SQLException (java.sql.SQLException)16