Skip to content

Commit 5833e57

Browse files
committed
GH-5149 code simplification and cleanup
1 parent 08b898c commit 5833e57

File tree

15 files changed

+141
-86
lines changed

15 files changed

+141
-86
lines changed

core/model-api/src/main/java/org/eclipse/rdf4j/model/Model.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public interface Model extends Set<Statement>, Serializable, NamespaceAware {
4545
*/
4646
default Namespace setNamespace(String prefix, String name) {
4747
Optional<? extends Namespace> result = getNamespace(prefix);
48-
if (!result.isPresent() || !result.get().getName().equals(name)) {
48+
if (result.isEmpty() || !result.get().getName().equals(name)) {
4949
result = Optional.of(new ModelNamespace(prefix, name));
5050
setNamespace(result.get());
5151
}

core/model/src/main/java/org/eclipse/rdf4j/model/util/Configurations.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ public static Optional<Resource> getSubjectByType(Model model, IRI type, IRI leg
240240

241241
private static void logDiscrepancyWarning(Optional<? extends Value> preferred,
242242
Optional<? extends Value> fallback) {
243-
if (!fallback.isEmpty() && !preferred.equals(fallback)) {
243+
if (fallback.isPresent() && !preferred.equals(fallback)) {
244244
var msg = "Discrepancy between use of the old and new config vocabulary.";
245245
// depending on whether preferred is set, we log on warn or debug
246246
if (preferred.isEmpty()) {

core/model/src/main/java/org/eclipse/rdf4j/model/util/GraphComparisons.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ private static boolean isomorphicSingleContext(Model model1, Model model2) {
169169

170170
// Because we have previously already checked that the models are the same size, we don't have to check both
171171
// ways to establish model equality.
172-
return !missingInModel2.isPresent();
172+
return missingInModel2.isEmpty();
173173
}
174174

175175
private static boolean mappingsIncompatible(Map<BNode, HashCode> mapping1, Map<BNode, HashCode> mapping2) {

core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/Contains.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx
4545
Literal rightLit = (Literal) rightVal;
4646

4747
if (leftLit.getLanguage().isPresent()) {
48-
if (!rightLit.getLanguage().isPresent() || rightLit.getLanguage().equals(leftLit.getLanguage())) {
48+
if (rightLit.getLanguage().isEmpty() || rightLit.getLanguage().equals(leftLit.getLanguage())) {
4949

5050
String leftLexVal = leftLit.getLabel();
5151
String rightLexVal = rightLit.getLabel();

core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/RDFParserHelper.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ public static Literal createLiteral(String label, String lang, IRI datatype, Par
190190
try {
191191
// Removes datatype for langString datatype with no language tag when VERIFY_DATATYPE_VALUES is False.
192192
if ((workingDatatype == null || RDF.LANGSTRING.equals(workingDatatype))
193-
&& (!workingLang.isPresent() || workingLang.get().isEmpty())
193+
&& (workingLang.isEmpty() || workingLang.get().isEmpty())
194194
&& !parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)) {
195195
workingLang = Optional.ofNullable(null);
196196
workingDatatype = null;

core/rio/jsonld-legacy/src/main/java/org/eclipse/rdf4j/rio/jsonld/legacy/JSONLDInternalRDFParser.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public void handleStatement(RDFDataset result, Statement nextStatement) {
6464

6565
// In RDF-1.1, RDF-1.0 Plain Literals are now Typed Literals with
6666
// type xsd:String
67-
if (!literal.getLanguage().isPresent() && datatype == null) {
67+
if (literal.getLanguage().isEmpty() && datatype == null) {
6868
datatype = XSD.STRING.stringValue();
6969
}
7070

core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchIndex.java

+38-38
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import java.util.HashMap;
1919
import java.util.HashSet;
2020
import java.util.Map;
21-
import java.util.Objects;
2221
import java.util.Properties;
2322
import java.util.Set;
2423

@@ -88,14 +87,13 @@
8887

8988
/**
9089
* Requires an Elasticsearch cluster with the DeleteByQuery plugin.
91-
*
90+
* <p>
9291
* Note that, while RDF4J is licensed under the EDL, several ElasticSearch dependencies are licensed under the Elastic
9392
* license or the SSPL, which may have implications for some projects.
94-
*
93+
* <p>
9594
* Please consult the ElasticSearch website and license FAQ for more information.
9695
*
9796
* @see <a href="https://www.elastic.co/licensing/elastic-license/faq">Elastic License FAQ</a>
98-
*
9997
* @see LuceneSail
10098
*/
10199
public class ElasticsearchIndex extends AbstractSearchIndex {
@@ -410,13 +408,8 @@ protected SearchDocument getDocument(String id) throws IOException {
410408
@Override
411409
protected Iterable<? extends SearchDocument> getDocuments(String resourceId) throws IOException {
412410
SearchHits hits = getDocuments(QueryBuilders.termQuery(SearchFields.URI_FIELD_NAME, resourceId));
413-
return Iterables.transform(hits, new Function<>() {
414-
415-
@Override
416-
public SearchDocument apply(SearchHit hit) {
417-
return new ElasticsearchDocument(hit, geoContextMapper);
418-
}
419-
});
411+
return Iterables.transform(hits,
412+
(Function<SearchHit, SearchDocument>) hit -> new ElasticsearchDocument(hit, geoContextMapper));
420413
}
421414

422415
@Override
@@ -578,19 +571,26 @@ protected Iterable<? extends DocumentScore> query(Resource subject, QuerySpec sp
578571
}
579572

580573
SearchHits hits;
581-
int numDocs = Objects.requireNonNullElse(spec.getNumDocs(), -1);
574+
575+
int numDocs;
576+
577+
Integer specNumDocs = spec.getNumDocs();
578+
if (specNumDocs != null) {
579+
if (specNumDocs < 0) {
580+
throw new IllegalArgumentException("numDocs must be >= 0");
581+
}
582+
numDocs = specNumDocs;
583+
} else {
584+
numDocs = -1;
585+
}
586+
582587
if (subject != null) {
583588
hits = search(subject, request, qb, numDocs);
584589
} else {
585590
hits = search(request, qb, numDocs);
586591
}
587-
return Iterables.transform(hits, new Function<>() {
588-
589-
@Override
590-
public DocumentScore apply(SearchHit hit) {
591-
return new ElasticsearchDocumentScore(hit, geoContextMapper);
592-
}
593-
});
592+
return Iterables.transform(hits,
593+
(Function<SearchHit, DocumentScore>) hit -> new ElasticsearchDocumentScore(hit, geoContextMapper));
594594
}
595595

596596
/**
@@ -701,13 +701,8 @@ protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, I
701701

702702
SearchRequestBuilder request = client.prepareSearch();
703703
SearchHits hits = search(request, QueryBuilders.boolQuery().must(qb).filter(fb));
704-
return Iterables.transform(hits, new Function<>() {
705-
706-
@Override
707-
public DocumentResult apply(SearchHit hit) {
708-
return new ElasticsearchDocumentResult(hit, geoContextMapper);
709-
}
710-
});
704+
return Iterables.transform(hits,
705+
(Function<SearchHit, DocumentResult>) hit -> new ElasticsearchDocumentResult(hit, geoContextMapper));
711706
}
712707

713708
private ShapeRelation toSpatialOp(String relation) {
@@ -735,30 +730,35 @@ public SearchHits search(SearchRequestBuilder request, QueryBuilder query) {
735730
*/
736731
public SearchHits search(SearchRequestBuilder request, QueryBuilder query, int numDocs) {
737732
String[] types = getTypes();
738-
int nDocs;
739-
if (numDocs > 0) {
740-
if (maxDocs > 0 && maxDocs < numDocs) {
741-
nDocs = maxDocs;
742-
} else {
743-
nDocs = numDocs;
744-
}
745-
} else if (defaultNumDocs > 0) {
746-
nDocs = defaultNumDocs;
747-
} else {
733+
734+
if (numDocs < -1) {
735+
throw new IllegalArgumentException("numDocs should be 0 or greater if defined by the user");
736+
}
737+
738+
int size = defaultNumDocs;
739+
if (numDocs >= 0) {
740+
// If the user has set numDocs we will use that. If it is 0 then the implementation may end up throwing an
741+
// exception.
742+
size = Math.min(maxDocs, numDocs);
743+
}
744+
745+
if (size < 0) {
746+
// defaultNumDocs is not set
748747
long docCount = client.prepareSearch(indexName)
749748
.setTypes(types)
750749
.setSource(new SearchSourceBuilder().size(0).query(query))
751750
.get()
752751
.getHits()
753752
.getTotalHits().value;
754-
nDocs = Math.max((int) Math.min(docCount, Integer.MAX_VALUE), 1);
753+
size = Math.max((int) Math.min(docCount, maxDocs), 1);
755754
}
755+
756756
SearchResponse response = request.setIndices(indexName)
757757
.setTypes(types)
758758
.setVersion(false)
759759
.seqNoAndPrimaryTerm(true)
760760
.setQuery(query)
761-
.setSize(nDocs)
761+
.setSize(size)
762762
.execute()
763763
.actionGet();
764764
return response.getHits();

core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/AbstractSearchIndex.java

+33-11
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import org.eclipse.rdf4j.query.MalformedQueryException;
4242
import org.eclipse.rdf4j.query.algebra.Var;
4343
import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
44+
import org.eclipse.rdf4j.sail.Sail;
4445
import org.eclipse.rdf4j.sail.SailException;
4546
import org.eclipse.rdf4j.sail.lucene.util.MapOfListMaps;
4647
import org.locationtech.spatial4j.context.SpatialContext;
@@ -65,8 +66,8 @@ public abstract class AbstractSearchIndex implements SearchIndex {
6566
REJECTED_DATATYPES.add("http://www.w3.org/2001/XMLSchema#float");
6667
}
6768

68-
protected int defaultNumDocs;
69-
protected int maxDocs;
69+
protected int defaultNumDocs = -1;
70+
protected int maxDocs = Integer.MAX_VALUE;
7071

7172
protected Set<String> wktFields = Collections.singleton(SearchFields.getPropertyField(GEO.AS_WKT));
7273

@@ -77,9 +78,28 @@ public abstract class AbstractSearchIndex implements SearchIndex {
7778
@Override
7879
public void initialize(Properties parameters) throws Exception {
7980
String maxDocumentsParam = parameters.getProperty(LuceneSail.MAX_DOCUMENTS_KEY);
80-
maxDocs = (maxDocumentsParam != null) ? Integer.parseInt(maxDocumentsParam) : -1;
8181
String defaultNumDocsParam = parameters.getProperty(LuceneSail.DEFAULT_NUM_DOCS_KEY);
82-
defaultNumDocs = (defaultNumDocsParam != null) ? Integer.parseInt(defaultNumDocsParam) : defaultNumDocs;
82+
83+
if ((maxDocumentsParam != null)) {
84+
maxDocs = Integer.parseInt(maxDocumentsParam);
85+
86+
// if maxDocs is set then defaultNumDocs is set to maxDocs if it is not set, because we now have a known
87+
// upper limit
88+
defaultNumDocs = (defaultNumDocsParam != null) ? Math.min(maxDocs, Integer.parseInt(defaultNumDocsParam))
89+
: maxDocs;
90+
} else {
91+
// we can never return more than Integer.MAX_VALUE documents
92+
maxDocs = Integer.MAX_VALUE;
93+
94+
// legacy behaviour is to return the number of documents that the query would return if there was no limit,
95+
// so if the defaultNumDocs is not set, we set it to -1 to signal that there is no limit
96+
defaultNumDocs = (defaultNumDocsParam != null) ? Integer.parseInt(defaultNumDocsParam) : -1;
97+
}
98+
99+
if (defaultNumDocs > maxDocs) {
100+
throw new IllegalArgumentException(LuceneSail.DEFAULT_NUM_DOCS_KEY + " must be less than or equal to "
101+
+ LuceneSail.MAX_DOCUMENTS_KEY + " (" + defaultNumDocs + " > " + maxDocs + ")");
102+
}
83103

84104
String wktFieldParam = parameters.getProperty(LuceneSail.WKT_FIELDS);
85105
if (wktFieldParam != null) {
@@ -149,7 +169,7 @@ public boolean accept(Literal literal) {
149169

150170
// we reject literals that aren't in the list of the indexed lang
151171
if (indexedLangs != null
152-
&& (!literal.getLanguage().isPresent()
172+
&& (literal.getLanguage().isEmpty()
153173
|| !indexedLangs.contains(literal.getLanguage().get().toLowerCase()
154174
))) {
155175
return false;
@@ -356,11 +376,8 @@ public final synchronized void addRemoveStatements(Collection<Statement> added,
356376
// remove value from both property field and the
357377
// corresponding text field
358378
String field = SearchFields.getPropertyField(r.getPredicate());
359-
Set<String> removedValues = removedOfResource.get(field);
360-
if (removedValues == null) {
361-
removedValues = new HashSet<>();
362-
removedOfResource.put(field, removedValues);
363-
}
379+
Set<String> removedValues = removedOfResource.computeIfAbsent(field,
380+
k -> new HashSet<>());
364381
removedValues.add(val);
365382
}
366383
}
@@ -548,7 +565,8 @@ private Iterable<? extends DocumentScore> evaluateQuery(QuerySpec query) {
548565
hits = query(query.getSubject(), query);
549566
}
550567
} catch (Exception e) {
551-
logger.error("There was a problem evaluating query '" + query.getCatQuery() + "'!", e);
568+
logger.error("There was a problem evaluating query '{}'!", query.getCatQuery(), e);
569+
assert false : "There was a problem evaluating query '" + query.getCatQuery() + "'!";
552570
}
553571

554572
return hits;
@@ -720,6 +738,8 @@ private Iterable<? extends DocumentDistance> evaluateQuery(DistanceQuerySpec que
720738
} catch (Exception e) {
721739
logger.error("There was a problem evaluating distance query 'within " + distance + getUnitSymbol(units)
722740
+ " of " + from.getLabel() + "'!", e);
741+
assert false : "There was a problem evaluating distance query 'within " + distance + getUnitSymbol(units)
742+
+ " of " + from.getLabel() + "'!";
723743
}
724744

725745
return hits;
@@ -828,6 +848,8 @@ private Iterable<? extends DocumentResult> evaluateQuery(GeoRelationQuerySpec qu
828848
} catch (Exception e) {
829849
logger.error("There was a problem evaluating spatial relation query '" + query.getRelation() + " "
830850
+ qgeom.getLabel() + "'!", e);
851+
assert false : "There was a problem evaluating spatial relation query '" + query.getRelation() + " "
852+
+ qgeom.getLabel() + "'!";
831853
}
832854

833855
return hits;

core/sail/lucene/src/main/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneIndex.java

+24-13
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,17 @@ protected Iterable<? extends DocumentScore> query(Resource subject, QuerySpec sp
752752
highlighter = null;
753753
}
754754

755-
int numDocs = Objects.requireNonNullElse(spec.getNumDocs(), -1);
755+
int numDocs;
756+
757+
Integer specNumDocs = spec.getNumDocs();
758+
if (specNumDocs != null) {
759+
if (specNumDocs < 0) {
760+
throw new IllegalArgumentException("numDocs must be >= 0");
761+
}
762+
numDocs = specNumDocs;
763+
} else {
764+
numDocs = -1;
765+
}
756766

757767
TopDocs docs;
758768
if (subject != null) {
@@ -1004,19 +1014,20 @@ public synchronized TopDocs search(Query query) throws IOException {
10041014
* @throws IOException
10051015
*/
10061016
public synchronized TopDocs search(Query query, int numDocs) throws IOException {
1007-
int nDocs;
1008-
if (numDocs > 0) {
1009-
if (maxDocs > 0 && maxDocs < numDocs) {
1010-
nDocs = maxDocs;
1011-
} else {
1012-
nDocs = numDocs;
1013-
}
1014-
} else if (defaultNumDocs > 0) {
1015-
nDocs = defaultNumDocs;
1016-
} else {
1017-
nDocs = Math.max(getIndexReader().numDocs(), 1);
1017+
if (numDocs < -1) {
1018+
throw new IllegalArgumentException("numDocs should be 0 or greater if defined by the user");
1019+
}
1020+
1021+
int size = defaultNumDocs;
1022+
if (numDocs >= 0) {
1023+
// If the user has set numDocs we will use that. If it is 0 then the implementation may end up throwing an
1024+
// exception.
1025+
size = Math.min(maxDocs, numDocs);
1026+
}
1027+
if (size < 0) {
1028+
size = Math.max(getIndexReader().numDocs(), 1);
10181029
}
1019-
return getIndexSearcher().search(query, nDocs);
1030+
return getIndexSearcher().search(query, size);
10201031
}
10211032

10221033
private QueryParser getQueryParser(IRI propertyURI) {

core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/constraintcomponents/UniqueLangConstraintComponent.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ public PlanNode generateTransactionalValidationPlan(ConnectionsGroup connections
120120
connectionsGroup.getRdfsSubClassOfReasoner(), stableRandomVariableProvider);
121121
Optional<Path> path = getTargetChain().getPath();
122122

123-
if (!path.isPresent() || scope != Scope.propertyShape) {
123+
if (path.isEmpty() || scope != Scope.propertyShape) {
124124
throw new IllegalStateException("UniqueLang only operates on paths");
125125
}
126126

core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NonUniqueTargetLang.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ private void calculateNext() {
149149
if (value.isLiteral()) {
150150
Optional<String> lang = ((Literal) value).getLanguage();
151151

152-
if (!lang.isPresent()) {
152+
if (lang.isEmpty()) {
153153
next = null;
154154
} else if (!seenLanguages.contains(lang.get())) {
155155
seenLanguages.add(lang.get());

core/sail/solr/src/main/java/org/eclipse/rdf4j/sail/solr/SolrIndex.java

+14-12
Original file line numberDiff line numberDiff line change
@@ -583,20 +583,22 @@ public QueryResponse search(SolrQuery query) throws SolrServerException, IOExcep
583583
* @throws IOException
584584
*/
585585
public QueryResponse search(SolrQuery query, int numDocs) throws SolrServerException, IOException {
586-
int nDocs;
587-
if (numDocs > 0) {
588-
if (maxDocs > 0 && maxDocs < numDocs) {
589-
nDocs = maxDocs;
590-
} else {
591-
nDocs = numDocs;
592-
}
593-
} else if (defaultNumDocs > 0) {
594-
nDocs = defaultNumDocs;
595-
} else {
586+
if (numDocs < -1) {
587+
throw new IllegalArgumentException("numDocs should be 0 or greater if defined by the user");
588+
}
589+
590+
int size = defaultNumDocs;
591+
if (numDocs >= 0) {
592+
// If the user has set numDocs we will use that. If it is 0 then the implementation may end up throwing an
593+
// exception.
594+
size = Math.min(maxDocs, numDocs);
595+
}
596+
597+
if (size < 0) {
596598
long docCount = client.query(query.setRows(0)).getResults().getNumFound();
597-
nDocs = Math.max((int) Math.min(docCount, Integer.MAX_VALUE), 1);
599+
size = Math.max((int) Math.min(docCount, maxDocs), 1);
598600
}
599-
return client.query(query.setRows(nDocs));
601+
return client.query(query.setRows(size));
600602
}
601603

602604
private SolrQuery prepareQuery(IRI propertyURI, SolrQuery query) {

0 commit comments

Comments
 (0)