use of org.wso2.carbon.apimgt.api.model.APIProductResource 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.APIProductResource 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.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method addAPIProductWithoutPublishingToGateway.
@Override
public Map<API, List<APIProductResource>> addAPIProductWithoutPublishingToGateway(APIProduct product) throws APIManagementException {
Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
validateApiProductInfo(product);
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
if (log.isDebugEnabled()) {
log.debug("API Product details successfully added to the registry. API Product Name: " + product.getId().getName() + ", API Product Version : " + product.getId().getVersion() + ", API Product context : " + // todo: log context
"change");
}
List<APIProductResource> resources = product.getProductResources();
// list to hold resources which are actually in an existing api. If user has created an API product with invalid
// API or invalid resource of a valid API, that content will be removed .validResources array will have only
// legitimate apis
List<APIProductResource> validResources = new ArrayList<APIProductResource>();
for (APIProductResource apiProductResource : resources) {
API api;
String apiUUID;
if (apiProductResource.getProductIdentifier() != null) {
APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
api = getAPIbyUUID(apiUUID, product.getOrganization());
} else {
apiUUID = apiProductResource.getApiId();
api = getAPIbyUUID(apiUUID, product.getOrganization());
// if API does not exist, getLightweightAPIByUUID() method throws exception.
}
if (api != null) {
validateApiLifeCycleForApiProducts(api);
if (api.getSwaggerDefinition() != null) {
api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, product.getOrganization()));
}
if (!apiToProductResourceMapping.containsKey(api)) {
apiToProductResourceMapping.put(api, new ArrayList<>());
}
List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
apiProductResources.add(apiProductResource);
apiProductResource.setApiIdentifier(api.getId());
apiProductResource.setProductIdentifier(product.getId());
if (api.isAdvertiseOnly()) {
apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
apiProductResource.setEndpointConfig(api.getEndpointConfig());
}
apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
URITemplate uriTemplate = apiProductResource.getUriTemplate();
Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
if (uriTemplate == null) {
// if no resources are define for the API, we ingore that api for the product
} else {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getResourceURI();
if (templateMap.containsKey(key)) {
// Since the template ID is not set from the request, we manually set it.
uriTemplate.setId(templateMap.get(key).getId());
// request has a valid API id and a valid resource. we add it to valid resource map
validResources.add(apiProductResource);
} else {
// ignore
log.warn("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getResourceURI() + " with http method " + uriTemplate.getHTTPVerb());
}
}
}
}
// set the valid resources only
product.setProductResources(validResources);
// now we have validated APIs and it's resources inside the API product. Add it to database
String provider = APIUtil.replaceEmailDomain(product.getId().getProviderName());
// Set version timestamp
product.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
// Create registry artifact
String apiProductUUID = createAPIProduct(product);
product.setUuid(apiProductUUID);
// Add to database
apiMgtDAO.addAPIProduct(product, product.getOrganization());
return apiToProductResourceMapping;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPI.
/**
* Updates an existing API
*
* @param api API
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update API
* @throws org.wso2.carbon.apimgt.api.FaultGatewaysException on Gateway Failure
*/
@Override
public void updateAPI(API api) throws APIManagementException, FaultGatewaysException {
boolean isValid = isAPIUpdateValid(api);
if (!isValid) {
throw new APIManagementException(" User doesn't have permission for update");
}
API oldApi = getAPIbyUUID(api.getUuid(), api.getOrganization());
String organization = api.getOrganization();
if (!oldApi.getStatus().equals(api.getStatus())) {
// Use changeAPIStatus for that kind of updates.
throw new APIManagementException("Invalid API update operation involving API status changes");
}
validateKeyManagers(api);
Gson gson = new Gson();
Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
Map<String, String> newMonetizationProperties = gson.fromJson(api.getMonetizationProperties().toString(), HashMap.class);
if (newMonetizationProperties != null) {
for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
String newValue = newMonetizationProperties.get(entry.getKey());
if (StringUtils.isAllBlank(newValue)) {
newMonetizationProperties.put(entry.getKey(), entry.getValue());
}
}
JSONParser parser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
api.setMonetizationProperties(jsonObj);
} catch (ParseException e) {
throw new APIManagementException("Error when parsing monetization properties ", e);
}
}
}
String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());
// Update WSDL in the registry
if (api.getWsdlUrl() != null && api.getWsdlResource() == null) {
updateWsdlFromUrl(api);
}
if (api.getWsdlResource() != null) {
updateWsdlFromResourceFile(api);
}
boolean updatePermissions = false;
if (APIUtil.isAccessControlEnabled()) {
if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
} else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
updateEndpointSecurity(oldApi, api);
String apiUUid = updateApiArtifact(api, true, updatePermissions);
api.setUuid(apiUUid);
if (!oldApi.getContext().equals(api.getContext())) {
api.setApiHeaderChanged(true);
}
int tenantId;
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
try {
tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new APIManagementException("Error in retrieving Tenant Information while updating api :" + api.getId().getApiName(), e);
}
validateResourceThrottlingTiers(api, tenantDomain);
// get product resource mappings on API before updating the API. Update uri templates on api will remove all
// product mappings as well.
List<APIProductResource> productResources = apiMgtDAO.getProductMappingsForAPI(api);
updateAPI(api, tenantId, userNameWithoutChange);
updateProductResourceMappings(api, organization, productResources);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the API: " + api.getId() + " in the database");
}
JSONObject apiLogObject = new JSONObject();
apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
// update doc visibility
List<Documentation> docsList = getAllDocumentation(api.getId());
if (docsList != null) {
Iterator it = docsList.iterator();
while (it.hasNext()) {
Object docsObject = it.next();
Documentation docs = (Documentation) docsObject;
updateDocVisibility(api, docs);
}
}
// notify key manager with API update
registerOrUpdateResourceInKeyManager(api, tenantDomain);
int apiId = apiMgtDAO.getAPIID(api.getUuid());
if (publishedDefaultVersion != null) {
if (api.isPublishedDefaultVersion() && !api.getId().getVersion().equals(publishedDefaultVersion)) {
APIIdentifier previousDefaultVersionIdentifier = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), publishedDefaultVersion);
sendUpdateEventToPreviousDefaultVersion(previousDefaultVersionIdentifier, organization);
}
}
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
// Extracting API details for the recommendation system
if (recommendationEnvironment != null) {
RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.ADD_API);
Thread recommendationThread = new Thread(extractor);
recommendationThread.start();
}
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method addAPIProductSwagger.
@Override
public void addAPIProductSwagger(String productId, Map<API, List<APIProductResource>> apiToProductResourceMapping, APIProduct apiProduct, String orgId) throws APIManagementException {
APIDefinition parser = new OAS3Parser();
SwaggerData swaggerData = new SwaggerData(apiProduct);
String apiProductSwagger = parser.generateAPIDefinition(swaggerData);
apiProductSwagger = OASParserUtil.updateAPIProductSwaggerOperations(apiToProductResourceMapping, apiProductSwagger);
saveSwaggerDefinition(productId, apiProductSwagger, orgId);
apiProduct.setDefinition(apiProductSwagger);
}
Aggregations