use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class ApiMgtDAO method getComments.
/**
**************************************
* Returns all the Comments on an API
*
* @param apiTypeWrapper API type Wrapper
* @param parentCommentID Parent Comment ID
* @return Comment Array
* @throws APIManagementException
*/
public CommentList getComments(ApiTypeWrapper apiTypeWrapper, String parentCommentID, Integer limit, Integer offset) throws APIManagementException {
CommentList commentList = null;
try (Connection connection = APIMgtDBUtil.getConnection()) {
int id = -1;
String uuid;
Identifier identifier;
String currentApiUuid;
if (apiTypeWrapper.isAPIProduct()) {
identifier = apiTypeWrapper.getApiProduct().getId();
uuid = apiTypeWrapper.getApiProduct().getUuid();
APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
if (apiRevision != null && apiRevision.getApiUUID() != null) {
currentApiUuid = apiRevision.getApiUUID();
} else {
currentApiUuid = uuid;
}
} else {
identifier = apiTypeWrapper.getApi().getId();
uuid = apiTypeWrapper.getApi().getUuid();
APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
if (apiRevision != null && apiRevision.getApiUUID() != null) {
currentApiUuid = apiRevision.getApiUUID();
} else {
currentApiUuid = uuid;
}
}
id = getAPIID(currentApiUuid, connection);
if (id == -1) {
String msg = "Could not load API record for: " + identifier.getName();
throw new APIManagementException(msg);
}
commentList = getComments(currentApiUuid, parentCommentID, limit, offset, connection);
} catch (SQLException e) {
handleException("Failed to retrieve comments for " + apiTypeWrapper.getName(), e);
}
return commentList;
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class ApiMgtDAO method updateSubscriptionPolicy.
/**
* Updates Subscription level policy.
* <p>policy name and tenant id should be specified in <code>policy</code></p>
*
* @param policy updated policy object
* @throws APIManagementException
*/
public void updateSubscriptionPolicy(SubscriptionPolicy policy) throws APIManagementException {
Connection connection = null;
PreparedStatement updateStatement = null;
boolean hasCustomAttrib = false;
String updateQuery;
try {
if (policy.getCustomAttributes() != null) {
hasCustomAttrib = true;
}
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_SQL;
if (hasCustomAttrib) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
}
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_BY_UUID_SQL;
if (hasCustomAttrib) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
}
} else {
String errorMsg = "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id" + " should be provided. Name: " + policy.getPolicyName() + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
log.error(errorMsg);
throw new APIManagementException(errorMsg);
}
connection = APIMgtDBUtil.getConnection();
connection.setAutoCommit(false);
updateStatement = connection.prepareStatement(updateQuery);
if (!StringUtils.isEmpty(policy.getDisplayName())) {
updateStatement.setString(1, policy.getDisplayName());
} else {
updateStatement.setString(1, policy.getPolicyName());
}
updateStatement.setString(2, policy.getDescription());
updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getRequestCount());
updateStatement.setString(5, null);
} else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getDataAmount());
updateStatement.setString(5, limit.getDataUnit());
} else if (PolicyConstants.EVENT_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
EventCountLimit limit = (EventCountLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getEventCount());
updateStatement.setString(5, null);
}
updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
updateStatement.setInt(8, policy.getRateLimitCount());
updateStatement.setString(9, policy.getRateLimitTimeUnit());
updateStatement.setBoolean(10, policy.isStopOnQuotaReach());
updateStatement.setInt(11, policy.getGraphQLMaxDepth());
updateStatement.setInt(12, policy.getGraphQLMaxComplexity());
updateStatement.setString(13, policy.getBillingPlan());
if (hasCustomAttrib) {
long lengthOfStream = policy.getCustomAttributes().length;
updateStatement.setBinaryStream(14, new ByteArrayInputStream(policy.getCustomAttributes()), lengthOfStream);
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement.setString(15, policy.getMonetizationPlan());
updateStatement.setString(16, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.FIXED_PRICE));
updateStatement.setString(17, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.BILLING_CYCLE));
updateStatement.setString(18, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.PRICE_PER_REQUEST));
updateStatement.setString(19, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.CURRENCY));
updateStatement.setInt(20, policy.getSubscriberCount());
updateStatement.setString(21, policy.getPolicyName());
updateStatement.setInt(22, policy.getTenantId());
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement.setString(15, policy.getMonetizationPlan());
updateStatement.setString(16, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.FIXED_PRICE));
updateStatement.setString(17, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.BILLING_CYCLE));
updateStatement.setString(18, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.PRICE_PER_REQUEST));
updateStatement.setString(19, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.CURRENCY));
updateStatement.setInt(20, policy.getSubscriberCount());
updateStatement.setString(21, policy.getUUID());
}
} else {
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement.setString(14, policy.getMonetizationPlan());
updateStatement.setString(15, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.FIXED_PRICE));
updateStatement.setString(16, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.BILLING_CYCLE));
updateStatement.setString(17, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.PRICE_PER_REQUEST));
updateStatement.setString(18, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.CURRENCY));
updateStatement.setInt(19, policy.getSubscriberCount());
updateStatement.setString(20, policy.getPolicyName());
updateStatement.setInt(21, policy.getTenantId());
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement.setString(14, policy.getMonetizationPlan());
updateStatement.setString(15, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.FIXED_PRICE));
updateStatement.setString(16, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.BILLING_CYCLE));
updateStatement.setString(17, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.PRICE_PER_REQUEST));
updateStatement.setString(18, policy.getMonetizationPlanProperties().get(APIConstants.Monetization.CURRENCY));
updateStatement.setInt(19, policy.getSubscriberCount());
updateStatement.setString(20, policy.getUUID());
}
}
updateStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
// Rollback failed. Exception will be thrown later for upper exception
log.error("Failed to rollback the update Subscription Policy: " + policy.toString(), ex);
}
}
handleException("Failed to update subscription policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
} finally {
APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
}
}
use of org.wso2.carbon.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class APIConsumerImpl method searchPaginatedAPIs.
/**
* Pagination API search based on solr indexing
*
* @param registry
* @param searchTerm
* @param searchType
* @return
* @throws APIManagementException
*/
public Map<String, Object> searchPaginatedAPIs(Registry registry, String searchTerm, String searchType, int start, int end, boolean limitAttributes) throws APIManagementException {
SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
List<API> apiList = new ArrayList<API>();
searchTerm = searchTerm.trim();
Map<String, Object> result = new HashMap<String, Object>();
int totalLength = 0;
boolean isMore = false;
String criteria = APIConstants.API_OVERVIEW_NAME;
try {
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;
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
if (artifactManager != null) {
if (APIConstants.API_PROVIDER.equalsIgnoreCase(searchType)) {
criteria = APIConstants.API_OVERVIEW_PROVIDER;
searchTerm = searchTerm.replaceAll("@", "-AT-");
} else if (APIConstants.API_VERSION_LABEL.equalsIgnoreCase(searchType)) {
criteria = APIConstants.API_OVERVIEW_VERSION;
} else if (APIConstants.API_CONTEXT.equalsIgnoreCase(searchType)) {
criteria = APIConstants.API_OVERVIEW_CONTEXT;
} else if (APIConstants.API_DESCRIPTION.equalsIgnoreCase(searchType)) {
criteria = APIConstants.API_OVERVIEW_DESCRIPTION;
} else if (APIConstants.API_TAG.equalsIgnoreCase(searchType)) {
criteria = APIConstants.API_OVERVIEW_TAG;
}
// Create the search attribute map for PUBLISHED APIs
final String searchValue = searchTerm;
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
listMap.put(criteria, new ArrayList<String>() {
{
add(searchValue);
}
});
boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
// multiple status. This is because pagination is breaking when we do a another filtering with the API Status
if (!displayAPIsWithMultipleStatus) {
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
}
GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
totalLength = PaginationContext.getInstance().getLength();
boolean isFound = true;
if (genericArtifacts == null || genericArtifacts.length == 0) {
if (APIConstants.API_OVERVIEW_PROVIDER.equals(criteria)) {
genericArtifacts = searchAPIsByOwner(artifactManager, searchValue);
if (genericArtifacts == null || genericArtifacts.length == 0) {
isFound = false;
}
} else {
isFound = false;
}
}
if (!isFound) {
result.put("apis", apiSet);
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 (GenericArtifact artifact : genericArtifacts) {
String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (APIUtil.isAllowDisplayAPIsWithMultipleStatus()) {
if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
API resultAPI;
if (limitAttributes) {
resultAPI = APIUtil.getAPI(artifact);
} else {
resultAPI = APIUtil.getAPI(artifact, registry);
}
if (resultAPI != null) {
apiList.add(resultAPI);
}
}
} else {
if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status)) {
API resultAPI;
if (limitAttributes) {
resultAPI = APIUtil.getAPI(artifact);
} else {
resultAPI = APIUtil.getAPI(artifact, registry);
}
if (resultAPI != null) {
apiList.add(resultAPI);
}
}
}
// 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;
}
}
apiSet.addAll(apiList);
}
} catch (RegistryException e) {
handleException("Failed to search APIs with type", e);
}
result.put("apis", apiSet);
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 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.apimgt.api.model.policy.Limit in project carbon-apimgt by wso2.
the class ThrottleHandlerTest method testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled.
@Test
public void testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled() {
ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
authenticationContext.setApiTier(throttlingTier);
messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
// Should continue the message flow if API level, application level, resource level, subscription level,
// subscription spike level and hard throttling limit levels are not throttled
Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
Aggregations