Search in sources :

Example 66 with Pageable

use of org.springframework.data.domain.Pageable in project CzechIdMng by bcvsolutions.

the class IdentityReportExecutor method generateData.

@Override
protected IdmAttachmentDto generateData(RptReportDto report) {
    // prepare temp file for json stream
    File temp = getAttachmentManager().createTempFile();
    // 
    try (FileOutputStream outputStream = new FileOutputStream(temp)) {
        // write into json stream
        JsonGenerator jGenerator = getMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8);
        try {
            // json will be array of identities
            jGenerator.writeStartArray();
            // form instance has useful methods to transform form values
            IdmFormInstanceDto formInstance = new IdmFormInstanceDto(report, getFormDefinition(), report.getFilter());
            // initialize filter by given form - transform to multi value map
            // => form attribute defined above will be automaticaly mapped to identity filter
            IdmIdentityFilter filter = new IdmIdentityFilter(formInstance.toMultiValueMap());
            // report extends long running task - show progress by count and counter lrt attributes
            counter = 0L;
            // find a first page of identities
            Pageable pageable = PageRequest.of(0, 100, new Sort(Direction.ASC, IdmIdentity_.username.getName()));
            do {
                Page<IdmIdentityDto> identities = identityService.find(filter, pageable, IdmBasePermission.READ);
                if (count == null) {
                    // report extends long running task - show progress by count and counter lrt attributes
                    count = identities.getTotalElements();
                }
                boolean canContinue = true;
                for (Iterator<IdmIdentityDto> i = identities.iterator(); i.hasNext() && canContinue; ) {
                    // write single identity into json
                    getMapper().writeValue(jGenerator, i.next());
                    // 
                    // supports cancel report generating (report extends long running task)
                    ++counter;
                    canContinue = updateState();
                }
                // iterate while next page of identities is available
                pageable = identities.hasNext() && canContinue ? identities.nextPageable() : null;
            } while (pageable != null);
            // 
            // close array of identities
            jGenerator.writeEndArray();
        } finally {
            // close json stream
            jGenerator.close();
        }
        // save create temp file with array of identities in json as attachment
        return createAttachment(report, new FileInputStream(temp));
    } catch (IOException ex) {
        throw new ReportGenerateException(report.getName(), ex);
    } finally {
        FileUtils.deleteQuietly(temp);
    }
}
Also used : IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) IOException(java.io.IOException) ReportGenerateException(eu.bcvsolutions.idm.rpt.api.exception.ReportGenerateException) FileInputStream(java.io.FileInputStream) Pageable(org.springframework.data.domain.Pageable) FileOutputStream(java.io.FileOutputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) Sort(org.springframework.data.domain.Sort) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) File(java.io.File)

Example 67 with Pageable

use of org.springframework.data.domain.Pageable in project hub-alert by blackducksoftware.

the class DefaultRestApiAuditAccessorTest method getPageOfAuditEntriesTest.

@Test
public void getPageOfAuditEntriesTest() {
    Integer pageNumber = 0;
    int pageSize = 2;
    String searchTerm = null;
    String sortField = "lastSent";
    String sortOrder = "ASC";
    Boolean onlyShowSentNotifications = Boolean.TRUE;
    String overallStatus = "overallStatusString";
    String lastSent = DateUtils.createCurrentDateString(DateUtils.AUDIT_DATE_FORMAT);
    AuditEntryRepository auditEntryRepository = Mockito.mock(AuditEntryRepository.class);
    DefaultNotificationAccessor notificationManager = Mockito.mock(DefaultNotificationAccessor.class);
    AuditNotificationRepository auditNotificationRepository = Mockito.mock(AuditNotificationRepository.class);
    PageRequest pageRequest = PageRequest.of(0, 10);
    Mockito.when(auditEntryRepository.findMatchingAudit(Mockito.anyLong(), Mockito.any(UUID.class))).thenReturn(Optional.empty());
    Mockito.when(notificationManager.getPageRequestForNotifications(pageNumber, pageSize, sortField, sortOrder)).thenReturn(pageRequest);
    // At least two AlertNotificationModel are required for the comparator
    AlertNotificationModel alertNotificationModel = new AlertNotificationModel(1L, 1L, "provider-test", "providerConfigName-test", "notificationType-test", "{content: \"content is here...\"}", DateUtils.createCurrentDateTimestamp(), DateUtils.createCurrentDateTimestamp(), false);
    AlertNotificationModel alertNotificationModel2 = new AlertNotificationModel(2L, 2L, "provider-test2", "providerConfigName-test2", "notificationType-test2", "{content: \"content is here2..\"}", DateUtils.createCurrentDateTimestamp().minusSeconds(15), DateUtils.createCurrentDateTimestamp().minusSeconds(10), false);
    Pageable auditPageable = Mockito.mock(Pageable.class);
    Mockito.when(auditPageable.getOffset()).thenReturn(pageNumber.longValue());
    Mockito.when(auditPageable.getPageSize()).thenReturn(pageSize);
    Page<AlertNotificationModel> auditPage = new PageImpl<>(List.of(alertNotificationModel, alertNotificationModel2), auditPageable, 1);
    Mockito.when(notificationManager.findAll(pageRequest, onlyShowSentNotifications)).thenReturn(auditPage);
    NotificationConfig notificationConfig = new NotificationConfig("3", "createdAtString", "providerString", 2L, "providerConfigNameString", "providerCreationTimeString", "notificationTypeString", "content-test");
    AuditEntryModel auditEntryModel = new AuditEntryModel("2", notificationConfig, List.of(), overallStatus, lastSent);
    Function<AlertNotificationModel, AuditEntryModel> notificationToAuditEntryConverter = (AlertNotificationModel notificationModel) -> auditEntryModel;
    DefaultRestApiAuditAccessor auditUtility = new DefaultRestApiAuditAccessor(auditEntryRepository, auditNotificationRepository, null, null, notificationManager, null);
    AuditEntryPageModel alertPagedModel = auditUtility.getPageOfAuditEntries(pageNumber, pageSize, searchTerm, sortField, sortOrder, onlyShowSentNotifications, notificationToAuditEntryConverter);
    assertEquals(1, alertPagedModel.getTotalPages());
    assertEquals(pageNumber.intValue(), alertPagedModel.getCurrentPage());
    assertEquals(pageSize, alertPagedModel.getPageSize());
    assertEquals(2, alertPagedModel.getContent().size());
    assertEquals(lastSent, alertPagedModel.getContent().get(0).getLastSent());
    assertEquals(lastSent, alertPagedModel.getContent().get(1).getLastSent());
    AuditEntryModel auditContentTest = alertPagedModel.getContent().stream().findFirst().orElse(null);
    assertEquals(auditEntryModel.getId(), auditContentTest.getId());
    assertEquals(notificationConfig, auditContentTest.getNotification());
    assertEquals(0, auditContentTest.getJobs().size());
    assertEquals(overallStatus, auditContentTest.getOverallStatus());
    assertEquals(lastSent, auditContentTest.getLastSent());
}
Also used : AlertNotificationModel(com.synopsys.integration.alert.common.rest.model.AlertNotificationModel) PageImpl(org.springframework.data.domain.PageImpl) AuditEntryPageModel(com.synopsys.integration.alert.common.persistence.model.AuditEntryPageModel) AuditEntryRepository(com.synopsys.integration.alert.database.audit.AuditEntryRepository) PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) AuditNotificationRepository(com.synopsys.integration.alert.database.audit.AuditNotificationRepository) NotificationConfig(com.synopsys.integration.alert.common.rest.model.NotificationConfig) UUID(java.util.UUID) AuditEntryModel(com.synopsys.integration.alert.common.persistence.model.AuditEntryModel) Test(org.junit.jupiter.api.Test)

Example 68 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-mongodb by spring-projects.

the class AggregationUtils method appendLimitAndOffsetIfPresent.

/**
 * Append {@code $skip} and {@code $limit} aggregation stage if {@link ConvertingParameterAccessor#getSort()} is
 * present.
 *
 * @param aggregationPipeline
 * @param accessor
 * @param offsetOperator
 * @param limitOperator
 * @since 3.3
 */
static void appendLimitAndOffsetIfPresent(List<AggregationOperation> aggregationPipeline, ConvertingParameterAccessor accessor, LongUnaryOperator offsetOperator, IntUnaryOperator limitOperator) {
    Pageable pageable = accessor.getPageable();
    if (pageable.isUnpaged()) {
        return;
    }
    if (pageable.getOffset() > 0) {
        aggregationPipeline.add(Aggregation.skip(offsetOperator.applyAsLong(pageable.getOffset())));
    }
    aggregationPipeline.add(Aggregation.limit(limitOperator.applyAsInt(pageable.getPageSize())));
}
Also used : Pageable(org.springframework.data.domain.Pageable)

Example 69 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-mongodb by spring-projects.

the class NearQueryUnitTests method shouldTakeSkipAndLimitSettingsFromPageableEvenIfItWasSpecifiedOnQuery.

// DATAMONGO-445, DATAMONGO-2264
@Test
public void shouldTakeSkipAndLimitSettingsFromPageableEvenIfItWasSpecifiedOnQuery() {
    int limit = 10;
    int skip = 5;
    Pageable pageable = PageRequest.of(3, 5);
    NearQuery query = NearQuery.near(new Point(1, 1)).query(Query.query(Criteria.where("foo").is("bar")).limit(limit).skip(skip)).with(pageable);
    assertThat(query.getSkip()).isEqualTo((long) pageable.getPageNumber() * pageable.getPageSize());
    assertThat(query.toDocument().get("num")).isEqualTo((long) pageable.getPageSize());
}
Also used : Pageable(org.springframework.data.domain.Pageable) Point(org.springframework.data.geo.Point) GeoJsonPoint(org.springframework.data.mongodb.core.geo.GeoJsonPoint) Point(org.springframework.data.geo.Point) GeoJsonPoint(org.springframework.data.mongodb.core.geo.GeoJsonPoint) Test(org.junit.jupiter.api.Test)

Example 70 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-mongodb by spring-projects.

the class AbstractMongoQueryUnitTests method slicedExecutionShouldIncrementLimitByOne.

// DATAMONGO-1057
@Test
void slicedExecutionShouldIncrementLimitByOne() {
    MongoQueryFake query = createQueryForMethod("findByLastname", String.class, Pageable.class);
    Pageable page1 = PageRequest.of(0, 10);
    Pageable page2 = page1.next();
    query.execute(new Object[] { "fake", page1 });
    query.execute(new Object[] { "fake", page2 });
    ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
    verify(executableFind, times(2)).as(Person.class);
    verify(withQueryMock, times(2)).matching(captor.capture());
    assertThat(captor.getAllValues().get(0).getLimit()).isEqualTo(11);
    assertThat(captor.getAllValues().get(1).getLimit()).isEqualTo(11);
}
Also used : Pageable(org.springframework.data.domain.Pageable) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) FindWithQuery(org.springframework.data.mongodb.core.ExecutableFindOperation.FindWithQuery) UpdateWithQuery(org.springframework.data.mongodb.core.ExecutableUpdateOperation.UpdateWithQuery) Query(org.springframework.data.mongodb.core.query.Query) Test(org.junit.jupiter.api.Test)

Aggregations

Pageable (org.springframework.data.domain.Pageable)172 PageRequest (org.springframework.data.domain.PageRequest)91 Sort (org.springframework.data.domain.Sort)79 Test (org.junit.Test)39 PageImpl (org.springframework.data.domain.PageImpl)24 Collectors (java.util.stream.Collectors)17 Page (org.springframework.data.domain.Page)16 ArrayList (java.util.ArrayList)14 Autowired (org.springframework.beans.factory.annotation.Autowired)14 GetMapping (org.springframework.web.bind.annotation.GetMapping)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 List (java.util.List)11 UUID (java.util.UUID)10 ApiOperation (io.swagger.annotations.ApiOperation)9 Calendar (java.util.Calendar)9 Test (org.junit.jupiter.api.Test)9 java.util (java.util)8 Lists (com.google.common.collect.Lists)7 Map (java.util.Map)6 Transactional (org.springframework.transaction.annotation.Transactional)6