use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method updateAPI.
@SuppressWarnings("unchecked")
@Override
public PublisherAPI updateAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
API api = APIMapper.INSTANCE.toApi(publisherAPI);
boolean transactionCommitted = false;
boolean tenantFlowStarted = false;
Registry registry = null;
try {
RegistryHolder holder = getRegistry(org.getName());
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
String apiArtifactId = registry.get(RegistryPersistenceUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifact artifact = getAPIArtifact(apiArtifactId, registry);
boolean isSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED));
boolean isDigestSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST));
String userName = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME);
String password = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD);
if (!isSecured && !isDigestSecured && userName != null) {
api.setEndpointUTUsername(userName);
api.setEndpointUTPassword(password);
}
String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
Resource apiResource = registry.get(artifact.getPath());
String oldAccessControlRoles = api.getAccessControlRoles();
if (apiResource != null) {
oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
}
GenericArtifact updateApiArtifact = RegistryPersistenceUtil.createAPIArtifactContent(artifact, api);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
if (oldTags != null) {
for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
registry.removeTag(artifactPath, tag.getTagName());
}
}
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
artifactManager.updateGenericArtifact(updateApiArtifact);
// write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
// to gain performance
// String apiStatus = api.getStatus().toUpperCase();
// saveAPIStatus(artifactPath, apiStatus);
String[] visibleRoles = new String[0];
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
// propagate api status change and access control roles change to document artifact
String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
RegistryPersistenceUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
RegistryPersistenceUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
if (api.getSwaggerDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getSwaggerDefinition());
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
}
// doc visibility change
String apiOrAPIProductDocPath = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
if (registry.resourceExists(apiOrAPIProductDocPath)) {
Resource resource = registry.get(apiOrAPIProductDocPath);
if (resource instanceof org.wso2.carbon.registry.core.Collection) {
String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
for (String docPath : docsPaths) {
if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
Resource docResource = registry.get(docPath);
GenericArtifactManager docArtifactManager = RegistryPersistenceDocUtil.getDocumentArtifactManager(registry);
GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + doc.getName();
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + doc.getName();
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = RegistryPersistenceDocUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
}
}
}
setSoapToRestSequences(publisherAPI, registry);
registry.commitTransaction();
transactionCommitted = true;
return APIMapper.INSTANCE.toPublisherApi(api);
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error from this level will mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
throw new APIPersistenceException("Error while performing registry transaction operation ", e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error occurred while rolling back the transaction. ", ex);
}
}
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method addAPI.
@SuppressWarnings("unchecked")
@Override
public PublisherAPI addAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
API api = APIMapper.INSTANCE.toApi(publisherAPI);
boolean transactionCommitted = false;
boolean tenantFlowStarted = false;
Registry registry = null;
try {
RegistryHolder holder = getRegistry(org.getName());
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when creating API " + api.getId().getApiName();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifact genericArtifact = artifactManager.newGovernanceArtifact(new QName(api.getId().getApiName()));
if (genericArtifact == null) {
String errorMessage = "Generic artifact is null when creating API " + api.getId().getApiName();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
genericArtifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
GenericArtifact artifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api);
artifactManager.addGenericArtifact(artifact);
// Attach the API lifecycle
artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
String providerPath = RegistryPersistenceUtil.getAPIProviderPath(api.getId());
// provider ------provides----> API
registry.addAssociation(providerPath, artifactPath, APIConstants.PROVIDER_ASSOCIATION);
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
String apiStatus = api.getStatus();
saveAPIStatus(registry, artifactPath, apiStatus);
String visibleRolesList = api.getVisibleRoles();
String[] visibleRoles = new String[0];
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
if (api.getSwaggerDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getSwaggerDefinition());
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
} else if (api.getAsyncApiDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getAsyncApiDefinition());
// add a constant for app.json
resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
registry.put(resourcePath, resource);
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
}
// Set permissions to doc path
String docLocation = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
RegistryPersistenceUtil.clearResourcePermissions(docLocation, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docLocation);
registry.commitTransaction();
api.setUuid(artifact.getId());
transactionCommitted = true;
if (log.isDebugEnabled()) {
log.debug("API details successfully added to the registry. API Name: " + api.getId().getApiName() + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
}
// set current time as created time for returning api.
api.setCreatedTime(String.valueOf(new Date().getTime()));
PublisherAPI returnAPI = APIMapper.INSTANCE.toPublisherApi(api);
if (log.isDebugEnabled()) {
log.debug("Created API :" + returnAPI.toString());
}
return returnAPI;
} catch (RegistryException e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error here would mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
throw new APIPersistenceException("Error while performing registry transaction operation", e);
} catch (APIManagementException e) {
throw new APIPersistenceException("Error while creating API", e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error while rolling back the transaction for API: " + api.getId().getApiName(), ex);
}
}
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method addAPIRevision.
@Override
public String addAPIRevision(Organization org, String apiUUID, int revisionId) throws APIPersistenceException {
String revisionUUID;
boolean transactionCommitted = false;
Registry registry = null;
boolean tenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiUUID);
if (apiArtifact != null) {
API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
APIIdentifier apiId = api.getId();
String apiPath = RegistryPersistenceUtil.getAPIPath(apiId);
int prependIndex = apiPath.lastIndexOf("/api");
String apiSourcePath = apiPath.substring(0, prependIndex);
String revisionTargetPath = RegistryPersistenceUtil.getRevisionPath(apiId.getUUID(), revisionId);
if (registry.resourceExists(revisionTargetPath)) {
throw new APIManagementException("API revision already exists with id: " + revisionId, ExceptionCodes.from(ExceptionCodes.EXISTING_API_REVISION_FOUND, String.valueOf(revisionId)));
}
registry.copy(apiSourcePath, revisionTargetPath);
Resource apiRevisionArtifact = registry.get(revisionTargetPath + "api");
registry.commitTransaction();
transactionCommitted = true;
if (log.isDebugEnabled()) {
String logMessage = "Revision for API Name: " + apiId.getApiName() + ", API Version " + apiId.getVersion() + " created";
log.debug(logMessage);
}
revisionUUID = apiRevisionArtifact.getUUID();
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + apiUUID + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (RegistryException e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error here would mask the original exception
log.error("Error while rolling back the transaction for API Revision create for API: " + apiUUID, re);
}
throw new APIPersistenceException("Error while performing registry transaction operation", e);
} catch (APIManagementException e) {
throw new APIPersistenceException("Error while creating API Revision", e);
} finally {
try {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error while rolling back the transaction for API Revision create for API: " + apiUUID, ex);
}
}
return revisionUUID;
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class GraphQLSchemaDefinition method extractGraphQLOperationList.
/**
* Extract GraphQL Operations from given schema.
*
* @param typeRegistry graphQL Schema Type Registry
* @param type operation type string
* @return the arrayList of APIOperationsDTO
*/
public List<URITemplate> extractGraphQLOperationList(TypeDefinitionRegistry typeRegistry, String type) {
List<URITemplate> operationArray = new ArrayList<>();
Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
Optional<SchemaDefinition> schemaDefinition = typeRegistry.schemaDefinition();
if (schemaDefinition.isPresent()) {
List<OperationTypeDefinition> operationTypeList = schemaDefinition.get().getOperationTypeDefinitions();
for (OperationTypeDefinition operationTypeDefinition : operationTypeList) {
if (entry.getValue().getName().equalsIgnoreCase(operationTypeDefinition.getTypeName().getName())) {
if (type == null) {
addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
} else if (type.equals(operationTypeDefinition.getName().toUpperCase())) {
addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
}
}
}
} else {
if (entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_QUERY) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_MUTATION) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_SUBSCRIPTION)) {
if (type == null) {
addOperations(entry, entry.getKey(), operationArray);
} else if (type.equals(entry.getValue().getName().toUpperCase())) {
addOperations(entry, entry.getKey(), operationArray);
}
}
}
}
return operationArray;
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class OAS2Parser method generateAPIDefinition.
/**
* This method generates API definition using the given api's URI templates and the swagger.
* It will alter the provided swagger definition based on the URI templates. For example: if there is a new
* URI template which is not included in the swagger, it will be added to the swagger as a basic resource. Any
* additional resources inside the swagger will be removed from the swagger. Changes to scopes, throtting policies,
* on the resource will be updated on the swagger
*
* @param swaggerData api
* @param swaggerObj swagger
* @return API definition in string format
* @throws APIManagementException if error occurred when generating API Definition
*/
private String generateAPIDefinition(SwaggerData swaggerData, Swagger swaggerObj) throws APIManagementException {
// Generates below model using the API's URI template
// path -> [verb1 -> template1, verb2 -> template2, ..]
Map<String, Map<String, SwaggerData.Resource>> resourceMap = getResourceMap(swaggerData);
Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, Path> pathEntry = itr.next();
String pathName = pathEntry.getKey();
Path path = pathEntry.getValue();
Map<String, SwaggerData.Resource> resourcesForPath = resourceMap.get(pathName);
if (resourcesForPath == null) {
// remove paths that are not in URI Templates
itr.remove();
} else {
// If path is available in the URI template, then check for operations(verbs)
for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
HttpMethod httpMethod = operationEntry.getKey();
Operation operation = operationEntry.getValue();
SwaggerData.Resource resource = resourcesForPath.get(httpMethod.toString().toUpperCase());
if (resource == null) {
// if particular operation is not available in URI templates, then remove it from swagger
path.set(httpMethod.toString().toLowerCase(), null);
} else {
// if operation is available in URI templates, update swagger operation
// with auth type, scope etc
updateOperationManagedInfo(resource, operation);
}
}
// if there are any verbs (operations) not defined in swagger then add them
for (Map.Entry<String, SwaggerData.Resource> resourcesForPathEntry : resourcesForPath.entrySet()) {
String verb = resourcesForPathEntry.getKey();
SwaggerData.Resource resource = resourcesForPathEntry.getValue();
HttpMethod method = HttpMethod.valueOf(verb.toUpperCase());
Operation operation = path.getOperationMap().get(method);
if (operation == null) {
operation = createOperation(resource);
path.set(resource.getVerb().toLowerCase(), operation);
}
}
}
}
// add to swagger if there are any new templates
for (Map.Entry<String, Map<String, SwaggerData.Resource>> resourceMapEntry : resourceMap.entrySet()) {
String path = resourceMapEntry.getKey();
Map<String, SwaggerData.Resource> verbMap = resourceMapEntry.getValue();
if (swaggerObj.getPath(path) == null) {
for (Map.Entry<String, SwaggerData.Resource> verbMapEntry : verbMap.entrySet()) {
SwaggerData.Resource resource = verbMapEntry.getValue();
addOrUpdatePathToSwagger(swaggerObj, resource);
}
}
}
updateSwaggerSecurityDefinition(swaggerObj, swaggerData, "https://test.com");
updateLegacyScopesFromSwagger(swaggerObj, swaggerData);
if (StringUtils.isEmpty(swaggerObj.getInfo().getTitle())) {
swaggerObj.getInfo().setTitle(swaggerData.getTitle());
}
if (StringUtils.isEmpty(swaggerObj.getInfo().getVersion())) {
swaggerObj.getInfo().setVersion(swaggerData.getVersion());
}
preserveResourcePathOrderFromAPI(swaggerData, swaggerObj);
return getSwaggerJsonString(swaggerObj);
}
Aggregations