Search in sources :

Example 21 with SwaggerData

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

the class OAS3Parser method generateAPIDefinition.

/**
 * This method generates API definition to the given api
 *
 * @param swaggerData api
 * @return API definition in string format
 * @throws APIManagementException
 */
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
    OpenAPI openAPI = new OpenAPI();
    // create path if null
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    // Create info object
    Info info = new Info();
    info.setTitle(swaggerData.getTitle());
    if (swaggerData.getDescription() != null) {
        info.setDescription(swaggerData.getDescription());
    }
    Contact contact = new Contact();
    // Create contact object and map business owner info
    if (swaggerData.getContactName() != null) {
        contact.setName(swaggerData.getContactName());
    }
    if (swaggerData.getContactEmail() != null) {
        contact.setEmail(swaggerData.getContactEmail());
    }
    if (swaggerData.getContactName() != null || swaggerData.getContactEmail() != null) {
        // put contact object to info object
        info.setContact(contact);
    }
    info.setVersion(swaggerData.getVersion());
    openAPI.setInfo(info);
    updateSwaggerSecurityDefinition(openAPI, swaggerData, OPENAPI_DEFAULT_AUTHORIZATION_URL);
    updateLegacyScopesFromSwagger(openAPI, swaggerData);
    if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        modifyGraphQLSwagger(openAPI);
    } else {
        for (SwaggerData.Resource resource : swaggerData.getResources()) {
            addOrUpdatePathToSwagger(openAPI, resource);
        }
    }
    return Json.pretty(openAPI);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Paths(io.swagger.v3.oas.models.Paths) Info(io.swagger.v3.oas.models.info.Info) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Contact(io.swagger.v3.oas.models.info.Contact)

Example 22 with SwaggerData

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

the class ApisApiServiceImpl method importOpenAPIDefinition.

private APIDTO importOpenAPIDefinition(InputStream definition, String definitionUrl, String inlineDefinition, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) throws APIManagementException {
    // Validate and retrieve the OpenAPI definition
    Map validationResponseMap = null;
    boolean isServiceAPI = false;
    try {
        if (service != null) {
            isServiceAPI = true;
        }
        validationResponseMap = validateOpenAPIDefinition(definitionUrl, definition, fileDetail, inlineDefinition, true, isServiceAPI);
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
    }
    OpenAPIDefinitionValidationResponseDTO validationResponseDTO = (OpenAPIDefinitionValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
    APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
    if (!validationResponseDTO.isIsValid()) {
        ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
        throw RestApiUtil.buildBadRequestException(errorDTO);
    }
    // Only HTTP or WEBHOOK type APIs should be allowed
    if (!(APIDTO.TypeEnum.HTTP.equals(apiDTOFromProperties.getType()) || APIDTO.TypeEnum.WEBHOOK.equals(apiDTOFromProperties.getType()))) {
        throw RestApiUtil.buildBadRequestException("The API's type is not supported when importing an OpenAPI definition");
    }
    // Import the API and Definition
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    if (isServiceAPI) {
        apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), null));
    }
    API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
    if (isServiceAPI) {
        apiToAdd.setServiceInfo("key", service.getKey());
        apiToAdd.setServiceInfo("md5", service.getMd5());
        apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
    }
    boolean syncOperations = apiDTOFromProperties.getOperations().size() > 0;
    // Rearrange paths according to the API payload and save the OpenAPI definition
    APIDefinition apiDefinition = validationResponse.getParser();
    SwaggerData swaggerData;
    String definitionToAdd = validationResponse.getJsonContent();
    if (syncOperations) {
        PublisherCommonUtils.validateScopes(apiToAdd);
        swaggerData = new SwaggerData(apiToAdd);
        definitionToAdd = apiDefinition.populateCustomManagementInfo(definitionToAdd, swaggerData);
    }
    definitionToAdd = OASParserUtil.preProcess(definitionToAdd);
    Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(definitionToAdd);
    Set<Scope> scopes = apiDefinition.getScopes(definitionToAdd);
    apiToAdd.setUriTemplates(uriTemplates);
    apiToAdd.setScopes(scopes);
    // Set extensions from API definition to API object
    apiToAdd = OASParserUtil.setExtensionsToAPI(definitionToAdd, apiToAdd);
    if (!syncOperations) {
        PublisherCommonUtils.validateScopes(apiToAdd);
        swaggerData = new SwaggerData(apiToAdd);
        definitionToAdd = apiDefinition.populateCustomManagementInfo(validationResponse.getJsonContent(), swaggerData);
    }
    // adding the API and definition
    apiToAdd.setSwaggerDefinition(definitionToAdd);
    API addedAPI = apiProvider.addAPI(apiToAdd);
    // apiProvider.saveSwaggerDefinition(apiToAdd, definitionToAdd);
    // retrieving the added API for returning as the response
    // this would provide the updated templates
    addedAPI = apiProvider.getAPIbyUUID(addedAPI.getUuid(), organization);
    return APIMappingUtil.fromAPItoDTO(addedAPI);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) OpenAPIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OpenAPIDefinitionValidationResponseDTO) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 23 with SwaggerData

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

the class ApisApiServiceImpl method importGraphQLSchema.

/**
 * Import a GraphQL Schema
 * @param type APIType
 * @param fileInputStream input file
 * @param fileDetail file Detail
 * @param additionalProperties api object as string format
 * @param ifMatch If--Match header value
 * @param messageContext messageContext
 * @return Response with GraphQL API
 */
@Override
public Response importGraphQLSchema(String ifMatch, String type, InputStream fileInputStream, Attachment fileDetail, String additionalProperties, MessageContext messageContext) {
    APIDTO additionalPropertiesAPI = null;
    String schema = "";
    try {
        if (fileInputStream == null || StringUtils.isBlank(additionalProperties)) {
            String errorMessage = "GraphQL schema and api details cannot be empty.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        } else {
            schema = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
        }
        if (!StringUtils.isBlank(additionalProperties) && !StringUtils.isBlank(schema)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties + "/n" + "importing schema: " + schema);
            }
        }
        additionalPropertiesAPI = new ObjectMapper().readValue(additionalProperties, APIDTO.class);
        additionalPropertiesAPI.setType(APIDTO.TypeEnum.GRAPHQL);
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(additionalPropertiesAPI, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
        // Save swagger definition of graphQL
        APIDefinition parser = new OAS3Parser();
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = parser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
        // adding the api
        API createdApi = apiProvider.addAPI(apiToAdd);
        apiProvider.saveGraphqlSchemaDefinition(createdApi.getUuid(), schema, organization);
        APIDTO createdApiDTO = APIMappingUtil.fromAPItoDTO(createdApi);
        // This URI used to set the location header of the POST response
        URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
        return Response.created(createdApiUri).entity(createdApiDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error while retrieving content from file : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 24 with SwaggerData

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

the class ApisApiServiceImpl method importSOAPAPI.

/**
 * Import an API from WSDL as a SOAP API
 *
 * @param fileInputStream file data as input stream
 * @param fileDetail file details
 * @param url URL of the WSDL
 * @param apiToAdd API object to be added to the system (which is not added yet)
 * @param organization Organization
 * @param service service
 * @return API added api
 */
private API importSOAPAPI(InputStream fileInputStream, Attachment fileDetail, String url, API apiToAdd, String organization, ServiceEntry service) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // adding the api
        apiProvider.addAPI(apiToAdd);
        if (StringUtils.isNotBlank(url)) {
            apiToAdd.setWsdlUrl(url);
            apiProvider.addWSDLResource(apiToAdd.getUuid(), null, url, organization);
        } else if (fileDetail != null && fileInputStream != null) {
            PublisherCommonUtils.addWsdl(fileDetail.getContentType().toString(), fileInputStream, apiToAdd, apiProvider, organization);
        } else if (service != null && fileInputStream == null) {
            RestApiUtil.handleBadRequest("Error while importing WSDL to create a SOAP API", log);
        } else if (service != null) {
            PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, fileInputStream, apiToAdd, apiProvider, organization);
        }
        // add the generated swagger definition to SOAP
        APIDefinition oasParser = new OAS2Parser();
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = generateSOAPAPIDefinition(oasParser.generateAPIDefinition(swaggerData));
        apiProvider.saveSwaggerDefinition(apiToAdd, apiDefinition, organization);
        APIIdentifier createdApiId = apiToAdd.getId();
        // Retrieve the newly added API to send in the response payload
        API createdApi = apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization);
        return createdApi;
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while importing WSDL to create a SOAP API", e, log);
    }
    return null;
}
Also used : OAS2Parser(org.wso2.carbon.apimgt.impl.definitions.OAS2Parser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 25 with SwaggerData

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

the class SynapseArtifactGenerator method generateGatewayArtifact.

@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList) throws APIManagementException {
    RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
    List<String> synapseArtifacts = new ArrayList<>();
    for (APIRuntimeArtifactDto runTimeArtifact : apiRuntimeArtifactDtoList) {
        if (runTimeArtifact.isFile()) {
            String tenantDomain = runTimeArtifact.getTenantDomain();
            String label = runTimeArtifact.getLabel();
            Environment environment = APIUtil.getEnvironments(tenantDomain).get(label);
            GatewayAPIDTO gatewayAPIDTO = null;
            if (environment != null) {
                try (InputStream artifact = (InputStream) runTimeArtifact.getArtifact()) {
                    File baseDirectory = CommonUtil.createTempDirectory(null);
                    try {
                        String extractedFolderPath = ImportUtils.getArchivePathOfExtractedDirectory(baseDirectory.getAbsolutePath(), artifact);
                        if (APIConstants.API_PRODUCT.equals(runTimeArtifact.getType())) {
                            APIProductDTO apiProductDTO = ImportUtils.retrieveAPIProductDto(extractedFolderPath);
                            apiProductDTO.setId(runTimeArtifact.getApiId());
                            APIProduct apiProduct = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, apiProductDTO.getProvider());
                            APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                            apiProduct.setDefinition(apiDefinitionValidationResponse.getContent());
                            gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(apiProduct, environment, tenantDomain, extractedFolderPath);
                        } else {
                            APIDTO apidto = ImportUtils.retrievedAPIDto(extractedFolderPath);
                            API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
                            api.setUUID(apidto.getId());
                            if (APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
                                APIDefinition parser = new OAS3Parser();
                                SwaggerData swaggerData = new SwaggerData(api);
                                String apiDefinition = parser.generateAPIDefinition(swaggerData);
                                api.setSwaggerDefinition(apiDefinition);
                                GraphqlComplexityInfo graphqlComplexityInfo = APIUtil.getComplexityDetails(api);
                                String graphqlSchema = ImportUtils.retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
                                api.setGraphQLSchema(graphqlSchema);
                                GraphQLSchemaDefinition graphQLSchemaDefinition = new GraphQLSchemaDefinition();
                                graphqlSchema = graphQLSchemaDefinition.buildSchemaWithAdditionalInfo(api, graphqlComplexityInfo);
                                api.setGraphQLSchema(graphqlSchema);
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath);
                            } 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()) || APIConstants.APITransportType.WEBHOOK.toString().equals(api.getType()))) {
                                APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                                api.setSwaggerDefinition(apiDefinitionValidationResponse.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath, apiDefinitionValidationResponse);
                            } 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()))) {
                                APIDefinitionValidationResponse asyncApiDefinition = ImportUtils.retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
                                api.setAsyncApiDefinition(asyncApiDefinition.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDtoForStreamingAPI(api, environment, tenantDomain, apidto, extractedFolderPath);
                            }
                        }
                        if (gatewayAPIDTO != null) {
                            String content = new Gson().toJson(gatewayAPIDTO);
                            synapseArtifacts.add(content);
                        }
                    } finally {
                        FileUtils.deleteQuietly(baseDirectory);
                    }
                } catch (Exception e) {
                    // only do error since we need to continue for other apis
                    log.error("Error while creating Synapse configurations", e);
                }
            }
        }
    }
    runtimeArtifactDto.setFile(false);
    runtimeArtifactDto.setArtifact(synapseArtifacts);
    return runtimeArtifactDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) InputStream(java.io.InputStream) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) Gson(com.google.gson.Gson) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File)

Aggregations

SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)21 API (org.wso2.carbon.apimgt.api.model.API)10 HashMap (java.util.HashMap)9 LinkedHashMap (java.util.LinkedHashMap)9 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)9 Scope (org.wso2.carbon.apimgt.api.model.Scope)8 Map (java.util.Map)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 ArrayList (java.util.ArrayList)6 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)6 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)5 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)5 OAS3Parser (org.wso2.carbon.apimgt.impl.definitions.OAS3Parser)5 Swagger (io.swagger.models.Swagger)3 OpenAPI (io.swagger.v3.oas.models.OpenAPI)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)3 HttpMethod (io.swagger.models.HttpMethod)2 PathItem (io.swagger.v3.oas.models.PathItem)2