use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method saveAsyncDefinition.
@Override
public void saveAsyncDefinition(Organization org, String apiId, String apiDefinition) throws AsyncSpecPersistenceException {
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
log.error(errorMessage);
throw new AsyncSpecPersistenceException(errorMessage);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
int prependIndex = apiPath.lastIndexOf("/api");
String apiSourcePath = apiPath.substring(0, prependIndex);
String resourcePath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(apiDefinition);
// add a constant for app.json
resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
registry.put(resourcePath, resource);
String[] visibleRolesArr = null;
if (visibleRoles != null) {
visibleRolesArr = visibleRoles.split(",");
}
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
} catch (RegistryException | APIPersistenceException | APIManagementException e) {
throw new AsyncSpecPersistenceException("Error while adding AsyncApi Definition for " + apiId, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method saveOASDefinition.
@Override
public void saveOASDefinition(Organization org, String apiId, String apiDefinition) throws OASPersistenceException {
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
log.error(errorMessage);
throw new OASPersistenceException(errorMessage);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(apiName, apiVersion, apiProviderName);
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(apiDefinition);
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
String[] visibleRolesArr = null;
if (visibleRoles != null) {
visibleRolesArr = visibleRoles.split(",");
}
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
} catch (RegistryException | APIPersistenceException | APIManagementException e) {
throw new OASPersistenceException("Error while adding OSA Definition for " + apiId, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class OAS3Parser method removeExamplesFromOpenAPI.
/**
* Remove x-examples from all the paths from the OpenAPI definition.
*
* @param apiDefinition OpenAPI definition as String
*/
public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException {
try {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
log.debug("Errors found when parsing OAS definition");
}
OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
String path = entry.getKey();
List<Operation> operations = openAPI.getPaths().get(path).readOperations();
for (Operation operation : operations) {
if (operation.getExtensions() != null && operation.getExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
}
}
}
return Yaml.pretty().writeValueAsString(openAPI);
} catch (JsonProcessingException e) {
throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES);
}
}
use of org.wso2.carbon.apimgt.api.APIDefinition 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.APIDefinition in project carbon-apimgt by wso2.
the class OAS3Parser method setExtensionsToAPI.
/**
* This method returns api that is attached with api extensions related to micro-gw
*
* @param apiDefinition String
* @param api API
* @return API
*/
@Override
public API setExtensionsToAPI(String apiDefinition, API api) throws APIManagementException {
OpenAPI openAPI = getOpenAPI(apiDefinition);
Map<String, Object> extensions = openAPI.getExtensions();
if (extensions == null) {
return api;
}
// Setup Custom auth header for API
String authHeader = OASParserUtil.getAuthorizationHeaderFromSwagger(extensions);
if (StringUtils.isNotBlank(authHeader)) {
api.setAuthorizationHeader(authHeader);
}
// Setup application Security
List<String> applicationSecurity = OASParserUtil.getApplicationSecurityTypes(extensions);
Boolean isOptional = OASParserUtil.getAppSecurityStateFromSwagger(extensions);
if (!applicationSecurity.isEmpty()) {
String securityList = api.getApiSecurity();
securityList = securityList == null ? "" : securityList;
for (String securityType : applicationSecurity) {
if (APIConstants.DEFAULT_API_SECURITY_OAUTH2.equals(securityType) && !securityList.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
securityList = securityList + "," + APIConstants.DEFAULT_API_SECURITY_OAUTH2;
}
if (APIConstants.API_SECURITY_BASIC_AUTH.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_BASIC_AUTH)) {
securityList = securityList + "," + APIConstants.API_SECURITY_BASIC_AUTH;
}
if (APIConstants.API_SECURITY_API_KEY.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_API_KEY)) {
securityList = securityList + "," + APIConstants.API_SECURITY_API_KEY;
}
}
if (!(isOptional || securityList.contains(APIConstants.MANDATORY))) {
securityList = securityList + "," + APIConstants.MANDATORY;
}
api.setApiSecurity(securityList);
}
// Setup mutualSSL configuration
String mutualSSL = OASParserUtil.getMutualSSLEnabledFromSwagger(extensions);
if (StringUtils.isNotBlank(mutualSSL)) {
String securityList = api.getApiSecurity();
if (StringUtils.isBlank(securityList)) {
securityList = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
}
if (APIConstants.OPTIONAL.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL)) {
securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL;
} else if (APIConstants.MANDATORY.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY)) {
securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL + "," + APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY;
}
api.setApiSecurity(securityList);
}
// Setup CORSConfigurations
CORSConfiguration corsConfiguration = OASParserUtil.getCorsConfigFromSwagger(extensions);
if (corsConfiguration != null) {
api.setCorsConfiguration(corsConfiguration);
}
// Setup Response cache enabling
boolean responseCacheEnable = OASParserUtil.getResponseCacheFromSwagger(extensions);
if (responseCacheEnable) {
api.setResponseCache(APIConstants.ENABLED);
}
// Setup cache timeOut
int cacheTimeOut = OASParserUtil.getCacheTimeOutFromSwagger(extensions);
if (cacheTimeOut != 0) {
api.setCacheTimeout(cacheTimeOut);
}
// Setup Transports
String transports = OASParserUtil.getTransportsFromSwagger(extensions);
if (StringUtils.isNotBlank(transports)) {
api.setTransports(transports);
}
// Setup Throttlingtiers
String throttleTier = OASParserUtil.getThrottleTierFromSwagger(extensions);
if (StringUtils.isNotBlank(throttleTier)) {
api.setApiLevelPolicy(throttleTier);
}
return api;
}
Aggregations