use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-business-process by wso2.
the class TenantProcessStoreImpl method undeploy.
/**
* Undeploying BPEL package.
*
* @param bpelPackageName Name of the BPEL package which going to be undeployed
*/
public void undeploy(String bpelPackageName) throws RegistryException, BPELUIException {
if (log.isDebugEnabled()) {
log.debug("Un-deploying BPEL package " + bpelPackageName + " ....");
}
if (!repository.isExistingBPELPackage(bpelPackageName)) {
// This can be a situation where we un-deploy the archive through management console,
// so that, the archive is deleted from the repo. As a result this method get invoked.
// to handle this case we just log the message but does not throw an exception.
final String warningMsg = "Cannot find BPEL package with name " + bpelPackageName + " in the repository. If the bpel package is un-deployed through the management" + " console or if this node is a member of a cluster, please ignore this warning.";
if (isConfigRegistryReadOnly()) {
// This is for the deployment synchronizer scenarios where package un-deployment on a worker node
// has to remove the deployed bpel package from the memory and remove associated services
handleUndeployOnSlaveNode(bpelPackageName);
} else {
log.warn(warningMsg);
}
return;
}
if (repository.isExistingBPELPackage(bpelPackageName) && isConfigRegistryReadOnly()) {
log.warn("This node seems to be a slave, since the configuration registry is in read-only mode, hence " + "processes cannot be directly undeployed from this node. Please undeploy the process in Master " + "node first.");
return;
}
List<String> versionsOfThePackage;
try {
versionsOfThePackage = repository.getAllVersionsForPackage(bpelPackageName);
} catch (RegistryException re) {
String errMessage = "Cannot get all versions of the package " + bpelPackageName + " from registry.";
log.error(errMessage);
throw re;
}
// check the instance count to be deleted
long instanceCount = getInstanceCountForPackage(versionsOfThePackage);
if (instanceCount > BPELServerImpl.getInstance().getBpelServerConfiguration().getBpelInstanceDeletionLimit()) {
throw new BPELUIException("Instance deletion limit reached.");
}
for (String nameWithVersion : versionsOfThePackage) {
parentProcessStore.deleteDeploymentUnitDataFromDB(nameWithVersion);
Utils.deleteInstances(getProcessesInPackage(nameWithVersion));
// location for extracted BPEL package
String bpelPackageLocation = parentProcessStore.getLocalDeploymentUnitRepo().getAbsolutePath() + File.separator + tenantId + File.separator + nameWithVersion;
File bpelPackage = new File(bpelPackageLocation);
// removing extracted bpel package at repository/bpel/0/
deleteBpelPackageFromRepo(bpelPackage);
for (QName pid : getProcessesInPackage(nameWithVersion)) {
ProcessConfigurationImpl processConf = (ProcessConfigurationImpl) getProcessConfiguration(pid);
// This property is read when we removing the axis service for this process.
// So that we can decide whether we should persist service QOS configs
processConf.setUndeploying(true);
}
}
try {
repository.handleBPELPackageUndeploy(bpelPackageName);
} catch (RegistryException re) {
String errMessage = "Cannot update the BPEL package repository for undeployment of" + "package " + bpelPackageName + ".";
log.error(errMessage);
throw re;
}
updateLocalInstanceWithUndeployment(bpelPackageName, versionsOfThePackage);
// We should use the deployment synchronizer, instead of the code below.
// parentProcessStore.sendProcessDeploymentNotificationsToCluster(
// new BPELPackageUndeployedCommand(versionsOfThePackage, bpelPackageName, tenantId),
// configurationContext);
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project product-iots by wso2.
the class MobileQSGTestCase method testPolicyCreation.
@Test(description = "This test case tests the policy creation through qsg script", dependsOnMethods = { "executeQSGScript" })
public void testPolicyCreation() throws Exception {
HttpResponse response = client.get(Constants.PolicyManagement.VIEW_POLICY_LIST_ENDPOINT + "?offset=0&limit=10");
Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK);
Assert.assertTrue(response.getData().contains("android-passcode-policy1"), "Android pass-code policy is not " + "added from qsg script");
Assert.assertTrue(response.getData().contains("windows-passcode-policy1"), "Windows pass-code policy is not " + "added from qsg script");
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class AbstractAPIManager method searchPaginatedAPIProducts.
/**
* Returns APIProduct Search result based on the provided query.
*
* @param registry
* @param searchQuery Ex: provider=*admin*
* @return APIProduct result
* @throws APIManagementException
*/
public Map<String, Object> searchPaginatedAPIProducts(Registry registry, String searchQuery, int start, int end) throws APIManagementException {
SortedSet<APIProduct> productSet = new TreeSet<APIProduct>(new APIProductNameComparator());
List<APIProduct> productList = new ArrayList<APIProduct>();
Map<String, Object> result = new HashMap<String, Object>();
int totalLength = 0;
boolean isMore = false;
try {
// for now will use the same config for api products too todo: change this
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);
List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(searchQuery), registry, APIConstants.API_RXT_MEDIA_TYPE, true);
totalLength = PaginationContext.getInstance().getLength();
boolean isFound = true;
if (!isFound) {
result.put("products", productSet);
result.put("length", 0);
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, cannot determine total API count without incurring perf hit
isMore = true;
// Remove the additional 1 added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GovernanceArtifact artifact : governanceArtifacts) {
APIProduct resultAPIProduct = APIUtil.getAPIProduct(artifact, registry);
if (resultAPIProduct != null) {
productList.add(resultAPIProduct);
}
// Ensure the APIs returned matches the length, there could be an additional API
// returned due incrementing the pagination limit when getting from registry
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
productSet.addAll(productList);
} catch (RegistryException e) {
String msg = "Failed to search APIProducts with type";
throw new APIManagementException(msg, e);
} finally {
PaginationContext.destroy();
}
result.put("products", productSet);
result.put("length", totalLength);
result.put("isMore", isMore);
return result;
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class AbstractAPIManager method searchPaginatedAPIsByContent.
/**
* Search api resources by their content
*
* @param registry
* @param searchQuery
* @param start
* @param end
* @return
* @throws APIManagementException
*/
public Map<String, Object> searchPaginatedAPIsByContent(Registry registry, int tenantId, String searchQuery, int start, int end, boolean limitAttributes) throws APIManagementException {
SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
SortedSet<APIProduct> apiProductSet = new TreeSet<APIProduct>(new APIProductNameComparator());
Map<Documentation, API> docMap = new HashMap<Documentation, API>();
Map<Documentation, APIProduct> productDocMap = new HashMap<Documentation, APIProduct>();
Map<String, Object> result = new HashMap<String, Object>();
int totalLength = 0;
boolean isMore = false;
// SortedSet<Object> compoundResult = new TreeSet<Object>(new ContentSearchResultNameComparator());
ArrayList<Object> compoundResult = new ArrayList<Object>();
try {
GenericArtifactManager apiArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
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);
if (tenantId == -1) {
tenantId = MultitenantConstants.SUPER_TENANT_ID;
}
UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
String newSearchQuery = getSearchQuery(searchQuery);
String[] searchQueries = newSearchQuery.split("&");
String apiState = "";
String publisherRoles = "";
Map<String, String> attributes = new HashMap<String, String>();
for (String searchCriterea : searchQueries) {
String[] keyVal = searchCriterea.split("=");
if (APIConstants.STORE_VIEW_ROLES.equals(keyVal[0])) {
attributes.put("propertyName", keyVal[0]);
attributes.put("rightPropertyValue", keyVal[1]);
attributes.put("rightOp", "eq");
} else if (APIConstants.PUBLISHER_ROLES.equals(keyVal[0])) {
publisherRoles = keyVal[1];
} else {
if (APIConstants.LCSTATE_SEARCH_KEY.equals(keyVal[0])) {
apiState = keyVal[1];
continue;
}
attributes.put(keyVal[0], keyVal[1]);
}
}
// check whether the new document indexer is engaged
RegistryConfigLoader registryConfig = RegistryConfigLoader.getInstance();
Map<String, Indexer> indexerMap = registryConfig.getIndexerMap();
Indexer documentIndexer = indexerMap.get(APIConstants.DOCUMENT_MEDIA_TYPE_KEY);
String complexAttribute;
if (documentIndexer != null && documentIndexer instanceof DocumentIndexer) {
// field check on document_indexed was added to prevent unindexed(by new DocumentIndexer) from coming up as search results
// on indexed documents this property is always set to true
complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND document_indexed_s:true)";
// this was designed this way so that content search can be fully functional if registry is re-indexed after engaging DocumentIndexer
if (!StringUtils.isEmpty(publisherRoles)) {
complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ") OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND publisher_roles_s:" + publisherRoles + ")";
}
} else {
// document indexer required for document content search is not engaged, therefore carry out the search only for api artifact contents
complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE);
if (!StringUtils.isEmpty(publisherRoles)) {
complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ")";
}
}
attributes.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, complexAttribute);
attributes.put(APIConstants.API_OVERVIEW_STATUS, apiState);
SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
String errorMsg = resultsBean.getErrorMessage();
if (errorMsg != null) {
handleException(errorMsg);
}
ResourceData[] resourceData = resultsBean.getResourceDataList();
if (resourceData == null || resourceData.length == 0) {
result.put("apis", compoundResult);
result.put("length", 0);
result.put("isMore", isMore);
}
totalLength = PaginationContext.getInstance().getLength();
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// More APIs exist, cannot determine total API count without incurring perf hit
isMore = true;
// Remove the additional 1 added earlier when setting max pagination limit
--totalLength;
}
for (ResourceData data : resourceData) {
String resourcePath = data.getResourcePath();
if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
resourcePath = resourcePath.substring(index);
Resource resource = registry.get(resourcePath);
if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
}
Resource docResource = registry.get(resourcePath);
String docArtifactId = docResource.getUUID();
GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
Documentation doc = APIUtil.getDocumentation(docArtifact);
API associatedAPI = null;
APIProduct associatedAPIProduct = null;
int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
Resource apiResource = registry.get(apiPath);
String apiArtifactId = apiResource.getUUID();
if (apiArtifactId != null) {
GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
} else {
associatedAPI = APIUtil.getAPI(apiArtifact, registry);
}
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
if (associatedAPI != null && doc != null) {
docMap.put(doc, associatedAPI);
}
if (associatedAPIProduct != null && doc != null) {
productDocMap.put(doc, associatedAPIProduct);
}
} else {
String apiArtifactId = resource.getUUID();
API api;
APIProduct apiProduct;
if (apiArtifactId != null) {
GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.API_PRODUCT)) {
apiProduct = APIUtil.getAPIProduct(apiArtifact, registry);
apiProductSet.add(apiProduct);
} else {
api = APIUtil.getAPI(apiArtifact, registry);
apiSet.add(api);
}
} else {
throw new GovernanceException("artifact id is null for " + resourcePath);
}
}
}
}
compoundResult.addAll(apiSet);
compoundResult.addAll(apiProductSet);
compoundResult.addAll(docMap.entrySet());
compoundResult.addAll(productDocMap.entrySet());
compoundResult.sort(new ContentSearchResultNameComparator());
} catch (RegistryException e) {
handleException("Failed to search APIs by content", e);
} catch (IndexerException e) {
handleException("Failed to search APIs by content", e);
}
result.put("apis", compoundResult);
result.put("length", totalLength);
result.put("isMore", isMore);
return result;
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class APIUtil method getTiersFromPolicies.
public static Map<String, Tier> getTiersFromPolicies(String policyLevel, int tenantId) throws APIManagementException {
Map<String, Tier> tierMap = new TreeMap<String, Tier>();
ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
Policy[] policies;
if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
policies = apiMgtDAO.getSubscriptionPolicies(tenantId);
} else if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyLevel)) {
policies = apiMgtDAO.getAPIPolicies(tenantId);
} else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyLevel)) {
policies = apiMgtDAO.getApplicationPolicies(tenantId);
} else {
throw new APIManagementException("No such a policy type : " + policyLevel);
}
for (Policy policy : policies) {
if (!APIConstants.UNLIMITED_TIER.equalsIgnoreCase(policy.getPolicyName())) {
Tier tier = new Tier(policy.getPolicyName());
tier.setDescription(policy.getDescription());
tier.setDisplayName(policy.getDisplayName());
Limit limit = policy.getDefaultQuotaPolicy().getLimit();
tier.setTimeUnit(limit.getTimeUnit());
tier.setUnitTime(limit.getUnitTime());
tier.setQuotaPolicyType(policy.getDefaultQuotaPolicy().getType());
// If the policy is a subscription policy
if (policy instanceof SubscriptionPolicy) {
SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) policy;
tier.setRateLimitCount(subscriptionPolicy.getRateLimitCount());
tier.setRateLimitTimeUnit(subscriptionPolicy.getRateLimitTimeUnit());
setBillingPlanAndCustomAttributesToTier(subscriptionPolicy, tier);
if (StringUtils.equals(subscriptionPolicy.getBillingPlan(), APIConstants.COMMERCIAL_TIER_PLAN)) {
tier.setMonetizationAttributes(subscriptionPolicy.getMonetizationPlanProperties());
}
}
if (limit instanceof RequestCountLimit) {
RequestCountLimit countLimit = (RequestCountLimit) limit;
tier.setRequestsPerMin(countLimit.getRequestCount());
tier.setRequestCount(countLimit.getRequestCount());
} else if (limit instanceof BandwidthLimit) {
BandwidthLimit bandwidthLimit = (BandwidthLimit) limit;
tier.setRequestsPerMin(bandwidthLimit.getDataAmount());
tier.setRequestCount(bandwidthLimit.getDataAmount());
tier.setBandwidthDataUnit(bandwidthLimit.getDataUnit());
} else {
EventCountLimit eventCountLimit = (EventCountLimit) limit;
tier.setRequestCount(eventCountLimit.getEventCount());
tier.setRequestsPerMin(eventCountLimit.getEventCount());
}
if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
tier.setTierPlan(((SubscriptionPolicy) policy).getBillingPlan());
}
tierMap.put(policy.getPolicyName(), tier);
} else {
if (APIUtil.isEnabledUnlimitedTier()) {
Tier tier = new Tier(policy.getPolicyName());
tier.setDescription(policy.getDescription());
tier.setDisplayName(policy.getDisplayName());
tier.setRequestsPerMin(Integer.MAX_VALUE);
tier.setRequestCount(Integer.MAX_VALUE);
if (isUnlimitedTierPaid(getTenantDomainFromTenantId(tenantId))) {
tier.setTierPlan(APIConstants.COMMERCIAL_TIER_PLAN);
} else {
tier.setTierPlan(APIConstants.BILLING_PLAN_FREE);
}
tierMap.put(policy.getPolicyName(), tier);
}
}
}
if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
tierMap.remove(APIConstants.UNAUTHENTICATED_TIER);
}
return tierMap;
}
Aggregations