use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.
the class ApiMgtDAO method getComments.
/**
**************************************
* Returns all the Comments on an API
*
* @param uuid API UUID
* @param parentCommentID Parent Comment ID
* @param limit The limit
* @param offset The offset
* @param connection Database connection
* @return Comment Array
* @throws APIManagementException
*/
private CommentList getComments(String uuid, String parentCommentID, Integer limit, Integer offset, Connection connection) throws APIManagementException {
List<Comment> list = new ArrayList<Comment>();
CommentList commentList = new CommentList();
Pagination pagination = new Pagination();
commentList.setPagination(pagination);
int total = 0;
String sqlQuery;
String sqlQueryForCount;
if (parentCommentID == null) {
sqlQueryForCount = SQLConstants.GET_ROOT_COMMENTS_COUNT_SQL;
} else {
sqlQueryForCount = SQLConstants.GET_REPLIES_COUNT_SQL;
}
try (PreparedStatement prepStmtForCount = connection.prepareStatement(sqlQueryForCount)) {
prepStmtForCount.setString(1, uuid);
if (parentCommentID != null) {
prepStmtForCount.setString(2, parentCommentID);
}
try (ResultSet resultSetForCount = prepStmtForCount.executeQuery()) {
while (resultSetForCount.next()) {
total = resultSetForCount.getInt("COMMENT_COUNT");
}
if (total > 0 && limit > 0) {
if (parentCommentID == null) {
sqlQuery = SQLConstantManagerFactory.getSQlString("GET_ROOT_COMMENTS_SQL");
} else {
sqlQuery = SQLConstantManagerFactory.getSQlString("GET_REPLIES_SQL");
}
try (PreparedStatement prepStmt = connection.prepareStatement(sqlQuery)) {
prepStmt.setString(1, uuid);
if (parentCommentID != null) {
prepStmt.setString(2, parentCommentID);
prepStmt.setInt(3, offset);
prepStmt.setInt(4, limit);
} else {
prepStmt.setInt(2, offset);
prepStmt.setInt(3, limit);
}
try (ResultSet resultSet = prepStmt.executeQuery()) {
while (resultSet.next()) {
Comment comment = new Comment();
comment.setId(resultSet.getString("COMMENT_ID"));
comment.setText(resultSet.getString("COMMENT_TEXT"));
comment.setUser(resultSet.getString("CREATED_BY"));
comment.setCreatedTime(resultSet.getTimestamp("CREATED_TIME"));
comment.setUpdatedTime(resultSet.getTimestamp("UPDATED_TIME"));
comment.setApiId(resultSet.getString("API_ID"));
comment.setParentCommentID(resultSet.getString("PARENT_COMMENT_ID"));
comment.setEntryPoint(resultSet.getString("ENTRY_POINT"));
comment.setCategory(resultSet.getString("CATEGORY"));
if (parentCommentID == null) {
comment.setReplies(getComments(uuid, resultSet.getString("COMMENT_ID"), APIConstants.REPLYLIMIT, APIConstants.REPLYOFFSET, connection));
} else {
CommentList emptyCommentList = new CommentList();
Pagination emptyPagination = new Pagination();
emptyCommentList.setPagination(emptyPagination);
emptyCommentList.getPagination().setTotal(0);
emptyCommentList.setCount(0);
comment.setReplies(emptyCommentList);
}
list.add(comment);
}
}
}
} else {
commentList.getPagination().setTotal(total);
commentList.setCount(total);
return commentList;
}
}
} catch (SQLException e) {
handleException("Failed to retrieve comments for API with UUID " + uuid, e);
}
pagination.setLimit(limit);
pagination.setOffset(offset);
commentList.getPagination().setTotal(total);
commentList.setList(list);
commentList.setCount(list.size());
return commentList;
}
use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.
the class APIProviderImpl method getAllPaginatedAPIs.
@Override
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Map<String, Object> result = new HashMap<String, Object>();
List<API> apiSortedList = new ArrayList<API>();
int totalLength = 0;
boolean isTenantFlowStarted = false;
try {
String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_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_PUBLISHER_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
} else // Else if the config is not specifed we go with default functionality and load all
{
maxPaginationLimit = Integer.MAX_VALUE;
}
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
isTenantFlowStarted = true;
}
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
APIUtil.loadTenantRegistry(tenantId);
userRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
}
PaginationContext.init(start, end, "ASC", APIConstants.PROVIDER_OVERVIEW_NAME, maxPaginationLimit);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
List<GovernanceArtifact> genericArtifacts = null;
if (isAccessControlRestrictionEnabled && !APIUtil.hasPermission(userNameWithoutChange, APIConstants.Permissions.APIM_ADMIN)) {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getUserRoleListQuery(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
} else {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(new HashMap<String, List<String>>(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
}
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.isEmpty()) {
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// performance hit
// Remove the additional 1 we added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GovernanceArtifact artifact : genericArtifacts) {
API api = APIUtil.getAPI(artifact);
if (api != null) {
apiSortedList.add(api);
}
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
Collections.sort(apiSortedList, new APINameComparator());
} else {
String errorMessage = "Failed to retrieve artifact manager when getting paginated APIs of tenant " + tenantDomain;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all APIs", e);
} finally {
PaginationContext.destroy();
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.
the class AbstractAPIManager method searchPaginatedAPIs.
/**
* Returns API Search result based on the provided query. This search method supports '&' based concatenate
* search in multiple fields.
*
* @param registry
* @param tenantId
* @param searchQuery Ex: provider=*admin*&version=*1*
* @return API result
* @throws APIManagementException
*/
public Map<String, Object> searchPaginatedAPIs(Registry registry, int tenantId, String searchQuery, int start, int end, boolean limitAttributes, boolean reducedPublisherAPIInfo) throws APIManagementException {
SortedSet<Object> apiSet = new TreeSet<>(new APIAPIProductNameComparator());
List<Object> apiList = new ArrayList<>();
Map<String, Object> result = new HashMap<String, Object>();
int totalLength = 0;
boolean isMore = false;
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;
}
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 (governanceArtifacts == null || governanceArtifacts.size() == 0) {
if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(searchQuery), registry, APIConstants.API_RXT_MEDIA_TYPE, true);
if (governanceArtifacts == null || governanceArtifacts.size() == 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 (GovernanceArtifact artifact : governanceArtifacts) {
String type = artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
if (APIConstants.API_PRODUCT.equals(type)) {
APIProduct resultAPI = APIUtil.getAPIProduct(artifact, registry);
if (resultAPI != null) {
apiList.add(resultAPI);
}
} else {
API resultAPI;
if (APIUtil.getAPIIdentifierFromUUID(artifact.getId()) != null) {
if (limitAttributes) {
resultAPI = APIUtil.getAPI(artifact);
} else {
if (reducedPublisherAPIInfo) {
resultAPI = APIUtil.getReducedPublisherAPIForListing(artifact, registry);
} 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;
}
}
// Creating a apiIds string
String apiIdsString = "";
int apiCount = apiList.size();
if (!reducedPublisherAPIInfo) {
for (int i = 0; i < apiCount; i++) {
Object api = apiList.get(i);
String apiId = "";
if (api instanceof API) {
apiId = ((API) api).getId().getApplicationId();
} else if (api instanceof APIProduct) {
apiId = ((APIProduct) api).getId().getApplicationId();
}
if (apiId != null && !apiId.isEmpty()) {
if (apiIdsString.isEmpty()) {
apiIdsString = apiId;
} else {
apiIdsString = apiIdsString + "," + apiId;
}
}
}
}
apiSet.addAll(apiList);
} catch (RegistryException e) {
String msg = "Failed to search APIs with type";
throw new APIManagementException(msg, e);
} finally {
PaginationContext.destroy();
}
result.put("apis", apiSet);
result.put("length", totalLength);
result.put("isMore", isMore);
return result;
}
use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsGet.
/**
* Get all subscriptions that are of user or shared subscriptions of the user's group.
* <p/>
* If apiId is specified this will return the subscribed applications of that api
* If application id is specified this will return the api subscriptions of that application
*
* @param apiId api identifier
* @param applicationId application identifier
* @param offset starting index of the subscription list
* @param limit max num of subscriptions returned
* @param ifNoneMatch If-None-Match header value
* @return matched subscriptions as a list of SubscriptionDTOs
*/
@Override
public Response subscriptionsGet(String apiId, String applicationId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
Subscriber subscriber = new Subscriber(username);
Set<SubscribedAPI> subscriptions;
List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
// pre-processing
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
// currently groupId is taken from the user so that groupId coming as a query parameter is not honored.
// As a improvement, we can check admin privileges of the user and honor groupId.
groupId = RestApiUtil.getLoggedInUserGroupId();
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
SubscriptionListDTO subscriptionListDTO;
if (!StringUtils.isEmpty(apiId)) {
// todo : FIX properly, need to done properly with backend side pagination.
// todo : getSubscribedIdentifiers() method should NOT be used. Appears to be too slow.
// This will fail with an authorization failed exception if user does not have permission to access the API
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
if (apiTypeWrapper.isAPIProduct()) {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
} else {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
}
// sort by application name
subscribedAPIList.addAll(subscriptions);
subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
SubscriptionMappingUtil.setPaginationParams(subscriptionListDTO, apiId, "", limit, offset, subscribedAPIList.size());
return Response.ok().entity(subscriptionListDTO).build();
} else if (!StringUtils.isEmpty(applicationId)) {
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
return null;
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
subscriptions = apiConsumer.getPaginatedSubscribedAPIsByApplication(application, offset, limit, organization);
subscribedAPIList.addAll(subscriptions);
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
return Response.ok().entity(subscriptionListDTO).build();
} else {
// neither apiId nor applicationId is given
RestApiUtil.handleBadRequest("Either applicationId or apiId should be available", log);
return null;
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
} else if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
RestApiUtil.handleInternalServerError("Error while getting subscriptions of the user " + username, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.
the class APIMappingUtil method setPaginationParams.
/**
* Sets pagination urls for a APIListDTO object given pagination parameters and url parameters
*
* @param apiListDTO APIListDTO object to which pagination urls need to be set
* @param query query parameter
* @param offset starting index
* @param limit max number of returned objects
* @param size max offset
*/
public static void setPaginationParams(APIListDTO apiListDTO, String query, int offset, int limit, int size) {
Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
String paginatedPrevious = "";
String paginatedNext = "";
if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
paginatedPrevious = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
}
if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
paginatedNext = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
}
PaginationDTO paginationDTO = CommonMappingUtil.getPaginationDTO(limit, offset, size, paginatedNext, paginatedPrevious);
apiListDTO.setPagination(paginationDTO);
}
Aggregations