Skip to content

Method: testCreateQueryNullQuery()

1: /**
2: * Copyright (C) 2022 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jopa.test.query.runner;
16:
17: import cz.cvut.kbss.jopa.exceptions.NoResultException;
18: import cz.cvut.kbss.jopa.exceptions.NoUniqueResultException;
19: import cz.cvut.kbss.jopa.model.annotations.OWLClass;
20: import cz.cvut.kbss.jopa.model.descriptors.Descriptor;
21: import cz.cvut.kbss.jopa.model.descriptors.EntityDescriptor;
22: import cz.cvut.kbss.jopa.model.query.TypedQuery;
23: import cz.cvut.kbss.jopa.test.*;
24: import cz.cvut.kbss.jopa.test.environment.DataAccessor;
25: import cz.cvut.kbss.jopa.test.environment.Generators;
26: import cz.cvut.kbss.jopa.test.query.QueryTestEnvironment;
27: import org.junit.jupiter.api.Disabled;
28: import org.junit.jupiter.api.Test;
29: import org.slf4j.Logger;
30:
31: import java.net.URI;
32: import java.time.LocalDateTime;
33: import java.time.ZoneOffset;
34: import java.time.temporal.ChronoUnit;
35: import java.util.*;
36: import java.util.stream.Collectors;
37: import java.util.stream.IntStream;
38:
39: import static org.junit.jupiter.api.Assertions.*;
40:
41: public abstract class TypedQueryRunner extends BaseQueryRunner {
42:
43: private static final String SELECT_BY_TYPE = "SELECT ?x WHERE { ?x a ?type .}";
44:
45: protected TypedQueryRunner(Logger logger, DataAccessor dataAccessor) {
46: super(logger, dataAccessor);
47: }
48:
49: @Test
50: void testFindAll() {
51: final TypedQuery<OWLClassD> q =
52: getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassD.class).setParameter("type", URI.create(
53: Vocabulary.C_OWL_CLASS_D));
54: final List<OWLClassD> ds = new ArrayList<>(QueryTestEnvironment.getDataByContext(null, OWLClassD.class));
55: final List<OWLClassD> res = q.getResultList();
56: assertNotNull(res);
57: assertFalse(res.isEmpty());
58: assertEquals(ds.size(), res.size());
59: boolean found;
60: for (OWLClassD d : ds) {
61: found = false;
62: for (OWLClassD dd : res) {
63: if (d.getUri().equals(dd.getUri())) {
64: found = true;
65: assertNotNull(dd.getOwlClassA());
66: assertEquals(d.getOwlClassA().getUri(), dd.getOwlClassA().getUri());
67: break;
68: }
69: }
70: assertTrue(found);
71: }
72: }
73:
74: @Test
75: void testSelectByTypeAndDataPropertyValue() {
76: final OWLClassB b = QueryTestEnvironment.getData(OWLClassB.class).get(5);
77: final String query =
78: "SELECT ?x WHERE { " +
79: "?x a ?type ; " +
80: "?stringAtt ?bString . }";
81: final TypedQuery<OWLClassB> q = getEntityManager().createNativeQuery(query, OWLClassB.class);
82: q.setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_B))
83: .setParameter("stringAtt", URI.create(Vocabulary.P_B_STRING_ATTRIBUTE))
84: .setParameter("bString", b.getStringAttribute(), "en");
85: final OWLClassB res = q.getSingleResult();
86: assertNotNull(res);
87: assertEquals(b.getUri(), res.getUri());
88: assertEquals(b.getStringAttribute(), res.getStringAttribute());
89: }
90:
91: @Test
92: void testSelectByObjectProperty() {
93: final String query = "SELECT ?x WHERE { ?x a ?type ; ?hasA ?y . }";
94: final List<OWLClassD> ds = new ArrayList<>(QueryTestEnvironment.getData(OWLClassD.class));
95: final OWLClassA a = ds.get(Generators.randomPositiveInt(2, ds.size())).getOwlClassA();
96: final TypedQuery<OWLClassD> q = getEntityManager().createNativeQuery(query, OWLClassD.class)
97: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_D))
98: .setParameter("hasA",
99: URI.create(Vocabulary.P_HAS_OWL_CLASS_A))
100: .setParameter("y", a.getUri());
101:
102: final List<OWLClassD> expected = ds.stream().filter(d -> d.getOwlClassA().getUri().equals(a.getUri())).collect(
103: Collectors.toList());
104: final List<OWLClassD> res = q.getResultList();
105: assertEquals(expected.size(), res.size());
106: }
107:
108: @Test
109: void testSetMaxResults() {
110: final TypedQuery<OWLClassE> q = getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassE.class)
111: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_E));
112: final int max = 5;
113: assertTrue(max < QueryTestEnvironment.getData(OWLClassE.class).size());
114: assertEquals(Integer.MAX_VALUE, q.getMaxResults());
115: q.setMaxResults(max);
116: assertEquals(max, q.getMaxResults());
117: final List<OWLClassE> res = q.getResultList();
118: assertNotNull(res);
119: assertFalse(res.isEmpty());
120: assertEquals(max, res.size());
121: }
122:
123: @Test
124: void testSetMaxResultsNegative() {
125: final TypedQuery<OWLClassE> q = getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassE.class)
126: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_E));
127: assertThrows(IllegalArgumentException.class, () -> q.setMaxResults(-1));
128: }
129:
130: @Test
131: void testSetMaxResultsZero() {
132: final TypedQuery<OWLClassE> q = getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassE.class)
133: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_E));
134: q.setMaxResults(0);
135: final List<OWLClassE> res = q.getResultList();
136: assertNotNull(res);
137: assertTrue(res.isEmpty());
138: }
139:
140: @Test
141: void testGetSingleResult() {
142: final OWLClassA a = QueryTestEnvironment.getData(OWLClassA.class).get(0);
143: final String query =
144: "SELECT ?x WHERE { ?x ?stringAtt ?aString .}";
145: final TypedQuery<OWLClassA> q = getEntityManager().createNativeQuery(query, OWLClassA.class);
146: q.setParameter("stringAtt", URI.create(Vocabulary.P_A_STRING_ATTRIBUTE))
147: .setParameter("aString", a.getStringAttribute(), "en");
148: final OWLClassA res = q.getSingleResult();
149: assertNotNull(res);
150: assertEquals(a.getUri(), res.getUri());
151: }
152:
153: @Test
154: void testGetSingleResultMultiples() {
155: final TypedQuery<OWLClassE> q = getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassE.class)
156: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_E));
157: assertThrows(NoUniqueResultException.class, q::getSingleResult);
158: }
159:
160: @Test
161: void testGetSingleResultNoResult() {
162: final String query =
163: "SELECT ?x WHERE { ?x a <http://krizik.felk.cvut.cz/ontologies/jopa/entities#OWLClassX> . }";
164: final TypedQuery<OWLClassE> q = getEntityManager().createNativeQuery(query, OWLClassE.class);
165: assertThrows(NoResultException.class, q::getSingleResult);
166: }
167:
168: @Test
169: void testCreateQueryNullQuery() {
170: assertThrows(NullPointerException.class, () -> getEntityManager().createNativeQuery(null, OWLClassA.class));
171: }
172:
173: @Test
174: void testCreateQueryNullClass() {
175: final String query = "SELECT ?x WHERE { ?x ?y ?z .}";
176: assertThrows(NullPointerException.class,
177: () -> getEntityManager().createNativeQuery(query, (Class<OWLClassA>) null));
178: }
179:
180: @Test
181: void askQueryReturnsTrue() {
182: final String query = "ASK { ?x a ?type . }";
183: final TypedQuery<Boolean> q = getEntityManager().createNativeQuery(query, Boolean.class)
184: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_A));
185: final Boolean res = q.getSingleResult();
186: assertNotNull(res);
187: assertTrue(res);
188: }
189:
190: @Test
191: void askQueryReturnsFalse() {
192: final String query = "ASK { ?x a <http://krizik.felk.cvut.cz/ontologies/jopa/entities#OWLClassX> . }";
193: final TypedQuery<Boolean> q = getEntityManager().createNativeQuery(query, Boolean.class);
194: final List<Boolean> res = q.getResultList();
195: assertNotNull(res);
196: assertEquals(1, res.size());
197: assertFalse(res.get(0));
198: }
199:
200: @Disabled
201: @Test
202: public void askQueryAgainstTransactionalOntologyContainsUncommittedChangesAsWell() {
203: final OWLClassE e = new OWLClassE();
204: getEntityManager().getTransaction().begin();
205: try {
206: getEntityManager().persist(e);
207: final TypedQuery<Boolean> query = getEntityManager().createNativeQuery(
208: "ASK { ?individual a ?type . }",
209: Boolean.class).setParameter("individual", e.getUri()).setParameter("type",
210: URI.create(Vocabulary.C_OWL_CLASS_E));
211: final Boolean res = query.getSingleResult();
212: assertTrue(res);
213: } finally {
214: getEntityManager().getTransaction().rollback();
215: }
216: }
217:
218: @Test
219: void askQueryWithPositionParameter() {
220: final String query = "ASK { ?x a $1 . }";
221: final URI paramValue = URI.create(OWLClassA.class.getAnnotation(OWLClass.class).iri());
222: final TypedQuery<Boolean> q = getEntityManager().createNativeQuery(query, Boolean.class)
223: .setParameter(1, paramValue);
224: final Boolean res = q.getSingleResult();
225: assertNotNull(res);
226: assertTrue(res);
227: }
228:
229: @Test
230: void testCreateTypedNamedNativeQuery() {
231: final List<OWLClassA> expected = QueryTestEnvironment.getData(OWLClassA.class);
232: final List<URI> uris = expected.stream().map(OWLClassA::getUri).collect(Collectors.toList());
233: final List<OWLClassA> res = getEntityManager().createNamedQuery("OWLClassA.findAll", OWLClassA.class)
234: .getResultList();
235: assertEquals(expected.size(), res.size());
236: res.forEach(a -> assertTrue(uris.contains(a.getUri())));
237: }
238:
239: @Test
240: void usingDescriptorAllowsToCustomizeQueryResults() {
241: final List<OWLClassA> expected = QueryTestEnvironment.getData(OWLClassA.class);
242: expected.forEach(a -> assertNotNull(a.getStringAttribute()));
243: final Descriptor descriptor = new EntityDescriptor();
244: descriptor.setLanguage("cs");
245: final List<OWLClassA> result = getEntityManager().createNamedQuery("OWLClassA.findAll", OWLClassA.class)
246: .setDescriptor(descriptor).getResultList();
247: assertEquals(expected.size(), result.size());
248: result.forEach(a -> assertNull(a.getStringAttribute())); // Because the data has @en language tag
249: }
250:
251: @Test
252: public void usingUntypedQueryAllowsToSpecifyLimitInQuery() {
253: final List<OWLClassA> expected = QueryTestEnvironment.getData(OWLClassA.class);
254: final int size = expected.size() / 2;
255: final List<OWLClassA> result = getEntityManager().createNativeQuery("SELECT ?x WHERE {" +
256: "?x a ?classA . } LIMIT ?limit", OWLClassA.class)
257: .setParameter("classA", URI.create(Vocabulary.C_OWL_CLASS_A))
258: .setUntypedParameter("limit", size).getResultList();
259: assertEquals(size, result.size());
260: }
261:
262: @Test
263: public void setFirstResultCanBeUsedToOffsetFirstQueryResult() {
264: final List<OWLClassA> expected = QueryTestEnvironment.getData(OWLClassA.class);
265: expected.sort(Comparator.comparing(OWLClassA::getUri));
266: final int offset = expected.size() / 2;
267: final List<OWLClassA> result = getEntityManager().createNamedQuery("OWLClassA.findAll", OWLClassA.class)
268: .setFirstResult(offset).getResultList();
269: assertEquals(expected.size() - offset, result.size());
270: for (int i = 0; i < result.size(); i++) {
271: assertEquals(expected.get(i + offset).getUri(), result.get(i).getUri());
272: }
273: }
274:
275: @Test
276: void querySupportsProcessingResultsUsingStream() {
277: final TypedQuery<OWLClassD> q =
278: getEntityManager().createNativeQuery(SELECT_BY_TYPE, OWLClassD.class).setParameter("type", URI.create(
279: Vocabulary.C_OWL_CLASS_D));
280: final List<OWLClassD> dList = QueryTestEnvironment.getData(OWLClassD.class);
281: final Set<URI> expected = dList.stream().map(OWLClassD::getUri).collect(Collectors.toSet());
282:
283: q.getResultStream().map(OWLClassD::getUri).forEach(rUri -> assertTrue(expected.contains(rUri)));
284: assertEquals(dList.size(), (int) q.getResultStream().count());
285: }
286:
287: @Test
288: void selectionByObjectPropertySupportsEntityAsQueryParameter() {
289: final String query = "SELECT ?x WHERE { ?x a ?type ; ?hasA ?y . }";
290: final List<OWLClassD> ds = new ArrayList<>(QueryTestEnvironment.getData(OWLClassD.class));
291: final OWLClassA a = ds.get(Generators.randomPositiveInt(2, ds.size())).getOwlClassA();
292: final TypedQuery<OWLClassD> q = getEntityManager().createNativeQuery(query, OWLClassD.class)
293: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_D))
294: .setParameter("hasA",
295: URI.create(Vocabulary.P_HAS_OWL_CLASS_A))
296: .setParameter("y", a);
297:
298: final List<OWLClassD> expected = ds.stream().filter(d -> d.getOwlClassA().getUri().equals(a.getUri()))
299: .sorted(Comparator.comparing(OWLClassD::getUri))
300: .collect(Collectors.toList());
301: final List<OWLClassD> res = q.getResultList();
302: res.sort(Comparator.comparing(OWLClassD::getUri));
303: assertEquals(expected.size(), res.size());
304: for (int i = 0; i < expected.size(); i++) {
305: assertEquals(expected.get(i).getUri(), res.get(i).getUri());
306: assertNotNull(res.get(i).getOwlClassA());
307: }
308: }
309:
310: @Test
311: protected void querySupportsCollectionParameters() {
312: final String query = "SELECT ?x WHERE { ?x a ?type . FILTER (?x IN (?values)) }";
313: final List<OWLClassA> as = QueryTestEnvironment.getData(OWLClassA.class).stream()
314: .filter(a -> Generators.randomBoolean())
315: .collect(Collectors.toList());
316: final TypedQuery<OWLClassA> q = getEntityManager().createNativeQuery(query, OWLClassA.class)
317: .setParameter("type", URI.create(Vocabulary.C_OWL_CLASS_A))
318: .setParameter("values", as.stream().map(OWLClassA::getUri)
319: .collect(Collectors.toList()));
320: final List<OWLClassA> result = q.getResultList();
321: assertEquals(as.size(), result.size());
322: for (OWLClassA exp : as) {
323: assertTrue(result.stream().anyMatch(a -> a.getUri().equals(exp.getUri())));
324: }
325: }
326:
327: @Test
328: protected void querySupportsSelectionByDate() {
329: final long now = System.currentTimeMillis() / 1000L;
330: final List<OWLClassM> mInstances = IntStream.range(0, 10).mapToObj(i -> {
331: final OWLClassM m = new OWLClassM();
332: m.setKey(Generators.generateUri().toString());
333: // Now minus i * hour
334: m.setDateAttribute(new Date(now - i * 60 * 60L));
335: return m;
336: }).collect(Collectors.toList());
337: getEntityManager().getTransaction().begin();
338: mInstances.forEach(getEntityManager()::persist);
339: getEntityManager().getTransaction().commit();
340: final LocalDateTime param = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS).minusHours(3);
341: final List<OWLClassM> matching = mInstances.stream()
342: .filter(m -> m.getDateAttribute().toInstant().atOffset(ZoneOffset.UTC).isBefore(param.atOffset(ZoneOffset.UTC)))
343: .collect(Collectors.toList());
344: try {
345: final List<OWLClassM> result = getEntityManager().createQuery("SELECT m FROM OWLClassM m WHERE m.dateAttribute < :date", OWLClassM.class)
346: .setParameter("date", param).getResultList();
347: assertEquals(matching.size(), result.size());
348: matching.forEach(m -> assertTrue(result.stream().anyMatch(rm -> rm.getKey().equals(m.getKey()))));
349: } finally {
350: cleanupTestData(Vocabulary.C_OWL_CLASS_M);
351: }
352: }
353:
354: private void cleanupTestData(String type) {
355: getEntityManager().getTransaction().begin();
356: getEntityManager().createNativeQuery("DELETE WHERE { ?x a ?type . ?x ?y ?z . }")
357: .setParameter("type", URI.create(type)).executeUpdate();
358: getEntityManager().getTransaction().commit();
359: }
360: }