use of org.wso2.carbon.apimgt.api.model.APIIdentifier 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.model.APIIdentifier 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.model.APIIdentifier 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.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method getAPI.
/**
* This Method is different from getAPI method, as this one returns
* URLTemplates without aggregating duplicates. This is to be used for building synapse config.
*
* @param artifact
* @param registry
* @return API
* @throws org.wso2.carbon.apimgt.api.APIManagementException
*/
public static API getAPI(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
API api;
try {
String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion, artifact.getId());
api = new API(apiIdentifier);
// set uuid
api.setUuid(artifact.getId());
// set rating
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
// String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
// + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
// + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
// + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
Resource apiResource = registry.get(artifactPath);
api = setResourceProperties(api, apiResource, artifactPath);
// set description
api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
// set url
api.setStatus(getLcStateFromArtifact(artifact));
api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
} else {
// If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
api.setEndpointUTPassword(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
}
api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
try {
String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
cacheTimeout = Integer.parseInt(strCacheTimeout);
}
} catch (NumberFormatException e) {
if (log.isWarnEnabled()) {
log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
}
// ignore the exception and use default cache timeout value
}
api.setCacheTimeout(cacheTimeout);
api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
Set<Tier> availableTiers = new HashSet<Tier>();
if (tiers != null) {
String[] tiersArray = tiers.split("\\|\\|");
for (String tierName : tiersArray) {
availableTiers.add(new Tier(tierName));
}
}
api.setAvailableTiers(availableTiers);
// This contains the resolved context
api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
// We set the context template here
api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
Set<String> tags = new HashSet<String>();
Tag[] tag = registry.getTags(artifactPath);
for (Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
api.setTags(tags);
api.setLastUpdated(apiResource.getLastModified());
api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
// set data and status related to monetization
api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
// set selected clusters which API needs to be deployed
String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
if (StringUtils.isNotBlank(monetizationInfo)) {
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
api.setMonetizationProperties(jsonObj);
}
api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
// get endpoint config string from artifact, parse it as a json and set the environment list configured with
// non empty URLs to API object
String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
if (StringUtils.isNotEmpty(keyManagers)) {
api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
} else {
api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
}
try {
api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
} catch (ParseException e) {
String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
log.error(msg, e);
throw new APIManagementException(msg, e);
} catch (ClassCastException e) {
String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
log.error(msg, e);
throw new APIManagementException(msg, e);
}
} catch (GovernanceException e) {
String msg = "Failed to get API for artifact ";
throw new APIManagementException(msg, e);
} catch (RegistryException e) {
String msg = "Failed to get LastAccess time or Rating";
throw new APIManagementException(msg, e);
} catch (UserStoreException e) {
String msg = "Failed to get User Realm of API Provider";
throw new APIManagementException(msg, e);
} catch (ParseException e) {
String msg = "Failed to get parse monetization information.";
throw new APIManagementException(msg, e);
}
return api;
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class GraphQLSchemaDefinition method getGraphqlSchemaDefinition.
/**
* Returns the graphQL content in registry specified by the wsdl name
*
* @param apiId Api Identifier
* @return graphQL content matching name if exist else null
*/
public String getGraphqlSchemaDefinition(APIIdentifier apiId, Registry registry) throws APIManagementException {
String apiName = apiId.getApiName();
String apiVersion = apiId.getVersion();
String apiProviderName = apiId.getProviderName();
APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId.getUUID());
String resourcePath;
if (apiRevision != null && apiRevision.getApiUUID() != null) {
resourcePath = APIUtil.getRevisionPath(apiRevision.getApiUUID(), apiRevision.getId());
} else {
resourcePath = APIUtil.getGraphqlDefinitionFilePath(apiName, apiVersion, apiProviderName);
}
String schemaDoc = null;
String schemaName = apiId.getProviderName() + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR + apiId.getApiName() + apiId.getVersion() + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION;
String schemaResourePath = resourcePath + schemaName;
try {
if (registry.resourceExists(schemaResourePath)) {
Resource schemaResource = registry.get(schemaResourePath);
schemaDoc = IOUtils.toString(schemaResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
}
} catch (RegistryException e) {
String msg = "Error while getting schema file from the registry " + schemaResourePath;
log.error(msg, e);
throw new APIManagementException(msg, e);
} catch (IOException e) {
String error = "Error occurred while getting the content of schema: " + schemaName;
log.error(error);
throw new APIManagementException(error, e);
}
return schemaDoc;
}
Aggregations