use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class OAS3Parser method validateAPIDefinition.
/**
* This method validates the given OpenAPI definition by content
*
* @param apiDefinition OpenAPI Definition content
* @param host OpenAPI Definition url
* @param returnJsonContent whether to return the converted json form of the OpenAPI definition
* @return APIDefinitionValidationResponse object with validation information
*/
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String host, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
validationResponse.setValid(false);
for (String message : parseAttemptForV3.getMessages()) {
OASParserUtil.addErrorToValidationResponse(validationResponse, message);
if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
ErrorItem errorItem = new ErrorItem();
errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
validationResponse.getErrorItems().add(errorItem);
}
}
} else {
OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
List<String> endpoints;
String endpointWithHost = "";
if (openAPI.getServers() == null || openAPI.getServers().isEmpty()) {
endpoints = null;
} else {
endpoints = openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList());
for (String endpoint : endpoints) {
if (endpoint.startsWith("/")) {
if (StringUtils.isEmpty(host)) {
endpointWithHost = "http://api.yourdomain.com" + endpoint;
} else {
endpointWithHost = host + endpoint;
}
endpoints.set(endpoints.indexOf(endpoint), endpointWithHost);
}
}
}
String title = null;
String context = null;
if (!StringUtils.isBlank(info.getTitle())) {
title = info.getTitle();
context = info.getTitle().replaceAll("\\s", "").toLowerCase();
}
OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, openAPI.getOpenapi(), title, info.getVersion(), context, info.getDescription(), endpoints);
validationResponse.setParser(this);
if (returnJsonContent) {
if (!apiDefinition.trim().startsWith("{")) {
// not a json (it is yaml)
JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
validationResponse.setJsonContent(jsonNode.toString());
} else {
validationResponse.setJsonContent(apiDefinition);
}
}
}
return validationResponse;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class AsyncApiParser method validateAPIDefinition.
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
// import and load AsyncAPI HyperSchema for JSON schema validation
JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
String protocol = StringUtils.EMPTY;
boolean validationSuccess = false;
List<String> validationErrorMessages = null;
boolean isWebSocket = false;
JSONObject schemaToBeValidated = new JSONObject(apiDefinition);
// validate AsyncAPI using JSON schema validation
try {
JSONParser parser = new JSONParser();
org.json.simple.JSONObject json = (org.json.simple.JSONObject) parser.parse(metaSchema);
SchemaLoader schemaLoader = SchemaLoader.builder().registerSchemaByURI(new URI("http://json-schema.org/draft-07/schema#"), json).schemaJson(hyperSchema).build();
Schema schemaValidator = schemaLoader.load().build();
schemaValidator.validate(schemaToBeValidated);
/*AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
validationErrorMessages = new ArrayList<>();
if (asyncApiDocument.getServers().size() == 1) {
if (!APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
validationErrorMessages.add("#:The protocol of the server should be 'ws' for websockets");
}
}
if (asyncApiDocument.getServers().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single server for websockets");
}
if (asyncApiDocument.getChannels().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
}
if (validationErrorMessages.size() == 0) {
validationSuccess = true;
validationErrorMessages = null;
}*/
// AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
/*//Checking whether it is a websocket
validationErrorMessages = new ArrayList<>();
if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(protocol)) {
isWebSocket = true;
}
}*/
// validating channel count for websockets
/*if (isWebSocket) {
if (asyncApiDocument.getChannels().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
}
}*/
/*if (validationErrorMessages.size() == 0) {
validationSuccess = true;
validationErrorMessages = null;
}*/
validationSuccess = true;
} catch (ValidationException e) {
// validation error messages
validationErrorMessages = e.getAllMessages();
} catch (URISyntaxException e) {
String msg = "Error occurred when registering the schema";
throw new APIManagementException(msg, e);
} catch (ParseException e) {
String msg = "Error occurred when parsing the schema";
throw new APIManagementException(msg, e);
}
// TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
validationSuccess = true;
if (validationSuccess) {
AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
ArrayList<String> endpoints = new ArrayList<>();
if (asyncApiDocument.getServers().size() == 1) {
protocol = asyncApiDocument.getServers().get(0).protocol;
}
/*for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null, //asyncApiDocument.getChannels().get(0)._name,
asyncApiDocument.info.description,
endpoints
);*/
/*if (isWebSocket) {
for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
asyncApiDocument.getChannels().get(0)._name, //make this null
asyncApiDocument.info.description,
endpoints
);
} else {
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null,
asyncApiDocument.info.description,
null
);
}*/
AsyncApiParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, asyncApiDocument.asyncapi, asyncApiDocument.info.title, asyncApiDocument.info.version, null, asyncApiDocument.info.description, null);
validationResponse.setParser(this);
if (returnJsonContent) {
validationResponse.setJsonContent(apiDefinition);
}
if (StringUtils.isNotEmpty(protocol)) {
validationResponse.setProtocol(protocol);
}
} else {
if (validationErrorMessages != null) {
validationResponse.setValid(false);
for (String errorMessage : validationErrorMessages) {
AsyncApiParserUtil.addErrorToValidationResponse(validationResponse, errorMessage);
}
}
}
return validationResponse;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class OASParserUtil method extractAndValidateOpenAPIArchive.
/**
* Extract the archive file and validates the openAPI definition
*
* @param inputStream file as input stream
* @param returnContent whether to return the content of the definition in the response DTO
* @return APIDefinitionValidationResponse
* @throws APIManagementException if error occurred while parsing definition
*/
public static APIDefinitionValidationResponse extractAndValidateOpenAPIArchive(InputStream inputStream, boolean returnContent) throws APIManagementException {
String path = System.getProperty(APIConstants.JAVA_IO_TMPDIR) + File.separator + APIConstants.OPENAPI_ARCHIVES_TEMP_FOLDER + File.separator + UUID.randomUUID().toString();
String archivePath = path + File.separator + APIConstants.OPENAPI_ARCHIVE_ZIP_FILE;
String extractedLocation = APIFileUtil.extractUploadedArchive(inputStream, APIConstants.OPENAPI_EXTRACTED_DIRECTORY, archivePath, path);
File[] listOfFiles = new File(extractedLocation).listFiles();
File archiveDirectory = null;
if (listOfFiles != null) {
if (listOfFiles.length > 1) {
throw new APIManagementException("Swagger Definitions should be placed under one root folder.");
}
for (File file : listOfFiles) {
if (file.isDirectory()) {
archiveDirectory = file.getAbsoluteFile();
break;
}
}
}
// If it is a single swagger file without remote references it can be imported directly, without zipping.
if (archiveDirectory == null) {
throw new APIManagementException("Could not find an archive in the given ZIP file.");
}
File masterSwagger = checkMasterSwagger(archiveDirectory);
String content;
try {
InputStream masterInputStream = new FileInputStream(masterSwagger);
content = IOUtils.toString(masterInputStream, APIConstants.DigestAuthConstants.CHARSET);
} catch (IOException e) {
throw new APIManagementException("Error reading master swagger file" + e);
}
String openAPIContent = "";
SwaggerVersion version;
version = getSwaggerVersion(content);
String filePath = masterSwagger.getAbsolutePath();
if (SwaggerVersion.OPEN_API.equals(version)) {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
OpenAPI openAPI = openAPIV3Parser.read(filePath, null, options);
openAPIContent = Json.pretty(openAPI);
} else if (SwaggerVersion.SWAGGER.equals(version)) {
SwaggerParser parser = new SwaggerParser();
Swagger swagger = parser.read(filePath, null, true);
try {
openAPIContent = Yaml.pretty().writeValueAsString(swagger);
} catch (IOException e) {
throw new APIManagementException("Error in converting swagger to openAPI content. " + e);
}
}
APIDefinitionValidationResponse apiDefinitionValidationResponse;
apiDefinitionValidationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
return apiDefinitionValidationResponse;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class OAS2Parser method validateAPIDefinition.
/**
* This method validates the given OpenAPI definition by content
*
* @param apiDefinition OpenAPI Definition content
* @param returnJsonContent whether to return the converted json form of the OpenAPI definition
* @return APIDefinitionValidationResponse object with validation information
*/
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(apiDefinition);
boolean swaggerErrorFound = false;
for (String message : parseAttemptForV2.getMessages()) {
OASParserUtil.addErrorToValidationResponse(validationResponse, message);
if (message.contains(APIConstants.SWAGGER_IS_MISSING_MSG)) {
ErrorItem errorItem = new ErrorItem();
errorItem.setErrorCode(ExceptionCodes.INVALID_OAS2_FOUND.getErrorCode());
errorItem.setMessage(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
errorItem.setDescription(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
validationResponse.getErrorItems().add(errorItem);
swaggerErrorFound = true;
}
}
if (parseAttemptForV2.getSwagger() == null || swaggerErrorFound) {
validationResponse.setValid(false);
} else {
Swagger swagger = parseAttemptForV2.getSwagger();
Info info = swagger.getInfo();
OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, swagger.getSwagger(), info.getTitle(), info.getVersion(), swagger.getBasePath(), info.getDescription(), (swagger.getHost() == null || swagger.getHost().isEmpty()) ? null : new ArrayList<String>(Arrays.asList(swagger.getHost())));
validationResponse.setParser(this);
if (returnJsonContent) {
if (!apiDefinition.trim().startsWith("{")) {
// not a json (it is yaml)
try {
JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition, new SwaggerDeserializationResult());
validationResponse.setJsonContent(jsonNode.toString());
} catch (IOException e) {
throw new APIManagementException("Error while reading API definition yaml", e);
}
} else {
validationResponse.setJsonContent(apiDefinition);
}
}
}
return validationResponse;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class OASParserUtil method validateAPIDefinitionByURL.
/**
* This method validates the given OpenAPI definition by URL
*
* @param url URL of the API definition
* @param returnJsonContent whether to return the converted json form of the
* @return APIDefinitionValidationResponse object with validation information
*/
public static APIDefinitionValidationResponse validateAPIDefinitionByURL(String url, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
try {
URL urlObj = new URL(url);
String host = urlObj.getHost();
HttpClient httpClient = APIUtil.getHttpClient(urlObj.getPort(), urlObj.getProtocol());
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
validationResponse = validateAPIDefinition(responseStr, host, returnJsonContent);
} else {
validationResponse.setValid(false);
validationResponse.getErrorItems().add(ExceptionCodes.OPENAPI_URL_NO_200);
}
} catch (IOException e) {
ErrorHandler errorHandler = ExceptionCodes.OPENAPI_URL_MALFORMED;
// Log the error and continue since this method is only intended to validate a definition
log.error(errorHandler.getErrorDescription(), e);
validationResponse.setValid(false);
validationResponse.getErrorItems().add(errorHandler);
}
return validationResponse;
}
Aggregations