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);
}
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);
}
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;
}
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;
}
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;
}
Aggregations