use of org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact in project carbon-apimgt by wso2.
the class APIConsumerImpl method isCandidateAPI.
private boolean isCandidateAPI(String apiPath, String loggedUsername, GenericArtifactManager artifactManager, int tenantId, boolean showAllAPIs, boolean allowMultipleVersions, String apiOwner, String providerId, Registry registry, Map<String, API> apiCollection) throws UserStoreException, RegistryException, APIManagementException {
AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
Comparator<API> versionComparator = new APIVersionComparator();
Resource resource;
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
boolean checkAuthorized;
String userNameWithoutDomain = loggedUsername;
if (!loggedUsername.isEmpty() && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
String[] nameParts = loggedUsername.split("@");
userNameWithoutDomain = nameParts[0];
}
int loggedInUserTenantDomain = -1;
if (!StringUtils.isEmpty(loggedUsername)) {
loggedInUserTenantDomain = APIUtil.getTenantId(loggedUsername);
}
if (loggedUsername.isEmpty()) {
// Anonymous user is viewing.
checkAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else if (tenantId != loggedInUserTenantDomain) {
// Cross tenant scenario
providerId = APIUtil.replaceEmailDomainBack(providerId);
String[] nameParts = providerId.split("@");
String provideNameWithoutDomain = nameParts[0];
checkAuthorized = manager.isUserAuthorized(provideNameWithoutDomain, path, ActionConstants.GET);
} else {
// Some user is logged in also user and api provider tenant domain are same.
checkAuthorized = manager.isUserAuthorized(userNameWithoutDomain, path, ActionConstants.GET);
}
String apiArtifactId = null;
if (checkAuthorized) {
resource = registry.get(apiPath);
apiArtifactId = resource.getUUID();
}
if (apiArtifactId != null) {
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
// check the API status
String status = APIUtil.getLcStateFromArtifact(artifact);
API api = null;
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (!showAllAPIs) {
// then we are only interested in published APIs here...
if (APIConstants.PUBLISHED.equals(status)) {
api = APIUtil.getAPI(artifact);
}
} else {
// else we are interested in both deprecated/published APIs here...
if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
api = APIUtil.getAPI(artifact);
}
}
if (api != null) {
String apiVisibility = api.getVisibility();
if (!StringUtils.isEmpty(apiVisibility) && !APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(apiVisibility)) {
String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
String loginUserDomain = MultitenantUtils.getTenantDomain(loggedUsername);
if (!StringUtils.isEmpty(providerDomain) && !StringUtils.isEmpty(loginUserDomain) && !providerDomain.equals(loginUserDomain)) {
return false;
}
}
// apiOwner is the value coming from front end and compared against the API instance
if (apiOwner != null && !apiOwner.isEmpty()) {
if (APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && api.getApiOwner() != null && !api.getApiOwner().isEmpty() && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
// reject remote APIs when local admin user's API selected
return false;
} else if (!APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
// reject local admin's APIs when remote API selected
return false;
}
}
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!allowMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = apiCollection.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
apiCollection.put(key, api);
return true;
}
} else {
// We haven't seen this API before
apiCollection.put(key, api);
return true;
}
} else {
// If allow showing multiple versions of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName() + COLON_CHAR + api.getId().getVersion();
// we're not really interested in the key, so generate one for the sake of adding this element to
// the map.
key = key + '_' + apiCollection.size();
apiCollection.put(key, api);
return true;
}
}
}
return false;
}
use of org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedPublishedLightWeightAPIs.
/**
* The method to get Light Weight APIs to Store view
* @param tenantDomain tenant domain
* @param start start limit
* @param end end limit
* @return Set<API> Set of APIs
* @throws APIManagementException
*/
public Map<String, Object> getAllPaginatedPublishedLightWeightAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Boolean displayAPIsWithMultipleStatus = false;
try {
if (tenantDomain != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
} finally {
endTenantFlow();
}
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (!displayAPIsWithMultipleStatus) {
// Create the search attribute map
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
} 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;
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();
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
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);
return result;
}
for (GenericArtifact artifact : genericArtifacts) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting paginated published API.");
continue;
}
// adding the API provider can mark the latest API .
API api = APIUtil.getLightWeightAPI(artifact);
if (api != null) {
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);
}
}
}
if (!displayMultipleVersions) {
apiSortedSet.addAll(latestPublishedAPIs.values());
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
} else {
apiVersionsSortedSet.addAll(multiVersionedAPIs);
result.put("apis", apiVersionsSortedSet);
result.put("totalLength", totalLength);
return result;
}
} else {
String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all Published APIs.";
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);
return result;
}
use of org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact in project carbon-apimgt by wso2.
the class CustomAPIIndexerTest method testIndexDocumentForNewAPI.
/**
* This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
*
* @throws RegistryException Registry Exception.
* @throws APIManagementException API Management Exception.
*/
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
Resource resource = new ResourceImpl();
PowerMockito.mockStatic(APIUtil.class);
GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(APIUtil.getArtifactManager((UserRegistry) (Mockito.anyObject()), Mockito.anyString())).thenReturn(artifactManager);
GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry)).thenReturn(Mockito.mock(API.class));
resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
indexer.getIndexedDocument(file2Index);
Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not " + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
use of org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAPIProduct.
/**
* Get API Product by product identifier
*
* @param identifier APIProductIdentifier
* @return API product identified by provider identifier
* @throws APIManagementException
*/
public APIProduct getAPIProduct(APIProductIdentifier identifier) throws APIManagementException {
String apiProductPath = APIUtil.getAPIProductPath(identifier);
Registry registry;
try {
String productTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
int productTenantId = getTenantManager().getTenantId(productTenantDomain);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(productTenantDomain)) {
APIUtil.loadTenantRegistry(productTenantId);
}
if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) {
// cross tenant scenario
registry = getRegistryService().getGovernanceUserRegistry(getTenantAwareUsername(APIUtil.replaceEmailDomainBack(identifier.getProviderName())), productTenantId);
} else {
registry = this.registry;
}
GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
Resource productResource = registry.get(apiProductPath);
String artifactId = productResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiProductPath);
}
GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId);
APIProduct apiProduct = APIUtil.getAPIProduct(productArtifact, registry);
return apiProduct;
} catch (RegistryException e) {
String msg = "Failed to get API Product from : " + apiProductPath;
throw new APIManagementException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Failed to get API Product from : " + apiProductPath;
throw new APIManagementException(msg, e);
}
}
use of org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact in project carbon-apimgt by wso2.
the class UserAwareAPIProvider method getAPI.
@Override
protected API getAPI(GenericArtifact apiArtifact) throws APIManagementException {
API api = APIUtil.getAPI(apiArtifact, registry);
if (api != null) {
APIUtil.updateAPIProductDependencies(api, registry);
checkAccessControlPermission(api.getId());
}
return api;
}
Aggregations