[inmemory] Add filterCritera ordering (#16185)

Signed-off-by: Jan N. Klug <github@klug.nrw>
This commit is contained in:
J-N-K 2024-01-02 20:22:37 +01:00 committed by Jacob Laursen
parent 733d2e7b0c
commit d434fc5e4e
2 changed files with 42 additions and 6 deletions

View File

@ -173,9 +173,14 @@ public class InMemoryPersistenceService implements ModifiablePersistenceService
Lock lock = persistItem.lock();
lock.lock();
Comparator<PersistEntry> comparator = filter.getOrdering() == FilterCriteria.Ordering.ASCENDING
? Comparator.comparing(PersistEntry::timestamp)
: Comparator.comparing(PersistEntry::timestamp).reversed();
try {
return persistItem.database().stream().filter(e -> applies(e, filter)).map(e -> toHistoricItem(itemName, e))
.toList();
return persistItem.database().stream().filter(e -> applies(e, filter)).sorted(comparator)
.map(e -> toHistoricItem(itemName, e)).toList();
} finally {
lock.unlock();
}

View File

@ -13,15 +13,14 @@
package org.openhab.persistence.inmemory.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.when;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -144,6 +143,38 @@ public class InMemoryPersistenceTests {
assertThat(storedStates, is(empty()));
}
@Test
public void querySupportsAscendingOrdering() {
ZonedDateTime start = ZonedDateTime.of(2020, 12, 1, 12, 0, 0, 0, ZoneId.systemDefault());
service.store(item, start, new DecimalType(1));
service.store(item, start.plusHours(1), new DecimalType(2));
service.store(item, start.plusHours(2), new DecimalType(3));
filterCriteria.setOrdering(FilterCriteria.Ordering.ASCENDING);
filterCriteria.setBeginDate(start);
List<Integer> resultSet = new ArrayList<>();
service.query(filterCriteria).forEach(h -> resultSet.add(((DecimalType) h.getState()).intValue()));
assertThat(resultSet, contains(1, 2, 3));
}
@Test
public void querySupportsDescendingOrdering() {
ZonedDateTime start = ZonedDateTime.of(2020, 12, 1, 12, 0, 0, 0, ZoneId.systemDefault());
service.store(item, start, new DecimalType(1));
service.store(item, start.plusHours(1), new DecimalType(2));
service.store(item, start.plusHours(2), new DecimalType(3));
filterCriteria.setOrdering(FilterCriteria.Ordering.DESCENDING);
filterCriteria.setBeginDate(start);
List<Integer> resultSet = new ArrayList<>();
service.query(filterCriteria).forEach(h -> resultSet.add(((DecimalType) h.getState()).intValue()));
assertThat(resultSet, contains(3, 2, 1));
}
@Test
public void removeBetweenTimes() {
State historicState1 = new StringType("value1");