use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method updateAPIProduct.
@Override
public PublisherAPIProduct updateAPIProduct(Organization org, PublisherAPIProduct publisherAPIProduct) throws APIPersistenceException {
String requestedTenantDomain = org.getName();
boolean isTenantFlowStarted = false;
boolean transactionCommitted = false;
APIProduct apiProduct;
Registry registry = null;
try {
RegistryHolder holder = getRegistry(requestedTenantDomain);
registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API Product with artifact ID " + publisherAPIProduct.getId();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
GenericArtifact artifact = artifactManager.getGenericArtifact(publisherAPIProduct.getId());
apiProduct = APIProductMapper.INSTANCE.toApiProduct(publisherAPIProduct);
APIProductIdentifier id = new APIProductIdentifier(publisherAPIProduct.getProviderName(), publisherAPIProduct.getApiProductName(), publisherAPIProduct.getVersion());
apiProduct.setID(id);
GenericArtifact updateApiProductArtifact = RegistryPersistenceUtil.createAPIProductArtifactContent(artifact, apiProduct);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiProductArtifact.getId());
artifactManager.updateGenericArtifact(updateApiProductArtifact);
String visibleRolesList = apiProduct.getVisibleRoles();
String[] visibleRoles = new String[0];
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
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 = apiProduct.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
String publisherAccessControlRoles = apiProduct.getAccessControlRoles();
updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, apiProduct.getAccessControl(), apiProduct.getAdditionalProperties());
RegistryPersistenceUtil.setResourcePermissions(apiProduct.getId().getProviderName(), apiProduct.getVisibility(), visibleRoles, artifactPath, registry);
registry.commitTransaction();
transactionCommitted = true;
return publisherAPIProduct;
} 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 Product: " + publisherAPIProduct.getApiProductName(), re);
}
throw new APIPersistenceException("Error while performing registry transaction operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error occurred while rolling back the transaction.", ex);
}
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method addAPIProduct.
@Override
public PublisherAPIProduct addAPIProduct(Organization org, PublisherAPIProduct publisherAPIProduct) throws APIPersistenceException {
Registry registry = null;
boolean isTenantFlowStarted = false;
boolean transactionCommitted = false;
APIProduct apiProduct;
try {
String tenantDomain = org.getName();
RegistryHolder holder = getRegistry(tenantDomain);
registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact genericArtifact = artifactManager.newGovernanceArtifact(new QName(publisherAPIProduct.getApiProductName()));
apiProduct = APIProductMapper.INSTANCE.toApiProduct(publisherAPIProduct);
APIProductIdentifier id = new APIProductIdentifier(publisherAPIProduct.getProviderName(), publisherAPIProduct.getApiProductName(), publisherAPIProduct.getVersion());
apiProduct.setID(id);
if (genericArtifact == null) {
String errorMessage = "Generic artifact is null when creating API Product" + apiProduct.getId().getName();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
GenericArtifact artifact = RegistryPersistenceUtil.createAPIProductArtifactContent(genericArtifact, apiProduct);
artifactManager.addGenericArtifact(artifact);
artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
String providerPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + id.getProviderName();
// provider ------provides----> APIProduct
registry.addAssociation(providerPath, artifactPath, APIConstants.PROVIDER_ASSOCIATION);
String apiProductStatus = apiProduct.getState();
saveAPIStatus(registry, artifactPath, apiProductStatus);
Set<String> tagSet = apiProduct.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
String visibleRolesList = apiProduct.getVisibleRoles();
String[] visibleRoles = new String[0];
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
String publisherAccessControlRoles = apiProduct.getAccessControlRoles();
updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, apiProduct.getAccessControl(), apiProduct.getAdditionalProperties());
RegistryPersistenceUtil.setResourcePermissions(apiProduct.getId().getProviderName(), apiProduct.getVisibility(), visibleRoles, artifactPath, registry);
registry.commitTransaction();
transactionCommitted = true;
if (log.isDebugEnabled()) {
String logMessage = "API Product Name: " + apiProduct.getId().getName() + ", API Product Version " + apiProduct.getId().getVersion() + " created";
log.debug(logMessage);
}
publisherAPIProduct.setCreatedTime(String.valueOf(new Date().getTime()));
publisherAPIProduct.setId(artifact.getId());
return publisherAPIProduct;
} 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 Product : " + publisherAPIProduct.getApiProductName(), re);
}
throw new APIPersistenceException("Error while performing registry transaction operation", e);
} catch (APIManagementException e) {
throw new APIPersistenceException("Error while creating API Product", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error while rolling back the transaction for API Product : " + publisherAPIProduct.getApiProductName(), ex);
}
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class RegistryPersistenceImplTestCase method testAddAPIProduct.
@Test
public void testAddAPIProduct() throws RegistryException, APIPersistenceException, APIManagementException {
GenericArtifact artifact = PersistenceHelper.getSampleAPIProductArtifact();
PublisherAPIProduct publisherAPI = new PublisherAPIProduct();
publisherAPI.setApiProductName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
publisherAPI.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
publisherAPI.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
APIProduct api = APIProductMapper.INSTANCE.toApiProduct(publisherAPI);
Registry registry = Mockito.mock(UserRegistry.class);
Resource resource = new ResourceImpl();
Mockito.when(registry.get(anyString())).thenReturn(resource);
Tag[] tags = new Tag[0];
Mockito.when(registry.getTags(anyString())).thenReturn(tags);
PowerMockito.mockStatic(RegistryPersistenceUtil.class);
GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
PowerMockito.when(RegistryPersistenceUtil.createAPIProductArtifactContent(any(GenericArtifact.class), any(APIProduct.class))).thenReturn(artifact);
GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(manager.newGovernanceArtifact(new QName(publisherAPI.getApiProductName()))).thenReturn(newArtifact);
Mockito.when(manager.getGenericArtifact(any(String.class))).thenReturn(newArtifact);
Mockito.doNothing().when(newArtifact).invokeAction("Publish", APIConstants.API_LIFE_CYCLE);
Organization org = new Organization(SUPER_TENANT_DOMAIN);
APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, artifact);
apiPersistenceInstance.addAPIProduct(org, publisherAPI);
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method setResourceProperties.
/**
* To set the resource properties to the API Product.
*
* @param apiProduct API Product that need to set the resource properties.
* @param registry Registry to get the resource from.
* @param artifactPath Path of the API Product artifact.
* @return Updated API.
* @throws RegistryException Registry Exception.
*/
private static APIProduct setResourceProperties(APIProduct apiProduct, Registry registry, String artifactPath) throws RegistryException {
Resource productResource = registry.get(artifactPath);
Properties properties = productResource.getProperties();
if (properties != null) {
Enumeration propertyNames = properties.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
if (log.isDebugEnabled()) {
log.debug("API Product '" + apiProduct.getId().toString() + "' " + "has the property " + propertyName);
}
if (propertyName.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
apiProduct.addProperty(propertyName.substring(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX.length()), productResource.getProperty(propertyName));
}
}
}
apiProduct.setAccessControl(productResource.getProperty(APIConstants.ACCESS_CONTROL));
String accessControlRoles = null;
String displayPublisherRoles = productResource.getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
if (displayPublisherRoles == null) {
String publisherRoles = productResource.getProperty(APIConstants.PUBLISHER_ROLES);
if (publisherRoles != null) {
accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(productResource.getProperty(APIConstants.PUBLISHER_ROLES)) ? null : productResource.getProperty(APIConstants.PUBLISHER_ROLES);
}
} else {
accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(displayPublisherRoles) ? null : displayPublisherRoles;
}
apiProduct.setAccessControlRoles(accessControlRoles);
return apiProduct;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method createAPIProductArtifactContent.
/**
* Create Governance artifact from given attributes
*
* @param artifact initial governance artifact
* @param apiProduct APIProduct object with the attributes value
* @return GenericArtifact
* @throws APIManagementException if failed to create API Product
*/
public static GenericArtifact createAPIProductArtifactContent(GenericArtifact artifact, APIProduct apiProduct) throws APIManagementException {
try {
// todo : review and add missing fields
artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, apiProduct.getId().getName());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, apiProduct.getId().getVersion());
artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, apiProduct.getId().getProviderName());
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, apiProduct.getContext());
artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, apiProduct.getDescription());
artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, APIConstants.AuditLogConstants.API_PRODUCT);
artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiProduct.getState());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, apiProduct.getVisibility());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, apiProduct.getVisibleRoles());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, apiProduct.getVisibleTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, apiProduct.getBusinessOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, apiProduct.getBusinessOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, apiProduct.getTechnicalOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, apiProduct.getTechnicalOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, apiProduct.getSubscriptionAvailability());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, apiProduct.getSubscriptionAvailableTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, apiProduct.getThumbnailUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(apiProduct.getCacheTimeout()));
StringBuilder policyBuilder = new StringBuilder();
for (Tier tier : apiProduct.getAvailableTiers()) {
policyBuilder.append(tier.getName());
policyBuilder.append("||");
}
String policies = policyBuilder.toString();
if (!"".equals(policies)) {
policies = policies.substring(0, policies.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
} else {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(apiProduct.getEnvironments()));
artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, apiProduct.getTransports());
artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, getCorsConfigurationJsonFromDto(apiProduct.getCorsConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, apiProduct.getAuthorizationHeader());
artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, apiProduct.getApiSecurity());
// Validate if the API has an unsupported context before setting it in the artifact
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(apiProduct.getContextTemplate())) {
throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
}
} else {
String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(apiProduct.getContextTemplate())) {
throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
}
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(apiProduct.isEnabledSchemaValidation()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(apiProduct.isEnableStore()));
artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, apiProduct.getResponseCache());
// This is to support the pluggable version strategy.
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, apiProduct.getContextTemplate());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
artifact.setAttribute(APIConstants.API_GATEWAY_VENDOR, apiProduct.getGatewayVendor());
// set monetization status (i.e - enabled or disabled)
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(apiProduct.getMonetizationStatus()));
// set additional monetization data
if (apiProduct.getMonetizationProperties() != null) {
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, apiProduct.getMonetizationProperties().toJSONString());
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = apiProduct.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
// set version timestamp
artifact.addAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, apiProduct.getVersionTimestamp());
} catch (GovernanceException e) {
String msg = "Failed to create API for : " + apiProduct.getId().getName();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return artifact;
}
Aggregations