use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class RegistryPersistenceImplTestCase method testUpdateAPI.
@Test
public void testUpdateAPI() throws APIPersistenceException, RegistryException, APIManagementException {
PublisherAPI publisherAPI = new PublisherAPI();
publisherAPI.setDescription("Modified description");
API api = APIMapper.INSTANCE.toApi(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);
GenericArtifact existArtifact = PersistenceHelper.getSampleAPIArtifact();
String apiUUID = existArtifact.getId();
PowerMockito.mockStatic(RegistryPersistenceUtil.class);
GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
Mockito.when(manager.getGenericArtifact(apiUUID)).thenReturn(existArtifact);
Mockito.doNothing().when(manager).updateGenericArtifact(existArtifact);
PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
GenericArtifact updatedArtifact = PersistenceHelper.getSampleAPIArtifact();
updatedArtifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
PowerMockito.when(RegistryPersistenceUtil.createAPIArtifactContent(any(GenericArtifact.class), any(API.class))).thenReturn(updatedArtifact);
Organization org = new Organization(SUPER_TENANT_DOMAIN);
APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, existArtifact);
PublisherAPI updatedAPI = apiPersistenceInstance.updateAPI(org, publisherAPI);
Assert.assertEquals("Updated API description does not match", "Modified description", updatedAPI.getDescription());
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class RegistryPersistenceImplTestCase method testRegistrySelectionForTenantUserCrossTenatAccess.
@Test
public void testRegistrySelectionForTenantUserCrossTenatAccess() throws Exception {
RegistryService registryService = Mockito.mock(RegistryService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(tenantManager.getTenantId(TENANT_DOMAIN)).thenReturn(TENANT_ID);
Mockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID);
PowerMockito.mockStatic(CarbonContext.class);
CarbonContext context = Mockito.mock(CarbonContext.class);
PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(context);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext);
PowerMockito.mockStatic(GovernanceUtils.class);
GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
List<GovernanceArtifact> artifacts = new ArrayList<GovernanceArtifact>();
artifacts.add(artifact);
PowerMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.any(String.class), Mockito.any(Registry.class), Mockito.any(String.class), Mockito.any(Boolean.class))).thenReturn(artifacts);
PowerMockito.mockStatic(RegistryPersistenceUtil.class);
ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder);
RealmService realmService = Mockito.mock(RealmService.class);
PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService);
UserRealm realm = Mockito.mock(UserRealm.class);
PowerMockito.when(realmService.getTenantUserRealm(TENANT_ID)).thenReturn(realm);
PowerMockito.doNothing().when(RegistryPersistenceUtil.class, "loadloadTenantAPIRXT", Mockito.any(String.class), Mockito.any(Integer.class));
Mockito.when(context.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(context.getTenantId()).thenReturn(TENANT_ID);
APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(tenantManager, registryService);
// return null artifact because we are not testing artifact related params. this is only to get the registry obj
GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.any(String.class))).thenReturn(artifactManager);
Mockito.when(artifactManager.getGenericArtifact(Mockito.any(String.class))).thenReturn(null);
// trigger registry object creation. access super tenant api
UserContext ctx = new UserContext("user", new Organization(TENANT_DOMAIN), null, null);
apiPersistenceInstance.searchAPIsForDevPortal(new Organization(SUPER_TENANT_DOMAIN), "", 0, 10, ctx);
// check whether super tenant's system registy is accessed
Mockito.verify(registryService, times(1)).getGovernanceSystemRegistry((SUPER_TENANT_ID));
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIUtil 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);
apiProductIdentifier.setUUID(artifact.getId());
apiProduct = new APIProduct(apiProductIdentifier);
apiProduct.setUuid(artifact.getId());
apiProduct.setRating(Float.toString(getAverageRating(artifact.getId())));
ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
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));
String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
apiProduct.setEnvironments(extractEnvironmentsForAPI(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);
Map<String, Tier> definedTiers = getTiers(tenantId);
Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, productName);
apiProduct.setAvailableTiers(availableTier);
// 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);
List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProductIdentifier);
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 = getScopeByName(scopeKey, tenantDomainName);
uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
} else {
resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
}
it.set(resourceScope);
}
}
Set<String> tags = new HashSet<String>();
Tag[] tag = registry.getTags(artifactPath);
for (Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
apiProduct.addTags(tags);
for (APIProductResource resource : resources) {
String apiPath = APIUtil.getAPIPath(resource.getApiIdentifier());
Resource productResource = null;
try {
// Handles store and publisher visibility issue when associated apis have different visibility
// restrictions.
productResource = registry.get(apiPath);
} catch (RegistryException e) {
if (e.getClass().equals(AuthorizationFailedException.class)) {
if (log.isDebugEnabled()) {
log.debug("User is not authorized to access the resource " + apiPath);
}
continue;
} else {
String msg = "Failed to get product resource";
throw new APIManagementException(msg, e);
}
}
String artifactId = productResource.getUUID();
resource.setApiId(artifactId);
GenericArtifactManager artifactManager = getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(resource.getApiId());
API api = getAPI(apiArtifact, registry);
resource.setEndpointConfig(api.getEndpointConfig());
resource.setEndpointSecurityMap(setEndpointSecurityForAPIProduct(api));
}
apiProduct.setProductResources(resources);
// 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;
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIUtilTest method testGetArtifactManager.
@Test
public void testGetArtifactManager() {
PowerMockito.mockStatic(GenericArtifactManager.class);
System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
Registry registry = Mockito.mock(UserRegistry.class);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
PowerMockito.mockStatic(GovernanceUtils.class);
PowerMockito.doNothing().when(GovernanceUtils.class, "loadGovernanceArtifacts", (UserRegistry) registry);
Mockito.when(GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry)).thenReturn(Mockito.mock(GovernanceArtifactConfiguration.class)).thenReturn(null).thenThrow(RegistryException.class);
GenericArtifactManager genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.whenNew(GenericArtifactManager.class).withArguments(registry, APIConstants.API_KEY).thenReturn(genericArtifactManager);
GenericArtifactManager retrievedGenericArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
Assert.assertEquals(genericArtifactManager, retrievedGenericArtifactManager);
APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
Assert.fail();
} catch (APIManagementException ex) {
Assert.assertTrue(ex.getMessage().contains("Failed to initialize GenericArtifactManager"));
} catch (org.wso2.carbon.registry.core.exceptions.RegistryException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAPIbyUUID.
/**
* Get API by registry artifact id
*
* @param uuid Registry artifact id
* @param organization organization for the registry
* @return API of the provided artifact id
* @throws APIManagementException
*/
public API getAPIbyUUID(String uuid, String organization) throws APIManagementException {
boolean tenantFlowStarted = false;
try {
Registry registry;
if (organization != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(organization)) {
int id = getTenantManager().getTenantId(organization);
startTenantFlow(organization);
tenantFlowStarted = true;
registry = getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
registry = getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
} else {
// both requested tenant and logged in user's tenant are carbon.super
registry = this.registry;
}
}
GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
if (apiArtifact != null) {
API api = getApiForPublishing(registry, apiArtifact);
WorkflowDTO workflowDTO = APIUtil.getAPIWorkflowStatus(api.getUuid(), WF_TYPE_AM_API_STATE);
if (workflowDTO != null) {
WorkflowStatus status = workflowDTO.getStatus();
api.setWorkflowStatus(status.toString());
}
return api;
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (RegistryException e) {
String msg = "Failed to get API";
throw new APIManagementException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Failed to get API";
throw new APIManagementException(msg, e);
} finally {
if (tenantFlowStarted) {
endTenantFlow();
}
}
}
Aggregations