2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.persistence.dynamodb.internal;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.concurrent.CompletableFuture;
18 import java.util.concurrent.atomic.AtomicInteger;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.reactivestreams.Subscriber;
23 import org.reactivestreams.Subscription;
26 * Subscriber that subscribes the page of interest
28 * @author Sami Salonen - Initial contribution
31 public class PageOfInterestSubscriber<T> implements Subscriber<T> {
33 private AtomicInteger skipped = new AtomicInteger();
35 private @Nullable Subscription subscription;
36 private int pageIndex;
39 private CompletableFuture<List<T>> future;
42 * Create new PageOfInterestSubscriber
44 * @param future subscriber to get the page of interest
45 * @param pageIndex page index that we want subscribe
46 * @param pageSize page size
48 protected PageOfInterestSubscriber(CompletableFuture<List<T>> future, int pageIndex, int pageSize) {
50 this.pageIndex = pageIndex;
51 this.pageSize = pageSize;
52 this.page = new ArrayList<>();
53 this.skip = pageIndex * pageSize;
57 public void onSubscribe(@Nullable Subscription subscription) {
58 this.subscription = subscription;
59 if (subscription != null) {
60 subscription.request(pageSize * (pageIndex + 1));
65 public void onNext(T t) {
66 Subscription localSubscription = subscription;
67 if (localSubscription == null) {
68 throw new IllegalStateException(
69 "Subscriber API has been contract violated: expecting a non-null subscriber");
71 if (future.isCancelled()) {
72 localSubscription.cancel();
73 onError(new InterruptedException());
74 } else if (skipped.getAndIncrement() >= skip && page.size() < pageSize) {
75 // We have skipped enough, start accumulating
77 if (page.size() == pageSize) {
78 // We have the full page read
79 localSubscription.cancel();
86 public void onError(@NonNullByDefault({}) Throwable t) {
87 if (!future.isDone()) {
88 future.completeExceptionally(t);
93 public void onComplete() {
94 if (!future.isDone()) {
95 future.complete(page);