diff --git a/jabgui/src/main/java/org/jabref/Launcher.java b/jabgui/src/main/java/org/jabref/Launcher.java index a561a4cad32..04f6af8bf54 100644 --- a/jabgui/src/main/java/org/jabref/Launcher.java +++ b/jabgui/src/main/java/org/jabref/Launcher.java @@ -105,7 +105,7 @@ public static void initLogging(String[] args) { // We must configure logging as soon as possible, which is why we cannot wait for the usual // argument parsing workflow to parse logging options e.g. --debug - boolean isDebugEnabled = Arrays.stream(args).anyMatch(arg -> "--debug".equalsIgnoreCase(arg)); + boolean isDebugEnabled = Arrays.stream(args).anyMatch("--debug"::equalsIgnoreCase); // addLogToDisk // We cannot use `Injector.instantiateModelOrService(BuildInfo.class).version` here, because this initializes logging diff --git a/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java b/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java index c58ffda2849..10a186aba44 100644 --- a/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java +++ b/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java @@ -28,8 +28,8 @@ public PersonNameStringConverter(AutoCompletePreferences preferences) { autoCompFF = false; autoCompLF = true; break; - default: case BOTH: + default: autoCompFF = true; autoCompLF = true; break; @@ -42,24 +42,20 @@ public PersonNameStringConverter(AutoCompletePreferences preferences) { public String toString(Author author) { if (autoCompLF) { switch (autoCompleteFirstNameMode) { - case ONLY_ABBREVIATED: + case ONLY_ABBREVIATED, BOTH: return author.getFamilyGiven(true); case ONLY_FULL: return author.getFamilyGiven(false); - case BOTH: - return author.getFamilyGiven(true); default: break; } } if (autoCompFF) { switch (autoCompleteFirstNameMode) { - case ONLY_ABBREVIATED: + case ONLY_ABBREVIATED, BOTH: return author.getGivenFamily(true); case ONLY_FULL: return author.getGivenFamily(false); - case BOTH: - return author.getGivenFamily(true); default: break; } diff --git a/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternSuggestionCell.java b/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternSuggestionCell.java index f8f2958b272..950b9beade3 100644 --- a/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternSuggestionCell.java +++ b/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternSuggestionCell.java @@ -74,14 +74,14 @@ public CitationKeyPatternSuggestionTextField(List citationKeyPatterns) { } private void setListener() { - textProperty().addListener((observable, oldValue, newValue) -> { + textProperty().addListener((_, _, _) -> { String enteredText = getText(); if (enteredText == null || enteredText.isEmpty()) { suggestionsList.hide(); } else { List filteredEntries = citationKeyPatterns.stream() .filter(e -> e.toLowerCase().contains(enteredText.toLowerCase())) - .collect(Collectors.toList()); + .toList(); if (!filteredEntries.isEmpty()) { populatePopup(filteredEntries); @@ -96,9 +96,7 @@ private void setListener() { } }); - focusedProperty().addListener((observable, oldValue, newValue) -> { - suggestionsList.hide(); - }); + focusedProperty().addListener((_, _, _) -> suggestionsList.hide()); } private void populatePopup(List searchResult) { @@ -119,7 +117,7 @@ private void populatePopup(List searchResult) { menuItems.add(item); - item.setOnAction(actionEvent -> { + item.setOnAction(_ -> { setText(result); positionCaret(result.length()); suggestionsList.hide(); diff --git a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java index ba1d8324b75..7924781dc3b 100644 --- a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java @@ -87,11 +87,10 @@ public void initialize() { message.message().getFirst().equals(viewModel.selectedEntryTypeProperty().get()) ); - viewModel.selectedEntryTypeProperty().addListener((obs, oldValue, newValue) -> { - filteredData.setPredicate(message -> - message.message().getFirst().equals(newValue) - ); - }); + viewModel.selectedEntryTypeProperty().addListener((_, _, newValue) -> + filteredData.setPredicate(message -> + message.message().getFirst().equals(newValue) + )); tableView.setItems(filteredData); diff --git a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java index 4e86115007a..5feea960485 100644 --- a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java @@ -45,7 +45,8 @@ public class ConsistencyCheckDialogViewModel extends AbstractViewModel { - private final Logger LOGGER = LoggerFactory.getLogger(ConsistencyCheckDialogViewModel.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ConsistencyCheckDialogViewModel.class); + private static final int EXTRA_COLUMNS_COUNT = 2; private final BibliographyConsistencyCheck.Result result; private final DialogService dialogService; @@ -54,7 +55,6 @@ public class ConsistencyCheckDialogViewModel extends AbstractViewModel { private final List allReportedFields; private final int columnCount; - private final int EXTRA_COLUMNS_COUNT = 2; private final ObservableList tableData = FXCollections.observableArrayList(); private final StringProperty selectedEntryType = new SimpleStringProperty(); @@ -85,9 +85,7 @@ public StringProperty selectedEntryTypeProperty() { public List getEntryTypes() { List entryTypes = new ArrayList<>(); - result.entryTypeToResultMap().forEach((entrySet, entryTypeResult) -> { - entryTypes.add(entrySet.toString()); - }); + result.entryTypeToResultMap().forEach((entrySet, _) -> entryTypes.add(entrySet.toString())); return entryTypes; } @@ -96,7 +94,7 @@ public ObservableList getTableData() { } public Set getColumnNames() { - Set result = new LinkedHashSet<>(columnCount + EXTRA_COLUMNS_COUNT); + Set result = LinkedHashSet.newLinkedHashSet(columnCount + EXTRA_COLUMNS_COUNT); result.add("Entry Type"); result.add("CitationKey"); allReportedFields.forEach(field-> result.add(field.getDisplayName().trim())); @@ -124,12 +122,12 @@ private void writeMapEntry(Map.Entry bibEntries = entries.sortedEntries(); - bibEntries.forEach(Unchecked.consumer(bibEntry -> { - writeBibEntry(bibEntry, entryType, requiredFields, optionalFields); - })); + bibEntries.forEach(Unchecked.consumer(bibEntry -> + writeBibEntry(bibEntry, entryType, requiredFields, optionalFields) + )); } - private void writeBibEntry(BibEntry bibEntry, String entryType, Set requiredFields, Set optionalFields) throws IOException { + private void writeBibEntry(BibEntry bibEntry, String entryType, Set requiredFields, Set optionalFields) { List theRecord = getFindingsAsList(bibEntry, entryType, requiredFields, optionalFields); List message = new ArrayList<>(); for (String s: theRecord) { @@ -143,7 +141,7 @@ private List getFindingsAsList(BibEntry bibEntry, String entryType, Set< List result = new ArrayList<>(columnCount + EXTRA_COLUMNS_COUNT); result.add(entryType); result.add(bibEntry.getCitationKey().orElse("")); - allReportedFields.forEach(field -> { + allReportedFields.forEach(field -> result.add(bibEntry.getField(field).map(_ -> { if (requiredFields.contains(field)) { return ConsistencySymbol.REQUIRED_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); @@ -152,8 +150,8 @@ private List getFindingsAsList(BibEntry bibEntry, String entryType, Set< } else { return ConsistencySymbol.UNKNOWN_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); } - }).orElse(ConsistencySymbol.UNSET_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText())); - }); + }).orElse(ConsistencySymbol.UNSET_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText())) + ); return result; } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java b/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java index c6be070e0e8..48133bb10da 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java @@ -72,7 +72,6 @@ public void execute() { } } else if ((focusOwner instanceof CodeArea) || (focusOwner instanceof WebView)) { LOGGER.debug("Ignoring request in CodeArea or WebView"); - return; } else { LOGGER.debug("Else: {}", focusOwner.getClass().getSimpleName()); // Not sure what is selected -> copy/paste/cut selected entries except for Preview and CodeArea diff --git a/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java b/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java index 223d1efdcb0..dd8579513f0 100644 --- a/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java +++ b/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java @@ -194,11 +194,11 @@ private Optional askForSavePath() { // Workaround for linux systems not adding file extension if (!savePath.getFileName().toString().toLowerCase().endsWith(".bib")) { savePath = Path.of(savePath.toString() + ".bib"); - if (!Files.notExists(savePath)) { - if (!dialogService.showConfirmationDialogAndWait(Localization.lang("Overwrite file"), Localization.lang("'%0' exists. Overwrite file?", savePath.getFileName()))) { + if (!Files.notExists(savePath) && !dialogService.showConfirmationDialogAndWait(Localization.lang("Overwrite file"), + Localization.lang("'%0' exists. Overwrite file?", savePath.getFileName()))) { return Optional.empty(); } - } + selectedPath = Optional.of(savePath); } } @@ -246,7 +246,7 @@ private boolean save(Path targetPath, SaveDatabaseMode mode) { dialogService.notify(Localization.lang("Library saved")); return success; } catch (SaveException ex) { - LOGGER.error("A problem occurred when trying to save the file %s".formatted(targetPath), ex); + LOGGER.error("A problem occurred when trying to save the file {}", targetPath, ex); dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); return false; } finally { @@ -307,7 +307,8 @@ private void saveWithDifferentEncoding(Path file, boolean selectedOnly, Charset .filter(buttonType -> buttonType.equals(tryDifferentEncoding)) .isPresent(); if (saveWithDifferentEncoding) { - Optional newEncoding = dialogService.showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select new encoding"), Localization.lang("Save library"), encoding, Encodings.getCharsets()); + Optional newEncoding = dialogService.showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select new encoding"), + Localization.lang("Save library"), encoding, Encodings.getCharsets()); if (newEncoding.isPresent()) { // Make sure to remember which encoding we used. libraryTab.getBibDatabaseContext().getMetaData().setEncoding(newEncoding.get(), ChangePropagation.DO_NOT_POST_EVENT); diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/ChainedFilters.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/ChainedFilters.java index 4162c9c674f..f612b0c179d 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/ChainedFilters.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/ChainedFilters.java @@ -17,6 +17,7 @@ public class ChainedFilters implements DirectoryStream.Filter { private DirectoryStream.Filter[] filters; + @SafeVarargs public ChainedFilters(DirectoryStream.Filter... filters) { this.filters = filters; } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java index 93986d5743e..b31b035d702 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java @@ -2,6 +2,7 @@ import java.io.File; import java.io.IOException; +import java.nio.file.DirectoryStream; import java.nio.file.DirectoryStream.Filter; import java.nio.file.Files; import java.nio.file.Path; @@ -91,7 +92,8 @@ FileNodeViewModel searchDirectory(Path directory, UnlinkedPDFFileFilter unlinked // 2. GitIgnoreFilter ChainedFilters filters = new ChainedFilters(unlinkedPDFFileFilter, new GitIgnoreFileFilter(directory)); Map> directoryAndFilePartition; - try (Stream filesStream = StreamSupport.stream(Files.newDirectoryStream(directory, filters).spliterator(), false)) { + try (DirectoryStream dirStream = Files.newDirectoryStream(directory, filters); + Stream filesStream = StreamSupport.stream(dirStream.spliterator(), false)) { directoryAndFilePartition = filesStream.collect(Collectors.partitioningBy(Files::isDirectory)); } catch (IOException e) { LOGGER.error("Error while searching files", e); @@ -136,7 +138,7 @@ FileNodeViewModel searchDirectory(Path directory, UnlinkedPDFFileFilter unlinked // create and add FileNodeViewModel to the FileNodeViewModel for the current directory fileNodeViewModelForCurrentDirectory.getChildren().addAll(resultingFiles.stream() .map(FileNodeViewModel::new) - .collect(Collectors.toList())); + .toList()); return fileNodeViewModelForCurrentDirectory; } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java index f91fda5f2fa..aadd9f52f3a 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java @@ -142,7 +142,7 @@ public KeywordsEditor(Field field, KeyBindingRepository keyBindingRepository = Injector.instantiateModelOrService(KeyBindingRepository.class); if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.PASTE, event)) { - String clipboardText = clipBoardManager.getContents(); + String clipboardText = ClipBoardManager.getContents(); if (!clipboardText.isEmpty()) { KeywordList keywordsList = KeywordList.parse(clipboardText, viewModel.getKeywordSeparator()); keywordsList.stream().forEach(keyword -> keywordTagsField.addTags(keyword)); diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/optioneditors/mapbased/MapBasedEditorViewModel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/optioneditors/mapbased/MapBasedEditorViewModel.java index 95a00ac2180..bf263402c30 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/optioneditors/mapbased/MapBasedEditorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/optioneditors/mapbased/MapBasedEditorViewModel.java @@ -63,7 +63,8 @@ protected T getValueFromString(String string) { try { return (T) string; } catch (ClassCastException ex) { - LOGGER.error("Could not cast string to type %1$s. Try overriding the method in a subclass and provide a conversion from string to the concrete type %1$s".formatted(string.getClass()), ex); + LOGGER.error("Could not cast string to type {}. Try overriding the method in a subclass and provide a conversion from string to the concrete type {}", + string.getClass(), string.getClass(), ex); } return null; } diff --git a/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java index dd8ef20c091..79c0d84a548 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java @@ -164,7 +164,7 @@ private void setupValidation() { } // Edit group, changed name to something that is already present - return (editedGroup == null) || editedGroup.getName().equals(name) || (groupsWithSameName <= 0); + return (editedGroup == null) || editedGroup.getName().equals(name) || (groupsWithSameName == 0); } return true; }, @@ -176,7 +176,7 @@ private void setupValidation() { keywordRegexValidator = new FunctionBasedValidator<>( keywordGroupSearchTermProperty, input -> { - if (!keywordGroupRegexProperty.getValue()) { + if (Boolean.FALSE.equals(keywordGroupRegexProperty.getValue())) { return true; } @@ -187,7 +187,7 @@ private void setupValidation() { try { Pattern.compile(input); return true; - } catch (PatternSyntaxException ignored) { + } catch (PatternSyntaxException _) { return false; } }, @@ -237,24 +237,24 @@ private void setupValidation() { }, ValidationMessage.error(Localization.lang("Please provide a valid aux file."))); - typeSearchProperty.addListener((obs, _oldValue, isSelected) -> { - if (isSelected) { + typeSearchProperty.addListener((_, _, isSelected) -> { + if (Boolean.TRUE.equals(isSelected)) { validator.addValidators(searchSearchTermEmptyValidator); } else { validator.removeValidators(searchSearchTermEmptyValidator); } }); - typeKeywordsProperty.addListener((obs, _oldValue, isSelected) -> { - if (isSelected) { + typeKeywordsProperty.addListener((_, _, isSelected) -> { + if (Boolean.TRUE.equals(isSelected)) { validator.addValidators(keywordFieldEmptyValidator, keywordRegexValidator, keywordSearchTermEmptyValidator); } else { validator.removeValidators(keywordFieldEmptyValidator, keywordRegexValidator, keywordSearchTermEmptyValidator); } }); - typeTexProperty.addListener((obs, oldValue, isSelected) -> { - if (isSelected) { + typeTexProperty.addListener((_, _, isSelected) -> { + if (Boolean.TRUE.equals(isSelected)) { validator.addValidators(texGroupFilePathValidator); } else { validator.removeValidators(texGroupFilePathValidator); @@ -279,8 +279,9 @@ private Path getAbsoluteTexGroupPath(String input) { public void validationHandler(Event event) { ValidationStatus validationStatus = validator.getValidationStatus(); - if (validationStatus.getHighestMessage().isPresent()) { - dialogService.showErrorDialogAndWait(validationStatus.getHighestMessage().get().getMessage()); + Optional highestMessage = validationStatus.getHighestMessage(); + if (highestMessage.isPresent()) { + dialogService.showErrorDialogAndWait(highestMessage.get().getMessage()); // consume the event to prevent the dialog to close event.consume(); } @@ -294,13 +295,13 @@ public AbstractGroup resultConverter(ButtonType button) { AbstractGroup resultingGroup = null; try { String groupName = nameProperty.getValue().trim(); - if (typeExplicitProperty.getValue()) { + if (Boolean.TRUE.equals(typeExplicitProperty.getValue())) { resultingGroup = new ExplicitGroup( groupName, groupHierarchySelectedProperty.getValue(), preferences.getBibEntryPreferences().getKeywordSeparator()); - } else if (typeKeywordsProperty.getValue()) { - if (keywordGroupRegexProperty.getValue()) { + } else if (Boolean.TRUE.equals(typeKeywordsProperty.getValue())) { + if (Boolean.TRUE.equals(keywordGroupRegexProperty.getValue())) { resultingGroup = new RegexKeywordGroup( groupName, groupHierarchySelectedProperty.getValue(), @@ -317,7 +318,7 @@ public AbstractGroup resultConverter(ButtonType button) { preferences.getBibEntryPreferences().getKeywordSeparator(), false); } - } else if (typeSearchProperty.getValue()) { + } else if (Boolean.TRUE.equals(typeSearchProperty.getValue())) { resultingGroup = new SearchGroup( groupName, groupHierarchySelectedProperty.getValue(), @@ -340,8 +341,8 @@ public AbstractGroup resultConverter(ButtonType button) { SearchGroup searchGroup = (SearchGroup) resultingGroup; searchGroup.setMatchedEntries(indexManager.get().search(searchGroup.getSearchQuery()).getMatchedEntries()); } - } else if (typeAutoProperty.getValue()) { - if (autoGroupKeywordsOptionProperty.getValue()) { + } else if (Boolean.TRUE.equals(typeAutoProperty.getValue())) { + if (Boolean.TRUE.equals(autoGroupKeywordsOptionProperty.getValue())) { // Set default value for delimiters: ',' for base and '>' for hierarchical char delimiter = ','; char hierarDelimiter = Keyword.DEFAULT_HIERARCHICAL_DELIMITER; @@ -365,7 +366,7 @@ public AbstractGroup resultConverter(ButtonType button) { groupHierarchySelectedProperty.getValue(), FieldFactory.parseField(autoGroupPersonsFieldProperty.getValue().trim())); } - } else if (typeTexProperty.getValue()) { + } else if (Boolean.TRUE.equals(typeTexProperty.getValue())) { resultingGroup = TexGroup.create( groupName, groupHierarchySelectedProperty.getValue(), @@ -378,7 +379,7 @@ public AbstractGroup resultConverter(ButtonType button) { if (resultingGroup != null) { preferences.getGroupsPreferences().setDefaultHierarchicalContext(groupHierarchySelectedProperty.getValue()); - resultingGroup.setColor(colorUseProperty.getValue() ? colorProperty.getValue() : null); + resultingGroup.setColor(Boolean.TRUE.equals(colorUseProperty.getValue()) ? colorProperty.getValue() : null); resultingGroup.setDescription(descriptionProperty.getValue()); resultingGroup.setIconName(iconProperty.getValue()); return resultingGroup; diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java b/jabgui/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java index 19fde3c24d9..e0e9a931dc4 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java @@ -104,7 +104,7 @@ public FileColumn(MainTableColumnModel model, .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { List filteredFiles = linkedFiles.stream() .filter(linkedFile -> linkedFile.getFileType().equalsIgnoreCase(fileType)) - .collect(Collectors.toList()); + .toList(); if (event.getButton() == MouseButton.PRIMARY) { if (filteredFiles.size() == 1) { @@ -120,7 +120,7 @@ public FileColumn(MainTableColumnModel model, entry.getEntry(), database, taskExecutor, dialogService, preferences); MenuItem menuItem = new MenuItem(linkedFileViewModel.getTruncatedDescriptionAndLink(), linkedFileViewModel.getTypeIcon().getGraphicNode()); - menuItem.setOnAction(e -> linkedFileViewModel.open()); + menuItem.setOnAction(_ -> linkedFileViewModel.open()); contextMenu.getItems().add(menuItem); } contextMenu.show((Node) event.getSource(), event.getScreenX(), event.getScreenY()); diff --git a/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java b/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java index 601c3314638..f11865c0734 100644 --- a/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java @@ -81,12 +81,12 @@ public class NewEntryViewModel { private Task>> bibtexWorker; public NewEntryViewModel(GuiPreferences preferences, - LibraryTab libraryTab, - DialogService dialogService, - StateManager stateManager, - UiTaskExecutor taskExecutor, - AiService aiService, - FileUpdateMonitor fileUpdateMonitor) { + LibraryTab libraryTab, + DialogService dialogService, + StateManager stateManager, + UiTaskExecutor taskExecutor, + AiService aiService, + FileUpdateMonitor fileUpdateMonitor) { this.preferences = preferences; this.libraryTab = libraryTab; this.dialogService = dialogService; @@ -100,23 +100,23 @@ public NewEntryViewModel(GuiPreferences preferences, idText = new SimpleStringProperty(); idTextValidator = new FunctionBasedValidator<>( - idText, - StringUtil::isNotBlank, - ValidationMessage.error(Localization.lang("You must specify an identifier."))); + idText, + StringUtil::isNotBlank, + ValidationMessage.error(Localization.lang("You must specify an identifier."))); idFetchers = new SimpleListProperty<>(FXCollections.observableArrayList()); idFetchers.addAll(WebFetchers.getIdBasedFetchers(preferences.getImportFormatPreferences(), preferences.getImporterPreferences())); idFetcher = new SimpleObjectProperty<>(); idFetcherValidator = new FunctionBasedValidator<>( - idFetcher, - Objects::nonNull, - ValidationMessage.error(Localization.lang("You must select an identifier type."))); + idFetcher, + Objects::nonNull, + ValidationMessage.error(Localization.lang("You must select an identifier type."))); idLookupWorker = null; interpretText = new SimpleStringProperty(); interpretTextValidator = new FunctionBasedValidator<>( - interpretText, - StringUtil::isNotBlank, - ValidationMessage.error(Localization.lang("You must specify one (or more) citations."))); + interpretText, + StringUtil::isNotBlank, + ValidationMessage.error(Localization.lang("You must specify one (or more) citations."))); interpretParsers = new SimpleListProperty<>(FXCollections.observableArrayList()); interpretParsers.addAll(PlainCitationParserChoice.values()); interpretParser = new SimpleObjectProperty<>(); @@ -124,9 +124,9 @@ public NewEntryViewModel(GuiPreferences preferences, bibtexText = new SimpleStringProperty(); bibtexTextValidator = new FunctionBasedValidator<>( - bibtexText, - StringUtil::isNotBlank, - ValidationMessage.error(Localization.lang("You must specify a Bib(La)TeX source."))); + bibtexText, + StringUtil::isNotBlank, + ValidationMessage.error(Localization.lang("You must specify a Bib(La)TeX source."))); bibtexWorker = null; } @@ -231,33 +231,33 @@ public void executeLookupIdentifier(boolean searchComposite) { if (exception instanceof FetcherClientException) { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "Bibliographic data could not be retrieved.\n" + - "This is likely due to an issue with your input, or your network connection.\n" + - "Check your provided identifier (and identifier type), and try again.\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "Bibliographic data could not be retrieved.\n" + + "This is likely due to an issue with your input, or your network connection.\n" + + "Check your provided identifier (and identifier type), and try again.\n" + + "%0", + exceptionMessage)); } else if (exception instanceof FetcherServerException) { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "Bibliographic data could not be retrieved.\n" + - "This is likely due to an issue being experienced by the server.\n" + - "Try again later.\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "Bibliographic data could not be retrieved.\n" + + "This is likely due to an issue being experienced by the server.\n" + + "Try again later.\n" + + "%0", + exceptionMessage)); } else { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "Bibliographic data could not be retrieved.\n" + - "The following error was encountered:\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "Bibliographic data could not be retrieved.\n" + + "The following error was encountered:\n" + + "%0", + exceptionMessage)); } - LOGGER.error("An exception occurred with the '{}' fetcher when resolving '{}': '{}'.", fetcherName, textString, exception); + LOGGER.error("An exception occurred with the '{}' fetcher when resolving '{}'.", fetcherName, textString, exception); executing.set(false); }); @@ -267,22 +267,22 @@ public void executeLookupIdentifier(boolean searchComposite) { if (result.isEmpty()) { dialogService.showWarningDialogAndWait( - Localization.lang("Invalid result returned"), - Localization.lang( - "An unknown error has occurred.\n" + - "This entry may need to be added manually.")); + Localization.lang("Invalid result returned"), + Localization.lang( + "An unknown error has occurred.\n" + + "This entry may need to be added manually.")); executing.set(false); return; } final ImportHandler handler = new ImportHandler( - libraryTab.getBibDatabaseContext(), - preferences, - fileUpdateMonitor, - libraryTab.getUndoManager(), - stateManager, - dialogService, - taskExecutor); + libraryTab.getBibDatabaseContext(), + preferences, + fileUpdateMonitor, + libraryTab.getUndoManager(), + stateManager, + dialogService, + taskExecutor); handler.importEntryWithDuplicateCheck(libraryTab.getBibDatabaseContext(), result.get()); executedSuccessfully.set(true); @@ -334,22 +334,22 @@ public void executeInterpretCitations() { if (exception instanceof FetcherException) { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "Failed to interpret citations.\n" + - "The following error was encountered:\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "Failed to interpret citations.\n" + + "The following error was encountered:\n" + + "%0", + exceptionMessage)); } else { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "The following error occurred:\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "The following error occurred:\n" + + "%0", + exceptionMessage)); } - LOGGER.error("An exception occurred with the '{}' parser: '{}'.", parserName, exception); + LOGGER.error("An exception occurred with the '{}' parser.", parserName, exception); executing.set(false); }); @@ -359,23 +359,23 @@ public void executeInterpretCitations() { if (result.isEmpty()) { dialogService.showWarningDialogAndWait( - Localization.lang("Invalid result"), - Localization.lang( - "An unknown error has occurred.\n" + - "Entries may need to be added manually.")); + Localization.lang("Invalid result"), + Localization.lang( + "An unknown error has occurred.\n" + + "Entries may need to be added manually.")); LOGGER.error("An invalid result was returned when parsing citations."); executing.set(false); return; } final ImportHandler handler = new ImportHandler( - libraryTab.getBibDatabaseContext(), - preferences, - fileUpdateMonitor, - libraryTab.getUndoManager(), - stateManager, - dialogService, - taskExecutor); + libraryTab.getBibDatabaseContext(), + preferences, + fileUpdateMonitor, + libraryTab.getUndoManager(), + stateManager, + dialogService, + taskExecutor); handler.importEntriesWithDuplicateCheck(libraryTab.getBibDatabaseContext(), result.get()); executedSuccessfully.set(true); @@ -419,22 +419,22 @@ public void executeSpecifyBibtex() { if (exception instanceof ParseException) { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "Failed to parse entries.\n" + - "The following error was encountered:\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "Failed to parse entries.\n" + + "The following error was encountered:\n" + + "%0", + exceptionMessage)); } else { dialogService.showInformationDialogAndWait( - dialogTitle, - Localization.lang( - "The following error occurred:\n" + - "%0", - exceptionMessage)); + dialogTitle, + Localization.lang( + "The following error occurred:\n" + + "%0", + exceptionMessage)); } - LOGGER.error("An exception occurred when parsing Bib(La)Tex entries: '{}'.", exception); + LOGGER.error("An exception occurred when parsing Bib(La)Tex entries.", exception); executing.set(false); }); @@ -444,23 +444,23 @@ public void executeSpecifyBibtex() { if (result.isEmpty()) { dialogService.showWarningDialogAndWait( - Localization.lang("Invalid result"), - Localization.lang( - "An unknown error has occurred.\n" + - "Entries may need to be added manually.")); + Localization.lang("Invalid result"), + Localization.lang( + "An unknown error has occurred.\n" + + "Entries may need to be added manually.")); LOGGER.error("An invalid result was returned when parsing Bib(La)Tex entries."); executing.set(false); return; } final ImportHandler handler = new ImportHandler( - libraryTab.getBibDatabaseContext(), - preferences, - fileUpdateMonitor, - libraryTab.getUndoManager(), - stateManager, - dialogService, - taskExecutor); + libraryTab.getBibDatabaseContext(), + preferences, + fileUpdateMonitor, + libraryTab.getUndoManager(), + stateManager, + dialogService, + taskExecutor); handler.importEntriesWithDuplicateCheck(libraryTab.getBibDatabaseContext(), result.get()); executedSuccessfully.set(true); diff --git a/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java b/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java index df4294df7eb..89cc4672f70 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java @@ -181,7 +181,7 @@ public static XMultiServiceFactory createSimpleServiceManager() throws Exception * @throws Exception if things go awry. */ public static XComponentContext defaultBootstrap_InitialComponentContext() { - return defaultBootstrap_InitialComponentContext((String) null, (Map) null); + return defaultBootstrap_InitialComponentContext(null, (Map) null); } /** diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTab.java b/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTab.java index 676e9243e8c..1f708435c3f 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTab.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTab.java @@ -118,9 +118,7 @@ private void initializeTemplates() { citationParsingSystemMessageTextArea.textProperty().bindBidirectional(viewModel.getTemplateSources().get(AiTemplate.CITATION_PARSING_SYSTEM_MESSAGE)); citationParsingUserMessageTextArea.textProperty().bindBidirectional(viewModel.getTemplateSources().get(AiTemplate.CITATION_PARSING_USER_MESSAGE)); - templatesTabPane.getSelectionModel().selectedItemProperty().addListener(_ -> { - viewModel.selectedTemplateProperty().set(getAiTemplate()); - }); + templatesTabPane.getSelectionModel().selectedItemProperty().addListener(_ -> viewModel.selectedTemplateProperty().set(getAiTemplate())); } private void initializeValidations() { diff --git a/jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java b/jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java index 85b98a01ec4..527349401ff 100644 --- a/jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java +++ b/jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java @@ -68,7 +68,7 @@ public void setLayoutCyclePosition(int position) { } public PreviewLayout getSelectedPreviewLayout() { - if (layoutCycle.size() <= 0 + if (layoutCycle.isEmpty() || layoutCyclePosition.getValue() < 0 || layoutCyclePosition.getValue() >= layoutCycle.size()) { return getCustomPreviewLayout(); diff --git a/jabgui/src/main/java/org/jabref/gui/search/Highlighter.java b/jabgui/src/main/java/org/jabref/gui/search/Highlighter.java index 4f53e7c4434..aedb59c05e7 100644 --- a/jabgui/src/main/java/org/jabref/gui/search/Highlighter.java +++ b/jabgui/src/main/java/org/jabref/gui/search/Highlighter.java @@ -19,7 +19,6 @@ import org.jabref.model.util.Range; import com.airhacks.afterburner.injection.Injector; -import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; @@ -38,6 +37,10 @@ public class Highlighter { private static final String REGEXP_POSITIONS = "SELECT * FROM regexp_positions(?, ?)"; private static Connection connection; + private Highlighter() { + // prevent instantiation + } + public static String highlightHtml(String htmlText, SearchQuery searchQuery) { Optional searchTermsPattern = buildSearchPattern(searchQuery); if (searchTermsPattern.isEmpty()) { @@ -45,16 +48,11 @@ public static String highlightHtml(String htmlText, SearchQuery searchQuery) { } Document document = Jsoup.parse(htmlText); - try { - highlightTextNodes(document.body(), searchTermsPattern.get()); - return document.outerHtml(); - } catch (InvalidTokenOffsetsException e) { - LOGGER.debug("Error highlighting search terms in HTML", e); - return htmlText; - } + highlightTextNodes(document.body(), searchTermsPattern.get()); + return document.outerHtml(); } - private static void highlightTextNodes(Element element, String searchPattern) throws InvalidTokenOffsetsException { + private static void highlightTextNodes(Element element, String searchPattern) { for (Node node : element.childNodes()) { if (node instanceof TextNode textNode) { String highlightedText = highlightNode(textNode.text(), searchPattern); diff --git a/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java index 0e567b10210..a39331be998 100644 --- a/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java @@ -236,7 +236,7 @@ private boolean openSharedDatabase(DBMSConnectionProperties connectionProperties ButtonType.OK, openHelp); result.filter(btn -> btn.equals(openHelp)).ifPresent(btn -> new HelpAction(HelpFile.SQL_DATABASE_MIGRATION, dialogService, preferences.getExternalApplicationsPreferences()).execute()); - result.filter(btn -> ButtonType.OK.equals(btn)).ifPresent(btn -> openSharedDatabase(connectionProperties)); + result.filter(ButtonType.OK::equals).ifPresent(btn -> openSharedDatabase(connectionProperties)); } loading.set(false); return false; diff --git a/jabgui/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java index f0194c0a5b9..326e97903b9 100644 --- a/jabgui/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java @@ -162,7 +162,7 @@ private FileNodeViewModel searchDirectory(Path directory) throws IOException { try (Stream filesStream = Files.list(directory)) { fileListPartition = filesStream.collect(Collectors.partitioningBy(path -> path.toFile().isDirectory())); } catch (IOException e) { - LOGGER.error("%s while searching files: %s".formatted(e.getClass().getName(), e.getMessage()), e); + LOGGER.error("{} while searching files:", e.getClass().getName(), e); return parent; } diff --git a/jabgui/src/main/java/org/jabref/gui/util/component/TemporalAccessorPicker.java b/jabgui/src/main/java/org/jabref/gui/util/component/TemporalAccessorPicker.java index 4b40aeb5e4f..332c5e6b1df 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/component/TemporalAccessorPicker.java +++ b/jabgui/src/main/java/org/jabref/gui/util/component/TemporalAccessorPicker.java @@ -89,7 +89,7 @@ private static LocalDate getLocalDate(TemporalAccessor dateTime) { try { return YearMonth.from(dateTime).atDay(1); - } catch (DateTimeException exception) { + } catch (DateTimeException _) { return Year.from(dateTime).atDay(1); } } @@ -110,7 +110,7 @@ public TemporalAccessor fromString(String value) { if (StringUtil.isNotBlank(value)) { try { return defaultFormatter.parse(value); - } catch (DateTimeParseException exception) { + } catch (DateTimeParseException _) { return Date.parse(value).map(Date::toTemporalAccessor).orElse(null); } } else { @@ -118,7 +118,7 @@ public TemporalAccessor fromString(String value) { } } }; - return Objects.requireNonNullElseGet(stringConverterProperty().get(), () -> newConverter); + return Objects.requireNonNullElse(stringConverterProperty().get(), newConverter); } public final void setStringConverter(StringConverter value) { diff --git a/jabgui/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadObservableList.java b/jabgui/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadObservableList.java index f6e935e7968..7635a441500 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadObservableList.java +++ b/jabgui/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadObservableList.java @@ -32,13 +32,15 @@ public void removeListener(ListChangeListener listener) { delegate.removeListener(listener); } + @SafeVarargs @Override - public boolean addAll(E... elements) { + public final boolean addAll(E... elements) { return delegate.addAll(elements); } + @SafeVarargs @Override - public boolean setAll(E... elements) { + public final boolean setAll(E... elements) { return delegate.setAll(elements); } @@ -47,13 +49,15 @@ public boolean setAll(Collection col) { return delegate.setAll(col); } + @SafeVarargs @Override - public boolean removeAll(E... elements) { + public final boolean removeAll(E... elements) { return delegate.removeAll(elements); } + @SafeVarargs @Override - public boolean retainAll(E... elements) { + public final boolean retainAll(E... elements) { return delegate.retainAll(elements); } diff --git a/jabkit/src/main/java/org/jabref/JabKit.java b/jabkit/src/main/java/org/jabref/JabKit.java index ee4b1f52d32..a7b6bab6da6 100644 --- a/jabkit/src/main/java/org/jabref/JabKit.java +++ b/jabkit/src/main/java/org/jabref/JabKit.java @@ -52,9 +52,9 @@ /// /// Does not do any preference migrations. public class JabKit { - private static Logger LOGGER; + private static final Logger LOGGER = LoggerFactory.getLogger(JabKit.class); - private static String JABKIT_BRAND = "JabKit - command line toolkit for JabRef"; + private static final String JABKIT_BRAND = "JabKit - command line toolkit for JabRef"; public static void main(String[] args) { initLogging(args); @@ -134,7 +134,7 @@ public static void initLogging(String[] args) { // We must configure logging as soon as possible, which is why we cannot wait for the usual // argument parsing workflow to parse logging options e.g. --debug - boolean isDebugEnabled = Arrays.stream(args).anyMatch(arg -> "--debug".equalsIgnoreCase(arg)); + boolean isDebugEnabled = Arrays.stream(args).anyMatch("--debug"::equalsIgnoreCase); // addLogToDisk // We cannot use `Injector.instantiateModelOrService(BuildInfo.class).version` here, because this initializes logging @@ -142,7 +142,6 @@ public static void initLogging(String[] args) { try { Files.createDirectories(directory); } catch (IOException e) { - LOGGER = LoggerFactory.getLogger(JabKit.class); LOGGER.error("Could not create log directory {}", directory, e); return; } @@ -159,8 +158,6 @@ public static void initLogging(String[] args) { "writerFile.policies", "startup", "writerFile.backups", "30"); configuration.forEach(Configuration::set); - - LOGGER = LoggerFactory.getLogger(JabKit.class); } private static void configureProxy(ProxyPreferences proxyPreferences) { diff --git a/jabkit/src/main/java/org/jabref/cli/CheckConsistency.java b/jabkit/src/main/java/org/jabref/cli/CheckConsistency.java index 01476e3f139..84a6851e21c 100644 --- a/jabkit/src/main/java/org/jabref/cli/CheckConsistency.java +++ b/jabkit/src/main/java/org/jabref/cli/CheckConsistency.java @@ -73,22 +73,7 @@ public Integer call() { }); Writer writer = new OutputStreamWriter(System.out); - BibliographyConsistencyCheckResultWriter checkResultWriter; - if ("txt".equalsIgnoreCase(outputFormat)) { - checkResultWriter = new BibliographyConsistencyCheckResultTxtWriter( - result, - writer, - sharedOptions.porcelain, - argumentProcessor.entryTypesManager, - databaseContext.getMode()); - } else { - checkResultWriter = new BibliographyConsistencyCheckResultCsvWriter( - result, - writer, - sharedOptions.porcelain, - argumentProcessor.entryTypesManager, - databaseContext.getMode()); - } + BibliographyConsistencyCheckResultWriter checkResultWriter = getBibliographyConsistencyCheckResultWriter(result, writer, databaseContext); // System.out should not be closed, therefore no try-with-resources try { @@ -108,4 +93,29 @@ public Integer call() { } return 0; } + + private BibliographyConsistencyCheckResultWriter getBibliographyConsistencyCheckResultWriter( + BibliographyConsistencyCheck.Result result, + Writer writer, + BibDatabaseContext databaseContext) { + BibliographyConsistencyCheckResultWriter checkResultWriter; + + if ("txt".equalsIgnoreCase(outputFormat)) { + checkResultWriter = new BibliographyConsistencyCheckResultTxtWriter( + result, + writer, + sharedOptions.porcelain, + argumentProcessor.entryTypesManager, + databaseContext.getMode()); + } else { + checkResultWriter = new BibliographyConsistencyCheckResultCsvWriter( + result, + writer, + sharedOptions.porcelain, + argumentProcessor.entryTypesManager, + databaseContext.getMode()); + } + + return checkResultWriter; + } } diff --git a/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java b/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java index c4abd643a77..b24c34d6460 100644 --- a/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java +++ b/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java @@ -582,7 +582,7 @@ private void bstMissing(BstVMVisitor visitor, ParserRuleContext ctx) { } if (!(o1 instanceof String)) { - LOGGER.warn("Not a string or missing field in operation missing$ (line %d)".formatted(ctx.start.getLine())); + LOGGER.warn("Not a string or missing field in operation missing$ (line {})", ctx.start.getLine()); stack.push(BstVM.TRUE); return; } diff --git a/jablib/src/main/java/org/jabref/logic/bst/util/BstNameFormatter.java b/jablib/src/main/java/org/jabref/logic/bst/util/BstNameFormatter.java index a49b1527a8d..b8fda0d7918 100644 --- a/jablib/src/main/java/org/jabref/logic/bst/util/BstNameFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/bst/util/BstNameFormatter.java @@ -194,7 +194,7 @@ public static String formatName(Author author, String format) { sb.append(d[j]); } } - if (sb.length() > 0) { + if (!sb.isEmpty()) { boolean noDisTie = false; if ((sb.charAt(sb.length() - 1) == '~') && ((BstNameFormatter.numberOfChars(sb.substring(groupStart, sb.length()), 4) >= 4) || diff --git a/jablib/src/main/java/org/jabref/logic/citationkeypattern/AbstractCitationKeyPatterns.java b/jablib/src/main/java/org/jabref/logic/citationkeypattern/AbstractCitationKeyPatterns.java index dd254069c27..9fae3571c08 100644 --- a/jablib/src/main/java/org/jabref/logic/citationkeypattern/AbstractCitationKeyPatterns.java +++ b/jablib/src/main/java/org/jabref/logic/citationkeypattern/AbstractCitationKeyPatterns.java @@ -22,11 +22,8 @@ public void addCitationKeyPattern(EntryType type, String pattern) { @Override public String toString() { - final StringBuilder sb = new StringBuilder("AbstractCitationKeyPattern{"); - sb.append("defaultPattern=").append(defaultPattern); - sb.append(", data=").append(data); - sb.append('}'); - return sb.toString(); + String sb = "AbstractCitationKeyPattern{defaultPattern=" + defaultPattern + ", data=" + data + '}'; + return sb; } @Override diff --git a/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java b/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java index 4d1fb957f70..6a18f02764c 100644 --- a/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java +++ b/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java @@ -46,10 +46,9 @@ public List cleanup(BibEntry entry) { entry.setField(StandardField.EPRINTTYPE, "arxiv") .ifPresent(changes::add); - arXivIdentifier.get().getClassification().ifPresent(classification -> - entry.setField(StandardField.EPRINTCLASS, classification) - .ifPresent(changes::add) - ); + arXivIdentifier.get().getClassification() + .flatMap(classification -> entry.setField(StandardField.EPRINTCLASS, classification)) + .ifPresent(changes::add); entry.clearField(field) .ifPresent(changes::add); diff --git a/jablib/src/main/java/org/jabref/logic/crawler/StudyFetcher.java b/jablib/src/main/java/org/jabref/logic/crawler/StudyFetcher.java index ebb77530aa9..016da334e78 100644 --- a/jablib/src/main/java/org/jabref/logic/crawler/StudyFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/crawler/StudyFetcher.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.PagedSearchBasedFetcher; @@ -40,7 +39,7 @@ class StudyFetcher { public List crawl() { return searchQueries.parallelStream() .map(this::getQueryResult) - .collect(Collectors.toList()); + .toList(); } private QueryResult getQueryResult(String searchQuery) { @@ -57,7 +56,7 @@ private List performSearchOnQuery(String searchQuery) { return activeFetchers.parallelStream() .map(fetcher -> performSearchOnQueryForFetcher(searchQuery, fetcher)) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .toList(); } private FetchResult performSearchOnQueryForFetcher(String searchQuery, SearchBasedFetcher fetcher) { @@ -73,7 +72,7 @@ private FetchResult performSearchOnQueryForFetcher(String searchQuery, SearchBas } return new FetchResult(fetcher.getName(), new BibDatabase(fetchResult)); } catch (FetcherException e) { - LOGGER.warn("%s API request failed".formatted(fetcher.getName()), e); + LOGGER.warn("{} API request failed", fetcher.getName(), e); return null; } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesParser.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesParser.java index c2f8aebe2be..f0704e398c9 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesParser.java @@ -34,9 +34,7 @@ public CollectionOfComputerScienceBibliographiesParser(ImportFormatPreferences i public List parseEntries(InputStream inputStream) throws ParseException { try { List links = matchRegexFromInputStreamHtml(inputStream, REGEX_FOR_LINKS); - String bibtexDataString = parseBibtexStringsFromLinks(links) - .stream() - .collect(Collectors.joining()); + String bibtexDataString = String.join("", parseBibtexStringsFromLinks(links)); return bibtexParser.parseEntries(bibtexDataString); } catch (IOException | FetcherException e) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CompositeSearchBasedFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CompositeSearchBasedFetcher.java index ba1b287119d..c4d5c71b484 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CompositeSearchBasedFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CompositeSearchBasedFetcher.java @@ -22,7 +22,7 @@ public class CompositeSearchBasedFetcher implements SearchBasedFetcher { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeSearchBasedFetcher.class); - private Set fetchers; + private final Set fetchers; private final int maximumNumberOfReturnedResults; public CompositeSearchBasedFetcher(Set searchBasedFetchers, ImporterPreferences importerPreferences, int maximumNumberOfReturnedResults) @@ -59,11 +59,11 @@ public List performSearch(QueryNode luceneQuery) throws FetcherExcepti try { return searchBasedFetcher.performSearch(luceneQuery).stream(); } catch (FetcherException e) { - LOGGER.warn("%s API request failed".formatted(searchBasedFetcher.getName()), e); + LOGGER.warn("{} API request failed", searchBasedFetcher.getName(), e); return Stream.empty(); } }) .limit(maximumNumberOfReturnedResults) - .collect(Collectors.toList()); + .toList(); } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java index 0681d7e2d59..8f087479b77 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java @@ -94,8 +94,8 @@ private void doAPILimiting(String identifier) { waitingTime = CROSSREF_DCN_RATE_LIMITER.acquire(); } // mEDRA does not explicit an API rating - LOGGER.trace("Thread %s, searching for DOI '%s', waited %.2fs because of API rate limiter".formatted( - Thread.currentThread().threadId(), identifier, waitingTime)); + LOGGER.trace("Thread {}, searching for DOI '{}', waited {} because of API rate limiter", + Thread.currentThread().threadId(), identifier, waitingTime); } } catch (FetcherException | MalformedURLException e) { LOGGER.warn("Could not limit DOI API access rate", e); @@ -194,7 +194,7 @@ private void updateCrossrefAPIRate(URLConnection existingConnection) { // In theory, the actual update might rarely happen... if (Math.abs(newRate - oldRate) >= 1.0) { - LOGGER.info("Updated Crossref API rate limit from %.2f to %.2f".formatted(oldRate, newRate)); + LOGGER.info("Updated Crossref API rate limit from {} to {}", oldRate, newRate); CROSSREF_DCN_RATE_LIMITER.setRate(newRate); } } catch (NullPointerException | IllegalArgumentException e) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiResolution.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiResolution.java index ff88a9127bb..e6dac8a9c7b 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiResolution.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiResolution.java @@ -10,7 +10,6 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; import org.jabref.logic.importer.FulltextFetcher; import org.jabref.logic.importer.ImportFormatPreferences; @@ -150,7 +149,7 @@ private Optional citationMetaTag(Document html) { if (citationPdfUrl.isPresent()) { try { return Optional.of(URLUtil.create(citationPdfUrl.get())); - } catch (MalformedURLException e) { + } catch (MalformedURLException _) { return Optional.empty(); } } @@ -167,7 +166,7 @@ private Optional findEmbeddedLink(Document html, URL base) { try { URL url = base.toURI().resolve(pdfUrl.get()).toURL(); return Optional.of(url); - } catch (MalformedURLException | URISyntaxException e) { + } catch (MalformedURLException | URISyntaxException _) { return Optional.empty(); } } @@ -175,7 +174,7 @@ private Optional findEmbeddedLink(Document html, URL base) { } private Optional findDistinctLinks(List urls) { - List distinctLinks = urls.stream().distinct().collect(Collectors.toList()); + List distinctLinks = urls.stream().distinct().toList(); if (distinctLinks.isEmpty()) { return Optional.empty(); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/MedlineQueryTransformer.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/MedlineQueryTransformer.java index 155b08b89d2..c9952d8be3e 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/MedlineQueryTransformer.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/MedlineQueryTransformer.java @@ -49,6 +49,6 @@ protected String handleYearRange(String yearRange) { if (endYear == Integer.MAX_VALUE) { return yearRange; } - return Integer.toString(startYear) + ":" + Integer.toString(endYear) + "[dp]"; + return startYear + ":" + endYear + "[dp]"; } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/IsiImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/IsiImporter.java index 652c0e3d6be..409e3f8ca7d 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/IsiImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/IsiImporter.java @@ -288,7 +288,7 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } } - if (pages.length() > 0) { + if (!pages.isEmpty()) { hm.put(StandardField.PAGES, pages.toString()); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/RepecNepImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/RepecNepImporter.java index af64a2dae62..2da652924c3 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/RepecNepImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/RepecNepImporter.java @@ -278,7 +278,7 @@ private void parseAuthors(BibEntry be, BufferedReader in) throws IOException { if (!institution.isEmpty()) { institutions.append( - institutions.isEmpty() ? institution.toString() : " and " + institution.toString()); + institutions.isEmpty() ? institution.toString() : " and " + institution); } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java b/jablib/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java index 59527031e4c..5ab21558195 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java @@ -123,7 +123,7 @@ public List parse() { } escaped = false; } - if (charactersOfCurrentElement.length() > 0) { + if (!charactersOfCurrentElement.isEmpty()) { linkedFileData.add(charactersOfCurrentElement.toString()); } if (!linkedFileData.isEmpty()) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java b/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java index f18372135ee..710138c9ed7 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java @@ -250,7 +250,7 @@ private static Optional getNextUnit(Reader reader) throws IOException { res.append((char) c); } } - if (res.length() > 0) { + if (!res.isEmpty()) { return Optional.of(res.toString()); } return Optional.empty(); diff --git a/jablib/src/main/java/org/jabref/logic/integrity/FileChecker.java b/jablib/src/main/java/org/jabref/logic/integrity/FileChecker.java index d59e3c5d1ea..dbb799f95c0 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/FileChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/FileChecker.java @@ -4,7 +4,6 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import org.jabref.logic.FilePreferences; import org.jabref.logic.importer.util.FileFieldParser; @@ -32,7 +31,7 @@ public Optional checkValue(String value) { List linkedFiles = FileFieldParser .parse(value).stream() .filter(file -> !file.isOnlineLink()) - .collect(Collectors.toList()); + .toList(); for (LinkedFile file : linkedFiles) { Optional linkedFile = file.findIn(context, filePreferences); diff --git a/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java b/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java index d21caa310ff..e6cbc6df15e 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java @@ -11,8 +11,8 @@ public class PagesChecker implements ValueChecker { - private static final String PAGES_EXP_BIBTEX = "" - + "\\A" // begin String + private static final String PAGES_EXP_BIBTEX = + "\\A" // begin String + "[A-Za-z]?\\d*" // optional prefix and number + "(" + "(\\+|-{2}|\u2013)" // separator, must contain exactly two dashes @@ -21,8 +21,8 @@ public class PagesChecker implements ValueChecker { + "\\z"; // end String // See https://packages.oth-regensburg.de/ctan/macros/latex/contrib/biblatex/doc/biblatex.pdf#subsubsection.3.15.3 for valid content - private static final String PAGES_EXP_BIBLATEX = "" - + "\\A" // begin String + private static final String PAGES_EXP_BIBLATEX = + "\\A" // begin String + "[A-Za-z]?\\d*" // optional prefix and number + "(" + "(\\+|-{1,2}|\u2013)" // separator diff --git a/jablib/src/main/java/org/jabref/logic/l10n/Encodings.java b/jablib/src/main/java/org/jabref/logic/l10n/Encodings.java index ac5efb19b54..83902567f55 100644 --- a/jablib/src/main/java/org/jabref/logic/l10n/Encodings.java +++ b/jablib/src/main/java/org/jabref/logic/l10n/Encodings.java @@ -2,26 +2,22 @@ import java.nio.charset.Charset; import java.util.List; -import java.util.stream.Collectors; public class Encodings { public static final Charset[] ENCODINGS; public static final String[] ENCODINGS_DISPLAYNAMES; - private static List encodingsList = Charset.availableCharsets().values().stream().distinct() - .collect(Collectors.toList()); + private static final List ENCODINGS_LIST = Charset.availableCharsets().values().stream().distinct().toList(); private Encodings() { } static { - List encodingsStringList = encodingsList.stream().map(Charset::displayName).distinct() - .collect(Collectors.toList()); - ENCODINGS = encodingsList.toArray(new Charset[encodingsList.size()]); - ENCODINGS_DISPLAYNAMES = encodingsStringList.toArray(new String[encodingsStringList.size()]); + ENCODINGS_DISPLAYNAMES = ENCODINGS_LIST.stream().map(Charset::displayName).distinct().toArray(String[]::new); + ENCODINGS = ENCODINGS_LIST.toArray(new Charset[0]); } public static List getCharsets() { - return encodingsList; + return ENCODINGS_LIST; } } diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/RTFChars.java b/jablib/src/main/java/org/jabref/logic/layout/format/RTFChars.java index 649e85b7ba3..54f4377fb3f 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/RTFChars.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/RTFChars.java @@ -94,11 +94,11 @@ public String format(String field) { assert incommand; // First test for braces that may be part of a LaTeX command: - if ((c == '{') && (currentCommand.length() == 0)) { + if ((c == '{') && (currentCommand.isEmpty())) { // We have seen something like \{, which is probably the start // of a command like \{aa}. Swallow the brace. continue; - } else if ((c == '}') && (currentCommand.length() > 0)) { + } else if ((c == '}') && (!currentCommand.isEmpty())) { // Seems to be the end of a command like \{aa}. Look it up: String command = currentCommand.toString(); String result = RTF_CHARS.get(command); @@ -116,7 +116,7 @@ public String format(String field) { break testContent; } - if (((c == '{') || (c == ' ')) && (currentCommand.length() > 0)) { + if (((c == '{') || (c == ' ')) && (!currentCommand.isEmpty())) { String command = currentCommand.toString(); // Then test if we are dealing with a italics or bold // command. If so, handle. diff --git a/jablib/src/main/java/org/jabref/logic/pdf/FileAnnotationCache.java b/jablib/src/main/java/org/jabref/logic/pdf/FileAnnotationCache.java index 69290dc020a..45dd5524d79 100644 --- a/jablib/src/main/java/org/jabref/logic/pdf/FileAnnotationCache.java +++ b/jablib/src/main/java/org/jabref/logic/pdf/FileAnnotationCache.java @@ -19,14 +19,14 @@ public class FileAnnotationCache { private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotationCache.class); // cache size in entries - private final static int CACHE_SIZE = 10; + private static final int CACHE_SIZE = 10; // the inner list holds the annotations per file, the outer collection maps this to a BibEntry. private LoadingCache>> annotationCache; /** * Creates an empty fil annotation cache. Required to allow the annotation cache to be injected into views without - * hitting the bug https://github.com/AdamBien/afterburner.fx/issues/71 . + * hitting the bug ... . */ public FileAnnotationCache() { } @@ -47,12 +47,12 @@ public Map> load(BibEntry entry) { * @return Map containing a list of annotations in a list for each file */ public Map> getFromCache(BibEntry entry) { - LOGGER.debug("Loading Bibentry '%s' from cache.".formatted(entry.getCitationKey().orElse(entry.getId()))); + LOGGER.debug("Loading Bibentry '{}' from cache.", entry.getCitationKey().orElse(entry.getId())); return annotationCache.getUnchecked(entry); } public void remove(BibEntry entry) { - LOGGER.debug("Deleted Bibentry '%s' from cache.".formatted(entry.getCitationKey().orElse(entry.getId()))); + LOGGER.debug("Deleted Bibentry '{}' from cache.", entry.getCitationKey().orElse(entry.getId())); annotationCache.invalidate(entry); } } diff --git a/jablib/src/main/java/org/jabref/logic/pdf/PdfAnnotationImporter.java b/jablib/src/main/java/org/jabref/logic/pdf/PdfAnnotationImporter.java index a23b93d6ca6..f880435cd2d 100644 --- a/jablib/src/main/java/org/jabref/logic/pdf/PdfAnnotationImporter.java +++ b/jablib/src/main/java/org/jabref/logic/pdf/PdfAnnotationImporter.java @@ -61,7 +61,7 @@ public List importAnnotations(final Path path) { } } } catch (IOException e) { - LOGGER.error("Failed to read file '%s'.".formatted(path), e); + LOGGER.error("Failed to read file '{}'.", path, e); } return annotationsList; } @@ -78,7 +78,7 @@ private boolean isSupportedAnnotationType(PDAnnotation annotation) { if (!Arrays.asList(FileAnnotationType.values()).contains(FileAnnotationType.valueOf(annotation.getSubtype()))) { return false; } - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { LOGGER.debug("Could not parse the FileAnnotation {} into any known FileAnnotationType. It was {}.", annotation, annotation.getSubtype()); } return true; @@ -93,7 +93,7 @@ private FileAnnotation createMarkedAnnotations(int pageIndex, PDPage page, PDAnn try { COSArray boundingBoxes = (COSArray) annotation.getCOSObject().getDictionaryObject(COSName.getPDFName("QuadPoints")); annotation.setContents(new TextExtractor(page, boundingBoxes).extractMarkedText()); - } catch (IOException e) { + } catch (IOException _) { annotation.setContents("JabRef: Could not extract any marked text!"); } } @@ -106,17 +106,17 @@ private boolean validatePath(Path path) { Objects.requireNonNull(path); if (!path.toString().toLowerCase(Locale.ROOT).endsWith(".pdf")) { - LOGGER.warn("File '%s' does not end with .pdf!".formatted(path)); + LOGGER.warn("File '{}' does not end with .pdf!", path); return false; } if (!Files.exists(path)) { - LOGGER.warn("File '%s' does not exist!".formatted(path)); + LOGGER.warn("File '{}' does not exist!", path); return false; } if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - LOGGER.warn("File '%s' is not readable!".formatted(path)); + LOGGER.warn("File '{}' is not readable!", path); return false; } diff --git a/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java b/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java index 53ae84fbdec..bcbd45bd1e6 100644 --- a/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java @@ -447,8 +447,9 @@ public class JabRefCliPreferences implements CliPreferences { */ public JabRefCliPreferences() { try { - if (Files.exists(Path.of("jabref.xml"))) { - importPreferences(Path.of("jabref.xml")); + Path preferebcesPath = Path.of("jabref.xml"); + if (Files.exists(preferebcesPath)) { + importPreferences(preferebcesPath); } } catch (JabRefException e) { LOGGER.warn("Could not import preferences from jabref.xml", e); diff --git a/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java b/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java index c4b50912cf1..10d93f1772a 100644 --- a/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java +++ b/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java @@ -192,13 +192,13 @@ public static void gracefullyShutdown(ExecutorService executorService) { // This is non-blocking. See https://stackoverflow.com/a/57383461/873282. executorService.shutdown(); if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { - LOGGER.debug("One minute passed, {} still not completed. Trying forced shutdown.", executorService.toString()); + LOGGER.debug("One minute passed, {} still not completed. Trying forced shutdown.", executorService); // those threads will be interrupted in their current task executorService.shutdownNow(); if (executorService.awaitTermination(60, TimeUnit.SECONDS)) { - LOGGER.debug("One minute passed again - forced shutdown of {} worked.", executorService.toString()); + LOGGER.debug("One minute passed again - forced shutdown of {} worked.", executorService); } else { - LOGGER.error("{} did not terminate", executorService.toString()); + LOGGER.error("{} did not terminate", executorService); } } } catch (InterruptedException ie) { diff --git a/jablib/src/main/java/org/jabref/logic/util/MscCodeUtils.java b/jablib/src/main/java/org/jabref/logic/util/MscCodeUtils.java index 8e7fe58bf05..b3d0162e00c 100644 --- a/jablib/src/main/java/org/jabref/logic/util/MscCodeUtils.java +++ b/jablib/src/main/java/org/jabref/logic/util/MscCodeUtils.java @@ -32,7 +32,8 @@ public static Optional> loadMscCodesFromJson(URL resou ObjectMapper mapper = new ObjectMapper(); try { Map mapping = - mapper.readValue(resourceUrl, new TypeReference>() { }); + mapper.readValue(resourceUrl, new TypeReference<>() { + }); HashBiMap result = HashBiMap.create(mapping); if (result.isEmpty()) { diff --git a/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java b/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java index 9093acfe570..9d99d4f9b8e 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java @@ -19,7 +19,6 @@ import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.FilePreferences; @@ -121,7 +120,7 @@ public static String getValidFileName(String fileName) { if (nameWithoutExtension.length() > MAXIMUM_FILE_NAME_LENGTH) { Optional extension = getFileExtension(fileName); String shortName = nameWithoutExtension.substring(0, MAXIMUM_FILE_NAME_LENGTH - extension.map(s -> s.length() + 1).orElse(0)); - LOGGER.info("Truncated the too long filename '%s' (%d characters) to '%s'.".formatted(fileName, fileName.length(), shortName)); + LOGGER.info("Truncated the too long filename '{}' ({}} characters) to '{}'.", fileName, fileName.length(), shortName); return extension.map(s -> shortName + "." + s).orElse(shortName); } @@ -285,7 +284,7 @@ public static List relativize(List entries, BibDatabaseConte List fileDirectories = databaseContext.getFileDirectories(filePreferences); return entries.stream() - .map(entry -> { + .peek(entry -> { if (entry.hasField(StandardField.FILE)) { List updatedLinkedFiles = entry.getFiles().stream().map(linkedFile -> { if (!linkedFile.isOnlineLink()) { @@ -296,7 +295,6 @@ public static List relativize(List entries, BibDatabaseConte }).toList(); entry.setFiles(updatedLinkedFiles); } - return entry; }).toList(); } @@ -314,7 +312,7 @@ public static List getListOfLinkedFiles(List bes, List fil return bes.stream() .flatMap(entry -> entry.getFiles().stream()) .flatMap(file -> file.findIn(fileDirs).stream()) - .collect(Collectors.toList()); + .toList(); } /** @@ -376,7 +374,7 @@ public static Optional findSingleFileRecursively(String filename, Path roo .filter(f -> f.getFileName().toString().equals(filename)) .findFirst(); } catch (UncheckedIOException | IOException ex) { - LOGGER.error("Error trying to locate the file {} inside the directory {}", filename, rootDirectory); + LOGGER.error("Error trying to locate the file {} inside the directory {}", filename, rootDirectory, ex); } return Optional.empty(); } @@ -517,7 +515,7 @@ public static boolean detectBadFileName(String fileName) { // but a perfectly legal one in the path at this position try { fileName = Path.of(fileName).getFileName().toString(); - } catch (InvalidPathException e) { + } catch (InvalidPathException _) { // in case the internal method cannot parse the path, it is surely illegal return true; } diff --git a/jablib/src/main/java/org/jabref/logic/util/io/RegExpBasedFileFinder.java b/jablib/src/main/java/org/jabref/logic/util/io/RegExpBasedFileFinder.java index 20ce8de443e..aab8c765811 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/RegExpBasedFileFinder.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/RegExpBasedFileFinder.java @@ -166,12 +166,9 @@ private List findFile(final BibEntry entry, final Path directory, final St } switch (dirToProcess) { case "." -> { - continue; // Stay in current directory - } - case ".." -> { - currentDirectory = currentDirectory.getParent(); - continue; + // Stay in current directory } + case ".." -> currentDirectory = currentDirectory.getParent(); case "*" -> { // for all direct subdirs String restOfFileString = StringUtil.join(fileParts, "/", index + 1, fileParts.length); diff --git a/jablib/src/main/java/org/jabref/model/entry/BibEntry.java b/jablib/src/main/java/org/jabref/model/entry/BibEntry.java index 221747e5565..90eaaf647c1 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibEntry.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibEntry.java @@ -18,7 +18,6 @@ import java.util.function.BiFunction; import java.util.function.Predicate; import java.util.stream.Collectors; -import java.util.stream.Stream; import javafx.beans.Observable; import javafx.beans.property.ObjectProperty; @@ -1127,15 +1126,15 @@ public Optional addFiles(List filesToAdd) { */ public SequencedSet getCites() { return this.getField(StandardField.CITES) - .map(content -> Arrays.stream(content.split(","))) - .orElseGet(Stream::empty) + .stream() + .flatMap(content -> Arrays.stream(content.split(","))) .map(String::trim) .filter(key -> !key.isEmpty()) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Optional setCites(SequencedSet keys) { - return this.setField(StandardField.CITES, keys.stream().collect(Collectors.joining(","))); + return this.setField(StandardField.CITES, String.join(",", keys)); } public void setDate(Date date) { diff --git a/jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java b/jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java index 13792de0204..517bec138a6 100644 --- a/jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java +++ b/jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java @@ -32,8 +32,7 @@ public class DOI implements Identifier { // Regex // (see http://www.doi.org/doi_handbook/2_Numbering.html) - private static final String DOI_EXP = "" - + "(?:urn:)?" // optional urn + private static final String DOI_EXP = "(?:urn:)?" // optional urn + "(?:doi:)?" // optional doi + "(" // begin group \1 + "10" // directory indicator @@ -41,8 +40,7 @@ public class DOI implements Identifier { + "[/:%]" // divider + "(?:.+)" // suffix alphanumeric string + ")"; // end group \1 - private static final String FIND_DOI_EXP = "" - + "(?:urn:)?" // optional urn + private static final String FIND_DOI_EXP = "(?:urn:)?" // optional urn + "(?:doi:)?" // optional doi + "(" // begin group \1 + "10" // directory indicator @@ -52,17 +50,13 @@ public class DOI implements Identifier { + ")"; // end group \1 // Regex (Short DOI) - private static final String SHORT_DOI_SHORTCUT = "" - + "^\\s*(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})\\s*$"; // eg https://doi.org/bfrhmx - private static final String IN_TEXT_SHORT_DOI_SHORTCUT = "" - + "(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})"; // eg https://doi.org/bfrhmx somewhere in the text - private static final String SHORT_DOI_EXP_PREFIX = "" - + "^(?:" // can begin with... + private static final String SHORT_DOI_SHORTCUT = "^\\s*(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})\\s*$"; // eg https://doi.org/bfrhmx + private static final String IN_TEXT_SHORT_DOI_SHORTCUT = "(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})"; // eg https://doi.org/bfrhmx somewhere in the text + private static final String SHORT_DOI_EXP_PREFIX = "^(?:" // can begin with... + "\\s*(?:https?://)?(?:www\\.)?" // optional url parts "http(s)://"+"www." + "[a-zA-Z\\.]*doi[a-zA-Z\\.]*" // eg "dx.doi." or "doi.acm." or "doi." if with url, must include "doi", otherwise too ambiguous + "\\.[a-zA-Z]{2,10}/)?"; // ".org" or ".de" or ".academy" - private static final String SHORT_DOI_EXP = "" - + "(?:" // begin "any one of these" + private static final String SHORT_DOI_EXP = "(?:" // begin "any one of these" + "(?:[\\s/]?(?:(?:urn:)|(?:doi:)|(?:urn:doi:)))" // "doi:10/12ab" or " urn:10/12ab" or "/urn:doi:/10/12ab" ... + "|(?:\\s?/?)" // or "/10/12ab" or " /10/12ab" or "10/12ab" or " 10/12ab" + ")" // end "any one of these" @@ -72,8 +66,7 @@ public class DOI implements Identifier { + "[a-zA-Z0-9]{3,}" // at least 3 characters + ")" // end group \1 + "\\s*$"; // must be the end - private static final String FIND_SHORT_DOI_EXP = "" - + "(?:" // begin "any one of these" (but not none of those!) + private static final String FIND_SHORT_DOI_EXP = "(?:" // begin "any one of these" (but not none of those!) + "(?:(?:www\\.)?doi\\.org/)" // either doi.org + "|" // or any of the following with doi.org or not... + "(?:(?:doi.org/)?(?:(?:urn:)|(?:doi:)|(?:urn:doi:)))" // "doi:10/12ab" or " urn:10/12ab" or "/urn:doi:/10/12ab" or "doi.org/doi:10/12ab"... diff --git a/jablib/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/jablib/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 3e1a58b92cd..2a08c962256 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -176,8 +176,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); expectEnd.push("/" + tagName); break; - case "i": - case "em": + case "i", "em": formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); expectEnd.push("/" + tagName); break; @@ -218,12 +217,12 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) } else { if (setParagraphStyle(cursor, value)) { // Presumably tested already: - LOGGER.debug("oo:ParaStyleName=\"%s\" failed".formatted(value)); + LOGGER.debug("oo:ParaStyleName=\"{}\" failed", value); } } break; default: - LOGGER.warn("Unexpected attribute '%s' for <%s>".formatted(key, tagName)); + LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); break; } } @@ -234,7 +233,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) String value = pair.b; switch (key) { case "target" -> UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); - default -> LOGGER.warn("Unexpected attribute '%s' for <%s>".formatted(key, tagName)); + default -> LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); } } break; @@ -262,10 +261,9 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); break; } - LOGGER.warn("Unexpected value %s for attribute '%s' for <%s>".formatted( - value, key, tagName)); + LOGGER.warn("Unexpected value {} for attribute '{}' for <{}>", value, key, tagName); } - default -> LOGGER.warn("Unexpected attribute '%s' for <%s>".formatted(key, tagName)); + default -> LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); } } formatStack.pushLayer(settings); @@ -284,14 +282,14 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) formatStack.popLayer(); String expected = expectEnd.pop(); if (!tagName.equals(expected)) { - LOGGER.warn("expected '<%s>', found '<%s>' after '%s'".formatted( + LOGGER.warn("expected '<{}>', found '<{}>' after '{}'", expected, tagName, - currentSubstring)); + currentSubstring); } break; default: - LOGGER.warn("ignoring unknown tag '<%s>'".formatted(tagName)); + LOGGER.warn("ignoring unknown tag '<{}>'", tagName); break; } @@ -309,7 +307,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) for (String s : expectEnd) { rest.insert(0, "<%s>".formatted(s)); } - LOGGER.warn("OOTextIntoOO.write: expectEnd stack is not empty at the end: %s%n".formatted(rest)); + LOGGER.warn("OOTextIntoOO.write: expectEnd stack is not empty at the end: {}", rest); } } @@ -373,7 +371,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { if (knownToFail.contains(p.Name)) { continue; } - LOGGER.warn("OOTextIntoOO.removeDirectFormatting failed on '%s'".formatted(p.Name)); + LOGGER.warn("OOTextIntoOO.removeDirectFormatting failed on '{}'", p.Name); } } @@ -511,7 +509,7 @@ void pushLayer(List> settings) { String name = pair.a; Integer index = goodNameToIndex.get(name); if (index == null) { - LOGGER.warn("pushLayer: '%s' is not in goodNameToIndex".formatted(name)); + LOGGER.warn("pushLayer: '{}' is not in goodNameToIndex", name); continue; } Object newValue = pair.b; @@ -561,9 +559,9 @@ void apply(XTextCursor cursor) { mps.setPropertyValues(namesArray, values.toArray()); } catch (UnknownPropertyException ex) { LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply", ex); - } catch (PropertyVetoException ex) { + } catch (PropertyVetoException _) { LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); - } catch (WrappedTargetException ex) { + } catch (WrappedTargetException _) { LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); } } diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 1a3645d12ed..647208d6fe3 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -60,7 +60,7 @@ public static Optional getStringValue(XTextDocument doc, String property try { String value = propertySet.get().getPropertyValue(property).toString(); return Optional.ofNullable(value); - } catch (UnknownPropertyException ex) { + } catch (UnknownPropertyException _) { return Optional.empty(); } } @@ -95,14 +95,14 @@ public static void setStringProperty(XTextDocument doc, String property, String try { propertySet.get().setPropertyValue(property, value); return; - } catch (UnknownPropertyException ex) { + } catch (UnknownPropertyException _) { // fall through to addProperty } } try { container.get().addProperty(property, PropertyAttribute.REMOVEABLE, new Any(Type.STRING, value)); - } catch (PropertyExistException ex) { + } catch (PropertyExistException _) { throw new java.lang.IllegalStateException("Caught PropertyExistException for property assumed not to exist"); } } @@ -127,8 +127,7 @@ public static void remove(XTextDocument doc, String property) try { container.get().removeProperty(property); } catch (UnknownPropertyException ex) { - LOGGER.warn("UnoUserDefinedProperty.remove(%s) This property was not there to remove".formatted( - property)); + LOGGER.warn("UnoUserDefinedProperty.remove({}) This property was not there to remove", property, ex); } } @@ -151,7 +150,7 @@ public static void removeIfExists(XTextDocument doc, String property) try { container.get().removeProperty(property); - } catch (UnknownPropertyException ex) { + } catch (UnknownPropertyException _) { // did not exist } } diff --git a/jablib/src/main/java/org/jabref/model/pdf/FileAnnotation.java b/jablib/src/main/java/org/jabref/model/pdf/FileAnnotation.java index c5e393ee61e..efb1a93465b 100644 --- a/jablib/src/main/java/org/jabref/model/pdf/FileAnnotation.java +++ b/jablib/src/main/java/org/jabref/model/pdf/FileAnnotation.java @@ -14,7 +14,7 @@ public class FileAnnotation { private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotation.class); - private final static int ABBREVIATED_ANNOTATION_NAME_LENGTH = 45; + private static final int ABBREVIATED_ANNOTATION_NAME_LENGTH = 45; private static final String DATE_TIME_STRING = "^D:\\d{14}$"; private static final String DATE_TIME_STRING_WITH_TIME_ZONE = "^D:\\d{14}.+"; private static final String ANNOTATION_DATE_FORMAT = "yyyyMMddHHmmss"; @@ -89,8 +89,8 @@ public static LocalDateTime extractModifiedTime(String dateTimeString) { try { return LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern(ANNOTATION_DATE_FORMAT)); - } catch (DateTimeParseException e) { - LOGGER.info("Expected a parseable date string! However, this text could not be parsed: '%s'".formatted(dateTimeString)); + } catch (DateTimeParseException _) { + LOGGER.info("Expected a parseable date string! However, this text could not be parsed: {}'", dateTimeString); return LocalDateTime.now(); } } @@ -116,7 +116,7 @@ private String parseContent(final String content) { */ private String abbreviateAnnotationName(final String annotationName) { if (annotationName.length() > ABBREVIATED_ANNOTATION_NAME_LENGTH) { - return annotationName.subSequence(0, ABBREVIATED_ANNOTATION_NAME_LENGTH).toString() + "..."; + return annotationName.subSequence(0, ABBREVIATED_ANNOTATION_NAME_LENGTH) + "..."; } return annotationName; } diff --git a/jablib/src/main/java/org/jabref/model/pdf/FileAnnotationType.java b/jablib/src/main/java/org/jabref/model/pdf/FileAnnotationType.java index dfd101026ad..6b1b10a914f 100644 --- a/jablib/src/main/java/org/jabref/model/pdf/FileAnnotationType.java +++ b/jablib/src/main/java/org/jabref/model/pdf/FileAnnotationType.java @@ -46,8 +46,8 @@ public enum FileAnnotationType { public static FileAnnotationType parse(PDAnnotation annotation) { try { return FileAnnotationType.valueOf(annotation.getSubtype().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - LOGGER.info("FileAnnotationType %s is not supported and was converted into 'Unknown'!".formatted(annotation.getSubtype())); + } catch (IllegalArgumentException _) { + LOGGER.info("FileAnnotationType {} is not supported and was converted into 'Unknown'!", annotation.getSubtype()); return UNKNOWN; } } @@ -61,7 +61,7 @@ public static FileAnnotationType parse(PDAnnotation annotation) { public static boolean isMarkedFileAnnotationType(String annotationType) { try { return FileAnnotationType.valueOf(annotationType.toUpperCase(Locale.ROOT)).linkedFileAnnotationType; - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { return false; } } @@ -70,6 +70,7 @@ public boolean isLinkedFileAnnotationType() { return linkedFileAnnotationType; } + @Override public String toString() { return this.name; } diff --git a/jablib/src/main/java/org/jabref/model/strings/StringUtil.java b/jablib/src/main/java/org/jabref/model/strings/StringUtil.java index 97310445a6a..d2ca2d075cb 100644 --- a/jablib/src/main/java/org/jabref/model/strings/StringUtil.java +++ b/jablib/src/main/java/org/jabref/model/strings/StringUtil.java @@ -287,7 +287,7 @@ public static String[][] decodeStringDoubleArray(String value) { } escaped = false; } - if (sb.length() > 0) { + if (!sb.isEmpty()) { thisEntry.add(sb.toString()); } if (!thisEntry.isEmpty()) {