Skip to content

Commit 4e8d537

Browse files
calixtuskoppor
andauthored
Fix Nullwarnings - A (#14116)
* Fix some null warnings * Remove artifact * Fix nullwarnings in FetcherException ISIDOREFetcher and ResearchGate * Undo newline * Introduce constant * Add link to related classes --------- Co-authored-by: Carl Christian Snethlage <[email protected]> Co-authored-by: Oliver Kopp <[email protected]>
1 parent e91fd89 commit 4e8d537

File tree

9 files changed

+54
-45
lines changed

9 files changed

+54
-45
lines changed

jablib/src/main/java/org/jabref/logic/ai/AiPreferences.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ public AiPreferences(boolean enableAi,
116116
this.ragMaxResultsCount = new SimpleIntegerProperty(ragMaxResultsCount);
117117
this.ragMinScore = new SimpleDoubleProperty(ragMinScore);
118118

119+
this.apiKeyChangeListener = () -> {
120+
};
121+
119122
this.templates = Map.of(
120123
AiTemplate.CHATTING_SYSTEM_MESSAGE, new SimpleStringProperty(templates.get(AiTemplate.CHATTING_SYSTEM_MESSAGE)),
121124
AiTemplate.CHATTING_USER_MESSAGE, new SimpleStringProperty(templates.get(AiTemplate.CHATTING_USER_MESSAGE)),
@@ -550,14 +553,14 @@ public void apiKeyUpdated() {
550553
}
551554

552555
public void setTemplate(AiTemplate aiTemplate, String template) {
553-
templates.get(aiTemplate).set(template);
556+
templateProperty(aiTemplate).set(template);
554557
}
555558

556559
public String getTemplate(AiTemplate aiTemplate) {
557-
return templates.get(aiTemplate).get();
560+
return templateProperty(aiTemplate).get();
558561
}
559562

560563
public StringProperty templateProperty(AiTemplate aiTemplate) {
561-
return templates.get(aiTemplate);
564+
return templates.getOrDefault(aiTemplate, new SimpleStringProperty(""));
562565
}
563566
}

jablib/src/main/java/org/jabref/logic/ai/ingestion/MVStoreEmbeddingStore.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@
4444
* <p>
4545
*/
4646
public class MVStoreEmbeddingStore extends MVStoreBase implements EmbeddingStore<TextSegment> {
47+
48+
private static final EmbeddingRecord EMPTY_EMBEDDING_RECORD = new EmbeddingRecord(null, "", new float[0]);
49+
4750
// `file` field is nullable, because {@link Optional} can't be serialized.
4851
private record EmbeddingRecord(@Nullable String file, String content, float[] embeddingVector) implements Serializable {
4952
}
@@ -125,7 +128,7 @@ public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request)
125128
PriorityQueue<EmbeddingMatch<TextSegment>> matches = new PriorityQueue<>(comparator);
126129

127130
applyFilter(request.filter()).forEach(id -> {
128-
EmbeddingRecord eRecord = embeddingsMap.get(id);
131+
EmbeddingRecord eRecord = embeddingsMap.getOrDefault(id, EMPTY_EMBEDDING_RECORD);
129132

130133
double cosineSimilarity = CosineSimilarity.between(Embedding.from(eRecord.embeddingVector), request.queryEmbedding());
131134
double score = RelevanceScore.fromCosineSimilarity(cosineSimilarity);

jablib/src/main/java/org/jabref/logic/ai/ingestion/model/JabRefEmbeddingModel.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,15 @@ public void startRebuildingTask() {
7474
predictorProperty.set(Optional.empty());
7575

7676
new UpdateEmbeddingModelTask(aiPreferences, predictorProperty)
77-
.onSuccess(v -> {
77+
.onSuccess(_ -> {
7878
LOGGER.info("Embedding model was successfully updated");
7979
errorWhileBuildingModel = "";
8080
eventBus.post(new EmbeddingModelBuiltEvent());
8181
})
8282
.onFailure(e -> {
8383
LOGGER.error("An error occurred while building the embedding model", e);
8484
notificationService.notify(Localization.lang("An error occurred while building the embedding model"));
85-
errorWhileBuildingModel = e.getMessage();
85+
errorWhileBuildingModel = e.getMessage() == null ? "" : e.getMessage();
8686
eventBus.post(new EmbeddingModelBuildingErrorEvent());
8787
})
8888
.executeWith(taskExecutor);

jablib/src/main/java/org/jabref/logic/ai/util/MVStoreBase.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import org.h2.mvstore.MVStore;
1010
import org.h2.mvstore.MVStoreException;
11-
import org.jspecify.annotations.Nullable;
11+
import org.jspecify.annotations.NonNull;
1212
import org.slf4j.Logger;
1313
import org.slf4j.LoggerFactory;
1414

@@ -17,7 +17,7 @@ public abstract class MVStoreBase implements AutoCloseable {
1717

1818
protected MVStore mvStore;
1919

20-
public MVStoreBase(@Nullable Path path, NotificationService dialogService) {
20+
public MVStoreBase(@NonNull Path path, NotificationService dialogService) {
2121
Path mvStorePath = path;
2222

2323
try {

jablib/src/main/java/org/jabref/logic/importer/FetcherException.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.jabref.logic.util.strings.StringUtil;
1010
import org.jabref.model.http.SimpleHttpResponse;
1111

12+
import org.jspecify.annotations.Nullable;
1213
import org.slf4j.Logger;
1314
import org.slf4j.LoggerFactory;
1415

@@ -18,10 +19,13 @@ public class FetcherException extends JabRefException {
1819
private static final Pattern API_KEY_PATTERN = Pattern.compile("(?i)(?<" + API_KEY_PARAM_NAME + ">api|key|api[-_]?key)=[^&]*");
1920
private static final String REDACTED_STRING = "[REDACTED]";
2021

22+
@Nullable
2123
private final String url;
24+
25+
@Nullable
2226
private final SimpleHttpResponse httpResponse;
2327

24-
public FetcherException(String url, SimpleHttpResponse httpResponse) {
28+
public FetcherException(@Nullable String url, @Nullable SimpleHttpResponse httpResponse) {
2529
// Empty string handled at org.jabref.logic.importer.FetcherException.getPrefix.
2630
super("");
2731
this.url = url;
@@ -87,7 +91,7 @@ public String getLocalizedMessage() {
8791
}
8892

8993
String getRedactedUrl() {
90-
return getRedactedUrl(url);
94+
return getRedactedUrl(url == null ? "" : url);
9195
}
9296

9397
public static String getRedactedUrl(String source) {

jablib/src/main/java/org/jabref/logic/importer/fetcher/ISIDOREFetcher.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ public Parser getParser() {
8282
} catch (ParserConfigurationException | IOException | SAXException e) {
8383
Unchecked.throwChecked(new FetcherException("Issue with parsing link", e));
8484
}
85-
return null;
85+
return List.of();
8686
};
8787
}
8888

jablib/src/main/java/org/jabref/logic/importer/fetcher/ResearchGate.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ public List<BibEntry> performSearch(BaseQueryNode queryNode) throws FetcherExcep
221221
html = getPage(url);
222222
// ResearchGate's server blocks when too many request are made
223223
if (!html.getElementsByClass("nova-legacy-v-publication-item__title").hasText()) {
224-
throw new FetcherException(url, "Required HTML element not found", null);
224+
throw new FetcherException(url, "Required HTML element not found", new IllegalStateException("Missing element"));
225225
}
226226
} catch (IOException e) {
227227
throw new FetcherException(url, e);
@@ -230,11 +230,13 @@ public List<BibEntry> performSearch(BaseQueryNode queryNode) throws FetcherExcep
230230
Elements sol = html.getElementsByClass("nova-legacy-v-publication-item__title");
231231
List<String> urls = sol.select("a").eachAttr("href").stream()
232232
.filter(stream -> stream.contains("publication/"))
233-
.map(resultStream -> resultStream.substring(resultStream.indexOf("publication/") + 12, resultStream.indexOf("_")))
233+
.map(resultStream -> resultStream.substring(
234+
resultStream.indexOf("publication/") + 12,
235+
resultStream.indexOf("_")))
234236
.map(idStream -> SEARCH_FOR_BIB_ENTRY + idStream)
235237
.map(this::getInputStream)
236-
.filter(Objects::nonNull)
237-
.map(stream -> stream.lines().collect(Collectors.joining(OS.NEWLINE)))
238+
.flatMap(Optional::stream)
239+
.map(reader -> reader.lines().collect(Collectors.joining(OS.NEWLINE)))
238240
.toList();
239241

240242
List<BibEntry> list = new ArrayList<>();
@@ -251,14 +253,14 @@ public List<BibEntry> performSearch(BaseQueryNode queryNode) throws FetcherExcep
251253
return list;
252254
}
253255

254-
private BufferedReader getInputStream(String urlString) {
256+
private Optional<BufferedReader> getInputStream(String urlString) {
255257
try {
256258
URL url = URLUtil.create(urlString);
257-
return new BufferedReader(new InputStreamReader(url.openStream()));
259+
return Optional.of(new BufferedReader(new InputStreamReader(url.openStream())));
258260
} catch (IOException e) {
259261
LOGGER.debug("Wrong URL", e);
262+
return Optional.empty();
260263
}
261-
return null;
262264
}
263265

264266
@Override

jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.jabref.model.study.Study;
3333

3434
import org.jspecify.annotations.NonNull;
35+
import org.jspecify.annotations.Nullable;
3536
import org.slf4j.Logger;
3637
import org.slf4j.LoggerFactory;
3738

@@ -62,9 +63,12 @@ public class BibDatabaseContext {
6263
/**
6364
* The path where this database was last saved to.
6465
*/
66+
@Nullable
6567
private Path path;
6668

69+
@Nullable
6770
private DatabaseSynchronizer dbmsSynchronizer;
71+
@Nullable
6872
private CoarseChangeFilter dbmsListener;
6973
private DatabaseLocation location;
7074

@@ -223,10 +227,15 @@ private Path getFileDirectoryPath(String directory) {
223227

224228
// If this path is relative, we try to interpret it as relative to the file path of this BIB file:
225229
return getDatabasePath()
226-
.map(databaseFile -> databaseFile.getParent().resolve(path).normalize().toAbsolutePath())
230+
.map(databaseFile -> Optional.ofNullable(databaseFile.getParent())
231+
.orElse(Path.of(""))
232+
.resolve(path)
233+
.normalize()
234+
.toAbsolutePath())
227235
.orElse(path);
228236
}
229237

238+
@Nullable
230239
public DatabaseSynchronizer getDBMSSynchronizer() {
231240
return this.dbmsSynchronizer;
232241
}
@@ -250,7 +259,9 @@ public void convertToSharedDatabase(DatabaseSynchronizer dmbsSynchronizer) {
250259

251260
public void convertToLocalDatabase() {
252261
if (dbmsListener != null && (location == DatabaseLocation.SHARED)) {
253-
dbmsListener.unregisterListener(dbmsSynchronizer);
262+
if (dbmsSynchronizer != null) {
263+
dbmsListener.unregisterListener(dbmsSynchronizer);
264+
}
254265
dbmsListener.shutdown();
255266
}
256267

jablib/src/main/java/org/jabref/model/entry/field/StandardField.java

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
import java.util.Set;
99

1010
/// Standard BibTeX and BibLaTeX fields, as well as "normal" JabRef specific fields.
11-
/// See `org.jabref.gui.fieldeditors.FieldNameLabel#getDescription(org.jabref.model.entry.field.Field)` for a description of each field.
11+
/// See [org.jabref.model.entry.field.FieldTextMapper] for the display name creation.
12+
/// See [org.jabref.gui.fieldeditors.FieldNameLabel#getDescription(org.jabref.model.entry.field.Field)] for a description of each field.
1213
public enum StandardField implements Field {
1314
ABSTRACT("abstract", FieldProperty.MULTILINE_TEXT),
1415
ADDENDUM("addendum"),
@@ -34,7 +35,7 @@ public enum StandardField implements Field {
3435
DATE("date", FieldProperty.DATE),
3536
DAY("day"),
3637
DAYFILED("dayfiled"),
37-
DOI("doi", "DOI", FieldProperty.VERBATIM, FieldProperty.IDENTIFIER),
38+
DOI("doi", FieldProperty.VERBATIM, FieldProperty.IDENTIFIER),
3839
EDITION("edition", FieldProperty.NUMERIC),
3940
EDITOR("editor", FieldProperty.PERSON_NAMES),
4041
EDITORA("editora", FieldProperty.PERSON_NAMES),
@@ -64,9 +65,9 @@ public enum StandardField implements Field {
6465
IDS("ids", FieldProperty.MULTIPLE_ENTRY_LINK),
6566
INSTITUTION("institution"),
6667
INTRODUCTION("introduction", FieldProperty.PERSON_NAMES),
67-
ISBN("isbn", "ISBN", FieldProperty.VERBATIM),
68-
ISRN("isrn", "ISRN", FieldProperty.VERBATIM),
69-
ISSN("issn", "ISSN", FieldProperty.VERBATIM),
68+
ISBN("isbn", FieldProperty.VERBATIM),
69+
ISRN("isrn", FieldProperty.VERBATIM),
70+
ISSN("issn", FieldProperty.VERBATIM),
7071
ISSUE("issue"),
7172
ISSUETITLE("issuetitle"),
7273
ISSUESUBTITLE("issuesubtitle"),
@@ -96,9 +97,9 @@ public enum StandardField implements Field {
9697
PAGETOTAL("pagetotal", FieldProperty.NUMERIC),
9798
PAGINATION("pagination", FieldProperty.PAGINATION),
9899
PART("part"),
99-
PDF("pdf", "PDF"),
100-
PMID("pmid", "PMID", FieldProperty.NUMERIC, FieldProperty.IDENTIFIER),
101-
PS("ps", "PS"),
100+
PDF("pdf"),
101+
PMID("pmid", FieldProperty.NUMERIC, FieldProperty.IDENTIFIER),
102+
PS("ps"),
102103
PUBLISHER("publisher"),
103104
PUBSTATE("pubstate"),
104105
PRIMARYCLASS("primaryclass"),
@@ -118,8 +119,8 @@ public enum StandardField implements Field {
118119
TITLEADDON("titleaddon"),
119120
TRANSLATOR("translator", FieldProperty.PERSON_NAMES),
120121
TYPE("type"),
121-
URI("uri", "URI", FieldProperty.EXTERNAL, FieldProperty.VERBATIM),
122-
URL("url", "URL", FieldProperty.EXTERNAL, FieldProperty.VERBATIM),
122+
URI("uri", FieldProperty.EXTERNAL, FieldProperty.VERBATIM),
123+
URL("url", FieldProperty.EXTERNAL, FieldProperty.VERBATIM),
123124
URLDATE("urldate", FieldProperty.DATE),
124125
VENUE("venue"),
125126
VERSION("version"),
@@ -152,7 +153,6 @@ public enum StandardField implements Field {
152153
private static final Map<String, StandardField> NAME_TO_STANDARD_FIELD = new HashMap<>();
153154

154155
private final String name;
155-
private final String displayName;
156156
private final EnumSet<FieldProperty> properties;
157157

158158
static {
@@ -163,25 +163,11 @@ public enum StandardField implements Field {
163163

164164
StandardField(String name) {
165165
this.name = name;
166-
this.displayName = null;
167166
this.properties = EnumSet.noneOf(FieldProperty.class);
168167
}
169168

170-
StandardField(String name, String displayName) {
171-
this.name = name;
172-
this.displayName = displayName;
173-
this.properties = EnumSet.noneOf(FieldProperty.class);
174-
}
175-
176-
StandardField(String name, String displayName, FieldProperty first, FieldProperty... rest) {
177-
this.name = name;
178-
this.displayName = displayName;
179-
this.properties = EnumSet.of(first, rest);
180-
}
181-
182169
StandardField(String name, FieldProperty first, FieldProperty... rest) {
183170
this.name = name;
184-
this.displayName = null;
185171
this.properties = EnumSet.of(first, rest);
186172
}
187173

0 commit comments

Comments
 (0)