use of org.wso2.carbon.identity.api.server.application.management.common.ApplicationManagementConstants.ErrorMessage 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.identity.api.server.application.management.common.ApplicationManagementConstants.ErrorMessage in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method searchPaginatedPublisherAPIsByDoc.
private PublisherAPISearchResult searchPaginatedPublisherAPIsByDoc(Registry registry, int tenantID, String searchQuery, String username, int start, int offset) throws APIPersistenceException {
PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
try {
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
if (docArtifactManager == null) {
String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
SolrClient client = SolrClient.getInstance();
Map<String, String> fields = new HashMap<String, String>();
fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
if (tenantID == -1) {
tenantID = MultitenantConstants.SUPER_TENANT_ID;
}
// PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
SolrDocumentList documentList = client.query(searchQuery, tenantID, fields);
org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
username = MultitenantUtils.getTenantAwareUsername(username);
List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
for (SolrDocument document : documentList) {
PublisherAPIInfo apiInfo = new PublisherAPIInfo();
String filePath = (String) document.getFieldValue("path_s");
String fileName = (String) document.getFieldValue("resourceName_s");
int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
filePath = filePath.substring(index);
boolean isAuthorized;
int indexOfContents = filePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
String documentationPath = filePath.substring(0, indexOfContents) + fileName;
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else {
isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
}
if (isAuthorized) {
int indexOfDocumentation = filePath.indexOf(APIConstants.DOCUMENTATION_KEY);
String apiPath = documentationPath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else {
isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
}
if (isAuthorized) {
Resource resource = registry.get(apiPath);
String apiArtifactId = resource.getUUID();
if (apiArtifactId != null) {
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status)) {
apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
apiInfo.setId(artifact.getId());
apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
apiInfo.setStatus(status);
apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
apiInfo.setCreatedTime(String.valueOf(resource.getCreatedTime().getTime()));
apiInfo.setUpdatedTime(resource.getLastModified());
apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
// apiInfo.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
publisherAPIInfoList.add(apiInfo);
}
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
}
}
}
// Sort the publisherAPIInfoList according to the API name.
Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
searchResults.setTotalAPIsCount(publisherAPIInfoList.size());
searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
} catch (RegistryException | UserStoreException | APIPersistenceException | IndexerException e) {
String msg = "Failed to search APIs with type";
throw new APIPersistenceException(msg, e);
} finally {
PaginationContext.destroy();
}
return searchResults;
}
use of org.wso2.carbon.identity.api.server.application.management.common.ApplicationManagementConstants.ErrorMessage in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method deleteAPI.
@Override
public void deleteAPI(Organization org, String apiId) throws APIPersistenceException {
boolean transactionCommitted = false;
boolean tenantFlowStarted = false;
Registry registry = null;
try {
String tenantDomain = org.getName();
RegistryHolder holder = getRegistry(tenantDomain);
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
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 APIPersistenceException(errorMessage);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
APIIdentifier identifier = new APIIdentifier(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
// Delete the dependencies associated with the api artifact
GovernanceArtifact[] dependenciesArray = apiArtifact.getDependencies();
if (dependenciesArray.length > 0) {
for (GovernanceArtifact artifact : dependenciesArray) {
registry.delete(artifact.getPath());
}
}
artifactManager.removeGenericArtifact(apiArtifact);
String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
Resource apiResource = registry.get(path);
String artifactId = apiResource.getUUID();
artifactManager.removeGenericArtifact(artifactId);
String thumbPath = RegistryPersistenceUtil.getIconPath(identifier);
if (registry.resourceExists(thumbPath)) {
registry.delete(thumbPath);
}
String wsdlArchivePath = RegistryPersistenceUtil.getWsdlArchivePath(identifier);
if (registry.resourceExists(wsdlArchivePath)) {
registry.delete(wsdlArchivePath);
}
/*Remove API Definition Resource - swagger*/
String apiDefinitionFilePath = APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + '-' + identifier.getVersion() + '-' + identifier.getProviderName();
if (registry.resourceExists(apiDefinitionFilePath)) {
registry.delete(apiDefinitionFilePath);
}
/*remove empty directories*/
String apiCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName();
if (registry.resourceExists(apiCollectionPath)) {
Resource apiCollection = registry.get(apiCollectionPath);
CollectionImpl collection = (CollectionImpl) apiCollection;
// if there is no other versions of apis delete the directory of the api
if (collection.getChildCount() == 0) {
if (log.isDebugEnabled()) {
log.debug("No more versions of the API found, removing API collection from registry");
}
registry.delete(apiCollectionPath);
}
}
String apiProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName();
if (registry.resourceExists(apiProviderPath)) {
Resource providerCollection = registry.get(apiProviderPath);
CollectionImpl collection = (CollectionImpl) providerCollection;
// if there is no api for given provider delete the provider directory
if (collection.getChildCount() == 0) {
if (log.isDebugEnabled()) {
log.debug("No more APIs from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
}
registry.delete(apiProviderPath);
}
}
registry.commitTransaction();
transactionCommitted = true;
} catch (RegistryException e) {
throw new APIPersistenceException("Failed to remove the API : " + apiId, 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.identity.api.server.application.management.common.ApplicationManagementConstants.ErrorMessage in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method deleteDocumentation.
@Override
public void deleteDocumentation(Organization org, String apiId, String docId) throws DocumentationPersistenceException {
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
GenericArtifactManager artifactManager = RegistryPersistenceDocUtil.getDocumentArtifactManager(registry);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when removing documentation of " + apiId + " Document ID " + docId;
log.error(errorMessage);
throw new DocumentationPersistenceException(errorMessage);
}
GenericArtifact artifact = artifactManager.getGenericArtifact(docId);
String docPath = artifact.getPath();
if (docPath != null) {
if (registry.resourceExists(docPath)) {
registry.delete(docPath);
}
}
} catch (RegistryException | APIPersistenceException e) {
throw new DocumentationPersistenceException("Failed to delete documentation", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.identity.api.server.application.management.common.ApplicationManagementConstants.ErrorMessage 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;
}
Aggregations