use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class UserAwareAPIProviderTest method init.
@Before
public void init() throws Exception {
System.setProperty("carbon.home", "");
apiIdentifier = new APIIdentifier("admin_identifier1_v1.0");
PowerMockito.mockStatic(ApiMgtDAO.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.mockStatic(RegistryUtils.class);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
RealmService realmService = Mockito.mock(RealmService.class);
RegistryService registryService = Mockito.mock(RegistryService.class);
userRegistry = Mockito.mock(UserRegistry.class);
GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
resource = Mockito.mock(Resource.class, Mockito.CALLS_REAL_METHODS);
Mockito.doReturn(apiManagerConfiguration).when(apiManagerConfigurationService).getAPIManagerConfiguration();
Mockito.doReturn(APIConstants.API_GATEWAY_TYPE_SYNAPSE).when(apiManagerConfiguration).getFirstProperty(APIConstants.API_GATEWAY_TYPE);
Mockito.doReturn("true").when(apiManagerConfiguration).getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_ACCESS_CONTROL_LEVELS);
Mockito.doReturn(userRegistry).when(registryService).getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt());
Mockito.doReturn(userRegistry).when(registryService).getGovernanceSystemRegistry();
Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry(Mockito.anyInt());
Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry();
Mockito.doReturn(resource).when(userRegistry).newResource();
Mockito.doReturn(null).when(userRegistry).getUserRealm();
PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
PowerMockito.when(APIUtil.getAPIPath(Mockito.any(APIIdentifier.class))).thenReturn("test");
PowerMockito.when(APIUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.anyString())).thenReturn(artifactManager);
PowerMockito.when(APIUtil.getInternalOrganizationDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PowerMockito.doNothing().when(ServiceReferenceHolder.class, "setUserRealm", Mockito.any());
PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
PowerMockito.when(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())).thenReturn(apiIdentifier.getProviderName());
Mockito.doReturn(realmService).when(serviceReferenceHolder).getRealmService();
Mockito.doReturn(tenantManager).when(realmService).getTenantManager();
Mockito.doReturn(registryService).when(serviceReferenceHolder).getRegistryService();
Mockito.doReturn(apiManagerConfigurationService).when(serviceReferenceHolder).getAPIManagerConfigurationService();
PowerMockito.when(APIUtil.compareRoleList(Mockito.any(String[].class), Mockito.anyString())).thenCallRealMethod();
ConfigurationContextService configurationContextService = TestUtils.initConfigurationContextService(true);
PowerMockito.when(ServiceReferenceHolder.getContextService()).thenReturn(configurationContextService);
userAwareAPIProvider = new UserAwareAPIProvider(ADMIN_ROLE_NAME);
PrivilegedCarbonContext prcontext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(prcontext);
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedAPIsByStatus.
/**
* The method to get APIs by given status to Store view
*
* @return Set<API> Set of APIs
* @throws APIManagementException
*/
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String apiStatus, boolean returnAPITags) throws APIManagementException {
try {
if (tenantDomain != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
} finally {
endTenantFlow();
}
Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (APIConstants.PROTOTYPED.equals(apiStatus)) {
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(apiStatus);
}
});
} else {
if (!displayAPIsWithMultipleStatus) {
// Create the search attribute map
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(apiStatus);
}
});
} else {
return getAllPaginatedAPIs(tenantDomain, start, end);
}
}
Map<String, Object> result = new HashMap<String, Object>();
SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
int totalLength = 0;
boolean isMore = false;
try {
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
// Tenant store anonymous mode
int tenantId = getTenantId(tenantDomain);
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(tenantId);
userRegistry = getGovernanceUserRegistry(tenantId);
setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
setUsernameToThreadLocalCarbonContext(this.username);
}
this.isTenantModeStoreView = isTenantMode;
this.requestedTenant = tenantDomain;
Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
List<API> multiVersionedAPIs = new ArrayList<API>();
Comparator<API> versionComparator = new APIVersionComparator();
Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
} else // Else if the config is not specified we go with default functionality and load all
{
maxPaginationLimit = Integer.MAX_VALUE;
}
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.length == 0) {
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// More APIs exist so we cannot determine the total API count without incurring a
isMore = true;
// performance hit
// Remove the additional 1 we added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GenericArtifact artifact : genericArtifacts) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting all paginated APIs by status.");
continue;
}
API api = null;
try {
api = APIUtil.getAPI(artifact);
} catch (APIManagementException e) {
// log and continue since we want to load the rest of the APIs.
log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
}
if (api != null) {
if (returnAPITags) {
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
Set<String> tags = new HashSet<String>();
org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
api.addTags(tags);
}
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!displayMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
} else {
// If allow showing multiple versions of an API
multiVersionedAPIs.add(api);
}
}
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
if (!displayMultipleVersions) {
apiSortedSet.addAll(latestPublishedAPIs.values());
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
} else {
apiVersionsSortedSet.addAll(multiVersionedAPIs);
result.put("apis", apiVersionsSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
}
} else {
String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving APIs by status.";
log.error(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all published APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all published APIs", e);
} finally {
PaginationContext.destroy();
}
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIProviderImpl method updateDocumentation.
/**
* Updates a given api product documentation
*
* @param productId APIProductIdentifier
* @param documentation Documentation
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update docs
*/
public void updateDocumentation(APIProductIdentifier productId, Documentation documentation) throws APIManagementException {
String productPath = APIUtil.getAPIProductPath(productId);
APIProduct product = getAPIProduct(productPath);
String docPath = APIUtil.getProductDocPath(productId) + documentation.getName();
try {
String docArtifactId = registry.get(docPath).getUUID();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(docArtifactId);
String docVisibility = documentation.getVisibility().name();
String[] authorizedRoles = new String[0];
String visibleRolesList = product.getVisibleRoles();
if (visibleRolesList != null) {
authorizedRoles = visibleRolesList.split(",");
}
String visibility = product.getVisibility();
if (docVisibility != null) {
if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_SHARED_VISIBILITY;
} else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_OWNER_VISIBILITY;
}
}
GenericArtifact updateDocArtifact = APIUtil.createDocArtifactContent(artifact, productId, documentation);
artifactManager.updateGenericArtifact(updateDocArtifact);
APIUtil.clearResourcePermissions(docPath, productId, ((UserRegistry) registry).getTenantId());
APIUtil.setResourcePermissions(product.getId().getProviderName(), visibility, authorizedRoles, artifact.getPath(), registry);
String docFilePath = artifact.getAttribute(APIConstants.DOC_FILE_PATH);
if (docFilePath != null && !"".equals(docFilePath)) {
// The docFilePatch comes as
// /t/tenanatdoman/registry/resource/_system/governance/apimgt/applicationdata..
// We need to remove the
// /t/tenanatdoman/registry/resource/_system/governance section
// to set permissions.
int startIndex = docFilePath.indexOf(APIConstants.GOVERNANCE) + (APIConstants.GOVERNANCE).length();
String filePath = docFilePath.substring(startIndex, docFilePath.length());
APIUtil.setResourcePermissions(product.getId().getProviderName(), visibility, authorizedRoles, filePath, registry);
}
} catch (RegistryException e) {
handleException("Failed to update documentation", e);
}
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIProviderImpl method createDocumentation.
/**
* Create a documentation
*
* @param api API
* @param documentation Documentation
* @throws APIManagementException if failed to add documentation
*/
private void createDocumentation(API api, Documentation documentation) throws APIManagementException {
try {
APIIdentifier apiId = api.getId();
GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
GenericArtifact artifact = artifactManager.newGovernanceArtifact(new QName(documentation.getName()));
artifactManager.addGenericArtifact(APIUtil.createDocArtifactContent(artifact, apiId, documentation));
String apiPath = APIUtil.getAPIPath(apiId);
String docVisibility = documentation.getVisibility().name();
String[] authorizedRoles = getAuthorizedRoles(apiPath);
String visibility = api.getVisibility();
if (docVisibility != null) {
if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_SHARED_VISIBILITY;
} else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_OWNER_VISIBILITY;
}
}
APIUtil.setResourcePermissions(api.getId().getProviderName(), visibility, authorizedRoles, artifact.getPath(), registry);
String docFilePath = artifact.getAttribute(APIConstants.DOC_FILE_PATH);
if (docFilePath != null && !"".equals(docFilePath)) {
// The docFilePatch comes as /t/tenanatdoman/registry/resource/_system/governance/apimgt/applicationdata..
// We need to remove the /t/tenanatdoman/registry/resource/_system/governance section to set permissions.
int startIndex = docFilePath.indexOf(APIConstants.GOVERNANCE) + (APIConstants.GOVERNANCE).length();
String filePath = docFilePath.substring(startIndex, docFilePath.length());
APIUtil.setResourcePermissions(api.getId().getProviderName(), visibility, authorizedRoles, filePath, registry);
}
documentation.setId(artifact.getId());
} catch (RegistryException e) {
handleException("Failed to add documentation", e);
} catch (UserStoreException e) {
handleException("Failed to add documentation", e);
}
}
use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.
the class APIProviderImpl method createDocumentation.
/**
* Create a product documentation
*
* @param product APIProduct
* @param documentation Documentation
* @throws APIManagementException if failed to add documentation
*/
private void createDocumentation(APIProduct product, Documentation documentation) throws APIManagementException {
try {
APIProductIdentifier productId = product.getId();
GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
GenericArtifact artifact = artifactManager.newGovernanceArtifact(new QName(documentation.getName()));
artifactManager.addGenericArtifact(APIUtil.createDocArtifactContent(artifact, productId, documentation));
String productPath = APIUtil.getAPIProductPath(productId);
// Adding association from api to documentation . (API Product -----> doc)
registry.addAssociation(productPath, artifact.getPath(), APIConstants.DOCUMENTATION_ASSOCIATION);
String docVisibility = documentation.getVisibility().name();
String[] authorizedRoles = getAuthorizedRoles(productPath);
String visibility = product.getVisibility();
if (docVisibility != null) {
if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_SHARED_VISIBILITY;
} else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
authorizedRoles = null;
visibility = APIConstants.DOC_OWNER_VISIBILITY;
}
}
APIUtil.setResourcePermissions(product.getId().getProviderName(), visibility, authorizedRoles, artifact.getPath(), registry);
String docFilePath = artifact.getAttribute(APIConstants.DOC_FILE_PATH);
if (docFilePath != null && !StringUtils.EMPTY.equals(docFilePath)) {
// The docFilePatch comes as /t/tenanatdoman/registry/resource/_system/governance/apimgt/applicationdata..
// We need to remove the /t/tenanatdoman/registry/resource/_system/governance section to set permissions.
int startIndex = docFilePath.indexOf(APIConstants.GOVERNANCE) + (APIConstants.GOVERNANCE).length();
String filePath = docFilePath.substring(startIndex, docFilePath.length());
APIUtil.setResourcePermissions(product.getId().getProviderName(), visibility, authorizedRoles, filePath, registry);
registry.addAssociation(artifact.getPath(), filePath, APIConstants.DOCUMENTATION_FILE_ASSOCIATION);
}
documentation.setId(artifact.getId());
} catch (RegistryException e) {
handleException("Failed to add documentation", e);
} catch (UserStoreException e) {
handleException("Failed to add documentation", e);
}
}
Aggregations