use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedAPIsByStatus.
/**
* The method to get APIs in any of the given LC status array
*
* @return Map<String, Object> API result set with pagination information
* @throws APIManagementException
*/
@Override
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String[] apiStatus, boolean returnAPITags) throws APIManagementException {
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;
String criteria = APIConstants.LCSTATE_SEARCH_TYPE_KEY;
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);
criteria = criteria + APIUtil.getORBasedSearchCriteria(apiStatus);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
if (apiStatus != null && apiStatus.length > 0) {
List<GovernanceArtifact> genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(criteria), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.size() == 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 (GovernanceArtifact artifact : genericArtifacts) {
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 all paginated 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.user.api.UserStoreException in project carbon-apimgt by wso2.
the class APIProviderImpl method addDocumentationContent.
/**
* This method used to save the documentation content
*
* @param api, API
* @param documentationName, name of the inline documentation
* @param text, content of the inline documentation
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to add the document as a resource to registry
*/
public void addDocumentationContent(API api, String documentationName, String text) throws APIManagementException {
APIIdentifier identifier = api.getId();
String documentationPath = APIUtil.getAPIDocPath(identifier) + documentationName;
String contentPath = APIUtil.getAPIDocPath(identifier) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + documentationName;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
Resource docResource = registry.get(documentationPath);
GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact);
Resource docContent;
if (!registry.resourceExists(contentPath)) {
docContent = registry.newResource();
} else {
docContent = registry.get(contentPath);
}
/* This is a temporary fix for doc content replace issue. We need to add
* separate methods to add inline content resource in document update */
if (!APIConstants.NO_CONTENT_UPDATE.equals(text)) {
docContent.setContent(text);
}
docContent.setMediaType(APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE);
registry.put(contentPath, docContent);
String apiPath = APIUtil.getAPIPath(identifier);
String[] authorizedRoles = getAuthorizedRoles(apiPath);
String docVisibility = doc.getVisibility().name();
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, contentPath, registry);
} catch (RegistryException e) {
String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
handleException(msg, e);
} catch (UserStoreException e) {
String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
handleException(msg, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class APIProviderImpl method getSubscriberClaims.
/**
* Returns the claims of subscriber for the given subscriber.
*
* @param subscriber The name of the subscriber to be returned
* @return The looked up claims of the subscriber or null if the requested subscriber does not exist
* @throws APIManagementException if failed to get Subscriber
*/
@Override
public Map<String, String> getSubscriberClaims(String subscriber) throws APIManagementException {
String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
int tenantId = 0;
Map<String, String> claimMap = new HashMap<>();
Map<String, String> subscriberClaims = null;
String configuredClaims = "";
try {
tenantId = getTenantId(tenantDomain);
UserStoreManager userStoreManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
if (userStoreManager.isExistingUser(subscriber)) {
subscriberClaims = APIUtil.getClaims(subscriber, tenantId, ClaimsRetriever.DEFAULT_DIALECT_URI);
APIManagerConfiguration configuration = getAPIManagerConfiguration();
configuredClaims = configuration.getFirstProperty(APIConstants.API_PUBLISHER_SUBSCRIBER_CLAIMS);
}
for (String claimURI : configuredClaims.split(",")) {
if (subscriberClaims != null) {
claimMap.put(claimURI, subscriberClaims.get(claimURI));
}
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while retrieving tenant id for tenant domain " + tenantDomain, e);
}
return claimMap;
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class ApplicationThrottleControllerTest method testCreatingThrottleContextThrowsSynapseExceptionWhileRetrievingTenantID.
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhileRetrievingTenantID() throws UserStoreException, RegistryException {
Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
PowerMockito.doThrow(new UserStoreException()).when(tenantManager).getTenantId(tenantDomain);
ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder, applicationId, THROTTLE_POLICY_KEY);
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class ApplicationThrottleControllerTest method testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyResourceRetrievalFailed.
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyResourceRetrievalFailed() throws UserStoreException, RegistryException {
Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
PowerMockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
PowerMockito.when(registryService.getGovernanceSystemRegistry(tenantID)).thenReturn(registry);
PowerMockito.when(registry.resourceExists(RESOURCE_PATH)).thenReturn(true);
PowerMockito.doThrow(new RegistryException("Error while fetching resource ")).when(registry).get(RESOURCE_PATH);
ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder, applicationId, THROTTLE_POLICY_KEY);
}
Aggregations