use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method validateOpenAPIDefinition.
/**
* Validate the provided OpenAPI definition (via file or url) and return a Map with the validation response
* information.
*
* @param url OpenAPI definition url
* @param fileInputStream file as input stream
* @param apiDefinition Swagger API definition String
* @param returnContent whether to return the content of the definition in the response DTO
* @return Map with the validation response information. A value with key 'dto' will have the response DTO
* of type OpenAPIDefinitionValidationResponseDTO for the REST API. A value with key 'model' will have the
* validation response of type APIDefinitionValidationResponse coming from the impl level.
*/
private Map validateOpenAPIDefinition(String url, InputStream fileInputStream, Attachment fileDetail, String apiDefinition, Boolean returnContent, Boolean isServiceAPI) throws APIManagementException {
// validate inputs
handleInvalidParams(fileInputStream, fileDetail, url, apiDefinition, isServiceAPI);
OpenAPIDefinitionValidationResponseDTO responseDTO;
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
if (url != null) {
validationResponse = OASParserUtil.validateAPIDefinitionByURL(url, returnContent);
} else if (fileInputStream != null) {
try {
if (fileDetail != null) {
String filename = fileDetail.getContentDisposition().getFilename();
if (filename.endsWith(".zip")) {
validationResponse = OASParserUtil.extractAndValidateOpenAPIArchive(fileInputStream, returnContent);
} else {
String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
}
} else {
String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
}
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error while reading file content", e, log);
}
} else if (apiDefinition != null) {
validationResponse = OASParserUtil.validateAPIDefinition(apiDefinition, returnContent);
}
responseDTO = APIMappingUtil.getOpenAPIDefinitionValidationResponseFromModel(validationResponse, returnContent);
Map response = new HashMap();
response.put(RestApiConstants.RETURN_MODEL, validationResponse);
response.put(RestApiConstants.RETURN_DTO, responseDTO);
return response;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method reimportServiceFromCatalog.
@Override
public Response reimportServiceFromCatalog(String apiId, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String username = RestApiCommonUtil.getLoggedInUsername();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
int tenantId = APIUtil.getTenantId(username);
try {
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
String serviceKey = apiProvider.retrieveServiceKeyByApiId(originalAPI.getId().getId(), tenantId);
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
JSONObject serviceInfo = new JSONObject();
serviceInfo.put("name", service.getName());
serviceInfo.put("version", service.getVersion());
serviceInfo.put("key", service.getKey());
serviceInfo.put("md5", service.getMd5());
api.setServiceInfo(serviceInfo);
Map validationResponseMap = new HashMap();
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
validationResponseMap = validateOpenAPIDefinition(null, service.getEndpointDef(), null, null, true, true);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
validationResponseMap = validateAsyncAPISpecification(null, service.getEndpointDef(), null, true, true);
} else if (!ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot re-import service to " + "API using the service type " + service.getDefinitionType(), log);
}
APIDefinitionValidationResponse validationAPIResponse = null;
if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, service.getEndpointDef(), api, apiProvider, organization);
} else {
validationAPIResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationAPIResponse.isValid()) {
RestApiUtil.handleBadRequest(validationAPIResponse.getErrorItems(), log);
}
}
String protocol = (validationAPIResponse != null ? validationAPIResponse.getProtocol() : "");
if (!APIConstants.API_TYPE_WEBSUB.equalsIgnoreCase(protocol)) {
api.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
}
API updatedApi = apiProvider.updateAPI(api, originalAPI);
if (validationAPIResponse != null) {
PublisherCommonUtils.updateAPIDefinition(apiId, validationAPIResponse, service, organization);
}
return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
} catch (APIManagementException e) {
if (ExceptionCodes.MISSING_PROTOCOL_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Missing protocol in the Service Definition", log);
} else if (ExceptionCodes.UNSUPPORTED_PROTOCOL_SPECIFIED_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Unsupported protocol specified in the Service Definition. Protocol " + "should be either sse or websub or ws", log);
}
RestApiUtil.handleInternalServerError("Error while retrieving the service key of the service " + "associated with API with id " + apiId, log);
} catch (FaultGatewaysException e) {
String errorMessage = "Error while updating API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method updateAPISwagger.
/**
* Updates the swagger definition of an existing API
*
* @param apiId API identifier
* @param apiDefinition Swagger definition
* @param url Swagger definition URL
* @param fileInputStream Swagger definition input file content
* @param fileDetail file meta information as Attachment
* @param ifMatch If-match header value
* @return updated swagger document of the API
*/
@Override
public Response updateAPISwagger(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) {
try {
String updatedSwagger;
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().getStatus());
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// Handle URL and file based definition imports
if (url != null || fileInputStream != null) {
// Validate and retrieve the OpenAPI definition
Map validationResponseMap = validateOpenAPIDefinition(url, fileInputStream, fileDetail, null, true, false);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponse.isValid()) {
RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
}
updatedSwagger = PublisherCommonUtils.updateSwagger(apiId, validationResponse, false, organization);
} else {
updatedSwagger = updateSwagger(apiId, apiDefinition, organization);
}
return Response.ok().entity(updatedSwagger).build();
} catch (APIManagementException e) {
// to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while updating swagger definition of API: " + apiId, e, log);
} else {
String errorMessage = "Error while updating the swagger definition of the API: " + apiId + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (FaultGatewaysException e) {
String errorMessage = "Error while updating API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class OASParserUtil method addErrorToValidationResponse.
/**
* Add error item with the provided message to the provided validation response object
*
* @param validationResponse APIDefinitionValidationResponse object
* @param errMessage error message
* @return added ErrorItem object
*/
public static ErrorItem addErrorToValidationResponse(APIDefinitionValidationResponse validationResponse, String errMessage) {
ErrorItem errorItem = new ErrorItem();
errorItem.setErrorCode(ExceptionCodes.OPENAPI_PARSE_EXCEPTION.getErrorCode());
errorItem.setMessage(ExceptionCodes.OPENAPI_PARSE_EXCEPTION.getErrorMessage());
errorItem.setDescription(errMessage);
validationResponse.getErrorItems().add(errorItem);
return errorItem;
}
use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateAsyncAPIDefinition.
/**
* update AsyncPI definition of the given api.
*
* @param apiId API Id
* @param response response of the AsyncAPI definition validation call
* @param organization identifier of the organization
* @return updated AsyncAPI definition
* @throws APIManagementException when error occurred updating AsyncAPI definition
* @throws FaultGatewaysException when error occurred publishing API to the gateway
*/
public static String updateAsyncAPIDefinition(String apiId, APIDefinitionValidationResponse response, String organization) throws APIManagementException, FaultGatewaysException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// this will fall if user does not have access to the API or the API does not exist
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
existingAPI.setOrganization(organization);
String apiDefinition = response.getJsonContent();
AsyncApiParser asyncApiParser = new AsyncApiParser();
// Set uri templates
Set<URITemplate> uriTemplates = asyncApiParser.getURITemplates(apiDefinition, APIConstants.API_TYPE_WS.equals(existingAPI.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(existingAPI.getGatewayVendor()));
if (uriTemplates == null || uriTemplates.isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
existingAPI.setUriTemplates(uriTemplates);
// Update ws uri mapping
existingAPI.setWsUriMapping(asyncApiParser.buildWSUriMapping(apiDefinition));
// updating APi with the new AsyncAPI definition
existingAPI.setAsyncApiDefinition(apiDefinition);
apiProvider.saveAsyncApiDefinition(existingAPI, apiDefinition);
apiProvider.updateAPI(existingAPI);
// retrieves the updated AsyncAPI definition
return apiProvider.getAsyncAPIDefinition(existingAPI.getId().getUUID(), organization);
}
Aggregations