Skip to contentMethod: tryAdvance(Consumer)
1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.model;
19:
20: import cz.cvut.kbss.jopa.utils.Procedure;
21: import cz.cvut.kbss.ontodriver.iteration.ResultRow;
22:
23: import java.util.Optional;
24: import java.util.Spliterator;
25: import java.util.Spliterators;
26: import java.util.function.Consumer;
27: import java.util.function.Function;
28:
29: /**
30: * Spliterator for processing {@link cz.cvut.kbss.ontodriver.ResultSet} from {@link cz.cvut.kbss.jopa.model.query.Query} or
31: * {@link cz.cvut.kbss.jopa.model.query.TypedQuery} stream support.
32: * <p>
33: * The main responsibilities of this spliterator are extracting result rows using the specified mapper,
34: * passing the extraction result to the specified consumer and invoking the {@code onClose} handler once the iteration is finished.
35: * This handler releases the underlying statement and result set.
36: *
37: * @param <X> The type of the extracted item
38: */
39: class QueryResultSpliterator<X> extends Spliterators.AbstractSpliterator<X> {
40:
41: private final Spliterator<ResultRow> resultSetSpliterator;
42: private final Function<ResultRow, Optional<X>> mapper;
43: private final Procedure onClose;
44:
45: QueryResultSpliterator(Spliterator<ResultRow> resultSetSpliterator, Function<ResultRow, Optional<X>> mapper,
46: Procedure onClose) {
47: super(Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.ORDERED | Spliterator.NONNULL);
48: this.resultSetSpliterator = resultSetSpliterator;
49: this.mapper = mapper;
50: this.onClose = onClose;
51: }
52:
53: private void mapAndApply(ResultRow row, Consumer<? super X> action) {
54: mapper.apply(row).ifPresent(action);
55: }
56:
57: @Override
58: public boolean tryAdvance(Consumer<? super X> action) {
59: try {
60: final boolean result = resultSetSpliterator.tryAdvance(row -> mapAndApply(row, action));
61:• if (!result) {
62: onClose.execute();
63: }
64: return result;
65: } catch (RuntimeException e) {
66: onClose.execute();
67: throw e;
68: }
69: }
70:
71: @Override
72: public void forEachRemaining(Consumer<? super X> action) {
73: try {
74: resultSetSpliterator.forEachRemaining(row -> mapAndApply(row, action));
75: } finally {
76: onClose.execute();
77: }
78: }
79: }