use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAllDocumentation.
public List<Documentation> getAllDocumentation(Identifier id) throws APIManagementException {
List<Documentation> documentationList = new ArrayList<Documentation>();
String docArtifactKeyType = StringUtils.EMPTY;
docArtifactKeyType = APIConstants.DOCUMENTATION_KEY;
String apiOrAPIProductDocPath;
APIRevision apiRevision = apiMgtDAO.checkAPIUUIDIsARevisionUUID(id.getUUID());
if (apiRevision != null && apiRevision.getApiUUID() != null) {
apiOrAPIProductDocPath = APIUtil.getAPIOrAPIProductRevisionDocPath(apiRevision.getApiUUID(), apiRevision.getId());
} else {
apiOrAPIProductDocPath = APIUtil.getAPIOrAPIProductDocPath(id);
}
String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
try {
if (registry.resourceExists(apiOrAPIProductDocPath)) {
Resource resource = registry.get(apiOrAPIProductDocPath);
if (resource instanceof org.wso2.carbon.registry.core.Collection) {
List<String> docPaths = getDocPaths((org.wso2.carbon.registry.core.Collection) resource, apiOrAPIProductDocPath);
for (String docPath : docPaths) {
if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
Resource docResource = registry.get(docPath);
GenericArtifactManager artifactManager = getAPIGenericArtifactManager(registry, docArtifactKeyType);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact);
Date contentLastModifiedDate;
Date docLastModifiedDate = docResource.getLastModified();
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = StringUtils.EMPTY;
if (id instanceof APIIdentifier) {
contentPath = APIUtil.getAPIDocContentPath((APIIdentifier) id, doc.getName());
} else if (id instanceof APIProductIdentifier) {
contentPath = APIUtil.getProductDocContentPath((APIProductIdentifier) id, doc.getName());
}
contentLastModifiedDate = registry.get(contentPath).getLastModified();
doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ? contentLastModifiedDate : docLastModifiedDate));
} else {
doc.setLastUpdated(docLastModifiedDate);
}
documentationList.add(doc);
}
}
}
}
} catch (RegistryException e) {
String msg = "Failed to get documentations for api/product " + id.getName();
throw new APIManagementException(msg, e);
}
return documentationList;
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class AbstractAPIManager method getDocumentationContent.
public String getDocumentationContent(Identifier identifier, String documentationName) throws APIManagementException {
String contentPath = StringUtils.EMPTY;
String identifierType = StringUtils.EMPTY;
if (identifier instanceof APIIdentifier) {
contentPath = APIUtil.getAPIDocPath((APIIdentifier) identifier) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + documentationName;
identifierType = APIConstants.API_IDENTIFIER_TYPE;
} else if (identifier instanceof APIProductIdentifier) {
contentPath = APIUtil.getProductDocPath((APIProductIdentifier) identifier) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + documentationName;
identifierType = APIConstants.API_PRODUCT_IDENTIFIER_TYPE;
}
String tenantDomain = getTenantDomain(identifier);
Registry registry;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
startTenantFlow(tenantDomain);
isTenantFlowStarted = true;
}
/* If the API provider is a tenant, load tenant registry*/
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int id = getTenantManager().getTenantId(tenantDomain);
registry = getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
registry = getRegistryService().getGovernanceUserRegistry(identifier.getProviderName(), MultitenantConstants.SUPER_TENANT_ID);
} else {
registry = this.registry;
}
}
if (registry.resourceExists(contentPath)) {
Resource docContent = registry.get(contentPath);
Object content = docContent.getContent();
if (content != null) {
return new String((byte[]) docContent.getContent(), Charset.defaultCharset());
}
}
} catch (RegistryException e) {
String msg = "No document content found for documentation: " + documentationName + " of " + identifierType + " : " + identifier.getName();
throw new APIManagementException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Failed to get document content found for documentation: " + documentationName + " of " + identifierType + " : " + identifier.getName();
throw new APIManagementException(msg, e);
} finally {
if (isTenantFlowStarted) {
endTenantFlow();
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class AbstractAPIManager method populateAPIProductInformation.
protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
Organization org = new Organization(organization);
apiProduct.setOrganization(organization);
ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
for (APIProductResource resource : resources) {
List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
ListIterator it = resourceScopes.listIterator();
while (it.hasNext()) {
Scope resourceScope = (Scope) it.next();
String scopeKey = resourceScope.getKey();
if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
resourceScope = APIUtil.getScopeByName(scopeKey, organization);
uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
} else {
resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
}
it.set(resourceScope);
}
}
for (APIProductResource resource : resources) {
String resourceAPIUUID = resource.getApiIdentifier().getUUID();
resource.setApiId(resourceAPIUUID);
try {
PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
API api = APIMapper.INSTANCE.toApi(publisherAPI);
if (api.isAdvertiseOnly()) {
resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
resource.setEndpointConfig(api.getEndpointConfig());
}
resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
} catch (APIPersistenceException e) {
throw new APIManagementException("Error while retrieving the api for api product " + e);
}
}
apiProduct.setProductResources(resources);
// UUID
if (apiProduct.getUuid() == null) {
apiProduct.setUuid(uuid);
}
// environment
String environmentString = null;
if (apiProduct.getEnvironments() != null) {
environmentString = String.join(",", apiProduct.getEnvironments());
}
apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
// workflow status
APIProductIdentifier productIdentifier = apiProduct.getId();
WorkflowDTO workflow;
String currentApiProductUuid = uuid;
if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
currentApiProductUuid = apiProduct.getRevisionedApiProductId();
}
workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
if (workflow != null) {
WorkflowStatus status = workflow.getStatus();
apiProduct.setWorkflowStatus(status.toString());
}
// available tier
String tiers = null;
Set<Tier> tiersSet = apiProduct.getAvailableTiers();
Set<String> tierNameSet = new HashSet<String>();
for (Tier t : tiersSet) {
tierNameSet.add(t.getName());
}
if (apiProduct.getAvailableTiers() != null) {
tiers = String.join("||", tierNameSet);
}
Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
apiProduct.setAvailableTiers(availableTier);
// Scopes
/*
Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
*/
// templates
String resourceConfigsString = null;
if (apiProduct.getDefinition() != null) {
resourceConfigsString = apiProduct.getDefinition();
} else {
resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
apiProduct.setDefinition(resourceConfigsString);
}
// CORS . if null is returned, set default config from the configuration
if (apiProduct.getCorsConfiguration() == null) {
apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
}
// set category
List<APICategory> categories = apiProduct.getApiCategories();
if (categories != null) {
List<String> categoriesOfAPI = new ArrayList<String>();
for (APICategory apiCategory : categories) {
categoriesOfAPI.add(apiCategory.getName());
}
List<APICategory> categoryList = new ArrayList<>();
if (!categoriesOfAPI.isEmpty()) {
// category array retrieved from artifact has only the category name, therefore we need to fetch
// categories
// and fill out missing attributes before attaching the list to the api
List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
// todo-category: optimize this loop with breaks
for (String categoryName : categoriesOfAPI) {
for (APICategory category : allCategories) {
if (categoryName.equals(category.getName())) {
categoryList.add(category);
break;
}
}
}
}
apiProduct.setApiCategories(categoryList);
}
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method deleteAPIProduct.
@Override
public void deleteAPIProduct(Organization org, String apiId) throws APIPersistenceException {
boolean tenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
tenantFlowStarted = holder.isTenantFlowStarted();
Registry registry = holder.getRegistry();
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 Product" + apiId;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
GenericArtifact apiProductArtifact = artifactManager.getGenericArtifact(apiId);
APIProductIdentifier identifier = new APIProductIdentifier(apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
// this is the product resource collection path
String productResourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
// this is the product rxt instance path
String apiProductArtifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
Resource apiProductResource = registry.get(productResourcePath);
String productResourceUUID = apiProductResource.getUUID();
if (productResourceUUID == null) {
throw new APIManagementException("artifact id is null for : " + productResourcePath);
}
Resource apiArtifactResource = registry.get(apiProductArtifactPath);
String apiArtifactResourceUUID = apiArtifactResource.getUUID();
if (apiArtifactResourceUUID == null) {
throw new APIManagementException("artifact id is null for : " + apiProductArtifactPath);
}
// Delete the dependencies associated with the api product artifact
GovernanceArtifact[] dependenciesArray = apiProductArtifact.getDependencies();
if (dependenciesArray.length > 0) {
for (GovernanceArtifact artifact : dependenciesArray) {
registry.delete(artifact.getPath());
}
}
// delete registry resources
artifactManager.removeGenericArtifact(apiProductArtifact);
artifactManager.removeGenericArtifact(productResourceUUID);
/* remove empty directories */
String apiProductCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
if (registry.resourceExists(apiProductCollectionPath)) {
// at the moment product versioning is not supported so we are directly deleting this collection as
// this is known to be empty
registry.delete(apiProductCollectionPath);
}
String productProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
if (registry.resourceExists(productProviderPath)) {
Resource providerCollection = registry.get(productProviderPath);
CollectionImpl collection = (CollectionImpl) providerCollection;
// if there is no api product for given provider delete the provider directory
if (collection.getChildCount() == 0) {
if (log.isDebugEnabled()) {
log.debug("No more API Products from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
}
registry.delete(productProviderPath);
}
}
} catch (RegistryException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} catch (APIManagementException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method getAPIProduct.
/**
* Retrieves api product artifact from registry
*
* @param artifact
* @param registry
* @return APIProduct
* @throws org.wso2.carbon.apimgt.api.APIManagementException
*/
public static APIProduct getAPIProduct(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
APIProduct apiProduct;
try {
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String productName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String productVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(providerName, productName, productVersion);
apiProduct = new APIProduct(apiProductIdentifier);
setResourceProperties(apiProduct, registry, artifactPath);
// set uuid
apiProduct.setUuid(artifact.getId());
apiProduct.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
apiProduct.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
apiProduct.setState(getLcStateFromArtifact(artifact));
apiProduct.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
apiProduct.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
apiProduct.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
apiProduct.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
apiProduct.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
apiProduct.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
apiProduct.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
apiProduct.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
apiProduct.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
apiProduct.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
apiProduct.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
apiProduct.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
apiProduct.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
apiProduct.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
apiProduct.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
apiProduct.setCreatedTime(registry.get(artifactPath).getCreatedTime());
apiProduct.setLastUpdated(registry.get(artifactPath).getLastModified());
apiProduct.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
apiProduct.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
apiProduct.setTenantDomain(tenantDomainName);
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));
}
}
apiProduct.setAvailableTiers(availableTiers);
// We set the context template here
apiProduct.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
apiProduct.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
apiProduct.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
apiProduct.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
apiProduct.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
try {
cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
} catch (NumberFormatException e) {
if (log.isDebugEnabled()) {
log.debug("Error in converting cache time out due to " + e.getMessage());
}
}
apiProduct.setCacheTimeout(cacheTimeout);
Set<String> tags = new HashSet<String>();
Tag[] tag = registry.getTags(artifactPath);
for (Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
apiProduct.addTags(tags);
/*
*/
// set data and status related to monetization
apiProduct.setMonetizationStatus(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
if (StringUtils.isNotBlank(monetizationInfo)) {
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
apiProduct.setMonetizationProperties(jsonObj);
}
apiProduct.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
} catch (GovernanceException e) {
String msg = "Failed to get API Product 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 Product Provider";
throw new APIManagementException(msg, e);
} catch (ParseException e) {
String msg = "Failed to get parse monetization information.";
throw new APIManagementException(msg, e);
}
return apiProduct;
}
Aggregations