Search in sources :

Example 41 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-business-process by wso2.

the class UserSubstitutionUtils method getQueryResultCount.

/**
 * Total count of query substitution result by given properties.
 * Allowed properties: user, substitute, enabled.
 * Pagination parameters : start, size, sort, order
 * @param propertiesMap
 * @return  Total count of query result
 */
public static int getQueryResultCount(Map<String, String> propertiesMap, int tenantId) {
    ActivitiDAO activitiDAO = SubstitutionDataHolder.getInstance().getActivitiDAO();
    PaginatedSubstitutesDataModel model = getPaginatedModelFromRequest(propertiesMap, tenantId);
    String enabled = propertiesMap.get(SubstitutionQueryProperties.ENABLED);
    boolean enabledProvided = false;
    if (enabled != null) {
        enabledProvided = true;
    }
    if (!enabledProvided) {
        return activitiDAO.selectQueryResultCountWithoutEnabled(model);
    } else {
        return activitiDAO.selectQueryResultCount(model);
    }
}
Also used : PaginatedSubstitutesDataModel(org.wso2.carbon.bpmn.core.mgt.model.PaginatedSubstitutesDataModel) ActivitiDAO(org.wso2.carbon.bpmn.core.mgt.dao.ActivitiDAO)

Example 42 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-business-process by wso2.

the class AbstractPaginateList method paginateList.

public DataResponse paginateList(Map<String, String> requestParams, PaginateRequest paginateRequest, Query query, String defaultSort, Map<String, QueryProperty> properties) {
    if (paginateRequest == null) {
        paginateRequest = new PaginateRequest();
    }
    // In case pagination request is incomplete, fill with values found in URL if possible
    if (paginateRequest.getStart() == null) {
        paginateRequest.setStart(RequestUtil.getInteger(requestParams, "start", 0));
    }
    if (paginateRequest.getSize() == null) {
        paginateRequest.setSize(RequestUtil.getInteger(requestParams, "size", 10));
    }
    if (paginateRequest.getOrder() == null) {
        paginateRequest.setOrder(requestParams.get("order"));
    }
    if (paginateRequest.getSort() == null) {
        paginateRequest.setSort(requestParams.get("sort"));
    }
    // Use defaults for paging, if not set in the PaginationRequest, nor in the URL
    Integer start = paginateRequest.getStart();
    if (start == null || start < 0) {
        start = 0;
    }
    Integer size = paginateRequest.getSize();
    if (size == null || size < 0) {
        size = 10;
    }
    String sort = paginateRequest.getSort();
    if (sort == null) {
        // id
        sort = defaultSort;
    }
    String order = paginateRequest.getOrder();
    if (order == null) {
        order = "asc";
    }
    // Sort order
    if (sort != null && !properties.isEmpty()) {
        QueryProperty qp = properties.get(sort);
        if (qp == null) {
            throw new ActivitiIllegalArgumentException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property");
        }
        ((AbstractQuery) query).orderBy(qp);
        if (order.equals("asc")) {
            query.asc();
        } else if (order.equals("desc")) {
            query.desc();
        } else {
            throw new ActivitiIllegalArgumentException("Value for param 'order' is not valid : '" + order + "', must be 'asc' or 'desc'");
        }
    }
    // Get result and set pagination parameters
    List list = processList(query.listPage(start, size));
    DataResponse response = new DataResponse();
    response.setStart(start);
    response.setSize(list.size());
    response.setSort(sort);
    response.setOrder(order);
    response.setTotal(query.count());
    response.setData(list);
    return response;
}
Also used : DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) QueryProperty(org.activiti.engine.query.QueryProperty) AbstractQuery(org.activiti.engine.impl.AbstractQuery) List(java.util.List)

Example 43 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class ApiProductsApiServiceImpl method getAllAPIProducts.

@Override
public Response getAllAPIProducts(Integer limit, Integer offset, String query, String accept, String ifNoneMatch, MessageContext messageContext) {
    List<APIProduct> allMatchedProducts = new ArrayList<>();
    APIProductListDTO apiProductListDTO;
    // setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    query = query == null ? "" : query;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (log.isDebugEnabled()) {
            log.debug("API Product list request by " + username);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        Map<String, Object> result = apiProvider.searchPaginatedAPIProducts(query, tenantDomain, offset, limit);
        Set<APIProduct> apiProducts = (Set<APIProduct>) result.get("products");
        allMatchedProducts.addAll(apiProducts);
        apiProductListDTO = APIMappingUtil.fromAPIProductListtoDTO(allMatchedProducts);
        // Add pagination section in the response
        Object totalLength = result.get("length");
        Integer length = 0;
        if (totalLength != null) {
            length = (Integer) totalLength;
        }
        APIMappingUtil.setPaginationParams(apiProductListDTO, query, offset, limit, length);
        return Response.ok().entity(apiProductListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API Products ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductListDTO) Set(java.util.Set) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 44 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class SubscriptionMappingUtil method setPaginationParams.

/**
 * Sets pagination urls for a SubscriptionListDTO object given pagination parameters and url parameters
 *
 * @param subscriptionListDTO a SubscriptionListDTO object
 * @param apiId               uuid/id of API
 * @param groupId             group id of the applications to be returned
 * @param limit               max number of objects returned
 * @param offset              starting index
 * @param size                max offset
 */
public static void setPaginationParams(SubscriptionListDTO subscriptionListDTO, String apiId, String groupId, int limit, int offset, int size) {
    String paginatedPrevious = "";
    String paginatedNext = "";
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = RestApiCommonUtil.getSubscriptionPaginatedURLForAPIId(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), apiId, groupId);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = RestApiCommonUtil.getSubscriptionPaginatedURLForAPIId(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), apiId, groupId);
    }
    PaginationDTO pagination = new PaginationDTO();
    pagination.setOffset(offset);
    pagination.setLimit(limit);
    pagination.setNext(paginatedNext);
    pagination.setPrevious(paginatedPrevious);
    pagination.setTotal(size);
    subscriptionListDTO.setPagination(pagination);
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO)

Example 45 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class WSO2APIPublisherTestCase method testDeletingAPI.

@Test
public void testDeletingAPI() throws Exception {
    // Test error path when deleting non existing API
    Mockito.doReturn(HttpStatus.SC_OK).when(statusLine).getStatusCode();
    String apiGetResponse = "{\n" + "    \"count\": 0,\n" + "    \"list\": [],\n" + "    \"pagination\": {\n" + "        \"offset\": 0,\n" + "        \"limit\": 25,\n" + "        \"total\": 0,\n" + "        \"next\": \"\",\n" + "        \"previous\": \"\"\n" + "    }\n" + "}";
    PowerMockito.when(EntityUtils.toString(Matchers.any())).thenReturn(apiGetResponse);
    try {
        wso2APIPublisher.deleteFromStore(identifier, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        String errorMessage = "API: " + identifier.getApiName() + " version: " + identifier.getVersion() + " does not exist in external store: " + store.getName();
        Assert.assertEquals(errorMessage, e.getMessage());
    }
    // Test successful API deletion
    apiGetResponse = "{\n" + "    \"count\": 1,\n" + "    \"list\": [\n" + "        {\n" + "            \"id\": \"735ad20d-f382-4ab3-8000-97fce885c853\",\n" + "            \"name\": \"API1\",\n" + "            \"version\": \"1.0.0\",\n" + "        }\n" + "    ],\n" + "    \"pagination\": {\n" + "        \"offset\": 0,\n" + "        \"limit\": 25,\n" + "        \"total\": 1,\n" + "        \"next\": \"\",\n" + "        \"previous\": \"\"\n" + "    }\n" + "}";
    PowerMockito.when(EntityUtils.toString(Matchers.any())).thenReturn(apiGetResponse);
    Assert.assertTrue("API deletion failed", wso2APIPublisher.deleteFromStore(identifier, store));
    // Test error path API deletion failed due to server error
    String apiDeleteResponse = "{\"code\":500,\"message\":\"\",\"description\":\"Internal Server Error\"," + "\"moreInfo\":\"\",\"error\":[]}";
    HttpDelete httpDeleteFail = Mockito.mock(HttpDelete.class);
    PowerMockito.whenNew(HttpDelete.class).withAnyArguments().thenReturn(httpDeleteFail);
    CloseableHttpResponse deletionFailedResponse = Mockito.mock(CloseableHttpResponse.class);
    StatusLine deletionFailedStatusLine = Mockito.mock(StatusLine.class);
    Mockito.doReturn(deletionFailedStatusLine).when(deletionFailedResponse).getStatusLine();
    HttpEntity deletionFailedEntity = Mockito.mock(HttpEntity.class);
    Mockito.doReturn(deletionFailedEntity).when(deletionFailedResponse).getEntity();
    PowerMockito.when(EntityUtils.toString(deletionFailedEntity)).thenReturn(apiDeleteResponse);
    Mockito.doReturn(deletionFailedResponse).when(defaultHttpClient).execute(httpDeleteFail);
    // Error path when deleting API
    Mockito.doReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR).when(deletionFailedStatusLine).getStatusCode();
    try {
        wso2APIPublisher.deleteFromStore(identifier, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        String errorMessage = "API Delete service call received unsuccessful response status: " + HttpStatus.SC_INTERNAL_SERVER_ERROR + " response: " + apiDeleteResponse;
        Assert.assertEquals(errorMessage, e.getMessage());
    }
}
Also used : StatusLine(org.apache.http.StatusLine) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ArrayList (java.util.ArrayList)20 HashMap (java.util.HashMap)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 JSONObject (org.json.simple.JSONObject)12 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 PaginationDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO)11 API (org.wso2.carbon.apimgt.api.model.API)10 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)8 PaginationDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO)8 GovernanceArtifact (org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact)8 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)8 TreeSet (java.util.TreeSet)7 Registry (org.wso2.carbon.registry.core.Registry)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 APINameComparator (org.wso2.carbon.apimgt.impl.utils.APINameComparator)6 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)6 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)5