diff --git a/build-support/src/main/java/CitationStyleCatalogGenerator.java b/build-support/src/main/java/CitationStyleCatalogGenerator.java index 0f00c97314f..d16f4d99cbd 100644 --- a/build-support/src/main/java/CitationStyleCatalogGenerator.java +++ b/build-support/src/main/java/CitationStyleCatalogGenerator.java @@ -1,5 +1,3 @@ -///usr/bin/env jbang "$0" "$@" ; exit $? - //JAVA 24 //RUNTIME_OPTIONS --enable-native-access=ALL-UNNAMED diff --git a/build-support/src/main/java/JournalListMvGenerator.java b/build-support/src/main/java/JournalListMvGenerator.java index cf945736b98..a67d38a2c74 100644 --- a/build-support/src/main/java/JournalListMvGenerator.java +++ b/build-support/src/main/java/JournalListMvGenerator.java @@ -1,5 +1,3 @@ -///usr/bin/env jbang "$0" "$@" ; exit $? - //JAVA 24 //RUNTIME_OPTIONS --enable-native-access=ALL-UNNAMED @@ -44,7 +42,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /// Has to be started in the root of the repository due to public class JournalListMvGenerator { diff --git a/build-support/src/main/java/LtwaListMvGenerator.java b/build-support/src/main/java/LtwaListMvGenerator.java index 063d3405380..2d5cfbb9fa1 100644 --- a/build-support/src/main/java/LtwaListMvGenerator.java +++ b/build-support/src/main/java/LtwaListMvGenerator.java @@ -1,5 +1,3 @@ -///usr/bin/env jbang "$0" "$@" ; exit $? - //JAVA 24 //RUNTIME_OPTIONS --enable-native-access=ALL-UNNAMED diff --git a/config/IntelliJ Code Style.xml b/config/IntelliJ Code Style.xml index ca64eea2719..6cee9322160 100644 --- a/config/IntelliJ Code Style.xml +++ b/config/IntelliJ Code Style.xml @@ -3,7 +3,9 @@ @@ -304,4 +306,4 @@ - \ No newline at end of file + diff --git a/jabgui/src/main/java/org/jabref/Launcher.java b/jabgui/src/main/java/org/jabref/Launcher.java index 2d8e9c2ba57..fdc3aa031e6 100644 --- a/jabgui/src/main/java/org/jabref/Launcher.java +++ b/jabgui/src/main/java/org/jabref/Launcher.java @@ -110,8 +110,8 @@ 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 Level logLevel = Arrays.stream(args).anyMatch("--debug"::equalsIgnoreCase) - ? Level.DEBUG - : Level.INFO; + ? Level.DEBUG + : Level.INFO; // addLogToDisk // We cannot use `Injector.instantiateModelOrService(BuildInfo.class).version` here, because this initializes logging diff --git a/jabgui/src/main/java/org/jabref/cli/CliImportHelper.java b/jabgui/src/main/java/org/jabref/cli/CliImportHelper.java index 759a5f2432d..7fa6265ddb8 100644 --- a/jabgui/src/main/java/org/jabref/cli/CliImportHelper.java +++ b/jabgui/src/main/java/org/jabref/cli/CliImportHelper.java @@ -30,8 +30,8 @@ public class CliImportHelper { * @param location URL or file path to import */ public static Optional importFile(String location, - CliPreferences cliPreferences, - boolean porcelain) { + CliPreferences cliPreferences, + boolean porcelain) { LOGGER.debug("Importing file from locaiton {}", location); String[] data = location.split(","); @@ -42,7 +42,7 @@ public static Optional importFile(String location, try { file = new URLDownload(address).toTemporaryFile(); } catch (FetcherException | - MalformedURLException e) { + MalformedURLException e) { System.err.println(Localization.lang("Problem downloading from %0: %1", address, e.getLocalizedMessage())); return Optional.empty(); } @@ -63,9 +63,9 @@ public static Optional importFile(String location, return importResult; } - public static Optional importFile(Path file, - CliPreferences cliPreferences, - boolean porcelain) { + public static Optional importFile(Path file, + CliPreferences cliPreferences, + boolean porcelain) { try { ImportFormatReader importFormatReader = new ImportFormatReader( cliPreferences.getImporterPreferences(), diff --git a/jabgui/src/main/java/org/jabref/gui/JabRefDialogService.java b/jabgui/src/main/java/org/jabref/gui/JabRefDialogService.java index 278049ec5d0..3d47502abbe 100644 --- a/jabgui/src/main/java/org/jabref/gui/JabRefDialogService.java +++ b/jabgui/src/main/java/org/jabref/gui/JabRefDialogService.java @@ -446,23 +446,23 @@ public void notify(String message) { LOGGER.info(message); UiTaskExecutor.runInJavaFXThread(() -> - Notifications.create() - .text(message) - .position(Pos.BOTTOM_CENTER) - .hideAfter(TOAST_MESSAGE_DISPLAY_TIME) - .owner(mainWindow) - .threshold(5, - Notifications.create() - .title(Localization.lang("Last notification")) - .text( - "(" + Localization.lang("Check the event log to see all notifications") + ")" - + "\n\n" + message) - .onAction(e -> { - ErrorConsoleAction ec = new ErrorConsoleAction(); - ec.execute(); - })) - .hideCloseButton() - .show()); + Notifications.create() + .text(message) + .position(Pos.BOTTOM_CENTER) + .hideAfter(TOAST_MESSAGE_DISPLAY_TIME) + .owner(mainWindow) + .threshold(5, + Notifications.create() + .title(Localization.lang("Last notification")) + .text( + "(" + Localization.lang("Check the event log to see all notifications") + ")" + + "\n\n" + message) + .onAction(e -> { + ErrorConsoleAction ec = new ErrorConsoleAction(); + ec.execute(); + })) + .hideCloseButton() + .show()); } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/JabRefGUI.java b/jabgui/src/main/java/org/jabref/gui/JabRefGUI.java index bbfa03714f0..dd5f3f4be1b 100644 --- a/jabgui/src/main/java/org/jabref/gui/JabRefGUI.java +++ b/jabgui/src/main/java/org/jabref/gui/JabRefGUI.java @@ -326,7 +326,7 @@ public void onShowing(WindowEvent event) { // Open last edited databases if (uiCommands.stream().noneMatch(UiCommand.BlankWorkspace.class::isInstance) - && preferences.getWorkspacePreferences().shouldOpenLastEdited()) { + && preferences.getWorkspacePreferences().shouldOpenLastEdited()) { mainFrame.openLastEditedDatabases(); } diff --git a/jabgui/src/main/java/org/jabref/gui/LibraryTab.java b/jabgui/src/main/java/org/jabref/gui/LibraryTab.java index 4891b5c6b20..5ce88cfb81e 100644 --- a/jabgui/src/main/java/org/jabref/gui/LibraryTab.java +++ b/jabgui/src/main/java/org/jabref/gui/LibraryTab.java @@ -53,7 +53,7 @@ import org.jabref.gui.maintable.MainTableDataModel; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.undo.CountingUndoManager; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; @@ -123,7 +123,6 @@ public class LibraryTab extends Tab implements CommandSelectionTab { private final BooleanProperty canGoForwardProperty = new SimpleBooleanProperty(false); private boolean backOrForwardNavigationActionTriggered = false; - private BibDatabaseContext bibDatabaseContext; // All subscribers needing "coarse" change events should use this filter @@ -210,8 +209,8 @@ private LibraryTab(@NonNull BibDatabaseContext bibDatabaseContext, stateManager.activeDatabaseProperty().addListener((_, _, _) -> { if (preferences.getSearchPreferences().isFulltext()) { - mainTable.getTableModel().refreshSearchMatches(); - } + mainTable.getTableModel().refreshSearchMatches(); + } }); } @@ -466,13 +465,13 @@ public SuggestionProviders getSuggestionProviders() { } public void registerUndoableChanges(List changes) { - NamedCompound ce = new NamedCompound(Localization.lang("Save actions")); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Save actions")); for (FieldChange change : changes) { - ce.addEdit(new UndoableFieldChange(change)); + compoundEdit.addEdit(new UndoableFieldChange(change)); } - ce.end(); - if (ce.hasEdits()) { - getUndoManager().addEdit(ce); + compoundEdit.end(); + if (compoundEdit.hasEdits()) { + getUndoManager().addEdit(compoundEdit); } } @@ -1025,7 +1024,7 @@ public void updateNavigationState() { * Creates a new library tab. Contents are loaded by the {@code dataLoadingTask}. Most of the other parameters are required by {@code resetChangeMonitor()}. * * @param dataLoadingTask The task to execute to load the data asynchronously. - * @param file the path to the file (loaded by the dataLoadingTask) + * @param file the path to the file (loaded by the dataLoadingTask) */ public static LibraryTab createLibraryTab(BackgroundTask dataLoadingTask, Path file, diff --git a/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/AiChatComponent.java b/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/AiChatComponent.java index 8a4b2db488d..2cdf73708df 100644 --- a/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/AiChatComponent.java +++ b/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/AiChatComponent.java @@ -95,8 +95,8 @@ public AiChatComponent(AiService aiService, aiService.getIngestionService().ingest(name, ListUtil.getLinkedFiles(entries).toList(), bibDatabaseContext); ViewLoader.view(this) - .root(this) - .load(); + .root(this) + .load(); } @FXML @@ -215,10 +215,11 @@ private List updateNotificationsForEntry(BibEntry entry) { entry.getFiles().stream().map(file -> aiService.getIngestionService().ingest(file, bibDatabaseContext)).forEach(ingestionStatus -> { switch (ingestionStatus.getState()) { - case PROCESSING -> notifications.add(new Notification( - Localization.lang("File %0 is currently being processed", ingestionStatus.getObject().getLink()), - Localization.lang("After the file is ingested, you will be able to chat with it.") - )); + case PROCESSING -> + notifications.add(new Notification( + Localization.lang("File %0 is currently being processed", ingestionStatus.getObject().getLink()), + Localization.lang("After the file is ingested, you will be able to chat with it.") + )); case ERROR -> { assert ingestionStatus.getException().isPresent(); // When the state is ERROR, the exception must be present. @@ -229,7 +230,8 @@ private List updateNotificationsForEntry(BibEntry entry) { )); } - case SUCCESS -> { } + case SUCCESS -> { + } } }); diff --git a/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/chatprompt/ChatPromptComponent.java b/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/chatprompt/ChatPromptComponent.java index 8bb590103ac..890e1761861 100644 --- a/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/chatprompt/ChatPromptComponent.java +++ b/jabgui/src/main/java/org/jabref/gui/ai/components/aichat/chatprompt/ChatPromptComponent.java @@ -127,9 +127,9 @@ private void initialize() { // The easy way to get rid of this ambiguity is to disallow scrolling when there are new lines in the prompt. // But the exception to this situation is when the caret position is at the beginning of the prompt. history.get().stream() - .skip(newValue.intValue()) - .findFirst() - .ifPresent(message -> userPromptTextArea.setText(message)); + .skip(newValue.intValue()) + .findFirst() + .ifPresent(message -> userPromptTextArea.setText(message)); } } else { // When currentUserMessageScroll is set to NEW_NON_EXISTENT_MESSAGE, then we should: diff --git a/jabgui/src/main/java/org/jabref/gui/ai/components/util/notifications/Notification.java b/jabgui/src/main/java/org/jabref/gui/ai/components/util/notifications/Notification.java index c8123974a16..96eeb7b4767 100644 --- a/jabgui/src/main/java/org/jabref/gui/ai/components/util/notifications/Notification.java +++ b/jabgui/src/main/java/org/jabref/gui/ai/components/util/notifications/Notification.java @@ -9,4 +9,5 @@ * about possible problems with entries (because that will affect LLM output), but on the other hand the user would * like to chat with all available entries in the group, even if some of them are not valid. */ -public record Notification(String title, String message) { } +public record Notification(String title, String message) { +} 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 c5fc8cf8fcc..a1869ff6e75 100644 --- a/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java +++ b/jabgui/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java @@ -41,7 +41,8 @@ public PersonNameStringConverter(AutoCompletePreferences preferences) { public String toString(Author author) { if (autoCompLF) { switch (autoCompleteFirstNameMode) { - case ONLY_ABBREVIATED, BOTH: + case ONLY_ABBREVIATED, + BOTH: return author.getFamilyGiven(true); case ONLY_FULL: return author.getFamilyGiven(false); @@ -51,7 +52,8 @@ public String toString(Author author) { } if (autoCompFF) { switch (autoCompleteFirstNameMode) { - case ONLY_ABBREVIATED, BOTH: + case ONLY_ABBREVIATED, + BOTH: return author.getGivenFamily(true); case ONLY_FULL: return author.getGivenFamily(false); diff --git a/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/AutosaveManager.java b/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/AutosaveManager.java index 95b7c9b3ffe..c8a012edc36 100644 --- a/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/AutosaveManager.java +++ b/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/AutosaveManager.java @@ -44,8 +44,8 @@ private AutosaveManager(BibDatabaseContext bibDatabaseContext, CoarseChangeFilte this.executor.scheduleAtFixedRate( () -> { if (needsSave) { - eventBus.post(new AutosaveEvent()); - needsSave = false; + eventBus.post(new AutosaveEvent()); + needsSave = false; } }, DELAY_BETWEEN_AUTOSAVE_ATTEMPTS_IN_SECONDS, diff --git a/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/BackupManager.java b/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/BackupManager.java index 6477c85aca2..983948d5edc 100644 --- a/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/BackupManager.java +++ b/jabgui/src/main/java/org/jabref/gui/autosaveandbackup/BackupManager.java @@ -137,11 +137,10 @@ public static void shutdown(BibDatabaseContext bibDatabaseContext, Path backupDi /** * Checks whether a backup file exists for the given database file. If it exists, it is checked whether it is * newer and different from the original. - * + *

* In case a discarded file is present, the method also returns false, See also {@link #discardBackup(Path)}. * * @param originalPath Path to the file a backup should be checked for. Example: jabref.bib. - * * @return true if backup file exists AND differs from originalPath. false is the * "default" return value in the good case. In case a discarded file exists, false is returned, too. * In the case of an exception true is returned to ensure that the user checks the output. @@ -303,7 +302,7 @@ private static Path determineDiscardedFile(Path file, Path backupDir) { /** * Marks the backups as discarded. - * + *

* We do not delete any files, because the user might want to recover old backup files. * Therefore, we mark discarded backups by a --discarded file. */ @@ -340,11 +339,11 @@ private void startBackupTask(Path backupDir) { fillQueue(backupDir); executor.scheduleAtFixedRate( - // We need to determine the backup path on each action, because we use the timestamp in the filename - () -> determineBackupPathForNewBackup(backupDir).ifPresent(this::performBackup), - DELAY_BETWEEN_BACKUP_ATTEMPTS_IN_SECONDS, - DELAY_BETWEEN_BACKUP_ATTEMPTS_IN_SECONDS, - TimeUnit.SECONDS); + // We need to determine the backup path on each action, because we use the timestamp in the filename + () -> determineBackupPathForNewBackup(backupDir).ifPresent(this::performBackup), + DELAY_BETWEEN_BACKUP_ATTEMPTS_IN_SECONDS, + DELAY_BETWEEN_BACKUP_ATTEMPTS_IN_SECONDS, + TimeUnit.SECONDS); } private void fillQueue(Path backupDir) { @@ -370,7 +369,7 @@ private void fillQueue(Path backupDir) { * Unregisters the BackupManager from the eventBus of {@link BibDatabaseContext}. * This method should only be used when closing a database/JabRef in a normal way. * - * @param backupDir The backup directory + * @param backupDir The backup directory * @param createBackup If the backup manager should still perform a backup */ private void shutdown(Path backupDir, boolean createBackup) { diff --git a/jabgui/src/main/java/org/jabref/gui/auximport/NewSubLibraryAction.java b/jabgui/src/main/java/org/jabref/gui/auximport/NewSubLibraryAction.java index 2af0171b5da..e807348e537 100644 --- a/jabgui/src/main/java/org/jabref/gui/auximport/NewSubLibraryAction.java +++ b/jabgui/src/main/java/org/jabref/gui/auximport/NewSubLibraryAction.java @@ -9,7 +9,7 @@ /** * The action concerned with generate a new (sub-)database from latex AUX file. - * + *

* A new library is created by {@link org.jabref.gui.importer.NewDatabaseAction} */ public class NewSubLibraryAction extends SimpleCommand { diff --git a/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java b/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java index c204060d7d2..468d606bc13 100644 --- a/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java +++ b/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java @@ -11,7 +11,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableKeyChange; import org.jabref.gui.util.UiTaskExecutor; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; @@ -105,36 +105,36 @@ private void checkOverwriteKeysChosen() { private BackgroundTask generateKeysInBackground() { return new BackgroundTask<>() { - private NamedCompound compound; + private NamedCompoundEdit compound; @Override public Void call() { - if (isCanceled) { - return null; - } - UiTaskExecutor.runInJavaFXThread(() -> { - updateProgress(0, entries.size()); - messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size())); - }); - stateManager.getActiveDatabase().ifPresent(databaseContext -> { - // generate the new citation keys for each entry - compound = new NamedCompound(Localization.lang("Autogenerate citation keys")); - CitationKeyGenerator keyGenerator = - new CitationKeyGenerator(databaseContext, preferences.getCitationKeyPatternPreferences()); - int entriesDone = 0; - for (BibEntry entry : entries) { - keyGenerator.generateAndSetKey(entry) - .ifPresent(fieldChange -> compound.addEdit(new UndoableKeyChange(fieldChange))); - entriesDone++; - int finalEntriesDone = entriesDone; - UiTaskExecutor.runInJavaFXThread(() -> { - updateProgress(finalEntriesDone, entries.size()); - messageProperty().set(Localization.lang("%0/%1 entries", finalEntriesDone, entries.size())); - }); - } - compound.end(); - }); + if (isCanceled) { return null; + } + UiTaskExecutor.runInJavaFXThread(() -> { + updateProgress(0, entries.size()); + messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size())); + }); + stateManager.getActiveDatabase().ifPresent(databaseContext -> { + // generate the new citation keys for each entry + compound = new NamedCompoundEdit(Localization.lang("Autogenerate citation keys")); + CitationKeyGenerator keyGenerator = + new CitationKeyGenerator(databaseContext, preferences.getCitationKeyPatternPreferences()); + int entriesDone = 0; + for (BibEntry entry : entries) { + keyGenerator.generateAndSetKey(entry) + .ifPresent(fieldChange -> compound.addEdit(new UndoableKeyChange(fieldChange))); + entriesDone++; + int finalEntriesDone = entriesDone; + UiTaskExecutor.runInJavaFXThread(() -> { + updateProgress(finalEntriesDone, entries.size()); + messageProperty().set(Localization.lang("%0/%1 entries", finalEntriesDone, entries.size())); + }); + } + compound.end(); + }); + return null; } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupAction.java b/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupAction.java index 1a59a432559..b623ae39bd7 100644 --- a/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupAction.java +++ b/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupAction.java @@ -15,7 +15,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.JabRefException; import org.jabref.logic.cleanup.CleanupPreferences; @@ -109,7 +109,7 @@ public void execute() { * * @return true iff entry was modified */ - private boolean doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompound ce) { + private boolean doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompoundEdit compoundEdit) { // Create and run cleaner CleanupWorker cleaner = new CleanupWorker( databaseContext, @@ -121,7 +121,7 @@ private boolean doCleanup(BibDatabaseContext databaseContext, CleanupPreferences // Register undo action for (FieldChange change : changes) { - ce.addEdit(new UndoableFieldChange(change)); + compoundEdit.addEdit(new UndoableFieldChange(change)); } failures.addAll(cleaner.getFailures()); @@ -151,18 +151,18 @@ private void cleanup(BibDatabaseContext databaseContext, CleanupPreferences clea this.failures.clear(); // undo granularity is on set of all entries - NamedCompound ce = new NamedCompound(Localization.lang("Clean up entries")); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Clean up entries")); for (BibEntry entry : List.copyOf(stateManager.getSelectedEntries())) { - if (doCleanup(databaseContext, cleanupPreferences, entry, ce)) { + if (doCleanup(databaseContext, cleanupPreferences, entry, compoundEdit)) { modifiedEntriesCount++; } } - ce.end(); + compoundEdit.end(); - if (ce.hasEdits()) { - undoManager.addEdit(ce); + if (compoundEdit.hasEdits()) { + undoManager.addEdit(compoundEdit); } if (!failures.isEmpty()) { diff --git a/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupSingleAction.java b/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupSingleAction.java index 6f9ffc08892..ccec9065541 100644 --- a/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupSingleAction.java +++ b/jabgui/src/main/java/org/jabref/gui/cleanup/CleanupSingleAction.java @@ -11,7 +11,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.JabRefException; import org.jabref.logic.cleanup.CleanupPreferences; @@ -79,7 +79,7 @@ public void execute() { /** * Runs the cleanup on the entry and records the change. */ - private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompound ce) { + private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompoundEdit compoundEdit) { // Create and run cleaner CleanupWorker cleaner = new CleanupWorker( databaseContext, @@ -91,7 +91,7 @@ private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences pr // Register undo action for (FieldChange change : changes) { - ce.addEdit(new UndoableFieldChange(change)); + compoundEdit.addEdit(new UndoableFieldChange(change)); } if (!cleaner.getFailures().isEmpty()) { @@ -100,15 +100,15 @@ private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences pr } private void cleanup(BibDatabaseContext databaseContext, CleanupPreferences cleanupPreferences) { - // undo granularity is on entry level - NamedCompound ce = new NamedCompound(Localization.lang("Cleanup entry")); + // undo granularity is on entry level + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Cleanup entry")); - doCleanup(databaseContext, cleanupPreferences, entry, ce); + doCleanup(databaseContext, cleanupPreferences, entry, compoundEdit); - ce.end(); - if (ce.hasEdits()) { - undoManager.addEdit(ce); - } + compoundEdit.end(); + if (compoundEdit.hasEdits()) { + undoManager.addEdit(compoundEdit); + } } private void showFailures(List failures) { diff --git a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChange.java b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChange.java index 2cd4105df0f..246386542ea 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChange.java @@ -17,7 +17,7 @@ import org.jabref.gui.collab.stringchange.BibTexStringChange; import org.jabref.gui.collab.stringdelete.BibTexStringDelete; import org.jabref.gui.collab.stringrename.BibTexStringRename; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.logic.util.OptionalObjectProperty; import org.jabref.model.database.BibDatabaseContext; @@ -67,5 +67,5 @@ public Optional getExternalChangeResolver() { return externalChangeResolver.get(); } - public abstract void applyChange(NamedCompound undoEdit); + public abstract void applyChange(NamedCompoundEdit undoEdit); } diff --git a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsViewFactory.java b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsViewFactory.java index 39939bce263..a9e49e3ce8f 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsViewFactory.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsViewFactory.java @@ -54,41 +54,51 @@ public DatabaseChangeDetailsViewFactory(BibDatabaseContext databaseContext, public DatabaseChangeDetailsView create(DatabaseChange databaseChange) { return switch (databaseChange) { - case EntryChange entryChange -> new EntryChangeDetailsView( - entryChange.getOldEntry(), - entryChange.getNewEntry(), - databaseContext, - dialogService, - themeManager, - preferences, - entryTypesManager, - previewViewer, - taskExecutor - ); - case EntryAdd entryAdd -> new EntryWithPreviewAndSourceDetailsView( - entryAdd.getAddedEntry(), - databaseContext, - preferences, - entryTypesManager, - previewViewer - ); - case EntryDelete entryDelete -> new EntryWithPreviewAndSourceDetailsView( - entryDelete.getDeletedEntry(), - databaseContext, - preferences, - entryTypesManager, - previewViewer - ); - case BibTexStringAdd stringAdd -> new BibTexStringAddDetailsView(stringAdd); - case BibTexStringDelete stringDelete -> new BibTexStringDeleteDetailsView(stringDelete); - case BibTexStringChange stringChange -> new BibTexStringChangeDetailsView(stringChange); - case BibTexStringRename stringRename -> new BibTexStringRenameDetailsView(stringRename); - case MetadataChange metadataChange -> new MetadataChangeDetailsView( - metadataChange, - preferences.getCitationKeyPatternPreferences().getKeyPatterns() - ); - case GroupChange groupChange -> new GroupChangeDetailsView(groupChange); - case PreambleChange preambleChange -> new PreambleChangeDetailsView(preambleChange); + case EntryChange entryChange -> + new EntryChangeDetailsView( + entryChange.getOldEntry(), + entryChange.getNewEntry(), + databaseContext, + dialogService, + themeManager, + preferences, + entryTypesManager, + previewViewer, + taskExecutor + ); + case EntryAdd entryAdd -> + new EntryWithPreviewAndSourceDetailsView( + entryAdd.getAddedEntry(), + databaseContext, + preferences, + entryTypesManager, + previewViewer + ); + case EntryDelete entryDelete -> + new EntryWithPreviewAndSourceDetailsView( + entryDelete.getDeletedEntry(), + databaseContext, + preferences, + entryTypesManager, + previewViewer + ); + case BibTexStringAdd stringAdd -> + new BibTexStringAddDetailsView(stringAdd); + case BibTexStringDelete stringDelete -> + new BibTexStringDeleteDetailsView(stringDelete); + case BibTexStringChange stringChange -> + new BibTexStringChangeDetailsView(stringChange); + case BibTexStringRename stringRename -> + new BibTexStringRenameDetailsView(stringRename); + case MetadataChange metadataChange -> + new MetadataChangeDetailsView( + metadataChange, + preferences.getCitationKeyPatternPreferences().getKeyPatterns() + ); + case GroupChange groupChange -> + new GroupChangeDetailsView(groupChange); + case PreambleChange preambleChange -> + new PreambleChangeDetailsView(preambleChange); }; } } diff --git a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeMonitor.java b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeMonitor.java index 3d965621b9d..9fedda759fc 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeMonitor.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangeMonitor.java @@ -14,7 +14,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.BackgroundTask; import org.jabref.logic.util.TaskExecutor; @@ -81,10 +81,10 @@ private void notifyOnChange(List changes) { DatabaseChangesResolverDialog databaseChangesResolverDialog = new DatabaseChangesResolverDialog(changes, database, Localization.lang("External Changes Resolver")); Optional areAllChangesResolved = dialogService.showCustomDialogAndWait(databaseChangesResolverDialog); saveState = stateManager.activeTabProperty().get().get(); - final NamedCompound ce = new NamedCompound(Localization.lang("Merged external changes")); - changes.stream().filter(DatabaseChange::isAccepted).forEach(change -> change.applyChange(ce)); - ce.end(); - undoManager.addEdit(ce); + final NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Merged external changes")); + changes.stream().filter(DatabaseChange::isAccepted).forEach(change -> change.applyChange(compoundEdit)); + compoundEdit.end(); + undoManager.addEdit(compoundEdit); if (areAllChangesResolved.get()) { if (databaseChangesResolverDialog.areAllChangesAccepted()) { // In case all changes of the file on disk are merged into the current in-memory file, the file on disk does not differ from the in-memory file diff --git a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangesResolverDialog.java b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangesResolverDialog.java index 3c0be42e6ed..153470dd696 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangesResolverDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/DatabaseChangesResolverDialog.java @@ -66,7 +66,7 @@ public class DatabaseChangesResolverDialog extends BaseDialog { * A dialog going through given changes, which are diffs to the provided database. * Each accepted change is written to the provided database. * - * @param changes The list of changes + * @param changes The list of changes * @param database The database to apply the changes to */ public DatabaseChangesResolverDialog(List changes, BibDatabaseContext database, String dialogTitle) { @@ -75,8 +75,8 @@ public DatabaseChangesResolverDialog(List changes, BibDatabaseCo this.setTitle(dialogTitle); ViewLoader.view(this) - .load() - .setAsDialogPane(this); + .load() + .setAsDialogPane(this); this.setResultConverter(button -> { if (viewModel.areAllChangesResolved()) { diff --git a/jabgui/src/main/java/org/jabref/gui/collab/entryadd/EntryAdd.java b/jabgui/src/main/java/org/jabref/gui/collab/entryadd/EntryAdd.java index abf8ae633bf..8405d30c0ec 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/entryadd/EntryAdd.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/entryadd/EntryAdd.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -15,12 +15,12 @@ public EntryAdd(BibEntry addedEntry, BibDatabaseContext databaseContext, Databas super(databaseContext, databaseChangeResolverFactory); this.addedEntry = addedEntry; setChangeName(addedEntry.getCitationKey() - .map(key -> Localization.lang("Added entry '%0'", key)) - .orElse(Localization.lang("Added entry"))); + .map(key -> Localization.lang("Added entry '%0'", key)) + .orElse(Localization.lang("Added entry"))); } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { databaseContext.getDatabase().insertEntry(addedEntry); undoEdit.addEdit(new UndoableInsertEntries(databaseContext.getDatabase(), addedEntry)); } diff --git a/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChange.java b/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChange.java index 44189beef93..e921ce482e0 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChange.java @@ -4,7 +4,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; @@ -20,7 +20,7 @@ public EntryChange(BibEntry oldEntry, BibEntry newEntry, BibDatabaseContext data this.oldEntry = oldEntry; this.newEntry = newEntry; setChangeName(oldEntry.getCitationKey().map(key -> Localization.lang("Modified entry '%0'", key)) - .orElse(Localization.lang("Modified entry"))); + .orElse(Localization.lang("Modified entry"))); } public EntryChange(BibEntry oldEntry, BibEntry newEntry, BibDatabaseContext databaseContext) { @@ -36,7 +36,7 @@ public BibEntry getNewEntry() { } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { databaseContext.getDatabase().removeEntry(oldEntry); databaseContext.getDatabase().insertEntry(newEntry); CompoundEdit changeEntryEdit = new CompoundEdit(); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeDetailsView.java b/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeDetailsView.java index 552e2e7bdb3..2f91e5fb135 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeDetailsView.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeDetailsView.java @@ -56,8 +56,8 @@ public EntryChangeDetailsView(BibEntry oldEntry, TabPane newEntryTabPane = newPreviewWithSourcesTab.getPreviewWithSourceTab(newEntry, databaseContext, preferences, entryTypesManager, previewViewer, Localization.lang("Entry Preview")); EasyBind.subscribe( - oldEntryTabPane.getSelectionModel().selectedIndexProperty(), - selectedIndex -> newEntryTabPane.getSelectionModel().select(selectedIndex.intValue())); + oldEntryTabPane.getSelectionModel().selectedIndexProperty(), + selectedIndex -> newEntryTabPane.getSelectionModel().select(selectedIndex.intValue())); EasyBind.subscribe(newEntryTabPane.getSelectionModel().selectedIndexProperty(), selectedIndex -> { if (oldEntryTabPane.getSelectionModel().getSelectedIndex() != selectedIndex.intValue()) { diff --git a/jabgui/src/main/java/org/jabref/gui/collab/entrydelete/EntryDelete.java b/jabgui/src/main/java/org/jabref/gui/collab/entrydelete/EntryDelete.java index 36116bb5845..d71e6f4fe83 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/entrydelete/EntryDelete.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/entrydelete/EntryDelete.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -15,12 +15,12 @@ public EntryDelete(BibEntry deletedEntry, BibDatabaseContext databaseContext, Da super(databaseContext, databaseChangeResolverFactory); this.deletedEntry = deletedEntry; setChangeName(deletedEntry.getCitationKey() - .map(key -> Localization.lang("Deleted entry '%0'", key)) - .orElse(Localization.lang("Deleted entry"))); + .map(key -> Localization.lang("Deleted entry '%0'", key)) + .orElse(Localization.lang("Deleted entry"))); } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { databaseContext.getDatabase().removeEntry(deletedEntry); undoEdit.addEdit(new UndoableRemoveEntries(databaseContext.getDatabase(), deletedEntry)); } diff --git a/jabgui/src/main/java/org/jabref/gui/collab/groupchange/GroupChange.java b/jabgui/src/main/java/org/jabref/gui/collab/groupchange/GroupChange.java index 4444d0f79c3..29457b24d7a 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/groupchange/GroupChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/groupchange/GroupChange.java @@ -4,7 +4,7 @@ import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.groups.GroupTreeNodeViewModel; import org.jabref.gui.groups.UndoableModifySubtree; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.logic.bibtex.comparator.GroupDiff; import org.jabref.logic.groups.DefaultGroupsFactory; import org.jabref.logic.l10n.Localization; @@ -22,7 +22,7 @@ public GroupChange(GroupDiff groupDiff, BibDatabaseContext databaseContext, Data } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { GroupTreeNode oldRoot = groupDiff.getOriginalGroupRoot(); GroupTreeNode newRoot = groupDiff.getNewGroupRoot(); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChange.java b/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChange.java index 571fe74b752..38c081fce2d 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChange.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.logic.bibtex.comparator.MetaDataDiff; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -17,7 +17,7 @@ public MetadataChange(MetaDataDiff metaDataDiff, BibDatabaseContext databaseCont } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { // TODO: Metadata edit should be undoable databaseContext.setMetaData(metaDataDiff.getNewMetaData()); // group change is handled by GroupChange, so we set the groups root to the original value diff --git a/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChangeDetailsView.java b/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChangeDetailsView.java index 09600d4c756..4700361558e 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChangeDetailsView.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChangeDetailsView.java @@ -38,8 +38,8 @@ public MetadataChangeDetailsView(MetadataChange metadataChange, GlobalCitationKe * Adds a view for a specific metadata difference to the container. * Default view if not a group diff. * - * @param container The parent container to add the difference view to - * @param diff The metadata difference to display + * @param container The parent container to add the difference view to + * @param diff The metadata difference to display * @param metadataChange The metadata change object containing all changes */ private void addDifferenceView(VBox container, MetaDataDiff.Difference diff, MetadataChange metadataChange) { @@ -176,14 +176,14 @@ private String convertGroupTreeToString(GroupTreeNode node) { /** * Recursively appends a group tree node to the string builder. * - * @param node The current node to append + * @param node The current node to append * @param builder The string builder to append to - * @param level The current depth level in the tree (for indentation) + * @param level The current depth level in the tree (for indentation) */ private void appendGroupTreeNode(GroupTreeNode node, StringBuilder builder, int level) { builder.append("| ".repeat(level)) - .append(node.getName()) - .append("\n"); + .append(node.getName()) + .append("\n"); for (GroupTreeNode child : node.getChildren()) { appendGroupTreeNode(child, builder, level + 1); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChange.java b/jabgui/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChange.java index 5789d2bbbcc..0011e0ecd9e 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChange.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoablePreambleChange; import org.jabref.logic.bibtex.comparator.PreambleDiff; import org.jabref.logic.l10n.Localization; @@ -24,7 +24,7 @@ public PreambleChange(PreambleDiff preambleDiff, BibDatabaseContext databaseCont } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { databaseContext.getDatabase().setPreamble(preambleDiff.getNewPreamble()); undoEdit.addEdit(new UndoablePreambleChange(databaseContext.getDatabase(), preambleDiff.getOriginalPreamble(), preambleDiff.getNewPreamble())); } diff --git a/jabgui/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAdd.java b/jabgui/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAdd.java index 98c311ca6dc..2ae2abbe6ee 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAdd.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAdd.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertString; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -24,7 +24,7 @@ public BibTexStringAdd(BibtexString addedString, BibDatabaseContext databaseCont } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { try { databaseContext.getDatabase().addString(addedString); undoEdit.addEdit(new UndoableInsertString(databaseContext.getDatabase(), addedString)); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChange.java b/jabgui/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChange.java index 8cb58e99d46..f9655e70467 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChange.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChange.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableStringChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -26,7 +26,7 @@ public BibTexStringChange(BibtexString oldString, BibtexString newString, BibDat } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { String oldContent = oldString.getContent(); String newContent = newString.getContent(); oldString.setContent(newContent); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDelete.java b/jabgui/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDelete.java index 2f55cf7d331..dbf14dd4219 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDelete.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDelete.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableRemoveString; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -23,7 +23,7 @@ public BibTexStringDelete(BibtexString deletedString, BibDatabaseContext databas } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { try { databaseContext.getDatabase().removeString(deletedString.getId()); undoEdit.addEdit(new UndoableRemoveString(databaseContext.getDatabase(), deletedString)); diff --git a/jabgui/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRename.java b/jabgui/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRename.java index 0236ebda467..90c732228fc 100644 --- a/jabgui/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRename.java +++ b/jabgui/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRename.java @@ -2,7 +2,7 @@ import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableStringChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; @@ -26,7 +26,7 @@ public BibTexStringRename(BibtexString oldString, BibtexString newString, BibDat } @Override - public void applyChange(NamedCompound undoEdit) { + public void applyChange(NamedCompoundEdit undoEdit) { if (databaseContext.getDatabase().hasStringByName(newString.getName())) { // The name to change to is already in the database, so we can't comply. LOGGER.info("Cannot rename string '{}' to '{}' because the name is already in use", oldString.getName(), newString.getName()); diff --git a/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanel.java b/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanel.java index 557f961d424..cf94debf73a 100644 --- a/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanel.java +++ b/jabgui/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanel.java @@ -60,8 +60,8 @@ private void initialize() { viewModel.sortCriteriaProperty().addListener((ListChangeListener) change -> { while (change.next()) { if (change.wasReplaced()) { - clearCriterionRow(change.getFrom()); - createCriterionRow(change.getAddedSubList().getFirst(), change.getFrom()); + clearCriterionRow(change.getFrom()); + createCriterionRow(change.getAddedSubList().getFirst(), change.getFrom()); } else if (change.wasAdded()) { for (SortCriterionViewModel criterionViewModel : change.getAddedSubList()) { int row = change.getFrom() + change.getAddedSubList().indexOf(criterionViewModel); 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 7924781dc3b..289c53c5a4d 100644 --- a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialog.java @@ -90,7 +90,7 @@ public void initialize() { viewModel.selectedEntryTypeProperty().addListener((_, _, newValue) -> filteredData.setPredicate(message -> message.message().getFirst().equals(newValue) - )); + )); tableView.setItems(filteredData); @@ -168,8 +168,8 @@ protected void updateItem(String item, boolean empty) { ); targetSymbols.stream() - .map(ConsistencySymbol::getText) - .forEach(this::removeColumnWithUniformValue); + .map(ConsistencySymbol::getText) + .forEach(this::removeColumnWithUniformValue); Arrays.stream(SpecialField.values()) .map(SpecialField::getDisplayName) 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 263cd7576b3..7463fccc971 100644 --- a/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/consistency/ConsistencyCheckDialogViewModel.java @@ -65,10 +65,10 @@ public ConsistencyCheckDialogViewModel(DialogService dialogService, this.result = result; this.allReportedFields = result.entryTypeToResultMap().values().stream() - .flatMap(entryTypeResult -> entryTypeResult.fields().stream()) - .sorted(Comparator.comparing(Field::getName)) - .distinct() - .toList(); + .flatMap(entryTypeResult -> entryTypeResult.fields().stream()) + .sorted(Comparator.comparing(Field::getName)) + .distinct() + .toList(); result.entryTypeToResultMap().entrySet().stream() .sorted(Comparator.comparing(entry -> entry.getKey().getName())) @@ -93,7 +93,7 @@ public List getColumnNames() { List result = new ArrayList<>(allReportedFields.size() + 2); // there are two extra columns result.add("Entry Type"); result.add("CitationKey"); - allReportedFields.forEach(field-> result.add(field.getDisplayName().trim())); + allReportedFields.forEach(field -> result.add(field.getDisplayName().trim())); return result; } @@ -119,14 +119,14 @@ private void writeMapEntry(Map.Entry bibEntries = entries.sortedEntries(); bibEntries.forEach(Unchecked.consumer(bibEntry -> - writeBibEntry(bibEntry, entryType, requiredFields, optionalFields) + writeBibEntry(bibEntry, entryType, requiredFields, optionalFields) )); } 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) { + for (String s : theRecord) { String modifiedString = s.replaceAll("\\s+", " "); message.add(modifiedString); } @@ -138,15 +138,15 @@ private List getFindingsAsList(BibEntry bibEntry, String entryType, Set< result.add(entryType); result.add(bibEntry.getCitationKey().orElse("")); allReportedFields.forEach(field -> - result.add(bibEntry.getField(field).map(_ -> { - if (requiredFields.contains(field)) { - return ConsistencySymbol.REQUIRED_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); - } else if (optionalFields.contains(field)) { - return ConsistencySymbol.OPTIONAL_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); - } else { - return ConsistencySymbol.UNKNOWN_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); - } - }).orElse(ConsistencySymbol.UNSET_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText())) + result.add(bibEntry.getField(field).map(_ -> { + if (requiredFields.contains(field)) { + return ConsistencySymbol.REQUIRED_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); + } else if (optionalFields.contains(field)) { + return ConsistencySymbol.OPTIONAL_FIELD_AT_ENTRY_TYPE_CELL_ENTRY.getText(); + } else { + return ConsistencySymbol.UNKNOWN_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/desktop/os/NativeDesktop.java b/jabgui/src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java index 39539032415..af7dea79214 100644 --- a/jabgui/src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java +++ b/jabgui/src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java @@ -49,7 +49,7 @@ *

* See https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform for more implementation hints. * https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html cannot be used as we don't want to rely on AWT. - * + *

* For non-GUI things, see {@link org.jabref.logic.os.OS}. */ @AllowedToUseAwt("Because of moveToTrash() is not available elsewhere.") @@ -139,7 +139,8 @@ public static void openExternalViewer(BibDatabaseContext databaseContext, LoggerFactory.getLogger(NativeDesktop.class).error("An error occurred on the command: {}", link, e); } } - case null, default -> + case null, + default -> LoggerFactory.getLogger(NativeDesktop.class).info("Message: currently only PDF, PS and HTML files can be opened by double clicking"); } } @@ -358,13 +359,13 @@ public static NativeDesktop get() { * @return the path */ public Path getDefaultFileChooserDirectory() { - Path userDirectory = Directories.getUserDirectory(); - Path documents = userDirectory.resolve("Documents"); - if (!Files.exists(documents)) { - return userDirectory; - } - return documents; - } + Path userDirectory = Directories.getUserDirectory(); + Path documents = userDirectory.resolve("Documents"); + if (!Files.exists(documents)) { + return userDirectory; + } + return documents; + } /** * Moves the given file to the trash. diff --git a/jabgui/src/main/java/org/jabref/gui/desktop/os/OSX.java b/jabgui/src/main/java/org/jabref/gui/desktop/os/OSX.java index 98feb0f4230..06762bce2f7 100644 --- a/jabgui/src/main/java/org/jabref/gui/desktop/os/OSX.java +++ b/jabgui/src/main/java/org/jabref/gui/desktop/os/OSX.java @@ -47,7 +47,7 @@ public void openFolderAndSelectFile(Path file) throws IOException { @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { - new ProcessBuilder("open", "-a", "Terminal", absolutePath).start(); + new ProcessBuilder("open", "-a", "Terminal", absolutePath).start(); } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/dialogs/BackupUIManager.java b/jabgui/src/main/java/org/jabref/gui/dialogs/BackupUIManager.java index 0df7d1c12e1..d79bed95e09 100644 --- a/jabgui/src/main/java/org/jabref/gui/dialogs/BackupUIManager.java +++ b/jabgui/src/main/java/org/jabref/gui/dialogs/BackupUIManager.java @@ -20,7 +20,7 @@ import org.jabref.gui.collab.DatabaseChangesResolverDialog; import org.jabref.gui.frame.ExternalApplicationsPreferences; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.util.UiTaskExecutor; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.OpenDatabase; @@ -102,7 +102,7 @@ private static Optional showReviewBackupDialog( ); Optional allChangesResolved = dialogService.showCustomDialogAndWait(reviewBackupDialog); LibraryTab saveState = stateManager.activeTabProperty().get().get(); - final NamedCompound CE = new NamedCompound(Localization.lang("Merged external changes")); + final NamedCompoundEdit CE = new NamedCompoundEdit(Localization.lang("Merged external changes")); changes.stream().filter(DatabaseChange::isAccepted).forEach(change -> change.applyChange(CE)); CE.end(); undoManager.addEdit(CE); diff --git a/jabgui/src/main/java/org/jabref/gui/documentviewer/DocumentViewerView.java b/jabgui/src/main/java/org/jabref/gui/documentviewer/DocumentViewerView.java index 9544366d836..24f7d31ce2e 100644 --- a/jabgui/src/main/java/org/jabref/gui/documentviewer/DocumentViewerView.java +++ b/jabgui/src/main/java/org/jabref/gui/documentviewer/DocumentViewerView.java @@ -103,7 +103,7 @@ private void setupFileChoice() { private void setupViewer() { viewModel.currentDocumentProperty().addListener((_, _, newDocument) -> { - viewer.show(newDocument); + viewer.show(newDocument); }); viewModel.currentPageProperty().bindBidirectional(viewer.currentPageProperty()); viewModel.highlightTextProperty().bindBidirectional(viewer.highlightTextProperty()); diff --git a/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateResolverDialog.java b/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateResolverDialog.java index 5629a41cc9c..945500f9ac2 100644 --- a/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateResolverDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateResolverDialog.java @@ -107,7 +107,8 @@ private void init(BibEntry one, BibEntry two, DuplicateResolverType type) { threeWayMerge = new ThreeWayMergeView(one, two, Localization.lang("Existing entry"), Localization.lang("From import"), preferences); } - default -> throw new IllegalStateException("Switch expression should be exhaustive"); + default -> + throw new IllegalStateException("Switch expression should be exhaustive"); } this.getDialogPane().getButtonTypes().addAll(first, second, both, merge, cancel); diff --git a/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateSearch.java b/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateSearch.java index f2e5ed1a0c8..73ea29d6f7e 100644 --- a/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateSearch.java +++ b/jabgui/src/main/java/org/jabref/gui/duplicationFinder/DuplicateSearch.java @@ -23,7 +23,7 @@ import org.jabref.gui.duplicationFinder.DuplicateResolverDialog.DuplicateResolverResult; import org.jabref.gui.duplicationFinder.DuplicateResolverDialog.DuplicateResolverType; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.gui.util.UiTaskExecutor; @@ -190,7 +190,7 @@ private void handleDuplicates(DuplicateSearchResult result) { } LibraryTab libraryTab = tabSupplier.get(); - final NamedCompound compoundEdit = new NamedCompound(Localization.lang("duplicate removal")); + final NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("duplicate removal")); // Now, do the actual removal: if (!result.getToRemove().isEmpty()) { compoundEdit.addEdit(new UndoableRemoveEntries(libraryTab.getDatabase(), result.getToRemove())); diff --git a/jabgui/src/main/java/org/jabref/gui/edit/CopyMoreAction.java b/jabgui/src/main/java/org/jabref/gui/edit/CopyMoreAction.java index d99d35c7863..1268ba239c5 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/CopyMoreAction.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/CopyMoreAction.java @@ -69,7 +69,8 @@ public void execute() { copyKeyAndTitle(); case COPY_CITATION_KEY_AND_LINK -> copyKeyAndLink(); - case COPY_DOI, COPY_DOI_URL -> + case COPY_DOI, + COPY_DOI_URL -> copyDoi(); case COPY_FIELD_AUTHOR -> copyField(StandardField.AUTHOR, Localization.lang("Author")); 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 48133bb10da..30df1722dc3 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/EditAction.java @@ -56,14 +56,22 @@ public void execute() { // Focus is on text field -> copy/paste/cut selected text // DELETE_ENTRY in text field should do forward delete switch (action) { - case SELECT_ALL -> textInput.selectAll(); - case COPY -> textInput.copy(); - case CUT -> textInput.cut(); - case PASTE -> textInput.paste(); - case DELETE -> textInput.clear(); - case DELETE_ENTRY -> textInput.deleteNextChar(); - case UNDO -> textInput.undo(); - case REDO -> textInput.redo(); + case SELECT_ALL -> + textInput.selectAll(); + case COPY -> + textInput.copy(); + case CUT -> + textInput.cut(); + case PASTE -> + textInput.paste(); + case DELETE -> + textInput.clear(); + case DELETE_ENTRY -> + textInput.deleteNextChar(); + case UNDO -> + textInput.undo(); + case REDO -> + textInput.redo(); default -> { String message = "Only cut/copy/paste supported in TextInputControl but got " + action; LOGGER.error(message); @@ -77,10 +85,14 @@ public void execute() { // Not sure what is selected -> copy/paste/cut selected entries except for Preview and CodeArea switch (action) { - case COPY -> tabSupplier.get().copyEntry(); - case CUT -> tabSupplier.get().cutEntry(); - case PASTE -> tabSupplier.get().pasteEntry(); - case DELETE_ENTRY -> tabSupplier.get().deleteEntry(); + case COPY -> + tabSupplier.get().copyEntry(); + case CUT -> + tabSupplier.get().cutEntry(); + case PASTE -> + tabSupplier.get().pasteEntry(); + case DELETE_ENTRY -> + tabSupplier.get().deleteEntry(); case UNDO -> { if (undoManager.canUndo()) { undoManager.undo(); @@ -91,7 +103,8 @@ public void execute() { undoManager.redo(); } } - default -> LOGGER.debug("Only cut/copy/paste/deleteEntry supported but got: {} and focus owner {}", action, focusOwner); + default -> + LOGGER.debug("Only cut/copy/paste/deleteEntry supported but got: {} and focus owner {}", action, focusOwner); } } }); diff --git a/jabgui/src/main/java/org/jabref/gui/edit/ManageKeywordsViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/ManageKeywordsViewModel.java index c4a5f8773a0..2012270e97c 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/ManageKeywordsViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/ManageKeywordsViewModel.java @@ -8,7 +8,7 @@ import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; @@ -104,15 +104,15 @@ public void saveChanges() { return; } - NamedCompound ce = updateKeywords(entries, keywordsToAdd, keywordsToRemove); - // TODO: bp.getUndoManager().addEdit(ce); + NamedCompoundEdit compoundEdit = updateKeywords(entries, keywordsToAdd, keywordsToRemove); + // TODO: bp.getUndoManager().addEdit(compoundEdit); } - private NamedCompound updateKeywords(List entries, KeywordList keywordsToAdd, - KeywordList keywordsToRemove) { + private NamedCompoundEdit updateKeywords(List entries, KeywordList keywordsToAdd, + KeywordList keywordsToRemove) { Character keywordSeparator = bibEntryPreferences.getKeywordSeparator(); - NamedCompound ce = new NamedCompound(Localization.lang("Update keywords")); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Update keywords")); for (BibEntry entry : entries) { KeywordList keywords = entry.getKeywords(keywordSeparator); @@ -122,9 +122,9 @@ private NamedCompound updateKeywords(List entries, KeywordList keyword // put keywords back Optional change = entry.putKeywords(keywords, keywordSeparator); - change.ifPresent(fieldChange -> ce.addEdit(new UndoableFieldChange(fieldChange))); + change.ifPresent(fieldChange -> compoundEdit.addEdit(new UndoableFieldChange(fieldChange))); } - ce.end(); - return ce; + compoundEdit.end(); + return compoundEdit; } } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/ReplaceStringViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/ReplaceStringViewModel.java index 04db4bf9147..bf5694b7a44 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/ReplaceStringViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/ReplaceStringViewModel.java @@ -10,7 +10,7 @@ import org.jabref.gui.AbstractViewModel; import org.jabref.gui.LibraryTab; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; @@ -42,7 +42,7 @@ public int replace() { boolean selOnly = selectOnlyProperty.getValue(); allFieldReplace = allFieldReplaceProperty.getValue(); - final NamedCompound compound = new NamedCompound(Localization.lang("Replace string")); + final NamedCompoundEdit compound = new NamedCompoundEdit(Localization.lang("Replace string")); int counter = 0; if (selOnly) { for (BibEntry bibEntry : this.panel.getSelectedEntries()) { @@ -60,7 +60,7 @@ public int replace() { * Does the actual operation on a Bibtex entry based on the settings specified in this same dialog. Returns the * number of occurrences replaced. */ - private int replaceItem(BibEntry entry, NamedCompound compound) { + private int replaceItem(BibEntry entry, NamedCompoundEdit compound) { int counter = 0; if (this.allFieldReplace) { for (Field field : entry.getFields()) { @@ -74,7 +74,7 @@ private int replaceItem(BibEntry entry, NamedCompound compound) { return counter; } - private int replaceField(BibEntry entry, Field field, NamedCompound compound) { + private int replaceField(BibEntry entry, Field field, NamedCompoundEdit compound) { if (!entry.hasField(field)) { return 0; } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorViewModel.java index 9eaddbc91d1..28eb1466445 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorViewModel.java @@ -10,13 +10,13 @@ import org.jabref.gui.edit.automaticfiededitor.copyormovecontent.CopyOrMoveFieldContentTabView; import org.jabref.gui.edit.automaticfiededitor.editfieldcontent.EditFieldContentTabView; import org.jabref.gui.edit.automaticfiededitor.renamefield.RenameFieldTabView; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.model.database.BibDatabase; public class AutomaticFieldEditorViewModel extends AbstractViewModel { public static final String NAMED_COMPOUND_EDITS = "EDIT_FIELDS"; private final ObservableList fieldEditorTabs = FXCollections.observableArrayList(); - private final NamedCompound dialogEdits = new NamedCompound(NAMED_COMPOUND_EDITS); + private final NamedCompoundEdit dialogEdits = new NamedCompoundEdit(NAMED_COMPOUND_EDITS); private final UndoManager undoManager; @@ -29,7 +29,7 @@ public AutomaticFieldEditorViewModel(BibDatabase database, UndoManager undoManag ); } - public NamedCompound getDialogEdits() { + public NamedCompoundEdit getDialogEdits() { return dialogEdits; } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/LastAutomaticFieldEditorEdit.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/LastAutomaticFieldEditorEdit.java index a1263576608..539f18d7423 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/LastAutomaticFieldEditorEdit.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/LastAutomaticFieldEditorEdit.java @@ -4,15 +4,15 @@ import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; public class LastAutomaticFieldEditorEdit extends AbstractUndoableEdit { private final Integer affectedEntries; - private final NamedCompound edit; + private final NamedCompoundEdit edit; private final Integer tabIndex; - public LastAutomaticFieldEditorEdit(Integer affectedEntries, Integer tabIndex, NamedCompound edit) { + public LastAutomaticFieldEditorEdit(Integer affectedEntries, Integer tabIndex, NamedCompoundEdit edit) { this.affectedEntries = affectedEntries; this.edit = edit; this.tabIndex = tabIndex; @@ -22,7 +22,7 @@ public Integer getAffectedEntries() { return affectedEntries; } - public NamedCompound getEdit() { + public NamedCompoundEdit getEdit() { return edit; } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/MoveFieldValueAction.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/MoveFieldValueAction.java index 4064b1f4c6b..f7de1d4dfdb 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/MoveFieldValueAction.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/MoveFieldValueAction.java @@ -3,7 +3,7 @@ import java.util.List; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; @@ -14,13 +14,13 @@ public class MoveFieldValueAction extends SimpleCommand { private final Field toField; private final List entries; - private final NamedCompound edits; + private final NamedCompoundEdit edits; private int affectedEntriesCount; private final boolean overwriteToFieldContent; - public MoveFieldValueAction(Field fromField, Field toField, List entries, NamedCompound edits, boolean overwriteToFieldContent) { + public MoveFieldValueAction(Field fromField, Field toField, List entries, NamedCompoundEdit edits, boolean overwriteToFieldContent) { this.fromField = fromField; this.toField = toField; this.entries = entries; @@ -28,7 +28,7 @@ public MoveFieldValueAction(Field fromField, Field toField, List entri this.overwriteToFieldContent = overwriteToFieldContent; } - public MoveFieldValueAction(Field fromField, Field toField, List entries, NamedCompound edits) { + public MoveFieldValueAction(Field fromField, Field toField, List entries, NamedCompoundEdit edits) { this(fromField, toField, entries, edits, true); } diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabViewModel.java index 3ed3a1b38ee..0ccc4262d01 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabViewModel.java @@ -13,7 +13,7 @@ import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel; import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit; import org.jabref.gui.edit.automaticfiededitor.MoveFieldValueAction; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -98,7 +98,7 @@ public BooleanProperty overwriteFieldContentProperty() { } public void copyValue() { - NamedCompound copyFieldValueEdit = new NamedCompound("COPY_FIELD_VALUE"); + NamedCompoundEdit copyFieldValueEdit = new NamedCompoundEdit("COPY_FIELD_VALUE"); int affectedEntriesCount = 0; for (BibEntry entry : selectedEntries) { String fromFieldValue = entry.getField(fromField.get()).orElse(""); @@ -124,7 +124,7 @@ public void copyValue() { } public void moveValue() { - NamedCompound moveEdit = new NamedCompound("MOVE_EDIT"); + NamedCompoundEdit moveEdit = new NamedCompoundEdit("MOVE_EDIT"); int affectedEntriesCount = 0; if (overwriteFieldContent.get()) { affectedEntriesCount = new MoveFieldValueAction(fromField.get(), @@ -142,7 +142,7 @@ public void moveValue() { } public void swapValues() { - NamedCompound swapFieldValuesEdit = new NamedCompound("SWAP_FIELD_VALUES"); + NamedCompoundEdit swapFieldValuesEdit = new NamedCompoundEdit("SWAP_FIELD_VALUES"); int affectedEntriesCount = 0; for (BibEntry entry : selectedEntries) { String fromFieldValue = entry.getField(fromField.get()).orElse(""); diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentViewModel.java index 933e1d4f87b..a8bab8e10da 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentViewModel.java @@ -16,7 +16,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel; import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -68,13 +68,13 @@ public BooleanBinding canAppendProperty() { } public void clearSelectedField() { - NamedCompound clearFieldEdit = new NamedCompound("CLEAR_SELECTED_FIELD"); + NamedCompoundEdit clearFieldEdit = new NamedCompoundEdit("CLEAR_SELECTED_FIELD"); int affectedEntriesCount = 0; for (BibEntry entry : selectedEntries) { Optional oldFieldValue = entry.getField(selectedField.get()); if (oldFieldValue.isPresent()) { entry.clearField(selectedField.get()) - .ifPresent(fieldChange -> clearFieldEdit.addEdit(new UndoableFieldChange(fieldChange))); + .ifPresent(fieldChange -> clearFieldEdit.addEdit(new UndoableFieldChange(fieldChange))); affectedEntriesCount++; } } @@ -90,7 +90,7 @@ public void clearSelectedField() { } public void setFieldValue() { - NamedCompound setFieldEdit = new NamedCompound("CHANGE_SELECTED_FIELD"); + NamedCompoundEdit setFieldEdit = new NamedCompoundEdit("CHANGE_SELECTED_FIELD"); String toSetFieldValue = fieldValue.getValue(); int affectedEntriesCount = 0; for (BibEntry entry : selectedEntries) { @@ -115,7 +115,7 @@ public void setFieldValue() { } public void appendToFieldValue() { - NamedCompound appendToFieldEdit = new NamedCompound("APPEND_TO_SELECTED_FIELD"); + NamedCompoundEdit appendToFieldEdit = new NamedCompoundEdit("APPEND_TO_SELECTED_FIELD"); String toAppendFieldValue = fieldValue.getValue(); int affectedEntriesCount = 0; for (BibEntry entry : selectedEntries) { @@ -125,7 +125,7 @@ public void appendToFieldValue() { String newFieldValue = oldFieldValue.orElse("").concat(toAppendFieldValue); entry.setField(selectedField.get(), newFieldValue) - .ifPresent(fieldChange -> appendToFieldEdit.addEdit(new UndoableFieldChange(fieldChange))); + .ifPresent(fieldChange -> appendToFieldEdit.addEdit(new UndoableFieldChange(fieldChange))); fieldValue.set(""); affectedEntriesCount++; diff --git a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldViewModel.java b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldViewModel.java index 6f22623d466..6a2ce0cec5e 100644 --- a/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldViewModel.java @@ -13,7 +13,7 @@ import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel; import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit; import org.jabref.gui.edit.automaticfiededitor.MoveFieldValueAction; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; @@ -93,7 +93,7 @@ public void selectField(Field field) { } public void renameField() { - NamedCompound renameEdit = new NamedCompound("RENAME_EDIT"); + NamedCompoundEdit renameEdit = new NamedCompoundEdit("RENAME_EDIT"); int affectedEntriesCount = 0; if (fieldNameValidationStatus().isValid()) { affectedEntriesCount = new MoveFieldValueAction(selectedField.get(), diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java index 4c72ecca4f7..fe4573adb69 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java @@ -496,8 +496,8 @@ private void fetchAndMerge(EntryBasedFetcher fetcher) { public void setFocusToField(Field field) { UiTaskExecutor.runInJavaFXThread(() -> { - Field actualField = field; - boolean fieldFound = false; + Field actualField = field; + boolean fieldFound = false; for (Tab tab : tabbed.getTabs()) { tabbed.getSelectionModel().select(tab); if ((tab instanceof FieldsEditorTab fieldsEditorTab) diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java index 04226effec1..9a9c14e4fa8 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java @@ -99,9 +99,9 @@ public void handleMouseClick(MouseEvent event, CitationsDisplay citationsDisplay String applicationName = preferences.getPushToApplicationPreferences() .getActiveApplicationName(); GuiPushToApplication application = GuiPushToApplications.getGUIApplicationByName( - applicationName, - dialogService, - preferences.getPushToApplicationPreferences()) + applicationName, + dialogService, + preferences.getPushToApplicationPreferences()) .orElseGet(() -> new GuiPushToTeXstudio(dialogService, preferences.getPushToApplicationPreferences())); preferences.getPushToApplicationPreferences().setActiveApplicationName(application.getDisplayName()); application.jumpToLine(selectedItem.path(), selectedItem.line(), selectedItem.colStart()); diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/OtherFieldsTab.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/OtherFieldsTab.java index e75e2dfc456..472d482e98b 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/OtherFieldsTab.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/OtherFieldsTab.java @@ -74,8 +74,8 @@ protected SequencedSet determineFieldsToShow(BibEntry entry) { Set allKnownFields = entryType.get().getAllFields(); // Remove all fields being required or optional SequencedSet otherFields = entry.getFields().stream() - .filter(field -> !allKnownFields.contains(field)) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter(field -> !allKnownFields.contains(field)) + .collect(Collectors.toCollection(LinkedHashSet::new)); // The key field is in the required tab, but has a special treatment otherFields.remove(InternalField.KEY_FIELD); // Remove all fields contained in JabRef's tab "Deprecated" diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/SciteTab.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/SciteTab.java index 5bb7390f7a1..0e580926a35 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/SciteTab.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/SciteTab.java @@ -200,9 +200,9 @@ private VBox getMessageBox(String url, Label titleLabel, Text message) { } catch (IOException ioex) { // Can't throw a checked exception from here, so display a message to the user instead. dialogService.showErrorDialogAndWait( - "An error occurred opening web browser", - "JabRef was unable to open a web browser for link:\n\n" + url + "\n\nError Message:\n\n" + ioex.getMessage(), - ioex + "An error occurred opening web browser", + "JabRef was unable to open a web browser for link:\n\n" + url + "\n\nError Message:\n\n" + ioex.getMessage(), + ioex ); } } diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/SourceTab.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/SourceTab.java index 996578ba346..214cbf8e00b 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/SourceTab.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/SourceTab.java @@ -30,7 +30,7 @@ import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.search.Highlighter; import org.jabref.gui.undo.CountingUndoManager; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.UiTaskExecutor; @@ -310,7 +310,7 @@ private void storeSource(BibEntry outOfFocusEntry, String text) { throw new IllegalStateException(parserResult.getErrorMessage()); } - NamedCompound compound = new NamedCompound(Localization.lang("source edit")); + NamedCompoundEdit compound = new NamedCompoundEdit(Localization.lang("source edit")); BibEntry newEntry = database.getEntries().getFirst(); String newKey = newEntry.getCitationKey().orElse(null); @@ -363,7 +363,9 @@ private void storeSource(BibEntry outOfFocusEntry, String text) { private void listenForSaveKeybinding(KeyEvent event) { keyBindingRepository.mapToKeyBinding(event).ifPresent(binding -> { switch (binding) { - case SAVE_DATABASE, SAVE_ALL, SAVE_DATABASE_AS -> + case SAVE_DATABASE, + SAVE_ALL, + SAVE_DATABASE_AS -> storeSource(currentEntry, codeArea.textProperty().getValue()); } }); @@ -380,10 +382,14 @@ public EditAction(StandardActions command) { @Override public void execute() { switch (command) { - case COPY -> codeArea.copy(); - case CUT -> codeArea.cut(); - case PASTE -> codeArea.paste(); - case SELECT_ALL -> codeArea.selectAll(); + case COPY -> + codeArea.copy(); + case CUT -> + codeArea.cut(); + case PASTE -> + codeArea.paste(); + case SELECT_ALL -> + codeArea.selectAll(); } codeArea.requestFocus(); } diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/BibEntryView.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/BibEntryView.java index 279f27072e7..71a92d092b4 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/BibEntryView.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/BibEntryView.java @@ -100,8 +100,8 @@ private static boolean isRTL(String text) { * * @param text The summary text content * @return Node with either: - * - ScrollPane (for RTL text) - * - TextFlowLimited (for LTR text) + * - ScrollPane (for RTL text) + * - TextFlowLimited (for LTR text) */ private static Node createSummary(String text) { if (isRTL(text)) { @@ -116,13 +116,13 @@ private static Node createSummary(String text) { } /** - * Creates a label with horizontal scrolling for RTL text, + * Creates a label with horizontal scrolling for RTL text, * avoiding JavaFX bug related to RTL text wrapping * * @param text The label text content * @return Node with either: - * - ScrollPane (for RTL text) - * - Wrapped Label (for LTR text) + * - ScrollPane (for RTL text) + * - Wrapped Label (for LTR text) */ private static Node createLabel(String text) { if (isRTL(text)) { diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationRelationsTab.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationRelationsTab.java index f67ed7b12e1..5ac9c7c8b86 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationRelationsTab.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationRelationsTab.java @@ -42,7 +42,7 @@ import org.jabref.gui.mergeentries.threewaymerge.EntriesMergeResult; import org.jabref.gui.mergeentries.threewaymerge.MergeEntriesDialog; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.gui.util.NoSelectionModel; @@ -121,12 +121,12 @@ public CitationRelationsTab(DialogService dialogService, this.searchCitationsRelationsService = searchCitationsRelationsService; this.citationsRelationsTabViewModel = new CitationsRelationsTabViewModel( - preferences, - undoManager, - stateManager, - dialogService, - fileUpdateMonitor, - taskExecutor + preferences, + undoManager, + stateManager, + dialogService, + fileUpdateMonitor, + taskExecutor ); } @@ -515,18 +515,18 @@ private void executeSearch(CitationComponents citationComponents) { * TODO: Make the method return a callable and let the calling method create the background task. */ private BackgroundTask> createBackgroundTask( - BibEntry entry, CitationFetcher.SearchType searchType + BibEntry entry, CitationFetcher.SearchType searchType ) { return switch (searchType) { case CitationFetcher.SearchType.CITES -> { citingTask = BackgroundTask.wrap( - () -> this.searchCitationsRelationsService.searchCites(entry) + () -> this.searchCitationsRelationsService.searchCites(entry) ); yield citingTask; } case CitationFetcher.SearchType.CITED_BY -> { citedByTask = BackgroundTask.wrap( - () -> this.searchCitationsRelationsService.searchCitedBy(entry) + () -> this.searchCitationsRelationsService.searchCitedBy(entry) ); yield citedByTask; } @@ -603,7 +603,7 @@ private void importEntries(List entriesToImport, CitationF * Function to open possible duplicate entries window to compare duplicate entries * * @param citationRelationItem duplicate in the citation relations tab - * @param listView CheckListView to display citations + * @param listView CheckListView to display citations */ private void openPossibleDuplicateEntriesWindow(CitationRelationItem citationRelationItem, CheckListView listView) { BibEntry libraryEntry = citationRelationItem.localEntry(); @@ -633,12 +633,12 @@ private void openPossibleDuplicateEntriesWindow(CitationRelationItem citationRel libraryTab.get().getMainTable().setCitationMergeMode(true); database.insertEntry(mergedEntry); - NamedCompound ce = new NamedCompound(Localization.lang("Merge entries")); - ce.addEdit(new UndoableRemoveEntries(database, mergeResult.originalLeftEntry())); - ce.addEdit(new UndoableInsertEntries(database, mergedEntry)); - ce.end(); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Merge entries")); + compoundEdit.addEdit(new UndoableRemoveEntries(database, mergeResult.originalLeftEntry())); + compoundEdit.addEdit(new UndoableInsertEntries(database, mergedEntry)); + compoundEdit.end(); - undoManager.addEdit(ce); + undoManager.addEdit(compoundEdit); dialogService.notify(Localization.lang("Merged entries")); }, () -> dialogService.notify(Localization.lang("Canceled merging entries"))); diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationsRelationsTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationsRelationsTabViewModel.java index 7f75c6c68b1..260a8b798e5 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationsRelationsTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/citationrelationtab/CitationsRelationsTabViewModel.java @@ -56,8 +56,10 @@ public void importEntries(List entriesToImport, CitationFe boolean generateNewKeyOnImport = preferences.getImporterPreferences().generateNewKeyOnImportProperty().get(); switch (searchType) { - case CITES -> importCites(entries, existingEntry, importHandler, generator, generateNewKeyOnImport); - case CITED_BY -> importCitedBy(entries, existingEntry, importHandler, generator, generateNewKeyOnImport); + case CITES -> + importCites(entries, existingEntry, importHandler, generator, generateNewKeyOnImport); + case CITED_BY -> + importCitedBy(entries, existingEntry, importHandler, generator, generateNewKeyOnImport); } } diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTab.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTab.java index 462618171ae..fd43d08a1f3 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTab.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTab.java @@ -38,12 +38,12 @@ public boolean shouldShow(BibEntry entry) { return entry.getField(StandardField.FILE).isPresent() && stateManager.activeTabProperty().get() - .map(tab -> tab.getAnnotationCache() - .getFromCache(entry) - .values() - .stream() - .anyMatch(list -> !list.isEmpty())) - .orElse(false); + .map(tab -> tab.getAnnotationCache() + .getFromCache(entry) + .values() + .stream() + .anyMatch(list -> !list.isEmpty())) + .orElse(false); } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/errorconsole/LogEventViewModel.java b/jabgui/src/main/java/org/jabref/gui/errorconsole/LogEventViewModel.java index 47ba7ac56ee..f549048fd21 100644 --- a/jabgui/src/main/java/org/jabref/gui/errorconsole/LogEventViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/errorconsole/LogEventViewModel.java @@ -24,17 +24,23 @@ public String getDisplayText() { public String getStyleClass() { return switch (logEvent.getLevel()) { - case ERROR -> "exception"; - case WARN -> "output"; - default -> "log"; + case ERROR -> + "exception"; + case WARN -> + "output"; + default -> + "log"; }; } public JabRefIcon getIcon() { return switch (logEvent.getLevel()) { - case ERROR -> IconTheme.JabRefIcons.INTEGRITY_FAIL; - case WARN -> IconTheme.JabRefIcons.INTEGRITY_WARN; - default -> IconTheme.JabRefIcons.INTEGRITY_INFO; + case ERROR -> + IconTheme.JabRefIcons.INTEGRITY_FAIL; + case WARN -> + IconTheme.JabRefIcons.INTEGRITY_WARN; + default -> + IconTheme.JabRefIcons.INTEGRITY_INFO; }; } diff --git a/jabgui/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java index 57613bd8af7..c09cdbcc037 100644 --- a/jabgui/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java @@ -74,8 +74,8 @@ public ExporterViewModel saveExporter() { public void browse() { String fileDir = layoutFile.getValue().isEmpty() - ? preferences.getExportPreferences().getExportWorkingDirectory().toString() - : layoutFile.getValue(); + ? preferences.getExportPreferences().getExportWorkingDirectory().toString() + : layoutFile.getValue(); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(Localization.lang("Custom layout file"), StandardFileType.LAYOUT) diff --git a/jabgui/src/main/java/org/jabref/gui/exporter/ExportCommand.java b/jabgui/src/main/java/org/jabref/gui/exporter/ExportCommand.java index ac54a3953fa..a771baf3675 100644 --- a/jabgui/src/main/java/org/jabref/gui/exporter/ExportCommand.java +++ b/jabgui/src/main/java/org/jabref/gui/exporter/ExportCommand.java @@ -71,8 +71,8 @@ public ExportCommand(ExportMethod exportMethod, this.taskExecutor = taskExecutor; this.executable.bind(exportMethod == ExportMethod.EXPORT_SELECTED - ? ActionHelper.needsEntriesSelected(stateManager) - : ActionHelper.needsDatabase(stateManager)); + ? ActionHelper.needsEntriesSelected(stateManager) + : ActionHelper.needsDatabase(stateManager)); } @Override @@ -112,8 +112,8 @@ private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilt } List fileDirForDatabase = stateManager.getActiveDatabase() - .map(db -> db.getFileDirectories(preferences.getFilePreferences())) - .orElse(List.of(preferences.getFilePreferences().getWorkingDirectory())); + .map(db -> db.getFileDirectories(preferences.getFilePreferences())) + .orElse(List.of(preferences.getFilePreferences().getWorkingDirectory())); // Make sure we remember which filter was used, to set // the default for next time: diff --git a/jabgui/src/main/java/org/jabref/gui/exporter/SaveAction.java b/jabgui/src/main/java/org/jabref/gui/exporter/SaveAction.java index 83f4011912e..5fa43071f4d 100644 --- a/jabgui/src/main/java/org/jabref/gui/exporter/SaveAction.java +++ b/jabgui/src/main/java/org/jabref/gui/exporter/SaveAction.java @@ -54,9 +54,12 @@ public void execute() { stateManager); switch (saveMethod) { - case SAVE -> saveDatabaseAction.save(); - case SAVE_AS -> saveDatabaseAction.saveAs(); - case SAVE_SELECTED -> saveDatabaseAction.saveSelectedAsPlain(); + case SAVE -> + saveDatabaseAction.save(); + case SAVE_AS -> + saveDatabaseAction.saveAs(); + case SAVE_SELECTED -> + saveDatabaseAction.saveSelectedAsPlain(); } } } 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 f9651ed03a2..882502bdd11 100644 --- a/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java +++ b/jabgui/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java @@ -100,23 +100,23 @@ public boolean saveAs(Path file) { private SelfContainedSaveOrder getSaveOrder() { return libraryTab.getBibDatabaseContext() - .getMetaData().getSaveOrder() - .map(so -> { - if (so.getOrderType() == SaveOrder.OrderType.TABLE) { - // We need to "flatten out" SaveOrder.OrderType.TABLE as BibWriter does not have access to preferences - List> sortOrder = libraryTab.getMainTable().getSortOrder(); - return new SelfContainedSaveOrder( - SaveOrder.OrderType.SPECIFIED, - sortOrder.stream() - .filter(col -> col instanceof MainTableColumn) - .map(column -> ((MainTableColumn) column).getModel()) - .flatMap(model -> model.getSortCriteria().stream()) - .toList()); - } else { - return SelfContainedSaveOrder.of(so); - } - }) - .orElse(SaveOrder.getDefaultSaveOrder()); + .getMetaData().getSaveOrder() + .map(so -> { + if (so.getOrderType() == SaveOrder.OrderType.TABLE) { + // We need to "flatten out" SaveOrder.OrderType.TABLE as BibWriter does not have access to preferences + List> sortOrder = libraryTab.getMainTable().getSortOrder(); + return new SelfContainedSaveOrder( + SaveOrder.OrderType.SPECIFIED, + sortOrder.stream() + .filter(col -> col instanceof MainTableColumn) + .map(column -> ((MainTableColumn) column).getModel()) + .flatMap(model -> model.getSortCriteria().stream()) + .toList()); + } else { + return SelfContainedSaveOrder.of(so); + } + }) + .orElse(SaveOrder.getDefaultSaveOrder()); } public void saveSelectedAsPlain() { diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoLinkFilesAction.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoLinkFilesAction.java index 3af24299587..420390340da 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoLinkFilesAction.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoLinkFilesAction.java @@ -11,7 +11,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.UiTaskExecutor; @@ -58,7 +58,7 @@ public void execute() { preferences.getExternalApplicationsPreferences(), preferences.getFilePreferences(), preferences.getAutoLinkPreferences()); - final NamedCompound nc = new NamedCompound(Localization.lang("Automatically set file links")); + final NamedCompoundEdit nc = new NamedCompoundEdit(Localization.lang("Automatically set file links")); Task linkFilesTask = new Task<>() { final BiConsumer onLinkedFile = (linkedFile, entry) -> { diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java index 1526290334e..b26593f541c 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java @@ -122,8 +122,8 @@ public List findAssociatedNotLinkedFiles(BibEntry entry) throws IOEx if (!fileAlreadyLinked) { Optional type = FileUtil.getFileExtension(foundFile) - .map(extension -> ExternalFileTypes.getExternalFileTypeByExt(extension, externalApplicationsPreferences)) - .orElse(Optional.of(new UnknownExternalFileType(""))); + .map(extension -> ExternalFileTypes.getExternalFileTypeByExt(extension, externalApplicationsPreferences)) + .orElse(Optional.of(new UnknownExternalFileType(""))); String strType = type.map(ExternalFileType::getName).orElse(""); Path relativeFilePath = FileUtil.relativize(foundFile, directories); diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/FileFilterUtils.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/FileFilterUtils.java index 22f2aee57f5..cf2735858e4 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/FileFilterUtils.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/FileFilterUtils.java @@ -69,11 +69,16 @@ public static boolean filterByDate(Path path, DateRange filter) { FileFilterUtils fileFilter = new FileFilterUtils(); LocalDateTime fileTime = FileFilterUtils.getFileTime(path); boolean isInDateRange = switch (filter) { - case DAY -> fileFilter.isDuringLastDay(fileTime); - case WEEK -> fileFilter.isDuringLastWeek(fileTime); - case MONTH -> fileFilter.isDuringLastMonth(fileTime); - case YEAR -> fileFilter.isDuringLastYear(fileTime); - case ALL_TIME -> true; + case DAY -> + fileFilter.isDuringLastDay(fileTime); + case WEEK -> + fileFilter.isDuringLastWeek(fileTime); + case MONTH -> + fileFilter.isDuringLastMonth(fileTime); + case YEAR -> + fileFilter.isDuringLastYear(fileTime); + case ALL_TIME -> + true; }; return isInDateRange; } @@ -84,11 +89,11 @@ public static boolean filterByDate(Path path, DateRange filter) { */ public List sortByDateAscending(List files) { return files.stream() - .sorted(Comparator.comparingLong(file -> FileFilterUtils.getFileTime(file) - .atZone(ZoneId.systemDefault()) - .toInstant() - .toEpochMilli())) - .collect(Collectors.toList()); + .sorted(Comparator.comparingLong(file -> FileFilterUtils.getFileTime(file) + .atZone(ZoneId.systemDefault()) + .toInstant() + .toEpochMilli())) + .collect(Collectors.toList()); } /** @@ -97,11 +102,11 @@ public List sortByDateAscending(List files) { */ public List sortByDateDescending(List files) { return files.stream() - .sorted(Comparator.comparingLong(file -> -FileFilterUtils.getFileTime(file) - .atZone(ZoneId.systemDefault()) - .toInstant() - .toEpochMilli())) - .collect(Collectors.toList()); + .sorted(Comparator.comparingLong(file -> -FileFilterUtils.getFileTime(file) + .atZone(ZoneId.systemDefault()) + .toInstant() + .toEpochMilli())) + .collect(Collectors.toList()); } /** @@ -111,9 +116,12 @@ public List sortByDateDescending(List files) { public static List sortByDate(List files, ExternalFileSorter sortType) { FileFilterUtils fileFilter = new FileFilterUtils(); List sortedFiles = switch (sortType) { - case DEFAULT -> files; - case DATE_ASCENDING -> fileFilter.sortByDateDescending(files); - case DATE_DESCENDING -> fileFilter.sortByDateAscending(files); + case DEFAULT -> + files; + case DATE_ASCENDING -> + fileFilter.sortByDateDescending(files); + case DATE_DESCENDING -> + fileFilter.sortByDateAscending(files); }; return sortedFiles; } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java index e396c4f883a..2ecb5dce845 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java @@ -60,7 +60,7 @@ public boolean accept(Path path) throws IOException { return gitIgnorePatterns.stream().noneMatch(filter -> // we need this one for "*.png" filter.matches(path.getFileName()) || - // we need this one for "**/*.png" - filter.matches(path)); + // we need this one for "**/*.png" + filter.matches(path)); } } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java index bb201b85f18..8d43ed1ac51 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java @@ -114,7 +114,7 @@ public BackgroundTask> importFilesInBackgro @Override public List call() { counter = 1; - CompoundEdit ce = new CompoundEdit(); + CompoundEdit compoundEdit = new CompoundEdit(); for (final Path file : files) { final List entriesToAdd = new ArrayList<>(); @@ -195,10 +195,10 @@ public List call() { } allEntriesToAdd.addAll(entriesToAdd); - ce.addEdit(new UndoableInsertEntries(bibDatabaseContext.getDatabase(), entriesToAdd)); - ce.end(); + compoundEdit.addEdit(new UndoableInsertEntries(bibDatabaseContext.getDatabase(), entriesToAdd)); + compoundEdit.end(); // prevent fx thread exception in undo manager - UiTaskExecutor.runInJavaFXThread(() -> undoManager.addEdit(ce)); + UiTaskExecutor.runInJavaFXThread(() -> undoManager.addEdit(compoundEdit)); counter++; } @@ -263,7 +263,7 @@ private void importEntryWithDuplicateCheck(BibDatabaseContext bibDatabaseContext if (existingDuplicateInLibrary.isPresent()) { Optional duplicateHandledEntry = handleDuplicates(bibDatabaseContext, entryToInsert, existingDuplicateInLibrary.get(), decision); if (duplicateHandledEntry.isEmpty()) { - tracker.markSkipped(); + tracker.markSkipped(); return; } finalEntry = duplicateHandledEntry.get(); @@ -350,7 +350,7 @@ private void addToGroups(List entries, Collection group List undo = entryChanger.add(entries); // TODO: Add undo // if (!undo.isEmpty()) { - // ce.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(new GroupTreeNodeViewModel(node), + // compoundEdit.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(new GroupTreeNodeViewModel(node), // undo)); // } } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/PdfMergeDialog.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/PdfMergeDialog.java index 6ea1b65568c..3dd1f38c118 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/PdfMergeDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/PdfMergeDialog.java @@ -28,9 +28,9 @@ public class PdfMergeDialog { * Thus, JabRef provides this merge dialog that collects the results of all {@link PdfImporter}s * and gives user a choice between field values. * - * @param entry the entry to merge with - * @param filePath the path to the PDF file. This PDF is used as the source for the {@link PdfImporter}s. - * @param preferences the preferences to use. Full preference object is required, because of current implementation of {@link MultiMergeEntriesView}. + * @param entry the entry to merge with + * @param filePath the path to the PDF file. This PDF is used as the source for the {@link PdfImporter}s. + * @param preferences the preferences to use. Full preference object is required, because of current implementation of {@link MultiMergeEntriesView}. * @param taskExecutor the task executor to use when the multi merge dialog executes the importers. */ public static MultiMergeEntriesView createMergeDialog(BibEntry entry, Path filePath, GuiPreferences preferences, TaskExecutor taskExecutor) { 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 9e13a0173c6..ed43c980bfa 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java @@ -74,7 +74,6 @@ public FileNodeViewModel call() throws IOException { * and then sorted according to the {@link ExternalFileSorter} value. * * @param unlinkedPDFFileFilter contains a BibDatabaseContext which is used to determine whether the file is linked - * * @return FileNodeViewModel containing the data of the current directory and all subdirectories * @throws IOException if directory is not a directory or empty */ @@ -138,8 +137,8 @@ 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) - .toList()); + .map(FileNodeViewModel::new) + .toList()); return fileNodeViewModelForCurrentDirectory; } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogView.java b/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogView.java index 9c51df3d6e6..469cb2a68fd 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogView.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogView.java @@ -163,8 +163,8 @@ private void initDirectorySelection() { fileTypeCombo.valueProperty().bindBidirectional(viewModel.selectedExtensionProperty()); new ViewModelListCellFactory() - .withText(DateRange::getDateRange) - .install(fileDateCombo); + .withText(DateRange::getDateRange) + .install(fileDateCombo); fileDateCombo.setItems(viewModel.getDateFilters()); fileDateCombo.valueProperty().bindBidirectional(viewModel.selectedDateProperty()); @@ -331,10 +331,14 @@ public SearchContextAction(StandardActions command) { @Override public void execute() { switch (command) { - case SELECT_ALL -> unlinkedFilesList.getCheckModel().checkAll(); - case UNSELECT_ALL -> unlinkedFilesList.getCheckModel().clearChecks(); - case EXPAND_ALL -> expandTree(unlinkedFilesList.getRoot(), true); - case COLLAPSE_ALL -> expandTree(unlinkedFilesList.getRoot(), false); + case SELECT_ALL -> + unlinkedFilesList.getCheckModel().checkAll(); + case UNSELECT_ALL -> + unlinkedFilesList.getCheckModel().clearChecks(); + case EXPAND_ALL -> + expandTree(unlinkedFilesList.getRoot(), true); + case COLLAPSE_ALL -> + expandTree(unlinkedFilesList.getRoot(), false); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiletype/CustomExternalFileType.java b/jabgui/src/main/java/org/jabref/gui/externalfiletype/CustomExternalFileType.java index 396e1cacf97..a050ef299dc 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiletype/CustomExternalFileType.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiletype/CustomExternalFileType.java @@ -10,7 +10,7 @@ * This class defines a type of external files that can be linked to from JabRef. * The class contains enough information to provide an icon, a standard extension * and a link to which application handles files of this type. - * + *

* TODO: Move to model (and then adapt {@link org.jabref.gui.fieldeditors.LinkedFilesEditorViewModel#fromFile(java.nio.file.Path, java.util.List, FilePreferences)}). */ public class CustomExternalFileType implements ExternalFileType { diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileType.java b/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileType.java index df386dbc19c..88d0c063551 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileType.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileType.java @@ -35,6 +35,6 @@ default Field getField() { * @return A String[] containing all information about this file type. */ default String[] toStringArray() { - return new String[]{getName(), getExtension(), getMimeType(), getOpenWithApplication(), getIcon().name()}; + return new String[] {getName(), getExtension(), getMimeType(), getOpenWithApplication(), getIcon().name()}; } } diff --git a/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java b/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java index 6946b5997ee..f945c2e5da5 100644 --- a/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java +++ b/jabgui/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java @@ -91,7 +91,7 @@ public static Optional getExternalFileTypeForName(String filen * * @param mimeType The MIME type. * @return The ExternalFileType registered, or null if none. For the mime type "text/html", a valid file type is - * guaranteed to be returned. + * guaranteed to be returned. */ public static Optional getExternalFileTypeByMimeType(String mimeType, ExternalApplicationsPreferences externalApplicationsPreferences) { // Ignores parameters according to link: (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) @@ -129,7 +129,7 @@ public static Optional getExternalFileTypeByLinkedFile(LinkedF // No type could be found from mime type. Try based on the extension: return FileUtil.getFileExtension(linkedFile.getLink()) - .flatMap(extension -> getExternalFileTypeByExt(extension, externalApplicationsPreferences)); + .flatMap(extension -> getExternalFileTypeByExt(extension, externalApplicationsPreferences)); } else { return type; } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditor.java index 68544e68f91..fab2681f720 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditor.java @@ -37,8 +37,8 @@ public class CitationCountEditor extends HBox implements FieldEditorFX { @Inject private SearchCitationsRelationsService searchCitationsRelationsService; public CitationCountEditor(Field field, - SuggestionProvider suggestionProvider, - FieldCheckers fieldCheckers) { + SuggestionProvider suggestionProvider, + FieldCheckers fieldCheckers) { Injector.registerExistingAndInject(this); this.viewModel = new CitationCountEditorViewModel( field, diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditorViewModel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditorViewModel.java index 173fc27c078..da74960f387 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/CitationCountEditorViewModel.java @@ -31,6 +31,7 @@ public class CitationCountEditorViewModel extends AbstractEditorViewModel { private final StateManager stateManager; private final GuiPreferences preferences; private final SearchCitationsRelationsService searchCitationsRelationsService; + public CitationCountEditorViewModel( Field field, SuggestionProvider suggestionProvider, diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/FieldNameLabel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/FieldNameLabel.java index f607bfa04ac..f9c8bf0b9cb 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/FieldNameLabel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/FieldNameLabel.java @@ -230,12 +230,18 @@ public String getDescription(Field field) { } } else if (field instanceof SpecialField specialField) { return switch (specialField) { - case PRINTED -> Localization.lang("User-specific printed flag, in case the entry has been printed."); - case PRIORITY -> Localization.lang("User-specific priority."); - case QUALITY -> Localization.lang("User-specific quality flag, in case its quality is assured."); - case RANKING -> Localization.lang("User-specific ranking."); - case READ_STATUS -> Localization.lang("User-specific read status."); - case RELEVANCE -> Localization.lang("User-specific relevance flag, in case the entry is relevant."); + case PRINTED -> + Localization.lang("User-specific printed flag, in case the entry has been printed."); + case PRIORITY -> + Localization.lang("User-specific priority."); + case QUALITY -> + Localization.lang("User-specific quality flag, in case its quality is assured."); + case RANKING -> + Localization.lang("User-specific ranking."); + case READ_STATUS -> + Localization.lang("User-specific read status."); + case RELEVANCE -> + Localization.lang("User-specific relevance flag, in case the entry is relevant."); }; } return ""; diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/GroupEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/GroupEditor.java index 16a50521b65..ca704e4e7aa 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/GroupEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/GroupEditor.java @@ -44,9 +44,9 @@ public GroupEditor(final Field field, List draggedGroups = (List) event.getDragboard().getContent(DragAndDropDataFormats.GROUP); if (bibEntry.isPresent() && draggedGroups.getFirst() != null) { String newGroup = bibEntry.map(entry -> entry.getField(StandardField.GROUPS) - .map(oldGroups -> oldGroups + (preferences.getBibEntryPreferences().getKeywordSeparator()) + (draggedGroups.getFirst())) - .orElse(draggedGroups.getFirst())) - .orElse(null); + .map(oldGroups -> oldGroups + (preferences.getBibEntryPreferences().getKeywordSeparator()) + (draggedGroups.getFirst())) + .orElse(draggedGroups.getFirst())) + .orElse(null); bibEntry.map(entry -> entry.setField(StandardField.GROUPS, newGroup)); success = true; } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/ICORERankingEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/ICORERankingEditor.java index 444f8a14c19..23b6b5ab1a7 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/ICORERankingEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/ICORERankingEditor.java @@ -43,8 +43,8 @@ public ICORERankingEditor(Field field, Injector.registerExistingAndInject(this); ViewLoader.view(this) - .root(this) - .load(); + .root(this) + .load(); this.viewModel = new ICORERankingEditorViewModel( field, diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/JournalInfoOptInDialogHelper.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/JournalInfoOptInDialogHelper.java index b1209ba95db..5a93dade847 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/JournalInfoOptInDialogHelper.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/JournalInfoOptInDialogHelper.java @@ -23,8 +23,8 @@ public static boolean isJournalInfoEnabled(DialogService dialogService, EntryEdi ); preferences.setEnableJournalPopup(enableJournalPopup - ? EntryEditorPreferences.JournalPopupEnabled.ENABLED - : EntryEditorPreferences.JournalPopupEnabled.DISABLED); + ? EntryEditorPreferences.JournalPopupEnabled.ENABLED + : EntryEditorPreferences.JournalPopupEnabled.DISABLED); return enableJournalPopup; } @@ -34,8 +34,8 @@ public static boolean isJournalInfoEnabled(DialogService dialogService, EntryEdi Localization.lang("Allow sending ISSN to a JabRef online service (SCimago) for fetching journal information")); preferences.setEnableJournalPopup(journalInfoEnabled - ? EntryEditorPreferences.JournalPopupEnabled.ENABLED - : EntryEditorPreferences.JournalPopupEnabled.DISABLED); + ? EntryEditorPreferences.JournalPopupEnabled.ENABLED + : EntryEditorPreferences.JournalPopupEnabled.DISABLED); return journalInfoEnabled; } } 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 8520161c1b2..3cd16a17025 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.java @@ -254,18 +254,18 @@ public void execute() { case COPY -> { clipBoardManager.setContent(keyword.get()); dialogService.notify(Localization.lang("Copied '%0' to clipboard.", - JabRefDialogService.shortenDialogMessage(keyword.get()))); + JabRefDialogService.shortenDialogMessage(keyword.get()))); } case CUT -> { clipBoardManager.setContent(keyword.get()); dialogService.notify(Localization.lang("Copied '%0' to clipboard.", - JabRefDialogService.shortenDialogMessage(keyword.get()))); + JabRefDialogService.shortenDialogMessage(keyword.get()))); keywordTagsField.removeTags(keyword); } case DELETE -> - keywordTagsField.removeTags(keyword); + keywordTagsField.removeTags(keyword); default -> - LOGGER.info("Action {} not defined", command.getText()); + LOGGER.info("Action {} not defined", command.getText()); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java index c262b5e753a..89e33d24aea 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java @@ -171,7 +171,7 @@ public String getTruncatedDescriptionAndLink() { return ControlHelper.truncateString(linkedFile.getDescription(), -1, "...", ControlHelper.EllipsisPosition.CENTER) + " (" + ControlHelper.truncateString(linkedFile.getLink(), -1, "...", - ControlHelper.EllipsisPosition.CENTER) + ")"; + ControlHelper.EllipsisPosition.CENTER) + ")"; } } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java index ff6992be048..5ff20f9e333 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java @@ -99,8 +99,8 @@ public LinkedFilesEditor(Field field, this.fieldCheckers = fieldCheckers; ViewLoader.view(this) - .root(this) - .load(); + .root(this) + .load(); decoratedModelList = new UiThreadObservableList<>(viewModel.filesProperty()); Bindings.bindContentBidirectional(listView.itemsProperty().get(), decoratedModelList); diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java index b5c488750ad..724adfbcbac 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java @@ -93,7 +93,7 @@ private static String getStringRepresentation(List files) { /** * Creates an instance of {@link LinkedFile} based on the given file. * We try to guess the file type and relativize the path against the given file directories. - * + *

* TODO: Move this method to {@link LinkedFile} as soon as {@link CustomExternalFileType} lives in model. */ public static LinkedFile fromFile(Path file, List fileDirectories, ExternalApplicationsPreferences externalApplicationsPreferences) { @@ -208,17 +208,17 @@ public void fetchFulltext() { } if (urlField.isEmpty() || !download_success) { BackgroundTask - .wrap(() -> fetcher.findFullTextPDF(entry)) - .onRunning(() -> fulltextLookupInProgress.setValue(true)) - .onFinished(() -> fulltextLookupInProgress.setValue(false)) - .onSuccess(url -> { - if (url.isPresent()) { - addFromURLAndDownload(url.get()); - } else { - dialogService.notify(Localization.lang("No full text document found")); - } - }) - .executeWith(taskExecutor); + .wrap(() -> fetcher.findFullTextPDF(entry)) + .onRunning(() -> fulltextLookupInProgress.setValue(true)) + .onFinished(() -> fulltextLookupInProgress.setValue(false)) + .onSuccess(url -> { + if (url.isPresent()) { + addFromURLAndDownload(url.get()); + } else { + dialogService.notify(Localization.lang("No full text document found")); + } + }) + .executeWith(taskExecutor); } } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ContextAction.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ContextAction.java index 09de1094123..1a3247661ab 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ContextAction.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ContextAction.java @@ -31,44 +31,66 @@ public ContextAction(StandardActions command, this.executable.bind( switch (command) { - case RENAME_FILE_TO_PATTERN -> Bindings.createBooleanBinding( - () -> !linkedFile.getFile().isOnlineLink() - && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent() - && !linkedFile.isGeneratedNameSameAsOriginal(), - linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); - case MOVE_FILE_TO_FOLDER, MOVE_FILE_TO_FOLDER_AND_RENAME -> Bindings.createBooleanBinding( - () -> !linkedFile.getFile().isOnlineLink() - && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent() - && !linkedFile.isGeneratedPathSameAsOriginal(), - linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); - case DOWNLOAD_FILE -> Bindings.createBooleanBinding( - () -> linkedFile.getFile().isOnlineLink(), - linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); - case REDOWNLOAD_FILE -> Bindings.createBooleanBinding( - () -> !linkedFile.getFile().getSourceUrl().isEmpty(), - linkedFile.getFile().sourceUrlProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); - case OPEN_FILE, OPEN_FOLDER, RENAME_FILE_TO_NAME, DELETE_FILE -> Bindings.createBooleanBinding( - () -> !linkedFile.getFile().isOnlineLink() - && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent(), - linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); - default -> BindingsHelper.constantOf(true); + case RENAME_FILE_TO_PATTERN -> + Bindings.createBooleanBinding( + () -> !linkedFile.getFile().isOnlineLink() + && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent() + && !linkedFile.isGeneratedNameSameAsOriginal(), + linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); + case MOVE_FILE_TO_FOLDER, + MOVE_FILE_TO_FOLDER_AND_RENAME -> + Bindings.createBooleanBinding( + () -> !linkedFile.getFile().isOnlineLink() + && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent() + && !linkedFile.isGeneratedPathSameAsOriginal(), + linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); + case DOWNLOAD_FILE -> + Bindings.createBooleanBinding( + () -> linkedFile.getFile().isOnlineLink(), + linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); + case REDOWNLOAD_FILE -> + Bindings.createBooleanBinding( + () -> !linkedFile.getFile().getSourceUrl().isEmpty(), + linkedFile.getFile().sourceUrlProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); + case OPEN_FILE, + OPEN_FOLDER, + RENAME_FILE_TO_NAME, + DELETE_FILE -> + Bindings.createBooleanBinding( + () -> !linkedFile.getFile().isOnlineLink() + && linkedFile.getFile().findIn(databaseContext, preferences.getFilePreferences()).isPresent(), + linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null)); + default -> + BindingsHelper.constantOf(true); }); } @Override public void execute() { switch (command) { - case EDIT_FILE_LINK -> linkedFile.edit(); - case OPEN_FILE -> linkedFile.open(); - case OPEN_FOLDER -> linkedFile.openFolder(); - case DOWNLOAD_FILE -> linkedFile.download(true); - case REDOWNLOAD_FILE -> linkedFile.redownload(); - case RENAME_FILE_TO_PATTERN -> linkedFile.renameToSuggestion(); - case RENAME_FILE_TO_NAME -> linkedFile.askForNameAndRename(); - case MOVE_FILE_TO_FOLDER -> linkedFile.moveToDefaultDirectory(); - case MOVE_FILE_TO_FOLDER_AND_RENAME -> linkedFile.moveToDefaultDirectoryAndRename(); - case DELETE_FILE -> viewModel.deleteFile(linkedFile); - case REMOVE_LINK, REMOVE_LINKS -> viewModel.removeFileLink(linkedFile); + case EDIT_FILE_LINK -> + linkedFile.edit(); + case OPEN_FILE -> + linkedFile.open(); + case OPEN_FOLDER -> + linkedFile.openFolder(); + case DOWNLOAD_FILE -> + linkedFile.download(true); + case REDOWNLOAD_FILE -> + linkedFile.redownload(); + case RENAME_FILE_TO_PATTERN -> + linkedFile.renameToSuggestion(); + case RENAME_FILE_TO_NAME -> + linkedFile.askForNameAndRename(); + case MOVE_FILE_TO_FOLDER -> + linkedFile.moveToDefaultDirectory(); + case MOVE_FILE_TO_FOLDER_AND_RENAME -> + linkedFile.moveToDefaultDirectoryAndRename(); + case DELETE_FILE -> + viewModel.deleteFile(linkedFile); + case REMOVE_LINK, + REMOVE_LINKS -> + viewModel.removeFileLink(linkedFile); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorContextAction.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorContextAction.java index 4aee5fa948a..d05d2087adc 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorContextAction.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorContextAction.java @@ -40,12 +40,18 @@ public EditorContextAction(StandardActions command, TextInputControl textInputCo this.executable.bind( switch (command) { - case COPY -> editableBinding.and(maskTextBinding.not()).and(hasSelectionBinding); - case CUT -> maskTextBinding.not().and(hasSelectionBinding); - case PASTE -> editableBinding.and(hasStringInClipboardBinding); - case DELETE -> editableBinding.and(hasSelectionBinding); - case UNDO -> undoableBinding; - case REDO -> redoableBinding; + case COPY -> + editableBinding.and(maskTextBinding.not()).and(hasSelectionBinding); + case CUT -> + maskTextBinding.not().and(hasSelectionBinding); + case PASTE -> + editableBinding.and(hasStringInClipboardBinding); + case DELETE -> + editableBinding.and(hasSelectionBinding); + case UNDO -> + undoableBinding; + case REDO -> + redoableBinding; case SELECT_ALL -> { if (SHOW_HANDLES) { yield hasTextBinding.and(allSelectedBinding.not()); @@ -53,20 +59,28 @@ public EditorContextAction(StandardActions command, TextInputControl textInputCo yield BindingsHelper.constantOf(true); } } - default -> BindingsHelper.constantOf(true); + default -> + BindingsHelper.constantOf(true); }); } @Override public void execute() { switch (command) { - case COPY -> textInputControl.copy(); - case CUT -> textInputControl.cut(); - case PASTE -> textInputControl.paste(); - case DELETE -> textInputControl.deleteText(textInputControl.getSelection()); - case SELECT_ALL -> textInputControl.selectAll(); - case UNDO -> textInputControl.undo(); - case REDO -> textInputControl.redo(); + case COPY -> + textInputControl.copy(); + case CUT -> + textInputControl.cut(); + case PASTE -> + textInputControl.paste(); + case DELETE -> + textInputControl.deleteText(textInputControl.getSelection()); + case SELECT_ALL -> + textInputControl.selectAll(); + case UNDO -> + textInputControl.undo(); + case REDO -> + textInputControl.redo(); } textInputControl.requestFocus(); } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/DoiIdentifierEditorViewModel.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/DoiIdentifierEditorViewModel.java index 91f60f0bd95..c65446e29d6 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/DoiIdentifierEditorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/DoiIdentifierEditorViewModel.java @@ -47,15 +47,15 @@ public void lookupIdentifier(BibEntry bibEntry) { CrossRef doiFetcher = new CrossRef(); BackgroundTask.wrap(() -> doiFetcher.findIdentifier(entry)) - .onRunning(() -> identifierLookupInProgress.setValue(true)) - .onFinished(() -> identifierLookupInProgress.setValue(false)) - .onSuccess(identifier -> { - if (identifier.isPresent()) { - entry.setField(field, identifier.get().asString()); - } else { - dialogService.notify(Localization.lang("No %0 found", field.getDisplayName())); - } - }).onFailure(e -> handleIdentifierFetchingError(e, doiFetcher)).executeWith(taskExecutor); + .onRunning(() -> identifierLookupInProgress.setValue(true)) + .onFinished(() -> identifierLookupInProgress.setValue(false)) + .onSuccess(identifier -> { + if (identifier.isPresent()) { + entry.setField(field, identifier.get().asString()); + } else { + dialogService.notify(Localization.lang("No %0 found", field.getDisplayName())); + } + }).onFailure(e -> handleIdentifierFetchingError(e, doiFetcher)).executeWith(taskExecutor); } @Override @@ -70,7 +70,7 @@ public void fetchBibliographyInformation(BibEntry bibEntry) { @Override public void openExternalLink() { identifier.get().map(DOI::asString) - .ifPresent(s -> NativeDesktop.openCustomDoi(s, preferences, dialogService)); + .ifPresent(s -> NativeDesktop.openCustomDoi(s, preferences, dialogService)); } @Override @@ -82,8 +82,8 @@ public void shortenID() { LOGGER.info("DOI is already shortened"); dialogService.notify(Localization.lang("DOI is already shortened")); } else { - LOGGER.info("Shortened DOI: {} to {}", doi, shortenedDOI); - dialogService.notify(Localization.lang("Shortened DOI to: %0", shortenedDOI)); + LOGGER.info("Shortened DOI: {} to {}", doi, shortenedDOI); + dialogService.notify(Localization.lang("Shortened DOI to: %0", shortenedDOI)); } }); } diff --git a/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/IdentifierEditor.java b/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/IdentifierEditor.java index e557900833b..f1b02f4f184 100644 --- a/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/IdentifierEditor.java +++ b/jabgui/src/main/java/org/jabref/gui/fieldeditors/identifier/IdentifierEditor.java @@ -64,15 +64,16 @@ public IdentifierEditor(Field field, this.viewModel = new EprintIdentifierEditorViewModel(suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences, undoManager); // TODO: Add support for PMID - case null, default -> { + case null, + default -> { assert field != null; throw new IllegalStateException("Unable to instantiate a view model for identifier field editor '%s'".formatted(field.getDisplayName())); } } ViewLoader.view(this) - .root(this) - .load(); + .root(this) + .load(); textField.textProperty().bindBidirectional(viewModel.textProperty()); diff --git a/jabgui/src/main/java/org/jabref/gui/frame/JabRefFrameViewModel.java b/jabgui/src/main/java/org/jabref/gui/frame/JabRefFrameViewModel.java index c16ad7ff8ca..8e5aa9306c4 100644 --- a/jabgui/src/main/java/org/jabref/gui/frame/JabRefFrameViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/frame/JabRefFrameViewModel.java @@ -120,10 +120,10 @@ public boolean close() { // Read the opened and focused databases before closing them List openedLibraries = tabContainer.getLibraryTabs().stream() - .map(LibraryTab::getBibDatabaseContext) - .map(BibDatabaseContext::getDatabasePath) - .flatMap(Optional::stream) - .toList(); + .map(LibraryTab::getBibDatabaseContext) + .map(BibDatabaseContext::getDatabasePath) + .flatMap(Optional::stream) + .toList(); Path focusedLibraries = Optional.ofNullable(tabContainer.getCurrentLibraryTab()) .map(LibraryTab::getBibDatabaseContext) .flatMap(BibDatabaseContext::getDatabasePath) @@ -164,9 +164,9 @@ public void handleUiCommands(List uiCommands) { // Handle OpenDatabases if (!blank) { uiCommands.stream() - .filter(UiCommand.OpenLibraries.class::isInstance) - .map(UiCommand.OpenLibraries.class::cast) - .forEach(command -> openDatabaseAction.get().openFiles(command.toImport())); + .filter(UiCommand.OpenLibraries.class::isInstance) + .map(UiCommand.OpenLibraries.class::cast) + .forEach(command -> openDatabaseAction.get().openFiles(command.toImport())); uiCommands.stream() .filter(UiCommand.AppendToCurrentLibrary.class::isInstance) diff --git a/jabgui/src/main/java/org/jabref/gui/frame/UiMessageHandler.java b/jabgui/src/main/java/org/jabref/gui/frame/UiMessageHandler.java index 38a41d7d83c..1315ae15b20 100644 --- a/jabgui/src/main/java/org/jabref/gui/frame/UiMessageHandler.java +++ b/jabgui/src/main/java/org/jabref/gui/frame/UiMessageHandler.java @@ -6,7 +6,7 @@ /** * Specifies an interface that can process either cli or remote commands to the ui - * + *

* See {@link org.jabref.logic.remote.server.RemoteMessageHandler} */ public interface UiMessageHandler { diff --git a/jabgui/src/main/java/org/jabref/gui/git/GitCommitDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/git/GitCommitDialogViewModel.java index 87ae3058081..14a5070c68e 100644 --- a/jabgui/src/main/java/org/jabref/gui/git/GitCommitDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/git/GitCommitDialogViewModel.java @@ -59,7 +59,7 @@ public GitCommitDialogViewModel( public void commit(Runnable onSuccess) { commitTask() - .onSuccess(_-> { + .onSuccess(_ -> { dialogService.notify(Localization.lang("Committed successfully")); onSuccess.run(); }) 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 72a5a0ea91c..887e8cda9f7 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java @@ -488,9 +488,9 @@ public void texGroupBrowse() { .addExtensionFilter(StandardFileType.AUX) .withDefaultExtension(StandardFileType.AUX) .withInitialDirectory(texGroupFilePathProperty.getValue().isBlank() ? - currentDatabase.getMetaData() - .getLatexFileDirectory(preferences.getFilePreferences().getUserAndHost()) - .orElse(FileUtil.getInitialDirectory(currentDatabase, preferences.getFilePreferences().getWorkingDirectory())).toString() : texGroupFilePathProperty.get()).build(); + currentDatabase.getMetaData() + .getLatexFileDirectory(preferences.getFilePreferences().getUserAndHost()) + .orElse(FileUtil.getInitialDirectory(currentDatabase, preferences.getFilePreferences().getWorkingDirectory())).toString() : texGroupFilePathProperty.get()).build(); dialogService.showFileOpenDialog(fileDialogConfiguration) .ifPresent(file -> texGroupFilePathProperty.setValue( FileUtil.relativize(file.toAbsolutePath(), getFileDirectoriesAsPaths()).toString() diff --git a/jabgui/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java b/jabgui/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java index 66ff70471a0..a34e961c4c9 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java @@ -395,9 +395,12 @@ public void draggedOn(GroupNodeViewModel target, DroppingMouseLocation mouseLoca // Bottom + top -> insert source row before / after this row // Center -> add as child switch (mouseLocation) { - case BOTTOM -> this.moveTo(targetParent.get(), targetIndex + 1); - case CENTER -> this.moveTo(target); - case TOP -> this.moveTo(targetParent.get(), targetIndex); + case BOTTOM -> + this.moveTo(targetParent.get(), targetIndex + 1); + case CENTER -> + this.moveTo(target); + case TOP -> + this.moveTo(targetParent.get(), targetIndex); } } else { // No parent = root -> just add @@ -461,67 +464,103 @@ public boolean canAddEntriesIn() { public boolean canBeDragged() { AbstractGroup group = groupNode.getGroup(); return switch (group) { - case AllEntriesGroup _, SmartGroup _ -> false; - case ExplicitGroup _, SearchGroup _, AutomaticKeywordGroup _, AutomaticPersonsGroup _, TexGroup _ -> true; + case AllEntriesGroup _, + SmartGroup _ -> + false; + case ExplicitGroup _, + SearchGroup _, + AutomaticKeywordGroup _, + AutomaticPersonsGroup _, + TexGroup _ -> + true; case KeywordGroup _ -> // KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup groupNode.getParent() - .map(GroupTreeNode::getGroup) - .map(groupParent -> - !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) - .orElse(false); - - case null -> throw new IllegalArgumentException("Group cannot be null"); - default -> throw new UnsupportedOperationException("canBeDragged method not yet implemented in group: " + group.getClass().getName()); + .map(GroupTreeNode::getGroup) + .map(groupParent -> + !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) + .orElse(false); + + case null -> + throw new IllegalArgumentException("Group cannot be null"); + default -> + throw new UnsupportedOperationException("canBeDragged method not yet implemented in group: " + group.getClass().getName()); }; } public boolean canAddGroupsIn() { AbstractGroup group = groupNode.getGroup(); return switch (group) { - case AllEntriesGroup _, ExplicitGroup _, SearchGroup _, TexGroup _ -> true; - case AutomaticKeywordGroup _, AutomaticPersonsGroup _, SmartGroup _ -> false; + case AllEntriesGroup _, + ExplicitGroup _, + SearchGroup _, + TexGroup _ -> + true; + case AutomaticKeywordGroup _, + AutomaticPersonsGroup _, + SmartGroup _ -> + false; case KeywordGroup _ -> // KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup groupNode.getParent() - .map(GroupTreeNode::getGroup) - .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) - .orElse(false); - case null -> throw new IllegalArgumentException("Group cannot be null"); - default -> throw new UnsupportedOperationException("canAddGroupsIn method not yet implemented in group: " + group.getClass().getName()); + .map(GroupTreeNode::getGroup) + .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) + .orElse(false); + case null -> + throw new IllegalArgumentException("Group cannot be null"); + default -> + throw new UnsupportedOperationException("canAddGroupsIn method not yet implemented in group: " + group.getClass().getName()); }; } public boolean canRemove() { AbstractGroup group = groupNode.getGroup(); return switch (group) { - case AllEntriesGroup _, SmartGroup _ -> false; - case ExplicitGroup _, SearchGroup _, AutomaticKeywordGroup _, AutomaticPersonsGroup _, TexGroup _ -> true; + case AllEntriesGroup _, + SmartGroup _ -> + false; + case ExplicitGroup _, + SearchGroup _, + AutomaticKeywordGroup _, + AutomaticPersonsGroup _, + TexGroup _ -> + true; case KeywordGroup _ -> // KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup groupNode.getParent() - .map(GroupTreeNode::getGroup) - .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) - .orElse(false); - case null -> throw new IllegalArgumentException("Group cannot be null"); - default -> throw new UnsupportedOperationException("canRemove method not yet implemented in group: " + group.getClass().getName()); + .map(GroupTreeNode::getGroup) + .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) + .orElse(false); + case null -> + throw new IllegalArgumentException("Group cannot be null"); + default -> + throw new UnsupportedOperationException("canRemove method not yet implemented in group: " + group.getClass().getName()); }; } public boolean isEditable() { AbstractGroup group = groupNode.getGroup(); return switch (group) { - case AllEntriesGroup _, SmartGroup _ -> false; - case ExplicitGroup _, SearchGroup _, AutomaticKeywordGroup _, AutomaticPersonsGroup _, TexGroup _ -> true; + case AllEntriesGroup _, + SmartGroup _ -> + false; + case ExplicitGroup _, + SearchGroup _, + AutomaticKeywordGroup _, + AutomaticPersonsGroup _, + TexGroup _ -> + true; case KeywordGroup _ -> // KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup groupNode.getParent() - .map(GroupTreeNode::getGroup) - .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) - .orElse(false); - - case null -> throw new IllegalArgumentException("Group cannot be null"); - default -> throw new UnsupportedOperationException("isEditable method not yet implemented in group: " + group.getClass().getName()); + .map(GroupTreeNode::getGroup) + .map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)) + .orElse(false); + + case null -> + throw new IllegalArgumentException("Group cannot be null"); + default -> + throw new UnsupportedOperationException("isEditable method not yet implemented in group: " + group.getClass().getName()); }; } diff --git a/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeView.java b/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeView.java index a22b7445ab4..1e90edea3f4 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeView.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeView.java @@ -98,7 +98,6 @@ public class GroupTreeView extends BorderPane { private final FileUpdateMonitor fileUpdateMonitor; private final KeyBindingRepository keyBindingRepository; - private TreeTableView groupTree; private TreeTableColumn mainColumn; private TreeTableColumn numberColumn; @@ -701,9 +700,12 @@ public ContextAction(StandardActions command, GroupNodeViewModel group) { this.executable.bind(BindingsHelper.constantOf( switch (command) { - case GROUP_EDIT, GROUP_SUBGROUP_RENAME -> + case GROUP_EDIT, + GROUP_SUBGROUP_RENAME -> group.isEditable(); - case GROUP_REMOVE, GROUP_REMOVE_WITH_SUBGROUPS, GROUP_REMOVE_KEEP_SUBGROUPS -> + case GROUP_REMOVE, + GROUP_REMOVE_WITH_SUBGROUPS, + GROUP_REMOVE_KEEP_SUBGROUPS -> group.isEditable() && group.canRemove(); case GROUP_SUGGESTED_GROUPS_ADD -> !group.hasAllSuggestedGroups(); @@ -716,7 +718,8 @@ public ContextAction(StandardActions command, GroupNodeViewModel group) { case GROUP_SUBGROUP_SORT -> group.isEditable() && group.hasSubgroups() && group.canAddEntriesIn() || group.isRoot(); - case GROUP_ENTRIES_ADD, GROUP_ENTRIES_REMOVE -> + case GROUP_ENTRIES_ADD, + GROUP_ENTRIES_REMOVE -> group.canAddEntriesIn(); default -> true; @@ -732,7 +735,8 @@ public void execute() { viewModel.removeGroupKeepSubgroups(group); case GROUP_REMOVE_WITH_SUBGROUPS -> viewModel.removeGroupAndSubgroups(group); - case GROUP_EDIT, GROUP_SUBGROUP_RENAME -> + case GROUP_EDIT, + GROUP_SUBGROUP_RENAME -> viewModel.editGroup(group); case GROUP_GENERATE_EMBEDDINGS -> viewModel.generateEmbeddings(group); diff --git a/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java b/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java index 1977ea34c24..95a3c107425 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java @@ -189,10 +189,10 @@ private void addGroupImportEntries(GroupNodeViewModel parent) { String grpName = preferences.getLibraryPreferences().getAddImportedEntriesGroupName(); AbstractGroup importEntriesGroup = new SmartGroup(grpName, GroupHierarchyType.INDEPENDENT, ','); boolean isGrpExist = parent.getGroupNode() - .getChildren() - .stream() - .map(GroupTreeNode::getGroup) - .anyMatch(grp -> grp instanceof SmartGroup); + .getChildren() + .stream() + .map(GroupTreeNode::getGroup) + .anyMatch(grp -> grp instanceof SmartGroup); if (!isGrpExist) { currentDatabase.ifPresent(db -> { GroupTreeNode newSubgroup = parent.addSubgroup(importEntriesGroup); diff --git a/jabgui/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java b/jabgui/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java index 69a7bc3e715..b95108400a2 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java @@ -51,17 +51,14 @@ public class UndoableAddOrRemoveGroup extends AbstractUndoableJabRefEdit { /** * Creates an object that can undo/redo an edit event. * - * @param groupsRoot - * The global groups root. - * @param editType - * The type of editing (ADD_NODE, REMOVE_NODE_KEEP_CHILDREN, - * REMOVE_NODE_AND_CHILDREN) - * @param editedNode - * The edited node (which was added or will be removed). The node - * must be a descendant of node groupsRoot! This means - * that, in case of adding, you first have to add it to the tree, - * then call this constructor. When removing, you first have to - * call this constructor, then remove the node. + * @param groupsRoot The global groups root. + * @param editType The type of editing (ADD_NODE, REMOVE_NODE_KEEP_CHILDREN, + * REMOVE_NODE_AND_CHILDREN) + * @param editedNode The edited node (which was added or will be removed). The node + * must be a descendant of node groupsRoot! This means + * that, in case of adding, you first have to add it to the tree, + * then call this constructor. When removing, you first have to + * call this constructor, then remove the node. */ public UndoableAddOrRemoveGroup(GroupTreeNodeViewModel groupsRoot, GroupTreeNodeViewModel editedNode, int editType) { @@ -71,9 +68,9 @@ public UndoableAddOrRemoveGroup(GroupTreeNodeViewModel groupsRoot, // storing a backup of the whole subtree is not required when children // are kept m_subtreeBackup = editType != UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN ? - editedNode.getNode() - .copySubtree() - : GroupTreeNode.fromGroup(editedNode.getNode().getGroup().deepCopy()); + editedNode.getNode() + .copySubtree() + : GroupTreeNode.fromGroup(editedNode.getNode().getGroup().deepCopy()); // remember path to edited node. this cannot be stored as a reference, // because the reference itself might change. the method below is more // robust. @@ -83,10 +80,14 @@ public UndoableAddOrRemoveGroup(GroupTreeNodeViewModel groupsRoot, @Override public String getPresentationName() { return switch (m_editType) { - case ADD_NODE -> Localization.lang("Add group"); - case REMOVE_NODE_KEEP_CHILDREN -> Localization.lang("Keep subgroups)"); - case REMOVE_NODE_AND_CHILDREN -> Localization.lang("Also remove subgroups"); - default -> "? (" + Localization.lang("unknown edit") + ")"; + case ADD_NODE -> + Localization.lang("Add group"); + case REMOVE_NODE_KEEP_CHILDREN -> + Localization.lang("Keep subgroups)"); + case REMOVE_NODE_AND_CHILDREN -> + Localization.lang("Also remove subgroups"); + default -> + "? (" + Localization.lang("unknown edit") + ")"; }; } diff --git a/jabgui/src/main/java/org/jabref/gui/groups/UndoableChangeEntriesOfGroup.java b/jabgui/src/main/java/org/jabref/gui/groups/UndoableChangeEntriesOfGroup.java index 3f4b36b6351..85092c43929 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/UndoableChangeEntriesOfGroup.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/UndoableChangeEntriesOfGroup.java @@ -4,7 +4,7 @@ import javax.swing.undo.AbstractUndoableEdit; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; @@ -16,7 +16,7 @@ private UndoableChangeEntriesOfGroup() { public static AbstractUndoableEdit getUndoableEdit(GroupTreeNodeViewModel node, List changes) { boolean hasEntryChanges = false; - NamedCompound entryChangeCompound = new NamedCompound(Localization.lang("change entries of group")); + NamedCompoundEdit entryChangeCompound = new NamedCompoundEdit(Localization.lang("change entries of group")); for (FieldChange fieldChange : changes) { hasEntryChanges = true; entryChangeCompound.addEdit(new UndoableFieldChange(fieldChange)); diff --git a/jabgui/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java b/jabgui/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java index a27ffacee40..24f5bfbacff 100644 --- a/jabgui/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java +++ b/jabgui/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java @@ -10,7 +10,7 @@ * Such an error console can be * useful in getting complete bug reports, especially from Windows users, * without asking users to run JabRef in a command window to catch the error info. - * + *

* It offers a separate tab for the log output. */ public class ErrorConsoleAction extends SimpleCommand { diff --git a/jabgui/src/main/java/org/jabref/gui/help/VersionWorker.java b/jabgui/src/main/java/org/jabref/gui/help/VersionWorker.java index a68781ef4a4..fc02498cb3f 100644 --- a/jabgui/src/main/java/org/jabref/gui/help/VersionWorker.java +++ b/jabgui/src/main/java/org/jabref/gui/help/VersionWorker.java @@ -22,7 +22,7 @@ * This worker checks if there is a new version of JabRef available. If there is it will display a dialog to the user * offering him multiple options to proceed (see changelog, go to the download page, ignore this version, and remind * later). - * + *

* If the versions check is executed manually and this is the latest version it will also display a dialog to inform the * user. */ @@ -99,7 +99,7 @@ private void showUpdateInfo(Optional newerVersion, boolean manualExecut } else { // notify the user about a newer version if (dialogService.showCustomDialogAndWait( - new NewVersionDialog(installedVersion, newerVersion.get(), dialogService, externalApplicationsPreferences)) + new NewVersionDialog(installedVersion, newerVersion.get(), dialogService, externalApplicationsPreferences)) .orElse(true)) { internalPreferences.setIgnoredVersion(newerVersion.get()); } diff --git a/jabgui/src/main/java/org/jabref/gui/importer/ImportCommand.java b/jabgui/src/main/java/org/jabref/gui/importer/ImportCommand.java index 5a9f78e4d48..8c079ccd143 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/ImportCommand.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/ImportCommand.java @@ -195,8 +195,8 @@ private ParserResult doImport(List files, Importer importFormat) throws IO () -> dialogService.showWarningDialogAndWait( Localization.lang("Import error"), Localization.lang("Please check your library file for wrong syntax.") - + "\n\n" - + ex.getLocalizedMessage())); + + "\n\n" + + ex.getLocalizedMessage())); } } diff --git a/jabgui/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java b/jabgui/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java index 849478abb0b..b80931e82bd 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java @@ -44,8 +44,8 @@ public ImportCustomEntryTypesDialog(BibDatabaseMode mode, List cus viewModel.importBibEntryTypes( unknownEntryTypesCheckList.getCheckModel().getCheckedItems(), differentCustomizationCheckList.getCheckModel().getCheckedItems().stream() - .map(BibEntryTypePrefsAndFileViewModel::customTypeFromPreferences) - .toList()); + .map(BibEntryTypePrefsAndFileViewModel::customTypeFromPreferences) + .toList()); } return null; }); diff --git a/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java b/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java index 03492d4cece..e2945be8aa6 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java @@ -110,9 +110,9 @@ public ImportEntriesDialog(BibDatabaseContext database, BackgroundTask task, SearchBasedFetcher fetcher, String query) { this.database = database; @@ -256,62 +256,62 @@ private void setupPaginationBindings() { }, viewModel.currentPageProperty(), viewModel.totalPagesProperty()); BooleanBinding isPagedFetcher = Bindings.createBooleanBinding(() -> - searchBasedFetcher.isPresent() && searchBasedFetcher.get() instanceof PagedSearchBasedFetcher + searchBasedFetcher.isPresent() && searchBasedFetcher.get() instanceof PagedSearchBasedFetcher ); // Disable: during loading OR when on the last page for non-paged fetchers // OR when the initial load is not complete for paged fetchers nextPageButton.disableProperty().bind( - loading.or(isOnLastPage.and(isPagedFetcher.not())) - .or(isPagedFetcher.and(initialLoadComplete.not())) + loading.or(isOnLastPage.and(isPagedFetcher.not())) + .or(isPagedFetcher.and(initialLoadComplete.not())) ); prevPageButton.disableProperty().bind(loading.or(viewModel.currentPageProperty().isEqualTo(0))); prevPageButton.textProperty().bind( - Bindings.when(loading) - .then("< " + Localization.lang("Loading...")) - .otherwise("< " + Localization.lang("Previous")) + Bindings.when(loading) + .then("< " + Localization.lang("Loading...")) + .otherwise("< " + Localization.lang("Previous")) ); nextPageButton.textProperty().bind( - Bindings.when(loading) - .then(Localization.lang("Loading...") + " >") - .otherwise( - Bindings.when(initialLoadComplete.not().and(isPagedFetcher)) - .then(Localization.lang("Loading initial entries...")) + Bindings.when(loading) + .then(Localization.lang("Loading...") + " >") .otherwise( - Bindings.when(isOnLastPage) - .then( - Bindings.when(isPagedFetcher) - .then(Localization.lang("Load More") + " >>") - .otherwise(Localization.lang("No more entries")) - ) - .otherwise(Localization.lang("Next") + " >") + Bindings.when(initialLoadComplete.not().and(isPagedFetcher)) + .then(Localization.lang("Loading initial entries...")) + .otherwise( + Bindings.when(isOnLastPage) + .then( + Bindings.when(isPagedFetcher) + .then(Localization.lang("Load More") + " >>") + .otherwise(Localization.lang("No more entries")) + ) + .otherwise(Localization.lang("Next") + " >") + ) ) - ) ); statusLabel.textProperty().bind( - Bindings.when(loading) - .then(Localization.lang("Fetching more entries...")) - .otherwise( - Bindings.when(initialLoadComplete.not().and(isPagedFetcher)) - .then(Localization.lang("Loading initial results...")) + Bindings.when(loading) + .then(Localization.lang("Fetching more entries...")) .otherwise( - Bindings.when(isOnLastPage) - .then( - Bindings.when(isPagedFetcher) - .then(Localization.lang("Click 'Load More' to fetch additional entries")) - .otherwise(Bindings.createStringBinding(() -> { - int totalEntries = viewModel.getAllEntries().size(); - return totalEntries > 0 ? - Localization.lang("All %0 entries loaded", String.valueOf(totalEntries)) : - Localization.lang("No entries available"); - }, viewModel.getAllEntries())) - ) - .otherwise("") + Bindings.when(initialLoadComplete.not().and(isPagedFetcher)) + .then(Localization.lang("Loading initial results...")) + .otherwise( + Bindings.when(isOnLastPage) + .then( + Bindings.when(isPagedFetcher) + .then(Localization.lang("Click 'Load More' to fetch additional entries")) + .otherwise(Bindings.createStringBinding(() -> { + int totalEntries = viewModel.getAllEntries().size(); + return totalEntries > 0 ? + Localization.lang("All %0 entries loaded", String.valueOf(totalEntries)) : + Localization.lang("No entries available"); + }, viewModel.getAllEntries())) + ) + .otherwise("") + ) ) - ) ); loading.addListener((_, _, newVal) -> { @@ -325,7 +325,7 @@ private void setupPaginationBindings() { statusLabel.getStyleClass().remove("info-message"); } }); -} + } private void updatePageUI() { pageNumberLabel.textProperty().bind(Bindings.createStringBinding(() -> { diff --git a/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java b/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java index c841a79c21b..0a39f06c331 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java @@ -165,7 +165,7 @@ public void loadEntries(List entries) { public boolean hasDuplicate(BibEntry entry) { return findInternalDuplicate(entry).isPresent() || new DuplicateCheck(entryTypesManager) - .containsDuplicate(selectedDb.getValue().getDatabase(), entry, selectedDb.getValue().getMode()).isPresent(); + .containsDuplicate(selectedDb.getValue().getDatabase(), entry, selectedDb.getValue().getMode()).isPresent(); } public String getSourceString(BibEntry entry) { @@ -281,8 +281,8 @@ private void updatePagedEntries() { public void fetchMoreEntries() { if (fetcher.isPresent() && - fetcher.get() instanceof PagedSearchBasedFetcher pagedFetcher && - query.isPresent() && !loading.get()) { + fetcher.get() instanceof PagedSearchBasedFetcher pagedFetcher && + query.isPresent() && !loading.get()) { loading.set(true); BackgroundTask> fetchTask = BackgroundTask .wrap(() -> { diff --git a/jabgui/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java b/jabgui/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java index 43fb3d836d2..cf446898cee 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java @@ -16,8 +16,8 @@ public class NewDatabaseAction extends SimpleCommand { /** * Constructs a command to create a new library of the default type * - * @param tabContainer the ui container for libraries - * @param preferences the preferencesService of JabRef + * @param tabContainer the ui container for libraries + * @param preferences the preferencesService of JabRef */ public NewDatabaseAction(LibraryTabContainer tabContainer, CliPreferences preferences) { this.tabContainer = tabContainer; diff --git a/jabgui/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java b/jabgui/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java index 63ae19877bd..7c000e3e86f 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java @@ -18,7 +18,7 @@ private ParserResultWarningDialog() { /** * Shows a dialog with the warnings from an import or open of a file * - * @param parserResult - ParserResult for the current import/open + * @param parserResult - ParserResult for the current import/open */ public static void showParserResultWarningDialog(final ParserResult parserResult, final DialogService dialogService) { diff --git a/jabgui/src/main/java/org/jabref/gui/importer/actions/GUIPostOpenAction.java b/jabgui/src/main/java/org/jabref/gui/importer/actions/GUIPostOpenAction.java index f4eec73e339..6904b0310b2 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/actions/GUIPostOpenAction.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/actions/GUIPostOpenAction.java @@ -29,10 +29,10 @@ public interface GUIPostOpenAction { * the isActionNecessary() method returned true. *

* Note: if several such methods need to be called sequentially, it is - * important that all implementations of this method do not return - * until the operation is finished. + * important that all implementations of this method do not return + * until the operation is finished. * - * @param pr The result of the BIB parse operation. + * @param pr The result of the BIB parse operation. */ void performAction(ParserResult pr, DialogService dialogService, CliPreferences preferences); } diff --git a/jabgui/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java b/jabgui/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java index 3e872e4ff31..590e21cbb1c 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java @@ -214,7 +214,7 @@ public void openFiles(List filesToOpen) { /** * This is the real file opening. Should be called via {@link #openFile(Path)} - * + *

* Similar method: {@link org.jabref.gui.frame.JabRefFrame#addTab(org.jabref.model.database.BibDatabaseContext, boolean)}. * * @param file the file, may be NOT null, but may not be existing @@ -281,18 +281,18 @@ private ParserResult loadDatabase(Path file) throws NotASharedDatabaseException, } if (parserResult.getDatabase().isShared()) { - openSharedDatabase( - parserResult, - tabContainer, - dialogService, - preferences, - aiService, - stateManager, - entryTypesManager, - fileUpdateMonitor, - undoManager, - clipboardManager, - taskExecutor); + openSharedDatabase( + parserResult, + tabContainer, + dialogService, + preferences, + aiService, + stateManager, + entryTypesManager, + fileUpdateMonitor, + undoManager, + clipboardManager, + taskExecutor); } return parserResult; } diff --git a/jabgui/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java b/jabgui/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java index 0b73e3bccab..9820bbd987d 100644 --- a/jabgui/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java +++ b/jabgui/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java @@ -9,7 +9,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.Action; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.UiTaskExecutor; @@ -70,7 +70,7 @@ public Action getAction() { private String lookupIdentifiers(List bibEntries) { String totalCount = Integer.toString(bibEntries.size()); - NamedCompound namedCompound = new NamedCompound(Localization.lang("Look up %0", fetcher.getIdentifierName())); + NamedCompoundEdit namedCompoundEdit = new NamedCompoundEdit(Localization.lang("Look up %0", fetcher.getIdentifierName())); int count = 0; int foundCount = 0; for (BibEntry bibEntry : bibEntries) { @@ -87,7 +87,7 @@ private String lookupIdentifiers(List bibEntries) { if (identifier.isPresent() && !bibEntry.hasField(identifier.get().getDefaultField())) { Optional fieldChange = bibEntry.setField(identifier.get().getDefaultField(), identifier.get().asString()); if (fieldChange.isPresent()) { - namedCompound.addEdit(new UndoableFieldChange(fieldChange.get())); + namedCompoundEdit.addEdit(new UndoableFieldChange(fieldChange.get())); foundCount++; final String nextStatusMessage = Localization.lang("Looking up %0... - entry %1 out of %2 - found %3", fetcher.getIdentifierName(), Integer.toString(count), totalCount, Integer.toString(foundCount)); @@ -95,9 +95,9 @@ private String lookupIdentifiers(List bibEntries) { } } } - namedCompound.end(); + namedCompoundEdit.end(); if (foundCount > 0) { - UiTaskExecutor.runInJavaFXThread(() -> undoManager.addEdit(namedCompound)); + UiTaskExecutor.runInJavaFXThread(() -> undoManager.addEdit(namedCompoundEdit)); } return Localization.lang("Determined %0 for %1 entries", fetcher.getIdentifierName(), Integer.toString(foundCount)); } diff --git a/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsPane.java b/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsPane.java index 096e5633884..d3a7f6ec71d 100644 --- a/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsPane.java +++ b/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsPane.java @@ -20,7 +20,7 @@ /** * Controller for the .blg file settings panel. - * + *

* Binds the path text field to the ViewModel, * and handles browse/reset button actions. */ diff --git a/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsViewModel.java b/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsViewModel.java index e6a1c39351b..2551fdded62 100644 --- a/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/integrity/BibLogSettingsViewModel.java @@ -54,7 +54,7 @@ public BibLogSettingsViewModel(MetaData metaData, Optional bibPath) { * * @param databaseContext the current database context used to resolve citation keys in warnings. * @return An Optional containing the list of integrity messages if the file exists and can be parsed, - * or an empty Optional if the file does not exist. + * or an empty Optional if the file does not exist. * @throws JabRefException if the .blg file cannot be parsed or read */ public Optional> getBlgWarnings(BibDatabaseContext databaseContext) throws JabRefException { diff --git a/jabgui/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java b/jabgui/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java index 8fcf14aa11e..bacffd5e16b 100644 --- a/jabgui/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java @@ -175,7 +175,7 @@ private void loadBibLogSettingsPane() { * Called on: * (1) Dialog initialization (default load) * (2) User triggers Browse or Reset in BibLogSettingsPane - * + *

* This reloads .blg warnings and merges them into the main message list. */ private void reloadBlgWarnings() { diff --git a/jabgui/src/main/java/org/jabref/gui/journals/AbbreviateAction.java b/jabgui/src/main/java/org/jabref/gui/journals/AbbreviateAction.java index edb54c40529..4fd4bb2aa29 100644 --- a/jabgui/src/main/java/org/jabref/gui/journals/AbbreviateAction.java +++ b/jabgui/src/main/java/org/jabref/gui/journals/AbbreviateAction.java @@ -11,7 +11,7 @@ import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; @@ -103,18 +103,18 @@ private String abbreviate(BibDatabaseContext databaseContext, List ent abbreviationType, journalAbbreviationPreferences.shouldUseFJournalField()); - NamedCompound ce = new NamedCompound(Localization.lang("Abbreviate journal names")); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Abbreviate journal names")); int count = entries.stream().mapToInt(entry -> (int) FieldFactory.getJournalNameFields().stream().filter(journalField -> - undoableAbbreviator.abbreviate(databaseContext.getDatabase(), entry, journalField, ce)).count()).sum(); + undoableAbbreviator.abbreviate(databaseContext.getDatabase(), entry, journalField, compoundEdit)).count()).sum(); if (count == 0) { return Localization.lang("No journal names could be abbreviated."); } - ce.end(); - undoManager.addEdit(ce); + compoundEdit.end(); + undoManager.addEdit(compoundEdit); tabSupplier.get().markBaseChanged(); return Localization.lang("Abbreviated %0 journal names.", String.valueOf(count)); } @@ -122,16 +122,16 @@ private String abbreviate(BibDatabaseContext databaseContext, List ent private String unabbreviate(BibDatabaseContext databaseContext, List entries) { UndoableUnabbreviator undoableAbbreviator = new UndoableUnabbreviator(abbreviationRepository); - NamedCompound ce = new NamedCompound(Localization.lang("Unabbreviate journal names")); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Unabbreviate journal names")); int count = entries.stream().mapToInt(entry -> (int) FieldFactory.getJournalNameFields().stream().filter(journalField -> - undoableAbbreviator.unabbreviate(databaseContext.getDatabase(), entry, journalField, ce)).count()).sum(); + undoableAbbreviator.unabbreviate(databaseContext.getDatabase(), entry, journalField, compoundEdit)).count()).sum(); if (count == 0) { return Localization.lang("No journal names could be unabbreviated."); } - ce.end(); - undoManager.addEdit(ce); + compoundEdit.end(); + undoManager.addEdit(compoundEdit); tabSupplier.get().markBaseChanged(); return Localization.lang("Unabbreviated %0 journal names.", String.valueOf(count)); } diff --git a/jabgui/src/main/java/org/jabref/gui/journals/AbbreviationType.java b/jabgui/src/main/java/org/jabref/gui/journals/AbbreviationType.java index 221141bf7cc..de30b58225c 100644 --- a/jabgui/src/main/java/org/jabref/gui/journals/AbbreviationType.java +++ b/jabgui/src/main/java/org/jabref/gui/journals/AbbreviationType.java @@ -2,7 +2,7 @@ /** * Defines the different abbreviation types that JabRef can operate with. - * + *

* DEFAULT: Default abbreviation type, which is the standard behavior. * DOTLESS: Abbreviation type that does not include dots in the abbreviation. * SHORTEST_UNIQUE: Abbreviation type that generates the shortest unique abbreviation. diff --git a/jabgui/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java b/jabgui/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java index b4cb7199a93..c4d93444bba 100644 --- a/jabgui/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java +++ b/jabgui/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java @@ -31,10 +31,10 @@ public UndoableAbbreviator(JournalAbbreviationRepository journalAbbreviationRepo * @param database The database the entry belongs to, or null if no database. * @param entry The entry to be treated. * @param fieldName The field name (e.g. "journal") - * @param ce If the entry is changed, add an edit to this compound. + * @param compoundEdit If the entry is changed, add an edit to this compound. * @return true if the entry was changed, false otherwise. */ - public boolean abbreviate(BibDatabase database, BibEntry entry, Field fieldName, CompoundEdit ce) { + public boolean abbreviate(BibDatabase database, BibEntry entry, Field fieldName, CompoundEdit compoundEdit) { if (!entry.hasField(fieldName)) { return false; } @@ -49,8 +49,8 @@ public boolean abbreviate(BibDatabase database, BibEntry entry, Field fieldName, } Optional newTextOptional = abbreviationType == AbbreviationType.LTWA - ? journalAbbreviationRepository.getLtwaAbbreviation(text) - : foundAbbreviation.map(this::getAbbreviatedName); + ? journalAbbreviationRepository.getLtwaAbbreviation(text) + : foundAbbreviation.map(this::getAbbreviatedName); // Return early if no abbreviation found or it matches original if (newTextOptional.isEmpty() || newTextOptional.get().equals(origText)) { @@ -64,12 +64,12 @@ public boolean abbreviate(BibDatabase database, BibEntry entry, Field fieldName, if (useFJournalField && (StandardField.JOURNAL == fieldName || StandardField.JOURNALTITLE == fieldName)) { String fullName = abbr.getName(); entry.setField(AMSField.FJOURNAL, fullName); - ce.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, null, fullName)); + compoundEdit.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, null, fullName)); } }); entry.setField(fieldName, newText); - ce.addEdit(new UndoableFieldChange(entry, fieldName, origText, newText)); + compoundEdit.addEdit(new UndoableFieldChange(entry, fieldName, origText, newText)); return true; } diff --git a/jabgui/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java b/jabgui/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java index acb101aef58..83945dd0374 100644 --- a/jabgui/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java +++ b/jabgui/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java @@ -24,15 +24,15 @@ public UndoableUnabbreviator(JournalAbbreviationRepository journalAbbreviationRe * * @param entry The entry to be treated. * @param field The field - * @param ce If the entry is changed, add an edit to this compound. + * @param compoundEdit If the entry is changed, add an edit to this compound. * @return true if the entry was changed, false otherwise. */ - public boolean unabbreviate(BibDatabase database, BibEntry entry, Field field, CompoundEdit ce) { + public boolean unabbreviate(BibDatabase database, BibEntry entry, Field field, CompoundEdit compoundEdit) { if (!entry.hasField(field)) { return false; } - if (restoreFromFJournal(entry, field, ce)) { + if (restoreFromFJournal(entry, field, compoundEdit)) { return true; } @@ -53,11 +53,11 @@ public boolean unabbreviate(BibDatabase database, BibEntry entry, Field field, C Abbreviation abbreviation = journalAbbreviationRepository.get(text).get(); String newText = abbreviation.getName(); entry.setField(field, newText); - ce.addEdit(new UndoableFieldChange(entry, field, origText, newText)); + compoundEdit.addEdit(new UndoableFieldChange(entry, field, origText, newText)); return true; } - public boolean restoreFromFJournal(BibEntry entry, Field field, CompoundEdit ce) { + public boolean restoreFromFJournal(BibEntry entry, Field field, CompoundEdit compoundEdit) { if ((StandardField.JOURNAL != field && StandardField.JOURNALTITLE != field) || !entry.hasField(AMSField.FJOURNAL)) { return false; } @@ -66,10 +66,10 @@ public boolean restoreFromFJournal(BibEntry entry, Field field, CompoundEdit ce) String newText = entry.getField(AMSField.FJOURNAL).get().trim(); entry.setField(AMSField.FJOURNAL, ""); - ce.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, newText, "")); + compoundEdit.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, newText, "")); entry.setField(field, newText); - ce.addEdit(new UndoableFieldChange(entry, field, origText, newText)); + compoundEdit.addEdit(new UndoableFieldChange(entry, field, origText, newText)); return true; } diff --git a/jabgui/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java b/jabgui/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java index 7140fefe4a6..2fe6622f52c 100644 --- a/jabgui/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java +++ b/jabgui/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java @@ -33,11 +33,15 @@ public static void call(Scene scene, KeyEvent event, KeyBindingRepository keyBin focusedTextField.nextWord(); event.consume(); } - case EDITOR_BEGINNING, EDITOR_UP, EDITOR_BEGINNING_DOC -> { + case EDITOR_BEGINNING, + EDITOR_UP, + EDITOR_BEGINNING_DOC -> { focusedTextField.home(); event.consume(); } - case EDITOR_END, EDITOR_DOWN, EDITOR_END_DOC -> { + case EDITOR_END, + EDITOR_DOWN, + EDITOR_END_DOC -> { focusedTextField.end(); event.consume(); } diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesViewModel.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesViewModel.java index 9c2cd72039b..303885c9c6a 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesViewModel.java @@ -40,7 +40,7 @@ public void storeAllSettings() { public boolean validateAllSettings() { for (PropertiesTab propertiesTab : propertiesTabs) { if (!propertiesTab.validateSettings()) { - return false; + return false; } } return true; diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java index 6633dbe1ac9..a7ca2fe833a 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java @@ -198,8 +198,8 @@ private List determineFieldsToRemove() { // Remove all content selectors that are not in the new list List result = new ArrayList<>(metaData.getContentSelectors().getFieldsWithSelectors().stream() - .filter(field -> !newlyAddedKeywords.contains(field)) - .toList()); + .filter(field -> !newlyAddedKeywords.contains(field)) + .toList()); // Remove all unset default fields result.addAll(fieldKeywordsMap.entrySet() .stream() diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java index 2b9ab5f3194..7bddc86c0b9 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java @@ -104,7 +104,7 @@ public void initialize() { libSpecificFileDirSwitchIcon.setGlyph(isAbsolute ? RELATIVE_PATH : ABSOLUTE_PATH); libSpecificFileDirSwitchTooltip.setText(isAbsolute ? switchToRelativeText : switchToAbsoluteText); librarySpecificFileDirectoryTooltip.setText(newValue.trim().isEmpty() ? - Localization.lang("Library-specific file directory") : Localization.lang("Library-specific file directory: %0", newValue)); + Localization.lang("Library-specific file directory") : Localization.lang("Library-specific file directory: %0", newValue)); }); userSpecificFileDirectory.textProperty().addListener((_, _, newValue) -> { boolean isAbsolute = Path.of(newValue).isAbsolute(); @@ -117,7 +117,7 @@ public void initialize() { laTexSpecificFileDirSwitchIcon.setGlyph(isAbsolute ? RELATIVE_PATH : ABSOLUTE_PATH); laTexSpecificFileDirSwitchTooltip.setText(isAbsolute ? switchToRelativeText : switchToAbsoluteText); latexFileDirectoryTooltip.setText(newValue.trim().isEmpty() - ? Localization.lang("LaTeX file directory") : Localization.lang("LaTeX file directory: %0", newValue)); + ? Localization.lang("LaTeX file directory") : Localization.lang("LaTeX file directory: %0", newValue)); }); Platform.runLater(() -> { diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java index b87b56c4f86..4a7e9c15021 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java @@ -287,7 +287,7 @@ public void togglePath(StringProperty fileDirectory) { /** * For a saved library, any directory relative to the library path will be set as relative; otherwise, it will be set as absolute. * - * @param fileDirectory file directory to be updated (lib/user/laTex) + * @param fileDirectory file directory to be updated (lib/user/laTex) * @param selectedDirPath path of directory (selected by user) */ private void setDirectory(StringProperty fileDirectory, Path selectedDirPath) { @@ -301,7 +301,7 @@ private void setDirectory(StringProperty fileDirectory, Path selectedDirPath) { // set relative path fileDirectory.setValue(libPath.get() - .getParent() - .relativize(selectedDirPath).toString()); + .getParent() + .relativize(selectedDirPath).toString()); } } diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java index e2701a309c3..489fd81644c 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java @@ -68,9 +68,12 @@ public void setValues() { // SaveOrderConfigPanel, included via in FXML switch (saveOrder.getOrderType()) { - case SPECIFIED -> saveInSpecifiedOrderProperty.setValue(true); - case ORIGINAL -> saveInOriginalProperty.setValue(true); - case TABLE -> saveInTableOrderProperty.setValue(true); + case SPECIFIED -> + saveInSpecifiedOrderProperty.setValue(true); + case ORIGINAL -> + saveInOriginalProperty.setValue(true); + case TABLE -> + saveInTableOrderProperty.setValue(true); } sortableFieldsProperty.clear(); diff --git a/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java b/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java index 941c5c92da7..e987d0e0edd 100644 --- a/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java +++ b/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java @@ -82,14 +82,14 @@ public void execute() { LinkedFileEditDialog dialog = new LinkedFileEditDialog(linkedFile); dialogService.showCustomDialogAndWait(dialog) - .ifPresent(editedLinkedFile -> { - Optional fieldChange = entry.addFile(editedLinkedFile); - fieldChange.ifPresent(change -> { - UndoableFieldChange ce = new UndoableFieldChange(change); - libraryTab.getUndoManager().addEdit(ce); - libraryTab.markBaseChanged(); - }); - }); + .ifPresent(editedLinkedFile -> { + Optional fieldChange = entry.addFile(editedLinkedFile); + fieldChange.ifPresent(change -> { + UndoableFieldChange compoundEdit = new UndoableFieldChange(change); + libraryTab.getUndoManager().addEdit(compoundEdit); + libraryTab.markBaseChanged(); + }); + }); }); } } diff --git a/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java b/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java index 8ac056f8119..a172f9dd866 100644 --- a/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java +++ b/jabgui/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java @@ -63,11 +63,11 @@ public void execute() { try { URL url = URLUtil.create(urlforDownload.get()); LinkedFileViewModel onlineFile = new LinkedFileViewModel( - new LinkedFile(url, ""), - entry, - databaseContext, - taskExecutor, - dialogService, + new LinkedFile(url, ""), + entry, + databaseContext, + taskExecutor, + dialogService, preferences); onlineFile.download(true); } catch (MalformedURLException exception) { diff --git a/jabgui/src/main/java/org/jabref/gui/linkedfile/RedownloadMissingFilesAction.java b/jabgui/src/main/java/org/jabref/gui/linkedfile/RedownloadMissingFilesAction.java index d7de66854cb..e8d96958df1 100644 --- a/jabgui/src/main/java/org/jabref/gui/linkedfile/RedownloadMissingFilesAction.java +++ b/jabgui/src/main/java/org/jabref/gui/linkedfile/RedownloadMissingFilesAction.java @@ -65,29 +65,29 @@ public void execute() { private void redownloadMissing(BibDatabaseContext databaseContext) { LOGGER.info("Redownloading missing files"); databaseContext.getEntries().forEach(entry -> - entry.getFiles().forEach(linkedFile -> { - if (linkedFile.isOnlineLink() || linkedFile.getSourceUrl().isEmpty()) { - return; - } + entry.getFiles().forEach(linkedFile -> { + if (linkedFile.isOnlineLink() || linkedFile.getSourceUrl().isEmpty()) { + return; + } - Optional path = FileUtil.find(this.databaseContext, linkedFile.getLink(), filePreferences); - if (path.isPresent() && Files.exists(path.get())) { - return; - } - String fileName = Path.of(linkedFile.getLink()).getFileName().toString(); + Optional path = FileUtil.find(this.databaseContext, linkedFile.getLink(), filePreferences); + if (path.isPresent() && Files.exists(path.get())) { + return; + } + String fileName = Path.of(linkedFile.getLink()).getFileName().toString(); - DownloadLinkedFileAction downloadAction = new DownloadLinkedFileAction( - this.databaseContext, - entry, - linkedFile, - linkedFile.getSourceUrl(), - dialogService, - externalApplicationsPreferences, - filePreferences, - taskExecutor, - fileName, - true); - downloadAction.execute(); - })); + DownloadLinkedFileAction downloadAction = new DownloadLinkedFileAction( + this.databaseContext, + entry, + linkedFile, + linkedFile.getSourceUrl(), + dialogService, + externalApplicationsPreferences, + filePreferences, + taskExecutor, + fileName, + true); + downloadAction.execute(); + })); } } diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/ExtractReferencesAction.java b/jabgui/src/main/java/org/jabref/gui/maintable/ExtractReferencesAction.java index b4aa68fd321..02474b59304 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/ExtractReferencesAction.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/ExtractReferencesAction.java @@ -36,7 +36,7 @@ *

  • Mode choice A: online or offline
  • *
  • Mode choice B: complete entry or single file (the latter is not implemented)
  • * - * + *

    * The mode is selected by the preferences whether to use Grobid or not. */ public class ExtractReferencesAction extends SimpleCommand { @@ -59,7 +59,7 @@ public ExtractReferencesAction(DialogService dialogService, /** * Can be used to bind the action on a context menu in the linked file view (future work) * - * @param entry the entry to handle (can be null) + * @param entry the entry to handle (can be null) * @param linkedFile the linked file (can be null) */ private ExtractReferencesAction(@NonNull DialogService dialogService, @@ -164,7 +164,7 @@ private void extractReferences(Iterator fileListIterator, ParserResult res /** * Creates the field content for the "cites" field. The field contains the citation keys of the imported entries. - * + *

    * TODO: Move this part to logic somehow * * @param currentEntry used to create citation keys if the importer did not provide one from the imported entry diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/MainTable.java b/jabgui/src/main/java/org/jabref/gui/maintable/MainTable.java index 0f59d35000d..3d8c9e8ec2a 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/MainTable.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/MainTable.java @@ -179,10 +179,10 @@ public MainTable(MainTableDataModel model, // force match category column to be the first sort order, (match_category column is always the first column) this.getSortOrder().addFirst(getColumns().getFirst()); this.getSortOrder().addListener((ListChangeListener>) change -> { - if (!this.getSortOrder().getFirst().equals(getColumns().getFirst())) { - this.getSortOrder().addFirst(getColumns().getFirst()); - } - }); + if (!this.getSortOrder().getFirst().equals(getColumns().getFirst())) { + this.getSortOrder().addFirst(getColumns().getFirst()); + } + }); mainTablePreferences.getColumnPreferences().getColumnSortOrder().forEach(columnModel -> this.getColumns().stream() @@ -434,7 +434,7 @@ private void setupKeyBindings(KeyBindingRepository keyBindings) { event.consume(); break; case SCROLL_TO_PREVIOUS_MATCH_CATEGORY: - scrollToPreviousMatchCategory(); + scrollToPreviousMatchCategory(); event.consume(); break; case OPEN_URL_OR_DOI: @@ -540,7 +540,9 @@ private void handleOnDragDropped(TableRow row, BibEntryT switch (ControlHelper.getDroppingMouseLocation(row, event)) { // Different actions depending on where the user releases the drop in the target row // - Bottom + top -> import entries - case TOP, BOTTOM -> importHandler.importFilesInBackground(files, database, filePreferences, transferMode).executeWith(taskExecutor); + case TOP, + BOTTOM -> + importHandler.importFilesInBackground(files, database, filePreferences, transferMode).executeWith(taskExecutor); // - Center -> modify entry: link files to entry case CENTER -> { BibEntry entry = target.getEntry(); @@ -600,13 +602,13 @@ public void setCitationMergeMode(boolean citationMerge) { } private void updatePlaceholder(VBox placeholderBox) { - if (database.getDatabase().getEntries().isEmpty()) { - this.setPlaceholder(placeholderBox); - // [impl->req~maintable.focus~1] - requestFocus(); - } else { - this.setPlaceholder(null); - } + if (database.getDatabase().getEntries().isEmpty()) { + this.setPlaceholder(placeholderBox); + // [impl->req~maintable.focus~1] + requestFocus(); + } else { + this.setPlaceholder(null); + } } private BibEntry addExampleEntry() { diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java index cc14cdb7ac1..0ded3319f92 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java @@ -34,6 +34,7 @@ public class MainTableColumnModel { public static final Character COLUMNS_QUALIFIER_DELIMITER = ':'; private static final Logger LOGGER = LoggerFactory.getLogger(MainTableColumnModel.class); + public enum Type { MATCH_CATEGORY("match_category"), // Not localized, because this column is always hidden INDEX("index", Localization.lang("Index")), @@ -47,7 +48,6 @@ public enum Type { SPECIALFIELD("special", Localization.lang("Special")), LIBRARY_NAME("library", Localization.lang("Library")); - public static final EnumSet ICON_COLUMNS = EnumSet.of(EXTRAFILE, FILES, GROUPS, GROUP_ICONS, LINKED_IDENTIFIER); private final String name; @@ -84,9 +84,9 @@ public static Type fromString(String text) { @Override public String toString() { return "Type{" + - "name='" + name + '\'' + - ", displayName='" + displayName + '\'' + - '}'; + "name='" + name + '\'' + + ", displayName='" + displayName + '\'' + + '}'; } } @@ -195,15 +195,15 @@ public ObjectProperty sortTypeProperty() { * Returns a list of sort cirteria based on the fields the current column displays. * In case it is single field, a single SortCriterion is returned. * In case of multiple fields, for each field, there is a SortCriterion contained in the list. - * + *

    * Implementation reason: We want to have SortCriterion handle a single field, because the UI allows for handling * "plain" fields only. */ public List getSortCriteria() { boolean descending = getSortType() == TableColumn.SortType.DESCENDING; return FieldFactory.parseOrFields(getQualifier()).getFields().stream() - .map(field -> new SaveOrder.SortCriterion(field, descending)) - .toList(); + .map(field -> new SaveOrder.SortCriterion(field, descending)) + .toList(); } @Override @@ -232,9 +232,9 @@ public int hashCode() { @Override public String toString() { return "MainTableColumnModel{" + - "qualifierProperty=" + qualifierProperty + - ", typeProperty=" + typeProperty + - '}'; + "qualifierProperty=" + qualifierProperty + + ", typeProperty=" + typeProperty + + '}'; } /** diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java index 643f04c505f..43837eb32e2 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java @@ -190,8 +190,8 @@ private static Optional createGroupMatcher(List selec final MatcherSet searchRules = MatcherSets.build( groupsPreferences.getGroupViewMode().contains(GroupViewMode.INTERSECTION) - ? MatcherSets.MatcherType.AND - : MatcherSets.MatcherType.OR); + ? MatcherSets.MatcherType.AND + : MatcherSets.MatcherType.OR); for (GroupTreeNode node : selectedGroups) { searchRules.addRule(node.getSearchMatcher()); @@ -222,8 +222,8 @@ public Optional getViewModelByIndex(int index) { public Optional getViewModelByCitationKey(String citationKey) { return entriesViewModel.stream() - .filter(viewModel -> citationKey.equals(viewModel.getEntry().getCitationKey().orElse(""))) - .findFirst(); + .filter(viewModel -> citationKey.equals(viewModel.getEntry().getCitationKey().orElse(""))) + .findFirst(); } public void resetFieldFormatter() { diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java index 33841527a34..a2838f709c4 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java @@ -29,7 +29,7 @@ public MainTableFieldValueFormatter(NameDisplayPreferences nameDisplayPreference * unicode if possible. * * @param fields the fields argument of {@link BibEntryTableViewModel#getFields(OrFields)}. - * @param entry the BibEntry of {@link BibEntryTableViewModel}. + * @param entry the BibEntry of {@link BibEntryTableViewModel}. * @return The formatted name field. */ public String formatFieldsValues(final OrFields fields, final BibEntry entry) { @@ -72,14 +72,18 @@ private String formatFieldWithAuthorValue(final String nameToFormat) { } return switch (displayStyle) { - default -> nameToFormat; - case FIRSTNAME_LASTNAME -> authors.latexFree().getAsFirstLastNames( - abbreviationStyle == AbbreviationStyle.FULL, - false); - case LASTNAME_FIRSTNAME -> authors.latexFree().getAsLastFirstNames( - abbreviationStyle == AbbreviationStyle.FULL, - false); - case NATBIB -> authors.latexFree().getAsNatbib(); + default -> + nameToFormat; + case FIRSTNAME_LASTNAME -> + authors.latexFree().getAsFirstLastNames( + abbreviationStyle == AbbreviationStyle.FULL, + false); + case LASTNAME_FIRSTNAME -> + authors.latexFree().getAsLastFirstNames( + abbreviationStyle == AbbreviationStyle.FULL, + false); + case NATBIB -> + authors.latexFree().getAsNatbib(); }; } } diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java index 7cfe366ff12..6fd0cbbd65e 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java @@ -153,7 +153,7 @@ private boolean isACommonColumn(MainTableColumn tableColumn) { * Determines if a list of TableColumns contains the searched column. */ private boolean isColumnInList(MainTableColumn searchColumn, List> tableColumns) { - for (TableColumn column: tableColumns) { + for (TableColumn column : tableColumns) { MainTableColumnModel model = ((MainTableColumn) column).getModel(); if (model.equals(searchColumn.getModel())) { return true; @@ -193,7 +193,7 @@ private boolean isColumnInList(MainTableColumn searchColumn, List> commonTableColumns = new ArrayList<>(); - for (MainTableColumnModel columnModel: commonColumns) { + for (MainTableColumnModel columnModel : commonColumns) { TableColumn tableColumn = factory.createColumn(columnModel); commonTableColumns.add(tableColumn); } diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java b/jabgui/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java index 8d3e362405c..758cfddf1a7 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java @@ -49,28 +49,28 @@ public OpenFolderAction(DialogService dialogService, @Override public void execute() { - stateManager.getActiveDatabase().ifPresent(databaseContext -> { - if (entry == null) { - stateManager.getSelectedEntries().stream().filter(entry -> !entry.getFiles().isEmpty()).forEach(entry -> { - LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( - entry.getFiles().getFirst(), - entry, - databaseContext, - taskExecutor, - dialogService, - preferences); - linkedFileViewModel.openFolder(); - }); - } else { + stateManager.getActiveDatabase().ifPresent(databaseContext -> { + if (entry == null) { + stateManager.getSelectedEntries().stream().filter(entry -> !entry.getFiles().isEmpty()).forEach(entry -> { LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( - linkedFile, + entry.getFiles().getFirst(), entry, databaseContext, taskExecutor, dialogService, preferences); linkedFileViewModel.openFolder(); - } - }); + }); + } else { + LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( + linkedFile, + entry, + databaseContext, + taskExecutor, + dialogService, + preferences); + linkedFileViewModel.openFolder(); + } + }); } } diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/RightClickMenu.java b/jabgui/src/main/java/org/jabref/gui/maintable/RightClickMenu.java index a7a913bf6e3..16d67dcaf49 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/RightClickMenu.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/RightClickMenu.java @@ -162,12 +162,12 @@ private static Menu createCopyToMenu(ActionFactory factory, } public static Menu createCopySubMenu(ActionFactory factory, - DialogService dialogService, - StateManager stateManager, - GuiPreferences preferences, - ClipBoardManager clipBoardManager, - JournalAbbreviationRepository abbreviationRepository, - TaskExecutor taskExecutor) { + DialogService dialogService, + StateManager stateManager, + GuiPreferences preferences, + ClipBoardManager clipBoardManager, + JournalAbbreviationRepository abbreviationRepository, + TaskExecutor taskExecutor) { Menu copySpecialMenu = factory.createMenu(StandardActions.COPY_MORE); copySpecialMenu.getItems().addAll( @@ -203,11 +203,11 @@ public static Menu createCopySubMenu(ActionFactory factory, } static Menu createCopyFieldContentSubMenu(ActionFactory factory, - DialogService dialogService, - StateManager stateManager, - ClipBoardManager clipBoardManager, - GuiPreferences preferences, - JournalAbbreviationRepository abbreviationRepository) { + DialogService dialogService, + StateManager stateManager, + ClipBoardManager clipBoardManager, + GuiPreferences preferences, + JournalAbbreviationRepository abbreviationRepository) { Menu copyFieldContentMenu = factory.createMenu(StandardActions.COPY_FIELD_CONTENT); copyFieldContentMenu.getItems().addAll( diff --git a/jabgui/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java b/jabgui/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java index 22aa68e43f4..15ac22caf79 100644 --- a/jabgui/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java +++ b/jabgui/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java @@ -62,7 +62,7 @@ public LinkedIdentifierColumn(MainTableColumnModel model, .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { // If we only have one identifer, open directly if ((linkedFiles.size() == 1) && (event.getButton() == MouseButton.PRIMARY)) { - new OpenUrlAction(dialogService, stateManager, preferences).execute(); + new OpenUrlAction(dialogService, stateManager, preferences).execute(); } }) .install(this); diff --git a/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java b/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java index 8d7a70f3e9e..94d4cd40eb3 100644 --- a/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java +++ b/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java @@ -5,7 +5,7 @@ import javax.swing.undo.UndoManager; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; @@ -25,7 +25,7 @@ public ChangeEntryTypeAction(EntryType type, List entries, UndoManager @Override public void execute() { - NamedCompound compound = new NamedCompound(Localization.lang("Change entry type")); + NamedCompoundEdit compound = new NamedCompoundEdit(Localization.lang("Change entry type")); entries.forEach(e -> e.setType(type) .ifPresent(change -> compound.addEdit(new UndoableChangeType(change)))); undoManager.addEdit(compound); diff --git a/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java b/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java index 4ad7dbe3cb2..638fd4a2d4a 100644 --- a/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java +++ b/jabgui/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java @@ -65,8 +65,8 @@ private ObservableList getMenuItems(List entries, BibDatabas createSubMenu(Localization.lang("Custom"), entryTypesManager.getAllCustomTypes(BibDatabaseMode.BIBLATEX), entries, undoManager) .ifPresent(subMenu -> items.addAll(new SeparatorMenuItem(), - subMenu - )); + subMenu + )); } else { // Default BibTeX createSubMenu(BibDatabaseMode.BIBTEX.getFormattedName(), BibtexEntryTypeDefinitions.ALL, entries, undoManager) diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeTask.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeTask.java index b4a9cb82977..52b895d0a59 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeTask.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeTask.java @@ -6,7 +6,7 @@ import javax.swing.undo.UndoManager; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.util.UiTaskExecutor; import org.jabref.logic.importer.fetcher.MergingIdBasedFetcher; import org.jabref.logic.l10n.Localization; @@ -24,7 +24,7 @@ public class BatchEntryMergeTask extends BackgroundTask { private static final Logger LOGGER = LoggerFactory.getLogger(BatchEntryMergeTask.class); - private final NamedCompound compoundEdit; + private final NamedCompoundEdit compoundEdit; private final List entries; private final MergingIdBasedFetcher fetcher; private final UndoManager undoManager; @@ -42,7 +42,7 @@ public BatchEntryMergeTask(List entries, this.undoManager = undoManager; this.notificationService = notificationService; - this.compoundEdit = new NamedCompound(Localization.lang("Merge entries")); + this.compoundEdit = new NamedCompoundEdit(Localization.lang("Merge entries")); this.processedEntries = 0; this.successfulUpdates = 0; @@ -53,24 +53,24 @@ public BatchEntryMergeTask(List entries, @Override public Void call() { - if (isCancelled()) { - notifyCancellation(); - return null; - } - - List updatedEntries = processMergeEntries(); + if (isCancelled()) { + notifyCancellation(); + return null; + } - if (isCancelled()) { - notifyCancellation(); - updateUndoManager(updatedEntries); - return null; - } + List updatedEntries = processMergeEntries(); + if (isCancelled()) { + notifyCancellation(); updateUndoManager(updatedEntries); - LOGGER.debug("Merge operation completed. Processed: {}, Successfully updated: {}", - processedEntries, successfulUpdates); - notifySuccess(successfulUpdates); return null; + } + + updateUndoManager(updatedEntries); + LOGGER.debug("Merge operation completed. Processed: {}, Successfully updated: {}", + processedEntries, successfulUpdates); + notifySuccess(successfulUpdates); + return null; } private void notifyCancellation() { @@ -125,8 +125,8 @@ private void updateUndoManager(List updatedEntries) { private void notifySuccess(int updateCount) { String message = updateCount == 0 - ? Localization.lang("No updates found.") - : Localization.lang("Batch update successful. %0 entry(s) updated.", updateCount); + ? Localization.lang("No updates found.") + : Localization.lang("Batch update successful. %0 entry(s) updated.", updateCount); notificationService.notify(message); } } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeWithFetchedDataAction.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeWithFetchedDataAction.java index 5fd2dcbe24f..76862ab543e 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeWithFetchedDataAction.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeWithFetchedDataAction.java @@ -17,7 +17,7 @@ /// Handles batch merging of bibliography entries with fetched data. /// -/// @see BatchEntryMergeTask +/// @see BatchEntryMergeTask /// public class BatchEntryMergeWithFetchedDataAction extends SimpleCommand { diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java index 14896fd7dd5..3f571373f24 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java @@ -13,7 +13,7 @@ import org.jabref.gui.mergeentries.threewaymerge.EntriesMergeResult; import org.jabref.gui.mergeentries.threewaymerge.MergeEntriesDialog; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.importer.EntryBasedFetcher; @@ -113,7 +113,7 @@ private void showMergeDialog(BibEntry originalEntry, BibEntry fetchedEntry, WebF Optional mergedEntry = dialogService.showCustomDialogAndWait(dialog).map(EntriesMergeResult::mergedEntry); if (mergedEntry.isPresent()) { - NamedCompound ce = new NamedCompound(Localization.lang("Merge entry with %0 information", fetcher.getName())); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Merge entry with %0 information", fetcher.getName())); // Updated the original entry with the new fields Set jointFields = new TreeSet<>(Comparator.comparing(Field::getName)); @@ -128,7 +128,7 @@ private void showMergeDialog(BibEntry originalEntry, BibEntry fetchedEntry, WebF if (!oldType.equals(newType)) { originalEntry.setType(newType); - ce.addEdit(new UndoableChangeType(originalEntry, oldType, newType)); + compoundEdit.addEdit(new UndoableChangeType(originalEntry, oldType, newType)); edited = true; } @@ -138,7 +138,7 @@ private void showMergeDialog(BibEntry originalEntry, BibEntry fetchedEntry, WebF Optional mergedString = mergedEntry.get().getField(field); if (originalString.isEmpty() || !originalString.equals(mergedString)) { originalEntry.setField(field, mergedString.get()); // mergedString always present - ce.addEdit(new UndoableFieldChange(originalEntry, field, originalString.orElse(null), + compoundEdit.addEdit(new UndoableFieldChange(originalEntry, field, originalString.orElse(null), mergedString.get())); edited = true; } @@ -149,14 +149,14 @@ private void showMergeDialog(BibEntry originalEntry, BibEntry fetchedEntry, WebF if (!jointFields.contains(field) && !FieldFactory.isInternalField(field)) { Optional originalString = originalEntry.getField(field); originalEntry.clearField(field); - ce.addEdit(new UndoableFieldChange(originalEntry, field, originalString.get(), null)); // originalString always present + compoundEdit.addEdit(new UndoableFieldChange(originalEntry, field, originalString.get(), null)); // originalString always present edited = true; } } if (edited) { - ce.end(); - undoManager.addEdit(ce); + compoundEdit.end(); + undoManager.addEdit(compoundEdit); dialogService.notify(Localization.lang("Updated entry with info from %0", fetcher.getName())); } else { dialogService.notify(Localization.lang("No information added")); diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/MergeEntriesHelper.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/MergeEntriesHelper.java index 717921f0b6d..18fb66d9492 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/MergeEntriesHelper.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/MergeEntriesHelper.java @@ -4,7 +4,7 @@ import java.util.Optional; import java.util.Set; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.model.entry.BibEntry; @@ -31,32 +31,32 @@ private MergeEntriesHelper() { /// /// @param entryFromFetcher The entry containing new information (source, from the fetcher) /// @param entryFromLibrary The entry to be updated (target, from the library) - /// @param namedCompound Compound edit to collect undo information - public static boolean mergeEntries(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompound namedCompound) { + /// @param namedCompoundEdit Compound edit to collect undo information + public static boolean mergeEntries(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompoundEdit namedCompoundEdit) { LOGGER.debug("Entry from fetcher: {}", entryFromFetcher); LOGGER.debug("Entry from library: {}", entryFromLibrary); - boolean typeChanged = mergeEntryType(entryFromFetcher, entryFromLibrary, namedCompound); - boolean fieldsChanged = mergeFields(entryFromFetcher, entryFromLibrary, namedCompound); - boolean fieldsRemoved = removeFieldsNotPresentInFetcher(entryFromFetcher, entryFromLibrary, namedCompound); + boolean typeChanged = mergeEntryType(entryFromFetcher, entryFromLibrary, namedCompoundEdit); + boolean fieldsChanged = mergeFields(entryFromFetcher, entryFromLibrary, namedCompoundEdit); + boolean fieldsRemoved = removeFieldsNotPresentInFetcher(entryFromFetcher, entryFromLibrary, namedCompoundEdit); return typeChanged || fieldsChanged || fieldsRemoved; } - private static boolean mergeEntryType(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompound namedCompound) { + private static boolean mergeEntryType(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompoundEdit namedCompoundEdit) { EntryType fetcherType = entryFromFetcher.getType(); EntryType libraryType = entryFromLibrary.getType(); if (!libraryType.equals(fetcherType)) { LOGGER.debug("Updating type {} -> {}", libraryType, fetcherType); entryFromLibrary.setType(fetcherType); - namedCompound.addEdit(new UndoableChangeType(entryFromLibrary, libraryType, fetcherType)); + namedCompoundEdit.addEdit(new UndoableChangeType(entryFromLibrary, libraryType, fetcherType)); return true; } return false; } - private static boolean mergeFields(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompound namedCompound) { + private static boolean mergeFields(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompoundEdit namedCompoundEdit) { Set allFields = new LinkedHashSet<>(); allFields.addAll(entryFromFetcher.getFields()); allFields.addAll(entryFromLibrary.getFields()); @@ -70,14 +70,14 @@ private static boolean mergeFields(BibEntry entryFromFetcher, BibEntry entryFrom if (fetcherValue.isPresent() && shouldUpdateField(fetcherValue.get(), libraryValue)) { LOGGER.debug("Updating field {}: {} -> {}", field, libraryValue.orElse(null), fetcherValue.get()); entryFromLibrary.setField(field, fetcherValue.get()); - namedCompound.addEdit(new UndoableFieldChange(entryFromLibrary, field, libraryValue.orElse(null), fetcherValue.get())); + namedCompoundEdit.addEdit(new UndoableFieldChange(entryFromLibrary, field, libraryValue.orElse(null), fetcherValue.get())); anyFieldsChanged = true; } } return anyFieldsChanged; } - private static boolean removeFieldsNotPresentInFetcher(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompound namedCompound) { + private static boolean removeFieldsNotPresentInFetcher(BibEntry entryFromFetcher, BibEntry entryFromLibrary, NamedCompoundEdit namedCompoundEdit) { Set obsoleteFields = new LinkedHashSet<>(entryFromLibrary.getFields()); obsoleteFields.removeAll(entryFromFetcher.getFields()); @@ -92,7 +92,7 @@ private static boolean removeFieldsNotPresentInFetcher(BibEntry entryFromFetcher if (value.isPresent()) { LOGGER.debug("Removing obsolete field {} with value {}", field, value.get()); entryFromLibrary.clearField(field); - namedCompound.addEdit(new UndoableFieldChange(entryFromLibrary, field, value.get(), null)); + namedCompoundEdit.addEdit(new UndoableFieldChange(entryFromLibrary, field, value.get(), null)); anyFieldsRemoved = true; } } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/multiwaymerge/DiffHighlightingEllipsingTextFlow.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/multiwaymerge/DiffHighlightingEllipsingTextFlow.java index f01bec88e49..7cc84913088 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/multiwaymerge/DiffHighlightingEllipsingTextFlow.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/multiwaymerge/DiffHighlightingEllipsingTextFlow.java @@ -132,9 +132,12 @@ public void highlightDiff() { text.getStyleClass().add("text-unchanged"); yield List.of(text); } - case WORD -> DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, " "); - case CHARACTER -> DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, ""); - default -> throw new UnsupportedOperationException("Not implemented " + diffMode.getValue()); + case WORD -> + DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, " "); + case CHARACTER -> + DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, ""); + default -> + throw new UnsupportedOperationException("Not implemented " + diffMode.getValue()); }; allChildren.addAll(highlightedText); } else { diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/FieldRowViewModel.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/FieldRowViewModel.java index 8c81fc77b05..94cb7611f39 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/FieldRowViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/FieldRowViewModel.java @@ -105,8 +105,10 @@ public FieldRowViewModel(Field field, BibEntry leftEntry, BibEntry rightEntry, B EasyBind.subscribe(selectionProperty(), selection -> { LOGGER.debug("Selecting {}' value for field {}", selection, field.getDisplayName()); switch (selection) { - case LEFT -> EasyBind.subscribe(leftFieldValueProperty(), this::setMergedFieldValue); - case RIGHT -> EasyBind.subscribe(rightFieldValueProperty(), this::setMergedFieldValue); + case LEFT -> + EasyBind.subscribe(leftFieldValueProperty(), this::setMergedFieldValue); + case RIGHT -> + EasyBind.subscribe(rightFieldValueProperty(), this::setMergedFieldValue); } }); @@ -129,13 +131,13 @@ public void autoSelectBetterValue() { String rightValue = getRightFieldValue(); if (StandardField.YEAR == field) { - YearFieldValuePlausibilityComparator comparator = new YearFieldValuePlausibilityComparator(); - ComparisonResult comparison = comparator.compare(leftValue, rightValue); - if (ComparisonResult.RIGHT_BETTER == comparison) { - selectRightValue(); - } else if (ComparisonResult.LEFT_BETTER == comparison) { - selectLeftValue(); - } + YearFieldValuePlausibilityComparator comparator = new YearFieldValuePlausibilityComparator(); + ComparisonResult comparison = comparator.compare(leftValue, rightValue); + if (ComparisonResult.RIGHT_BETTER == comparison) { + selectRightValue(); + } else if (ComparisonResult.LEFT_BETTER == comparison) { + selectLeftValue(); + } } else if (InternalField.TYPE_HEADER == field) { if (leftValue.equalsIgnoreCase(StandardEntryType.Misc.getName())) { selectRightValue(); diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/GroupDiffMode.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/GroupDiffMode.java index 0f284526c57..c6c577e8d3b 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/GroupDiffMode.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/GroupDiffMode.java @@ -5,7 +5,7 @@ public class GroupDiffMode implements DiffMethod { private final String separator; public GroupDiffMode(String separator) { - this.separator = separator; + this.separator = separator; } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/MergeTwoEntriesAction.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/MergeTwoEntriesAction.java index 4e4993b2d1b..d8d24eb8461 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/MergeTwoEntriesAction.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/MergeTwoEntriesAction.java @@ -7,7 +7,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; @@ -37,11 +37,11 @@ public void execute() { database.insertEntry(entriesMergeResult.mergedEntry()); database.removeEntries(entriesToRemove); - NamedCompound ce = new NamedCompound(Localization.lang("Merge entries")); - ce.addEdit(new UndoableInsertEntries(stateManager.getActiveDatabase().get().getDatabase(), entriesMergeResult.mergedEntry())); - ce.addEdit(new UndoableRemoveEntries(database, entriesToRemove)); - ce.end(); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(Localization.lang("Merge entries")); + compoundEdit.addEdit(new UndoableInsertEntries(stateManager.getActiveDatabase().get().getDatabase(), entriesMergeResult.mergedEntry())); + compoundEdit.addEdit(new UndoableRemoveEntries(database, entriesToRemove)); + compoundEdit.end(); - undoManager.addEdit(ce); + undoManager.addEdit(compoundEdit); } } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeHeaderView.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeHeaderView.java index b4d9a713ea8..5c0a1a3cf05 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeHeaderView.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeHeaderView.java @@ -26,10 +26,10 @@ public ThreeWayMergeHeaderView(String leftHeader, String rightHeader) { this.mergedHeaderCell = new HeaderCell(Localization.lang("Merged entry")); addRow(0, - new HeaderCell(""), - leftHeaderCell, - rightHeaderCell, - mergedHeaderCell + new HeaderCell(""), + leftHeaderCell, + rightHeaderCell, + mergedHeaderCell ); setPrefHeight(Control.USE_COMPUTED_SIZE); diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeView.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeView.java index 0f177bea80d..c089904cb7e 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeView.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/ThreeWayMergeView.java @@ -117,9 +117,9 @@ private void updateDiff() { private void initializeHeaderView() { headerView.getColumnConstraints().addAll(fieldNameColumnConstraints, - leftEntryColumnConstraints, - rightEntryColumnConstraints, - mergedEntryColumnConstraints); + leftEntryColumnConstraints, + rightEntryColumnConstraints, + mergedEntryColumnConstraints); } private void initializeScrollPane() { @@ -216,8 +216,8 @@ private static BibEntry safeClone(BibEntry primary, BibEntry peer) { return new BibEntry(primary); } BibEntry placeholder = peer != null && peer.getType() != null - ? new BibEntry(peer.getType()) - : new BibEntry(); + ? new BibEntry(peer.getType()) + : new BibEntry(); if (peer != null) { peer.getCitationKey().ifPresent(placeholder::withCitationKey); } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/MergedFieldCell.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/MergedFieldCell.java index 050b85e70f4..e50de5d95fe 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/MergedFieldCell.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/MergedFieldCell.java @@ -28,9 +28,9 @@ private void initialize() { private void initializeTextArea() { BindingsHelper.bindBidirectional(textArea.textProperty(), - textProperty(), - textArea::replaceText, - textProperty()::setValue); + textProperty(), + textArea::replaceText, + textProperty()::setValue); setAlignment(Pos.CENTER); textArea.setWrapText(true); diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/OpenExternalLinkAction.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/OpenExternalLinkAction.java index 43e00e1ecca..eeb39e9e192 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/OpenExternalLinkAction.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/cell/OpenExternalLinkAction.java @@ -40,7 +40,7 @@ public void execute() { ); } else { NativeDesktop.openBrowser(urlOrDoi, externalApplicationPreferences - ); + ); } } catch (IOException e) { LOGGER.warn("Cannot open the given external link '{}'", urlOrDoi, e); diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/diffhighlighter/SplitDiffHighlighter.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/diffhighlighter/SplitDiffHighlighter.java index e6285f812cd..f2edf46f0ee 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/diffhighlighter/SplitDiffHighlighter.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/diffhighlighter/SplitDiffHighlighter.java @@ -38,16 +38,16 @@ public void highlight() { List affectedTokensInSource = delta.getSource().getLines(); List affectedTokensInTarget = delta.getTarget().getLines(); int joinedSourceTokensLength = affectedTokensInSource.stream() - .map(String::length) - .reduce(Integer::sum) - .map(value -> value + (getSeparator().length() * (affectedTokensInSource.size() - 1))) - .orElse(0); + .map(String::length) + .reduce(Integer::sum) + .map(value -> value + (getSeparator().length() * (affectedTokensInSource.size() - 1))) + .orElse(0); int joinedTargetTokensLength = affectedTokensInTarget.stream() - .map(String::length) - .reduce(Integer::sum) - .map(value -> value + (getSeparator().length() * (affectedTokensInTarget.size() - 1))) - .orElse(0); + .map(String::length) + .reduce(Integer::sum) + .map(value -> value + (getSeparator().length() * (affectedTokensInTarget.size() - 1))) + .orElse(0); int affectedSourceTokensPositionInText = getPositionInText(affectedSourceTokensPosition, sourceTokens); int affectedTargetTokensPositionInText = getPositionInText(affectedTargetTokensPosition, targetTokens); switch (delta.getType()) { @@ -68,9 +68,9 @@ public int getPositionInText(int positionInTokenList, List tokenList) { return 0; } else { return tokenList.stream().limit(positionInTokenList).map(String::length) - .reduce(Integer::sum) - .map(value -> value + (getSeparator().length() * positionInTokenList)) - .orElse(0); + .reduce(Integer::sum) + .map(value -> value + (getSeparator().length() * positionInTokenList)) + .orElse(0); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FieldMergerFactory.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FieldMergerFactory.java index 9af2f85be0c..44b341f39f1 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FieldMergerFactory.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FieldMergerFactory.java @@ -13,12 +13,18 @@ public FieldMergerFactory(BibEntryPreferences bibEntryPreferences) { public FieldMerger create(Field field) { return switch (field) { - case StandardField.GROUPS -> new GroupMerger(bibEntryPreferences); - case StandardField.KEYWORDS -> new KeywordMerger(bibEntryPreferences); - case StandardField.COMMENT -> new CommentMerger(); - case StandardField.FILE -> new FileMerger(); - case null -> throw new IllegalArgumentException("Field must not be null"); - default -> throw new IllegalArgumentException("No implementation found for merging the given field: " + field.getDisplayName()); + case StandardField.GROUPS -> + new GroupMerger(bibEntryPreferences); + case StandardField.KEYWORDS -> + new KeywordMerger(bibEntryPreferences); + case StandardField.COMMENT -> + new CommentMerger(); + case StandardField.FILE -> + new FileMerger(); + case null -> + throw new IllegalArgumentException("Field must not be null"); + default -> + throw new IllegalArgumentException("No implementation found for merging the given field: " + field.getDisplayName()); }; } diff --git a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/toolbar/ThreeWayMergeToolbar.java b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/toolbar/ThreeWayMergeToolbar.java index 74cc54a255d..f086f0c7dbc 100644 --- a/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/toolbar/ThreeWayMergeToolbar.java +++ b/jabgui/src/main/java/org/jabref/gui/mergeentries/threewaymerge/toolbar/ThreeWayMergeToolbar.java @@ -64,8 +64,8 @@ public class ThreeWayMergeToolbar extends AnchorPane { public ThreeWayMergeToolbar() { ViewLoader.view(this) - .root(this) - .load(); + .root(this) + .load(); } @FXML diff --git a/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryView.java b/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryView.java index a6173daff6a..53e9c00e18d 100644 --- a/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryView.java +++ b/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryView.java @@ -209,12 +209,12 @@ public void initialize() { visualizer.setDecoration(new IconValidationDecorator()); EasyBind.subscribe( - viewModel.executedSuccessfullyProperty(), - succeeded -> { - if (succeeded) { - onSuccessfulExecution(); - } - }); + viewModel.executedSuccessfullyProperty(), + succeeded -> { + if (succeeded) { + onSuccessfulExecution(); + } + }); initializeAddEntry(); initializeLookupIdentifier(); @@ -514,38 +514,70 @@ private static String descriptionOfStandardEntryType(StandardEntryType type) { // Biblatex is a superset of bibtex, with more elaborate descriptions, so its documentation is preferred. // See [https://mirrors.ibiblio.org/pub/mirrors/CTAN/macros/latex/contrib/biblatex/doc/biblatex.pdf]. return switch (type) { - case Article -> Localization.lang("An article in a journal, magazine, newspaper, or other periodical which forms a self-contained unit with its own title."); - case Book -> Localization.lang("A single-volume book with one or more authors where the authors share credit for the work as a whole."); - case Booklet -> Localization.lang("A book-like work without a formal publisher or sponsoring institution."); - case Collection -> Localization.lang("A single-volume collection with multiple, self-contained contributions by distinct authors which have their own title. The work as a whole has no overall author but it will usually have an editor."); - case Conference -> Localization.lang("A legacy alias for \"InProceedings\"."); - case InBook -> Localization.lang("A part of a book which forms a self-contained unit with its own title."); - case InCollection -> Localization.lang("A contribution to a collection which forms a self-contained unit with a distinct author and title."); - case InProceedings -> Localization.lang("An article in a conference proceedings."); - case Manual -> Localization.lang("Technical or other documentation, not necessarily in printed form."); - case MastersThesis -> Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term Master's thesis."); - case Misc -> Localization.lang("A fallback type for entries which do not fit into any other category."); - case PhdThesis -> Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term PhD thesis."); - case Proceedings -> Localization.lang("A single-volume conference proceedings. This type is very similar to \"Collection\"."); - case TechReport -> Localization.lang("Similar to \"Report\" except that the type field is optional and defaults to the localised term technical report."); - case Unpublished -> Localization.lang("A work with an author and a title which has not been formally published, such as a manuscript or the script of a talk."); - case BookInBook -> Localization.lang("This type is similar to \"InBook\" but intended for works originally published as a stand-alone book."); - case InReference -> Localization.lang("An article in a work of reference. This is a more specific variant of the generic \"InCollection\" entry type."); - case MvBook -> Localization.lang("A multi-volume \"Book\"."); - case MvCollection -> Localization.lang("A multi-volume \"Collection\"."); - case MvProceedings -> Localization.lang("A multi-volume \"Proceedings\" entry."); - case MvReference -> Localization.lang("A multi-volume \"Reference\" entry. The standard styles will treat this entry type as an alias for \"MvCollection\"."); - case Online -> Localization.lang("This entry type is intended for sources such as web sites which are intrinsically online resources."); - case Reference -> Localization.lang("A single-volume work of reference such as an encyclopedia or a dictionary."); - case Report -> Localization.lang("A technical report, research report, or white paper published by a university or some other institution."); - case Set -> Localization.lang("An entry set is a group of entries which are cited as a single reference and listed as a single item in the bibliography."); - case SuppBook -> Localization.lang("Supplemental material in a \"Book\". This type is provided for elements such as prefaces, introductions, forewords, afterwords, etc. which often have a generic title only."); - case SuppCollection -> Localization.lang("Supplemental material in a \"Collection\"."); - case SuppPeriodical -> Localization.lang("Supplemental material in a \"Periodical\". This type may be useful when referring to items such as regular columns, obituaries, letters to the editor, etc. which only have a generic title."); - case Thesis -> Localization.lang("A thesis written for an educational institution to satisfy the requirements for a degree."); - case WWW -> Localization.lang("An alias for \"Online\", provided for jurabib compatibility."); - case Software -> Localization.lang("Computer software. The standard styles will treat this entry type as an alias for \"Misc\"."); - case Dataset -> Localization.lang("A data set or a similar collection of (mostly) raw data."); + case Article -> + Localization.lang("An article in a journal, magazine, newspaper, or other periodical which forms a self-contained unit with its own title."); + case Book -> + Localization.lang("A single-volume book with one or more authors where the authors share credit for the work as a whole."); + case Booklet -> + Localization.lang("A book-like work without a formal publisher or sponsoring institution."); + case Collection -> + Localization.lang("A single-volume collection with multiple, self-contained contributions by distinct authors which have their own title. The work as a whole has no overall author but it will usually have an editor."); + case Conference -> + Localization.lang("A legacy alias for \"InProceedings\"."); + case InBook -> + Localization.lang("A part of a book which forms a self-contained unit with its own title."); + case InCollection -> + Localization.lang("A contribution to a collection which forms a self-contained unit with a distinct author and title."); + case InProceedings -> + Localization.lang("An article in a conference proceedings."); + case Manual -> + Localization.lang("Technical or other documentation, not necessarily in printed form."); + case MastersThesis -> + Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term Master's thesis."); + case Misc -> + Localization.lang("A fallback type for entries which do not fit into any other category."); + case PhdThesis -> + Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term PhD thesis."); + case Proceedings -> + Localization.lang("A single-volume conference proceedings. This type is very similar to \"Collection\"."); + case TechReport -> + Localization.lang("Similar to \"Report\" except that the type field is optional and defaults to the localised term technical report."); + case Unpublished -> + Localization.lang("A work with an author and a title which has not been formally published, such as a manuscript or the script of a talk."); + case BookInBook -> + Localization.lang("This type is similar to \"InBook\" but intended for works originally published as a stand-alone book."); + case InReference -> + Localization.lang("An article in a work of reference. This is a more specific variant of the generic \"InCollection\" entry type."); + case MvBook -> + Localization.lang("A multi-volume \"Book\"."); + case MvCollection -> + Localization.lang("A multi-volume \"Collection\"."); + case MvProceedings -> + Localization.lang("A multi-volume \"Proceedings\" entry."); + case MvReference -> + Localization.lang("A multi-volume \"Reference\" entry. The standard styles will treat this entry type as an alias for \"MvCollection\"."); + case Online -> + Localization.lang("This entry type is intended for sources such as web sites which are intrinsically online resources."); + case Reference -> + Localization.lang("A single-volume work of reference such as an encyclopedia or a dictionary."); + case Report -> + Localization.lang("A technical report, research report, or white paper published by a university or some other institution."); + case Set -> + Localization.lang("An entry set is a group of entries which are cited as a single reference and listed as a single item in the bibliography."); + case SuppBook -> + Localization.lang("Supplemental material in a \"Book\". This type is provided for elements such as prefaces, introductions, forewords, afterwords, etc. which often have a generic title only."); + case SuppCollection -> + Localization.lang("Supplemental material in a \"Collection\"."); + case SuppPeriodical -> + Localization.lang("Supplemental material in a \"Periodical\". This type may be useful when referring to items such as regular columns, obituaries, letters to the editor, etc. which only have a generic title."); + case Thesis -> + Localization.lang("A thesis written for an educational institution to satisfy the requirements for a degree."); + case WWW -> + Localization.lang("An alias for \"Online\", provided for jurabib compatibility."); + case Software -> + Localization.lang("Computer software. The standard styles will treat this entry type as an alias for \"Misc\"."); + case Dataset -> + Localization.lang("A data set or a similar collection of (mostly) raw data."); }; } @@ -595,9 +627,9 @@ private Optional fetcherForIdentifier(Identifier id) { for (IdBasedFetcher fetcher : idFetcher.getItems()) { if ((id instanceof DOI && fetcher instanceof DoiFetcher) || (id instanceof ISBN && (fetcher instanceof IsbnFetcher) || - (id instanceof ArXivIdentifier && fetcher instanceof ArXivFetcher) || - (id instanceof RFC && fetcher instanceof RfcFetcher) || - (id instanceof SSRN && fetcher instanceof DoiFetcher))) { + (id instanceof ArXivIdentifier && fetcher instanceof ArXivFetcher) || + (id instanceof RFC && fetcher instanceof RfcFetcher) || + (id instanceof SSRN && fetcher instanceof DoiFetcher))) { return Optional.of(fetcher); } } 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 b3cb2d42ad2..8675547e7b8 100644 --- a/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/newentry/NewEntryViewModel.java @@ -357,9 +357,12 @@ protected Optional> call() throws FetcherException { } final PlainCitationParser parser = switch (parserChoice) { - case PlainCitationParserChoice.RULE_BASED -> new RuleBasedPlainCitationParser(); - case PlainCitationParserChoice.GROBID -> new GrobidPlainCitationParser(preferences.getGrobidPreferences(), preferences.getImportFormatPreferences()); - case PlainCitationParserChoice.LLM -> new LlmPlainCitationParser(aiService.getTemplatesService(), preferences.getImportFormatPreferences(), aiService.getChatLanguageModel()); + case PlainCitationParserChoice.RULE_BASED -> + new RuleBasedPlainCitationParser(); + case PlainCitationParserChoice.GROBID -> + new GrobidPlainCitationParser(preferences.getGrobidPreferences(), preferences.getImportFormatPreferences()); + case PlainCitationParserChoice.LLM -> + new LlmPlainCitationParser(aiService.getTemplatesService(), preferences.getImportFormatPreferences(), aiService.getChatLanguageModel()); }; final SeveralPlainCitationParser setParser = new SeveralPlainCitationParser(parser); 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 89cc4672f70..cccaf6243c7 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/Bootstrap.java @@ -52,26 +52,27 @@ import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; -/** Bootstrap offers functionality to obtain a context or simply - * a service manager. - * The service manager can create a few basic services, whose implementations are: - *

      - *
    • com.sun.star.comp.loader.JavaLoader
    • - *
    • com.sun.star.comp.urlresolver.UrlResolver
    • - *
    • com.sun.star.comp.bridgefactory.BridgeFactory
    • - *
    • com.sun.star.comp.connections.Connector
    • - *
    • com.sun.star.comp.connections.Acceptor
    • - *
    • com.sun.star.comp.servicemanager.ServiceManager
    • - *
    - * - * Other services can be inserted into the service manager by - * using its XSet interface: - *
    -  *     XSet xSet = UnoRuntime.queryInterface( XSet.class, aMultiComponentFactory );
    -  *     // insert the service manager
    -  *     xSet.insert( aSingleComponentFactory );
    -  * 
    -*/ +/** + * Bootstrap offers functionality to obtain a context or simply + * a service manager. + * The service manager can create a few basic services, whose implementations are: + *
      + *
    • com.sun.star.comp.loader.JavaLoader
    • + *
    • com.sun.star.comp.urlresolver.UrlResolver
    • + *
    • com.sun.star.comp.bridgefactory.BridgeFactory
    • + *
    • com.sun.star.comp.connections.Connector
    • + *
    • com.sun.star.comp.connections.Acceptor
    • + *
    • com.sun.star.comp.servicemanager.ServiceManager
    • + *
    + *

    + * Other services can be inserted into the service manager by + * using its XSet interface: + *

    + *     XSet xSet = UnoRuntime.queryInterface( XSet.class, aMultiComponentFactory );
    + *     // insert the service manager
    + *     xSet.insert( aSingleComponentFactory );
    + * 
    + */ public class Bootstrap { private static final Random RANDOM_PIPE_NAME = new Random(); diff --git a/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 483eb775220..7a4e45d18cc 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -365,15 +365,18 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, if (internalName.isEmpty()) { String msg = switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> Localization.lang("The %0 paragraph style '%1' is missing from the document", - labelInJstyleFile, - styleName); - case UnoStyle.CHARACTER_STYLES -> Localization.lang("The %0 character style '%1' is missing from the document", - labelInJstyleFile, - styleName); - default -> throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is missing from the document", + labelInJstyleFile, + styleName); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is missing from the document", + labelInJstyleFile, + styleName); + default -> + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please create it in the document or change in the file:") @@ -385,17 +388,20 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, if (!internalName.get().equals(styleName)) { String msg = switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - case UnoStyle.CHARACTER_STYLES -> Localization.lang("The %0 character style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - default -> throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + default -> + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please use the latter in the style file below" @@ -525,14 +531,14 @@ public void guiActionApplyCitationEntries(List citationEntries) { *

    * Note: Undo does not remove or reestablish custom properties. * - * @param entries The entries to cite. - * @param bibDatabaseContext The database the entries belong to (all of them). Used when creating the citation mark. - *

    - * Consistency: for each entry in {@code entries}: looking it up in {@code syncOptions.get().databases} (if present) should yield {@code database}. - * @param style The bibliography style we are using. - * @param citationType Indicates whether it is an in-text citation, a citation in parenthesis or an invisible citation. - * @param pageInfo A single page-info for these entries. Attributed to the last entry. - * @param syncOptions Indicates whether in-text citations should be refreshed in the document. Optional.empty() indicates no refresh. Otherwise provides options for refreshing the reference list. + * @param entries The entries to cite. + * @param bibDatabaseContext The database the entries belong to (all of them). Used when creating the citation mark. + *

    + * Consistency: for each entry in {@code entries}: looking it up in {@code syncOptions.get().databases} (if present) should yield {@code database}. + * @param style The bibliography style we are using. + * @param citationType Indicates whether it is an in-text citation, a citation in parenthesis or an invisible citation. + * @param pageInfo A single page-info for these entries. Attributed to the last entry. + * @param syncOptions Indicates whether in-text citations should be refreshed in the document. Optional.empty() indicates no refresh. Otherwise provides options for refreshing the reference list. */ public void guiActionInsertEntry(List entries, BibDatabaseContext bibDatabaseContext, diff --git a/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 333c9ed3d49..79ce4e8267b 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -86,8 +86,8 @@ public static void closeOfficeConnection() { try { // get the bridge factory from the local service manager XBridgeFactory bridgeFactory = queryInterface(XBridgeFactory.class, - Bootstrap.createSimpleServiceManager() - .createInstance("com.sun.star.bridge.BridgeFactory")); + Bootstrap.createSimpleServiceManager() + .createInstance("com.sun.star.bridge.BridgeFactory")); if (bridgeFactory != null) { for (XBridge bridge : bridgeFactory.getExistingBridges()) { @@ -148,8 +148,8 @@ public String toString() { } List viewModel = list.stream() - .map(DocumentTitleViewModel::new) - .collect(Collectors.toList()); + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX diff --git a/jabgui/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/jabgui/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 5ee9823a118..de8bc8b8b0f 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -38,7 +38,7 @@ import org.jabref.gui.help.HelpAction; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableKeyChange; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.UiTaskExecutor; @@ -517,8 +517,8 @@ private static CitationType citationTypeFromOptions(boolean withText, boolean in return CitationType.INVISIBLE_CIT; } return inParenthesis - ? CitationType.AUTHORYEAR_PAR - : CitationType.AUTHORYEAR_INTEXT; + ? CitationType.AUTHORYEAR_PAR + : CitationType.AUTHORYEAR_INTEXT; } private void pushEntries(CitationType citationType, boolean addPageInfo) { @@ -572,8 +572,8 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) { Optional syncOptions = openOfficePreferences.getSyncWhenCiting() - ? Optional.of(new Update.SyncOptions(getBaseList())) - : Optional.empty(); + ? Optional.of(new Update.SyncOptions(getBaseList())) + : Optional.empty(); // Sync options are non-null only when "Automatically sync bibliography when inserting citations" is enabled if (syncOptions.isPresent() && openOfficePreferences.getSyncWhenCiting()) { @@ -619,7 +619,7 @@ private boolean checkThatEntriesHaveKeys(List entries) { Optional databaseContext = stateManager.getActiveDatabase(); if (citePressed && databaseContext.isPresent()) { // Generate keys - NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite")); + NamedCompoundEdit undoCompound = new NamedCompoundEdit(Localization.lang("Cite")); for (BibEntry entry : entries) { if (entry.getCitationKey().isEmpty()) { // Generate key @@ -662,7 +662,8 @@ private ContextMenu createSettingsPopup() { } case CitationStyle _ -> contextMenu.getItems().remove(alwaysAddCitedOnPagesText); - default -> { } + default -> { + } } }); diff --git a/jabgui/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 2858430a06f..50372f5eb7f 100644 --- a/jabgui/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -149,10 +149,10 @@ public OOStyle getSelectedStyle() { public void storeStylePreferences() { // save external jstyles List externalJStyles = jStyles.stream() - .map(this::toJStyle) - .filter(style -> !style.isInternalStyle()) - .map(JStyle::getPath) - .toList(); + .map(this::toJStyle) + .filter(style -> !style.isInternalStyle()) + .map(JStyle::getPath) + .toList(); openOfficePreferences.setExternalJStyles(externalJStyles); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/JabRefGuiPreferences.java b/jabgui/src/main/java/org/jabref/gui/preferences/JabRefGuiPreferences.java index e91f4d6bd62..91ba662a4e8 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/JabRefGuiPreferences.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/JabRefGuiPreferences.java @@ -403,8 +403,8 @@ private JabRefGuiPreferences() { /** * @deprecated Never ever add a call to this method. There should be only one caller. - * All other usages should get the preferences passed (or injected). - * The JabRef team leaves the {@code @deprecated} annotation to have IntelliJ listing this method with a strike-through. + * All other usages should get the preferences passed (or injected). + * The JabRef team leaves the {@code @deprecated} annotation to have IntelliJ listing this method with a strike-through. */ @Deprecated public static JabRefGuiPreferences getInstance() { @@ -1169,8 +1169,8 @@ public NewEntryPreferences getNewEntryPreferences() { final int approachIndex = getInt(CREATE_ENTRY_APPROACH); NewEntryDialogTab approach = NewEntryDialogTab.values().length > approachIndex - ? NewEntryDialogTab.values()[approachIndex] - : NewEntryDialogTab.values()[0]; + ? NewEntryDialogTab.values()[approachIndex] + : NewEntryDialogTab.values()[0]; final String immediateTypeName = get(CREATE_ENTRY_IMMEDIATE_TYPE); EntryType immediateType = StandardEntryType.Article; @@ -1182,14 +1182,14 @@ public NewEntryPreferences getNewEntryPreferences() { } newEntryPreferences = new NewEntryPreferences( - approach, - getBoolean(CREATE_ENTRY_EXPAND_RECOMMENDED), - getBoolean(CREATE_ENTRY_EXPAND_OTHER), - getBoolean(CREATE_ENTRY_EXPAND_CUSTOM), - immediateType, - getBoolean(CREATE_ENTRY_ID_LOOKUP_GUESSING), - get(CREATE_ENTRY_ID_FETCHER_NAME), - get(CREATE_ENTRY_INTERPRET_PARSER_NAME)); + approach, + getBoolean(CREATE_ENTRY_EXPAND_RECOMMENDED), + getBoolean(CREATE_ENTRY_EXPAND_OTHER), + getBoolean(CREATE_ENTRY_EXPAND_CUSTOM), + immediateType, + getBoolean(CREATE_ENTRY_ID_LOOKUP_GUESSING), + get(CREATE_ENTRY_ID_FETCHER_NAME), + get(CREATE_ENTRY_INTERPRET_PARSER_NAME)); EasyBind.listen(newEntryPreferences.latestApproachProperty(), (_, _, newValue) -> putInt(CREATE_ENTRY_APPROACH, List.of(NewEntryDialogTab.values()).indexOf(newValue))); EasyBind.listen(newEntryPreferences.typesRecommendedExpandedProperty(), (_, _, newValue) -> putBoolean(CREATE_ENTRY_EXPAND_RECOMMENDED, newValue)); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/PreferenceTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/PreferenceTabViewModel.java index 393db8e1c03..48fb0c634bf 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/PreferenceTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/PreferenceTabViewModel.java @@ -7,7 +7,7 @@ public interface PreferenceTabViewModel { /** * This method is called when the dialog is opened, or if it is made * visible after being hidden. The tab should update all its values. - * + *

    * This is the ONLY PLACE to set values for the fields in the tab. It * is ILLEGAL to set values only at construction time, because the dialog * will be reused and updated. diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java b/jabgui/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java index 689b303f883..06f5ffcc469 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java @@ -56,8 +56,8 @@ public void filterTabs(String query) { String searchQuery = query.toLowerCase(Locale.ROOT); List matchedTabs = preferenceTabs.stream() - .filter(tab -> tabMatchesQuery(tab, searchQuery)) - .collect(Collectors.toList()); + .filter(tab -> tabMatchesQuery(tab, searchQuery)) + .collect(Collectors.toList()); filteredPreferenceTabs.setAll(matchedTabs); } @@ -65,7 +65,7 @@ public void filterTabs(String query) { /** * Checks if a tab matches the given search query either by its name or by its controls. * - * @param tab The preferences tab to check. + * @param tab The preferences tab to check. * @param query The search query. * @return True if the tab matches the query. */ @@ -73,10 +73,10 @@ private boolean tabMatchesQuery(PreferencesTab tab, String query) { boolean tabNameMatches = tab.getTabName().toLowerCase(Locale.ROOT).contains(query); boolean controlMatches = preferenceTabsControls.get(tab).stream() - .filter(control -> controlMatchesQuery(control, query)) - .peek(this::highlightControl) - .findAny() - .isPresent(); + .filter(control -> controlMatchesQuery(control, query)) + .peek(this::highlightControl) + .findAny() + .isPresent(); return tabNameMatches || controlMatches; } @@ -102,8 +102,8 @@ private boolean controlMatchesQuery(Control control, String query) { if (control instanceof ComboBox comboBox && !comboBox.getItems().isEmpty()) { return comboBox.getItems().stream() - .map(Object::toString) - .anyMatch(item -> item.toLowerCase(Locale.ROOT).contains(query)); + .map(Object::toString) + .anyMatch(item -> item.toLowerCase(Locale.ROOT).contains(query)); } if (control instanceof TextField textField && textField.getText() != null) { @@ -160,9 +160,9 @@ private ArrayListMultimap getPreferenceTabsControlsMap( /** * Recursively scans nodes and collects all controls. * - * @param node The current node being scanned. + * @param node The current node being scanned. * @param controlMap Map storing tabs and their corresponding controls. - * @param tab The PreferencesTab associated with the current node. + * @param tab The PreferencesTab associated with the current node. */ private void scanControls(Node node, ArrayListMultimap controlMap, PreferencesTab tab) { if (node instanceof Control control) { diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTabViewModel.java index 87e62180be7..68861d4383b 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/ai/AiTabViewModel.java @@ -132,7 +132,7 @@ public AiTabViewModel(CliPreferences preferences) { }); this.customizeExpertSettings.addListener((_, _, newValue) -> - disableExpertSettings.set(!newValue || !enableAi.get()) + disableExpertSettings.set(!newValue || !enableAi.get()) ); this.selectedAiProvider.addListener((_, oldValue, newValue) -> { @@ -168,7 +168,7 @@ public AiTabViewModel(CliPreferences preferences) { huggingFaceApiKey.set(currentApiKey.get()); huggingFaceApiBaseUrl.set(currentApiBaseUrl.get()); } - case GPT4ALL-> { + case GPT4ALL -> { gpt4AllChatModel.set(oldChatModel); gpt4AllApiKey.set(currentApiKey.get()); gpt4AllApiBaseUrl.set(currentApiBaseUrl.get()); @@ -211,11 +211,16 @@ public AiTabViewModel(CliPreferences preferences) { } switch (selectedAiProvider.get()) { - case OPEN_AI -> openAiChatModel.set(newValue); - case MISTRAL_AI -> mistralAiChatModel.set(newValue); - case GEMINI -> geminiChatModel.set(newValue); - case HUGGING_FACE -> huggingFaceChatModel.set(newValue); - case GPT4ALL -> gpt4AllChatModel.set(newValue); + case OPEN_AI -> + openAiChatModel.set(newValue); + case MISTRAL_AI -> + mistralAiChatModel.set(newValue); + case GEMINI -> + geminiChatModel.set(newValue); + case HUGGING_FACE -> + huggingFaceChatModel.set(newValue); + case GPT4ALL -> + gpt4AllChatModel.set(newValue); } contextWindowSize.set(AiDefaultPreferences.getContextWindowSize(selectedAiProvider.get(), newValue)); @@ -223,21 +228,31 @@ public AiTabViewModel(CliPreferences preferences) { this.currentApiKey.addListener((_, _, newValue) -> { switch (selectedAiProvider.get()) { - case OPEN_AI -> openAiApiKey.set(newValue); - case MISTRAL_AI -> mistralAiApiKey.set(newValue); - case GEMINI -> geminiAiApiKey.set(newValue); - case HUGGING_FACE -> huggingFaceApiKey.set(newValue); - case GPT4ALL -> gpt4AllApiKey.set(newValue); + case OPEN_AI -> + openAiApiKey.set(newValue); + case MISTRAL_AI -> + mistralAiApiKey.set(newValue); + case GEMINI -> + geminiAiApiKey.set(newValue); + case HUGGING_FACE -> + huggingFaceApiKey.set(newValue); + case GPT4ALL -> + gpt4AllApiKey.set(newValue); } }); this.currentApiBaseUrl.addListener((_, _, newValue) -> { switch (selectedAiProvider.get()) { - case OPEN_AI -> openAiApiBaseUrl.set(newValue); - case MISTRAL_AI -> mistralAiApiBaseUrl.set(newValue); - case GEMINI -> geminiApiBaseUrl.set(newValue); - case HUGGING_FACE -> huggingFaceApiBaseUrl.set(newValue); - case GPT4ALL -> gpt4AllApiBaseUrl.set(newValue); + case OPEN_AI -> + openAiApiBaseUrl.set(newValue); + case MISTRAL_AI -> + mistralAiApiBaseUrl.set(newValue); + case GEMINI -> + geminiApiBaseUrl.set(newValue); + case HUGGING_FACE -> + huggingFaceApiBaseUrl.set(newValue); + case GPT4ALL -> + gpt4AllApiBaseUrl.set(newValue); } }); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java index 125b1a7b830..d2ac844aeec 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java @@ -50,9 +50,12 @@ public void setValues() { } switch (autoCompletePreferences.getFirstNameMode()) { - case ONLY_ABBREVIATED -> firstNameModeAbbreviatedProperty.setValue(true); - case ONLY_FULL -> firstNameModeFullProperty.setValue(true); - default -> firstNameModeBothProperty.setValue(true); + case ONLY_ABBREVIATED -> + firstNameModeAbbreviatedProperty.setValue(true); + case ONLY_FULL -> + firstNameModeFullProperty.setValue(true); + default -> + firstNameModeBothProperty.setValue(true); } } diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java index eab2fc87d62..9554ab2fcdb 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java @@ -44,7 +44,7 @@ public class CustomEntryTypesTabViewModel implements PreferenceTabViewModel { private final ObjectProperty selectedEntryType = new SimpleObjectProperty<>(); private final StringProperty entryTypeToAdd = new SimpleStringProperty(""); private final ObjectProperty newFieldToAdd = new SimpleObjectProperty<>(); - private final ObservableList entryTypesWithFields = FXCollections.observableArrayList(extractor -> new Observable[]{extractor.entryType(), extractor.fields()}); + private final ObservableList entryTypesWithFields = FXCollections.observableArrayList(extractor -> new Observable[] {extractor.entryType(), extractor.fields()}); private final List entryTypesToDelete = new ArrayList<>(); private final CliPreferences preferences; diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java index 56525a2877b..1f1f432897b 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java @@ -23,11 +23,11 @@ public class EntryTypeViewModel { public EntryTypeViewModel(BibEntryType entryType, Predicate isMultiline) { this.entryType.set(entryType); List allFieldsForType = entryType.getAllBibFields() - .stream().map(bibField -> new FieldViewModel(bibField.field(), - entryType.isRequired(bibField.field()) ? Mandatory.REQUIRED : Mandatory.OPTIONAL, - bibField.priority(), - isMultiline.test(bibField.field()))) - .collect(Collectors.toList()); + .stream().map(bibField -> new FieldViewModel(bibField.field(), + entryType.isRequired(bibField.field()) ? Mandatory.REQUIRED : Mandatory.OPTIONAL, + bibField.priority(), + isMultiline.test(bibField.field()))) + .collect(Collectors.toList()); fields = FXCollections.observableArrayList(allFieldsForType); } diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java index fc992cd9ed0..99d389afd5d 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java @@ -105,8 +105,8 @@ public void storeSettings() { entryEditorPreferences.setEnableValidation(enableValidationProperty.getValue()); entryEditorPreferences.setAllowIntegerEditionBibtex(allowIntegerEditionProperty.getValue()); entryEditorPreferences.setEnableJournalPopup(journalPopupProperty.getValue() - ? EntryEditorPreferences.JournalPopupEnabled.ENABLED - : EntryEditorPreferences.JournalPopupEnabled.DISABLED); + ? EntryEditorPreferences.JournalPopupEnabled.ENABLED + : EntryEditorPreferences.JournalPopupEnabled.DISABLED); // entryEditorPreferences.setDividerPosition(); entryEditorPreferences.setAutoLinkFilesEnabled(autoLinkEnabledProperty.getValue()); entryEditorPreferences.setShouldShowSciteTab(enableSciteTabProperty.getValue()); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java index 00717280eaf..3760dd37b8c 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java @@ -36,9 +36,12 @@ public ExportTabViewModel(ExportPreferences exportPreferences) { public void setValues() { SaveOrder exportSaveOrder = exportPreferences.getExportSaveOrder(); switch (exportSaveOrder.getOrderType()) { - case SPECIFIED -> exportInSpecifiedOrderProperty.setValue(true); - case ORIGINAL -> exportInOriginalProperty.setValue(true); - case TABLE -> exportInTableOrderProperty.setValue(true); + case SPECIFIED -> + exportInSpecifiedOrderProperty.setValue(true); + case ORIGINAL -> + exportInOriginalProperty.setValue(true); + case TABLE -> + exportInTableOrderProperty.setValue(true); } sortCriteriaProperty.addAll(exportSaveOrder.getSortCriteria().stream() .map(SortCriterionViewModel::new) diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java index cc00d452bdd..6a816f5ecb6 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java @@ -166,9 +166,9 @@ public void pushToApplicationSettings() { dialogPane.setContent(settings.getSettingsPane()); dialogService.showCustomDialogAndWait( - Localization.lang("Application settings"), - dialogPane, - ButtonType.OK, ButtonType.CANCEL) + Localization.lang("Application settings"), + dialogPane, + ButtonType.OK, ButtonType.CANCEL) .ifPresent(btn -> { if (btn == ButtonType.OK) { settings.storeSettings(); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java index 04b34be5b60..aa2f63470b5 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java @@ -408,7 +408,7 @@ public StringProperty customPathToThemeProperty() { public void importCSSFile() { String fileDir = customPathToThemeProperty.getValue().isEmpty() ? preferences.getInternalPreferences().getLastPreferencesExportPath().toString() - : customPathToThemeProperty.getValue(); + : customPathToThemeProperty.getValue(); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(StandardFileType.CSS) diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java index ad451dba57e..6d5093516c5 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java @@ -83,7 +83,7 @@ public void filterValues(String term) { * Searches for the term in the keybinding's localization, category, or key combination * * @param keyBinding keybinding to search in - * @param searchTerm term to search for + * @param searchTerm term to search for * @return true if the term is found in the keybinding */ private boolean matchesSearchTerm(KeyBinding keyBinding, String searchTerm) { diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java index 313274508f6..f1c81db708f 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java @@ -93,9 +93,12 @@ public void setValues() { // Autolink preferences switch (autoLinkPreferences.getCitationKeyDependency()) { - case START -> autolinkFileStartsBibtexProperty.setValue(true); - case EXACT -> autolinkFileExactBibtexProperty.setValue(true); - case REGEX -> autolinkUseRegexProperty.setValue(true); + case START -> + autolinkFileStartsBibtexProperty.setValue(true); + case EXACT -> + autolinkFileExactBibtexProperty.setValue(true); + case REGEX -> + autolinkUseRegexProperty.setValue(true); } autolinkRegexKeyProperty.setValue(autoLinkPreferences.getRegularExpression()); diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java index 3db20e5be94..11f07fe6c70 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java @@ -59,7 +59,6 @@ public class NetworkTabViewModel implements PreferenceTabViewModel { private final DialogService dialogService; private final CliPreferences preferences; - private final ProxyPreferences proxyPreferences; private final ProxyPreferences backupProxyPreferences; private final InternalPreferences internalPreferences; diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java b/jabgui/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java index 733dcec512f..a30e7437077 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java @@ -121,18 +121,26 @@ public ContextAction(StandardActions command, ProtectedTermsListItemModel itemMo this.executable.bind(BindingsHelper.constantOf( switch (command) { - case EDIT_LIST, REMOVE_LIST, RELOAD_LIST -> !itemModel.getTermsList().isInternalList(); - default -> true; + case EDIT_LIST, + REMOVE_LIST, + RELOAD_LIST -> + !itemModel.getTermsList().isInternalList(); + default -> + true; })); } @Override public void execute() { switch (command) { - case EDIT_LIST -> viewModel.edit(itemModel); - case VIEW_LIST -> viewModel.displayContent(itemModel); - case REMOVE_LIST -> viewModel.removeList(itemModel); - case RELOAD_LIST -> viewModel.reloadList(itemModel); + case EDIT_LIST -> + viewModel.edit(itemModel); + case VIEW_LIST -> + viewModel.displayContent(itemModel); + case REMOVE_LIST -> + viewModel.removeList(itemModel); + case RELOAD_LIST -> + viewModel.reloadList(itemModel); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java index 12ae933265e..4625ad54f8e 100644 --- a/jabgui/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java @@ -149,16 +149,23 @@ public void setValues() { } switch (nameDisplayPreferences.getDisplayStyle()) { - case NATBIB -> namesNatbibProperty.setValue(true); - case AS_IS -> nameAsIsProperty.setValue(true); - case FIRSTNAME_LASTNAME -> nameFirstLastProperty.setValue(true); - case LASTNAME_FIRSTNAME -> nameLastFirstProperty.setValue(true); + case NATBIB -> + namesNatbibProperty.setValue(true); + case AS_IS -> + nameAsIsProperty.setValue(true); + case FIRSTNAME_LASTNAME -> + nameFirstLastProperty.setValue(true); + case LASTNAME_FIRSTNAME -> + nameLastFirstProperty.setValue(true); } switch (nameDisplayPreferences.getAbbreviationStyle()) { - case FULL -> abbreviationEnabledProperty.setValue(true); - case LASTNAME_ONLY -> abbreviationLastNameOnlyProperty.setValue(true); - case NONE -> abbreviationDisabledProperty.setValue(true); + case FULL -> + abbreviationEnabledProperty.setValue(true); + case LASTNAME_ONLY -> + abbreviationLastNameOnlyProperty.setValue(true); + case NONE -> + abbreviationDisabledProperty.setValue(true); } } diff --git a/jabgui/src/main/java/org/jabref/gui/preview/ClipboardContentGenerator.java b/jabgui/src/main/java/org/jabref/gui/preview/ClipboardContentGenerator.java index b3c2ddb774b..930b7f07e97 100644 --- a/jabgui/src/main/java/org/jabref/gui/preview/ClipboardContentGenerator.java +++ b/jabgui/src/main/java/org/jabref/gui/preview/ClipboardContentGenerator.java @@ -35,9 +35,12 @@ public ClipboardContent generate(List selectedEntries, CitationStyleOu if (previewPreferences.getSelectedPreviewLayout() instanceof CitationStylePreviewLayout) { // if it's generated by a citation style take care of each output format return switch (outputFormat) { - case HTML -> processHtml(citations); - case TEXT -> processText(citations); - case MARKDOWN -> processMarkdown(citations); + case HTML -> + processHtml(citations); + case TEXT -> + processText(citations); + case MARKDOWN -> + processMarkdown(citations); }; } else { // if it is not a citation style take care of the preview diff --git a/jabgui/src/main/java/org/jabref/gui/preview/PreviewViewer.java b/jabgui/src/main/java/org/jabref/gui/preview/PreviewViewer.java index 06f7060019c..ae05d601ac8 100644 --- a/jabgui/src/main/java/org/jabref/gui/preview/PreviewViewer.java +++ b/jabgui/src/main/java/org/jabref/gui/preview/PreviewViewer.java @@ -55,26 +55,26 @@ public class PreviewViewer extends ScrollPane implements InvalidationListener { // https://stackoverflow.com/questions/5669448/get-selected-texts-html-in-div/5670825#5670825 private static final String JS_GET_SELECTION_HTML_SCRIPT = """ - function getSelectionHtml() { - var html = ""; - if (typeof window.getSelection != "undefined") { - var sel = window.getSelection(); - if (sel.rangeCount) { - var container = document.createElement("div"); - for (var i = 0, len = sel.rangeCount; i < len; ++i) { - container.appendChild(sel.getRangeAt(i).cloneContents()); + function getSelectionHtml() { + var html = ""; + if (typeof window.getSelection != "undefined") { + var sel = window.getSelection(); + if (sel.rangeCount) { + var container = document.createElement("div"); + for (var i = 0, len = sel.rangeCount; i < len; ++i) { + container.appendChild(sel.getRangeAt(i).cloneContents()); + } + html = container.innerHTML; + } + } else if (typeof document.selection != "undefined") { + if (document.selection.type == "Text") { + html = document.selection.createRange().htmlText; } - html = container.innerHTML; - } - } else if (typeof document.selection != "undefined") { - if (document.selection.type == "Text") { - html = document.selection.createRange().htmlText; } + return html; } - return html; - } - getSelectionHtml(); - """; + getSelectionHtml(); + """; private final ClipBoardManager clipBoardManager; private final DialogService dialogService; diff --git a/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplication.java b/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplication.java index d776f344f57..8a658f9ff43 100644 --- a/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplication.java +++ b/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplication.java @@ -29,6 +29,6 @@ default Action getAction() { } default GuiPushToApplicationSettings getSettings(PushToApplication application, DialogService dialogService, FilePreferences filePreferences, PushToApplicationPreferences pushToApplicationPreferences) { - return new GuiPushToApplicationSettings(application, dialogService, filePreferences, pushToApplicationPreferences); + return new GuiPushToApplicationSettings(application, dialogService, filePreferences, pushToApplicationPreferences); } } diff --git a/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplicationCommand.java b/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplicationCommand.java index 5523e11cc16..b4ccfd84e0f 100644 --- a/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplicationCommand.java +++ b/jabgui/src/main/java/org/jabref/gui/push/GuiPushToApplicationCommand.java @@ -72,9 +72,9 @@ public void registerReconfigurable(Object node) { private void setApplication(String applicationName) { final ActionFactory factory = new ActionFactory(); GuiPushToApplication application = GuiPushToApplications.getGUIApplicationByName( - applicationName, - dialogService, - preferences.getPushToApplicationPreferences()) + applicationName, + dialogService, + preferences.getPushToApplicationPreferences()) .orElseGet(() -> new GuiPushToEmacs(dialogService, preferences.getPushToApplicationPreferences())); preferences.getPushToApplicationPreferences().setActiveApplicationName(application.getDisplayName()); diff --git a/jabgui/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java b/jabgui/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java index f279233aec7..e58aeca7c9a 100644 --- a/jabgui/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java @@ -110,8 +110,8 @@ private void initialize() { keepOnTopSubscription = EasyBind.subscribe(viewModel.keepOnTop(), value -> { stage.setAlwaysOnTop(value); keepOnTop.setGraphic(value - ? IconTheme.JabRefIcons.KEEP_ON_TOP.getGraphicNode() - : IconTheme.JabRefIcons.KEEP_ON_TOP_OFF.getGraphicNode()); + ? IconTheme.JabRefIcons.KEEP_ON_TOP.getGraphicNode() + : IconTheme.JabRefIcons.KEEP_ON_TOP_OFF.getGraphicNode()); }); stage.setOnShown(event -> { diff --git a/jabgui/src/main/java/org/jabref/gui/search/SearchTextField.java b/jabgui/src/main/java/org/jabref/gui/search/SearchTextField.java index 4cb2b060ba6..9dfe3fbc013 100644 --- a/jabgui/src/main/java/org/jabref/gui/search/SearchTextField.java +++ b/jabgui/src/main/java/org/jabref/gui/search/SearchTextField.java @@ -29,8 +29,8 @@ public static CustomTextField create(KeyBindingRepository keyBindingRepository) // Otherwise, we would have to add a new class for this and handle the case hitting that class in TextInputKeyBindings if (keyBindingRepository.matches(event, KeyBinding.CLEAR_SEARCH)) { - textField.clear(); - event.consume(); + textField.clear(); + event.consume(); } }); diff --git a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePane.java b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePane.java index 1a9ccd5e2c8..a50d1b2082d 100644 --- a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePane.java +++ b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePane.java @@ -64,13 +64,13 @@ public SidePane(LibraryTabContainer tabContainer, updateView(); } - private void updateView() { + private void updateView() { getChildren().clear(); - for (SidePaneType type : stateManager.getVisibleSidePaneComponents()) { - SidePaneComponent view = viewModel.getSidePaneComponent(type); - getChildren().add(view); - } - } + for (SidePaneType type : stateManager.getVisibleSidePaneComponents()) { + SidePaneComponent view = viewModel.getSidePaneComponent(type); + getChildren().add(view); + } + } public BooleanBinding paneVisibleBinding(SidePaneType pane) { BooleanBinding visibility = Bindings.createBooleanBinding( diff --git a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java index b8d1dfdc967..a02a28d78c1 100644 --- a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java +++ b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java @@ -64,35 +64,38 @@ public SidePaneContentFactory(LibraryTabContainer tabContainer, public Node create(SidePaneType sidePaneType) { return switch (sidePaneType) { - case GROUPS -> new GroupTreeView( - taskExecutor, - stateManager, - adaptVisibleTabs, - preferences, - dialogService, - aiService, - undoManager, - fileUpdateMonitor); - case OPEN_OFFICE -> new OpenOfficePanel( - tabContainer, - preferences, - preferences.getOpenOfficePreferences(Injector.instantiateModelOrService(JournalAbbreviationRepository.class)), - preferences.getExternalApplicationsPreferences(), - preferences.getLayoutFormatterPreferences(), - preferences.getCitationKeyPatternPreferences(), - abbreviationRepository, - (UiTaskExecutor) taskExecutor, - dialogService, - aiService, - stateManager, - fileUpdateMonitor, - entryTypesManager, - clipBoardManager, - undoManager).getContent(); - case WEB_SEARCH -> new WebSearchPaneView( - preferences, - dialogService, - stateManager); + case GROUPS -> + new GroupTreeView( + taskExecutor, + stateManager, + adaptVisibleTabs, + preferences, + dialogService, + aiService, + undoManager, + fileUpdateMonitor); + case OPEN_OFFICE -> + new OpenOfficePanel( + tabContainer, + preferences, + preferences.getOpenOfficePreferences(Injector.instantiateModelOrService(JournalAbbreviationRepository.class)), + preferences.getExternalApplicationsPreferences(), + preferences.getLayoutFormatterPreferences(), + preferences.getCitationKeyPatternPreferences(), + abbreviationRepository, + (UiTaskExecutor) taskExecutor, + dialogService, + aiService, + stateManager, + fileUpdateMonitor, + entryTypesManager, + clipBoardManager, + undoManager).getContent(); + case WEB_SEARCH -> + new WebSearchPaneView( + preferences, + dialogService, + stateManager); }; } } diff --git a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java index ecbeac0e2b9..76b8065059f 100644 --- a/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java @@ -88,18 +88,21 @@ protected SidePaneComponent getSidePaneComponent(SidePaneType pane) { SidePaneComponent sidePaneComponent = sidePaneComponentLookup.get(pane); if (sidePaneComponent == null) { sidePaneComponent = switch (pane) { - case GROUPS -> new GroupsSidePaneComponent( - new ClosePaneAction(pane), - new MoveUpAction(pane), - new MoveDownAction(pane), - sidePaneContentFactory, - preferences.getGroupsPreferences(), - dialogService); - case WEB_SEARCH, OPEN_OFFICE -> new SidePaneComponent(pane, - new ClosePaneAction(pane), - new MoveUpAction(pane), - new MoveDownAction(pane), - sidePaneContentFactory); + case GROUPS -> + new GroupsSidePaneComponent( + new ClosePaneAction(pane), + new MoveUpAction(pane), + new MoveDownAction(pane), + sidePaneContentFactory, + preferences.getGroupsPreferences(), + dialogService); + case WEB_SEARCH, + OPEN_OFFICE -> + new SidePaneComponent(pane, + new ClosePaneAction(pane), + new MoveUpAction(pane), + new MoveDownAction(pane), + sidePaneContentFactory); }; sidePaneComponentLookup.put(pane, sidePaneComponent); } diff --git a/jabgui/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java b/jabgui/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java index 809d7ba7a76..e1d66d6e074 100644 --- a/jabgui/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java +++ b/jabgui/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java @@ -41,7 +41,7 @@ public class ExistingStudySearchAction extends SimpleCommand { private final Supplier openDatabaseActionSupplier; /** - * @param tabContainer Required to close the tab before the study is updated + * @param tabContainer Required to close the tab before the study is updated * @param openDatabaseActionSupplier Required to open the tab after the study is executed */ public ExistingStudySearchAction( diff --git a/jabgui/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java b/jabgui/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java index e2de7631aae..c7fe540cccf 100644 --- a/jabgui/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java +++ b/jabgui/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java @@ -103,7 +103,7 @@ public ManageStudyDefinitionView(Path pathToStudyDataDirectory) { /** * This is used to edit an existing study. * - * @param study the study to edit + * @param study the study to edit * @param studyDirectory the directory of the study */ public ManageStudyDefinitionView(Study study, Path studyDirectory) { @@ -128,10 +128,10 @@ private void setupSaveSurveyButton(boolean isEdit) { saveSurveyButton.disableProperty().bind(Bindings.or(Bindings.or(Bindings.or(Bindings.or(Bindings.or( Bindings.isEmpty(viewModel.getQueries()), Bindings.isEmpty(viewModel.getCatalogs())), - Bindings.isEmpty(viewModel.getAuthors())), - viewModel.getTitle().isEmpty()), - viewModel.getDirectory().isEmpty()), - directoryWarning.visibleProperty())); + Bindings.isEmpty(viewModel.getAuthors())), + viewModel.getTitle().isEmpty()), + viewModel.getDirectory().isEmpty()), + directoryWarning.visibleProperty())); setResultConverter(button -> { if (button == saveSurveyButtonType) { diff --git a/jabgui/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java b/jabgui/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java index 27cc961e3db..58694e310e3 100644 --- a/jabgui/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java +++ b/jabgui/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java @@ -28,9 +28,9 @@ *

  • Let the user input meta data for the study.
  • *
  • Let JabRef do the crawling afterwards.
  • * - * + *

    * Needs to inherit {@link ExistingStudySearchAction}, because that action implements the real crawling. - * + *

    * There is the hook {@link StartNewStudyAction#crawlPreparation(Path)}, which is used by {@link ExistingStudySearchAction#crawl()}. */ public class StartNewStudyAction extends ExistingStudySearchAction { diff --git a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java index a38baf4c6be..dbca898f46a 100644 --- a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java +++ b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java @@ -13,7 +13,7 @@ import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; -import org.jabref.gui.undo.NamedCompound; +import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.logic.preferences.CliPreferences; @@ -70,17 +70,17 @@ public void execute() { if ((bes == null) || bes.isEmpty()) { return; } - NamedCompound ce = new NamedCompound(undoText); + NamedCompoundEdit compoundEdit = new NamedCompoundEdit(undoText); List besCopy = new ArrayList<>(bes); for (BibEntry bibEntry : besCopy) { // if (value==null) and then call nullField has been omitted as updatefield also handles value==null Optional change = UpdateField.updateField(bibEntry, specialField, value, nullFieldIfValueIsTheSame); - change.ifPresent(fieldChange -> ce.addEdit(new UndoableFieldChange(fieldChange))); + change.ifPresent(fieldChange -> compoundEdit.addEdit(new UndoableFieldChange(fieldChange))); } - ce.end(); - if (ce.hasEdits()) { - undoManager.addEdit(ce); + compoundEdit.end(); + if (compoundEdit.hasEdits()) { + undoManager.addEdit(compoundEdit); tabSupplier.get().markBaseChanged(); String outText; if (nullFieldIfValueIsTheSame || value == null) { diff --git a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java index e2d3ffda9a6..33f587bb204 100644 --- a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java @@ -32,43 +32,75 @@ public String getMenuString() { public String getToolTipText() { return switch (value) { - case PRINTED -> Localization.lang("Toggle print status"); - case CLEAR_PRIORITY -> Localization.lang("No priority information"); - case PRIORITY_HIGH -> Localization.lang("Priority high"); - case PRIORITY_MEDIUM -> Localization.lang("Priority medium"); - case PRIORITY_LOW -> Localization.lang("Priority low"); - case QUALITY_ASSURED -> Localization.lang("Toggle quality assured"); - case CLEAR_RANK -> Localization.lang("No rank information"); - case RANK_1 -> Localization.lang("One star"); - case RANK_2 -> Localization.lang("Two stars"); - case RANK_3 -> Localization.lang("Three stars"); - case RANK_4 -> Localization.lang("Four stars"); - case RANK_5 -> Localization.lang("Five stars"); - case CLEAR_READ_STATUS -> Localization.lang("No read status information"); - case READ -> Localization.lang("Read status read"); - case SKIMMED -> Localization.lang("Read status skimmed"); - case RELEVANT -> Localization.lang("Toggle relevance"); + case PRINTED -> + Localization.lang("Toggle print status"); + case CLEAR_PRIORITY -> + Localization.lang("No priority information"); + case PRIORITY_HIGH -> + Localization.lang("Priority high"); + case PRIORITY_MEDIUM -> + Localization.lang("Priority medium"); + case PRIORITY_LOW -> + Localization.lang("Priority low"); + case QUALITY_ASSURED -> + Localization.lang("Toggle quality assured"); + case CLEAR_RANK -> + Localization.lang("No rank information"); + case RANK_1 -> + Localization.lang("One star"); + case RANK_2 -> + Localization.lang("Two stars"); + case RANK_3 -> + Localization.lang("Three stars"); + case RANK_4 -> + Localization.lang("Four stars"); + case RANK_5 -> + Localization.lang("Five stars"); + case CLEAR_READ_STATUS -> + Localization.lang("No read status information"); + case READ -> + Localization.lang("Read status read"); + case SKIMMED -> + Localization.lang("Read status skimmed"); + case RELEVANT -> + Localization.lang("Toggle relevance"); }; } public Action getAction() { return switch (value) { - case PRINTED -> StandardActions.TOGGLE_PRINTED; - case CLEAR_PRIORITY -> StandardActions.CLEAR_PRIORITY; - case PRIORITY_HIGH -> StandardActions.PRIORITY_HIGH; - case PRIORITY_MEDIUM -> StandardActions.PRIORITY_MEDIUM; - case PRIORITY_LOW -> StandardActions.PRIORITY_LOW; - case QUALITY_ASSURED -> StandardActions.QUALITY_ASSURED; - case CLEAR_RANK -> StandardActions.CLEAR_RANK; - case RANK_1 -> StandardActions.RANK_1; - case RANK_2 -> StandardActions.RANK_2; - case RANK_3 -> StandardActions.RANK_3; - case RANK_4 -> StandardActions.RANK_4; - case RANK_5 -> StandardActions.RANK_5; - case CLEAR_READ_STATUS -> StandardActions.CLEAR_READ_STATUS; - case READ -> StandardActions.READ; - case SKIMMED -> StandardActions.SKIMMED; - case RELEVANT -> StandardActions.RELEVANT; + case PRINTED -> + StandardActions.TOGGLE_PRINTED; + case CLEAR_PRIORITY -> + StandardActions.CLEAR_PRIORITY; + case PRIORITY_HIGH -> + StandardActions.PRIORITY_HIGH; + case PRIORITY_MEDIUM -> + StandardActions.PRIORITY_MEDIUM; + case PRIORITY_LOW -> + StandardActions.PRIORITY_LOW; + case QUALITY_ASSURED -> + StandardActions.QUALITY_ASSURED; + case CLEAR_RANK -> + StandardActions.CLEAR_RANK; + case RANK_1 -> + StandardActions.RANK_1; + case RANK_2 -> + StandardActions.RANK_2; + case RANK_3 -> + StandardActions.RANK_3; + case RANK_4 -> + StandardActions.RANK_4; + case RANK_5 -> + StandardActions.RANK_5; + case CLEAR_READ_STATUS -> + StandardActions.CLEAR_READ_STATUS; + case READ -> + StandardActions.READ; + case SKIMMED -> + StandardActions.SKIMMED; + case RELEVANT -> + StandardActions.RELEVANT; }; } } diff --git a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java index e2f4387bb39..ea76a8b9861 100644 --- a/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java @@ -65,12 +65,18 @@ public String getLocalization() { public Action getAction() { return switch (field) { - case PRINTED -> StandardActions.PRINTED; - case PRIORITY -> StandardActions.PRIORITY; - case QUALITY -> StandardActions.QUALITY; - case RANKING -> StandardActions.RANKING; - case READ_STATUS -> StandardActions.READ_STATUS; - case RELEVANCE -> StandardActions.RELEVANCE; + case PRINTED -> + StandardActions.PRINTED; + case PRIORITY -> + StandardActions.PRIORITY; + case QUALITY -> + StandardActions.QUALITY; + case RANKING -> + StandardActions.RANKING; + case READ_STATUS -> + StandardActions.READ_STATUS; + case RELEVANCE -> + StandardActions.RELEVANCE; }; } diff --git a/jabgui/src/main/java/org/jabref/gui/theme/StyleSheetFile.java b/jabgui/src/main/java/org/jabref/gui/theme/StyleSheetFile.java index 515f37854ed..ee1cecd07c1 100644 --- a/jabgui/src/main/java/org/jabref/gui/theme/StyleSheetFile.java +++ b/jabgui/src/main/java/org/jabref/gui/theme/StyleSheetFile.java @@ -20,17 +20,17 @@ final class StyleSheetFile extends StyleSheet { /** * A size limit above which Theme will not attempt to keep a data-embedded URL in memory for the CSS. - * + *

    * It's tolerable for CSS to exceed this limit; the functional benefit of the encoded CSS is in some edge * case error handling. Specifically, having a reference to a data-embedded URL means that the Preview Viewer * isn't impacted if the source CSS file is removed while the application is running. - * + *

    * If the CSS is over this limit, then the user won't see any functional impact, as long as the file exists. Only if * it becomes unavailable, might there be some impact. First, the Preview Viewer when created might not be themed. * Second, there is a very small chance of uncaught exceptions. Theme makes a best effort to avoid this: * it checks for CSS file existence before passing it to the Preview Viewer for theming. Still, as file existence * checks are immediately out of date, it can't be perfectly ruled out. - * + *

    * At the time of writing this comment: * *

      @@ -39,9 +39,9 @@ final class StyleSheetFile extends StyleSheet { *
    • The dark custom theme in the Jabref documentation is 2k, see * Custom themes
    • *
    - * + *

    * So realistic custom themes will fit comfortably within 48k, even if they are modified copies of the base theme. - * + *

    * Note that Base-64 encoding will increase the memory footprint of the URL by a third. */ static final int MAX_IN_MEMORY_CSS_LENGTH = 48000; diff --git a/jabgui/src/main/java/org/jabref/gui/theme/Theme.java b/jabgui/src/main/java/org/jabref/gui/theme/Theme.java index 03e6e414aed..f8a4cc0f496 100644 --- a/jabgui/src/main/java/org/jabref/gui/theme/Theme.java +++ b/jabgui/src/main/java/org/jabref/gui/theme/Theme.java @@ -40,7 +40,7 @@ public Theme(String name) { } } else { this.additionalStylesheet = StyleSheet.create(name); - if (this.additionalStylesheet.isPresent()) { + if (this.additionalStylesheet.isPresent()) { this.type = Type.CUSTOM; this.name = name; } else { diff --git a/jabgui/src/main/java/org/jabref/gui/theme/ThemeManager.java b/jabgui/src/main/java/org/jabref/gui/theme/ThemeManager.java index 6e2682c6379..efcdcf98d57 100644 --- a/jabgui/src/main/java/org/jabref/gui/theme/ThemeManager.java +++ b/jabgui/src/main/java/org/jabref/gui/theme/ThemeManager.java @@ -115,7 +115,7 @@ public void installCss(@NonNull Scene scene) { public void installCss(WebEngine webEngine) { if (this.webEngines.add(webEngine)) { webEngine.setUserStyleSheetLocation(this.theme.getAdditionalStylesheet().isPresent() ? - this.theme.getAdditionalStylesheet().get().getWebEngineStylesheet() : ""); + this.theme.getAdditionalStylesheet().get().getWebEngineStylesheet() : ""); } } diff --git a/jabgui/src/main/java/org/jabref/gui/theme/ThemeTypes.java b/jabgui/src/main/java/org/jabref/gui/theme/ThemeTypes.java index 73523ae9c47..a68bc3b3e37 100644 --- a/jabgui/src/main/java/org/jabref/gui/theme/ThemeTypes.java +++ b/jabgui/src/main/java/org/jabref/gui/theme/ThemeTypes.java @@ -4,17 +4,17 @@ public enum ThemeTypes { - LIGHT(Localization.lang("Light")), - DARK(Localization.lang("Dark")), - CUSTOM(Localization.lang("Custom...")); + LIGHT(Localization.lang("Light")), + DARK(Localization.lang("Dark")), + CUSTOM(Localization.lang("Custom...")); - private final String displayName; + private final String displayName; - ThemeTypes(String displayName) { - this.displayName = displayName; - } + ThemeTypes(String displayName) { + this.displayName = displayName; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } } diff --git a/jabgui/src/main/java/org/jabref/gui/undo/NamedCompound.java b/jabgui/src/main/java/org/jabref/gui/undo/NamedCompoundEdit.java similarity index 91% rename from jabgui/src/main/java/org/jabref/gui/undo/NamedCompound.java rename to jabgui/src/main/java/org/jabref/gui/undo/NamedCompoundEdit.java index 55be19a96e3..4c880f4af1d 100644 --- a/jabgui/src/main/java/org/jabref/gui/undo/NamedCompound.java +++ b/jabgui/src/main/java/org/jabref/gui/undo/NamedCompoundEdit.java @@ -5,12 +5,12 @@ import org.jabref.logic.l10n.Localization; -public class NamedCompound extends CompoundEdit { +public class NamedCompoundEdit extends CompoundEdit { private final String name; private boolean hasEdits; - public NamedCompound(String name) { + public NamedCompoundEdit(String name) { super(); this.name = name; } diff --git a/jabgui/src/main/java/org/jabref/gui/undo/UndoableStringChange.java b/jabgui/src/main/java/org/jabref/gui/undo/UndoableStringChange.java index 883f1675750..3ee7669c6e7 100644 --- a/jabgui/src/main/java/org/jabref/gui/undo/UndoableStringChange.java +++ b/jabgui/src/main/java/org/jabref/gui/undo/UndoableStringChange.java @@ -22,8 +22,8 @@ public UndoableStringChange(BibtexString string, boolean nameChange, String oldV public String getPresentationName() { return nameChange ? Localization.lang("change string name %0 to %1", StringUtil.boldHTML(oldValue), StringUtil.boldHTML(newValue)) : - Localization.lang("change string content %0 to %1", - StringUtil.boldHTML(oldValue), StringUtil.boldHTML(newValue)); + Localization.lang("change string content %0 to %1", + StringUtil.boldHTML(oldValue), StringUtil.boldHTML(newValue)); } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/util/ControlHelper.java b/jabgui/src/main/java/org/jabref/gui/util/ControlHelper.java index d998764cfb7..ba392ec62ae 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/ControlHelper.java +++ b/jabgui/src/main/java/org/jabref/gui/util/ControlHelper.java @@ -103,11 +103,11 @@ public static void removeDroppingPseudoClasses(Cell cell) { /** * If needed, truncates a given string to maxCharacters, adding ellipsisString instead. * - * @param text text which should be truncated, if needed - * @param maxCharacters maximum amount of characters which the resulting text should have, including the - * ellipsisString; if set to -1, then the default length of 75 characters will be - * used - * @param ellipsisString string which should be used for indicating the truncation + * @param text text which should be truncated, if needed + * @param maxCharacters maximum amount of characters which the resulting text should have, including the + * ellipsisString; if set to -1, then the default length of 75 characters will be + * used + * @param ellipsisString string which should be used for indicating the truncation * @param ellipsisPosition location in the given text where the truncation should be performed * @return the new, truncated string */ @@ -135,7 +135,8 @@ public static String truncateString(String text, int maxCharacters, String ellip int partialLength = (int) Math.floor((maxCharacters - ellipsisString.length()) / 2f); yield text.substring(0, partialLength) + ellipsisString + text.substring(text.length() - partialLength); } - case ENDING -> text.substring(0, maxCharacters - ellipsisString.length()) + ellipsisString; + case ENDING -> + text.substring(0, maxCharacters - ellipsisString.length()) + ellipsisString; }; } diff --git a/jabgui/src/main/java/org/jabref/gui/util/CustomTitledPaneSkin.java b/jabgui/src/main/java/org/jabref/gui/util/CustomTitledPaneSkin.java index 2b85377d971..5e6d8c6cee3 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/CustomTitledPaneSkin.java +++ b/jabgui/src/main/java/org/jabref/gui/util/CustomTitledPaneSkin.java @@ -123,8 +123,13 @@ private void adjustTitleLayout() { textGraphicTranslateBinding = Bindings.createDoubleBinding( () -> switch (getSkinnable().getAlignment()) { - case TOP_CENTER, CENTER, BOTTOM_CENTER, BASELINE_CENTER -> 0.0; - default -> -arrowButton.getWidth(); + case TOP_CENTER, + CENTER, + BOTTOM_CENTER, + BASELINE_CENTER -> + 0.0; + default -> + -arrowButton.getWidth(); }, getSkinnable().alignmentProperty(), arrowButton.widthProperty()); text.translateXProperty().bind(textGraphicTranslateBinding); @@ -194,7 +199,6 @@ public StyleableProperty getStyleableProperty(TitledPane styleable) { } return null; } - }; private static final List> CSS_META_DATA; @@ -205,6 +209,5 @@ public StyleableProperty getStyleableProperty(TitledPane styleable) { list.add(ARROW_SIDE); CSS_META_DATA = Collections.unmodifiableList(list); } - } } diff --git a/jabgui/src/main/java/org/jabref/gui/util/FieldsUtil.java b/jabgui/src/main/java/org/jabref/gui/util/FieldsUtil.java index 67ffcb0b8f0..2998a7d547f 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/FieldsUtil.java +++ b/jabgui/src/main/java/org/jabref/gui/util/FieldsUtil.java @@ -37,11 +37,16 @@ public static String getNameWithType(Field field, CliPreferences preferences, Un case SpecialField specialField -> new SpecialFieldViewModel(specialField, preferences, undoManager).getLocalization() + " (" + Localization.lang("Special") + ")"; - case IEEEField _ -> field.getDisplayName() + " (" + Localization.lang("IEEE") + ")"; - case InternalField _ -> field.getDisplayName() + " (" + Localization.lang("Internal") + ")"; - case UnknownField _ -> field.getDisplayName() + " (" + Localization.lang("Custom") + ")"; - case null -> throw new IllegalArgumentException("Field must not be null"); - default -> field.getDisplayName(); + case IEEEField _ -> + field.getDisplayName() + " (" + Localization.lang("IEEE") + ")"; + case InternalField _ -> + field.getDisplayName() + " (" + Localization.lang("Internal") + ")"; + case UnknownField _ -> + field.getDisplayName() + " (" + Localization.lang("Custom") + ")"; + case null -> + throw new IllegalArgumentException("Field must not be null"); + default -> + field.getDisplayName(); }; } } diff --git a/jabgui/src/main/java/org/jabref/gui/util/FileFilterConverter.java b/jabgui/src/main/java/org/jabref/gui/util/FileFilterConverter.java index 619d656cddf..43b154e1392 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/FileFilterConverter.java +++ b/jabgui/src/main/java/org/jabref/gui/util/FileFilterConverter.java @@ -106,8 +106,8 @@ public static Filter toDirFilter(List extensions) { return _ -> true; } else { return path -> FileUtil.getFileExtension(path) - .map(extensionsCleaned::contains) - .orElse(false); + .map(extensionsCleaned::contains) + .orElse(false); } } } diff --git a/jabgui/src/main/java/org/jabref/gui/util/IconValidationDecorator.java b/jabgui/src/main/java/org/jabref/gui/util/IconValidationDecorator.java index 4fdc492d228..9556e177472 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/IconValidationDecorator.java +++ b/jabgui/src/main/java/org/jabref/gui/util/IconValidationDecorator.java @@ -39,8 +39,8 @@ public IconValidationDecorator(Pos position) { @Override public Node createDecorationNode(ValidationMessage message) { Node graphic = Severity.ERROR == message.getSeverity() - ? IconTheme.JabRefIcons.ERROR.getGraphicNode() - : IconTheme.JabRefIcons.WARNING.getGraphicNode(); + ? IconTheme.JabRefIcons.ERROR.getGraphicNode() + : IconTheme.JabRefIcons.WARNING.getGraphicNode(); graphic.getStyleClass().add(Severity.ERROR == message.getSeverity() ? "error-icon" : "warning-icon"); Label label = new Label(); label.setGraphic(graphic); diff --git a/jabgui/src/main/java/org/jabref/gui/util/URLs.java b/jabgui/src/main/java/org/jabref/gui/util/URLs.java index bd6069fc465..f246d7568fc 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/URLs.java +++ b/jabgui/src/main/java/org/jabref/gui/util/URLs.java @@ -30,7 +30,7 @@ public class URLs { public static final String LINK_EXTERNAL_FILE_WALKTHROUGH_EXAMPLE_PDF = "https://nutritionandmetabolism.biomedcentral.com/counter/pdf/10.1186/1743-7075-3-2.pdf"; public static final String ADD_PDF_DOC = "https://docs.jabref.org/collect/add-pdfs-to-an-entry"; public static final String FIND_UNLINKED_FILES_DOC = "https://docs.jabref.org/collect/findunlinkedfiles"; - + // AboutDialogViewModel URLs public static final String HOMEPAGE_URL = "https://www.jabref.org"; public static final String DONATION_URL = "https://donations.jabref.org"; diff --git a/jabgui/src/main/java/org/jabref/gui/util/UiTaskExecutor.java b/jabgui/src/main/java/org/jabref/gui/util/UiTaskExecutor.java index 3001b3f6956..08e68e1980b 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/UiTaskExecutor.java +++ b/jabgui/src/main/java/org/jabref/gui/util/UiTaskExecutor.java @@ -103,8 +103,7 @@ public static void runInJavaFXThread(Runnable runnable) { * The JavaFX task executes the call method a background thread and the onFailed onSucceed on the FX UI thread * * @param task the BackgroundTask to run - * @param The background task type - * + * @param The background task type * @return Future of a JavaFX Task which will execute the call method a background thread */ @Override diff --git a/jabgui/src/main/java/org/jabref/gui/util/ViewModelTextFieldTableCellVisualizationFactory.java b/jabgui/src/main/java/org/jabref/gui/util/ViewModelTextFieldTableCellVisualizationFactory.java index 9ddfaf3b29a..e3abb6379bf 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/ViewModelTextFieldTableCellVisualizationFactory.java +++ b/jabgui/src/main/java/org/jabref/gui/util/ViewModelTextFieldTableCellVisualizationFactory.java @@ -63,8 +63,8 @@ private Optional lookupTextField() { } else { // Could be an HBox with some graphic and a TextField if a graphic is specified for the TableCell if (getGraphic() instanceof HBox hbox - && hbox.getChildren().size() > 1 - && hbox.getChildren().get(1) instanceof TextField textField) { + && hbox.getChildren().size() > 1 + && hbox.getChildren().get(1) instanceof TextField textField) { return Optional.of(textField); } diff --git a/jabgui/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java b/jabgui/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java index 7bc6f8dda48..14c2d48fa33 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java +++ b/jabgui/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java @@ -70,7 +70,7 @@ public TreeCell call(TreeView tree) { @Override public String toString(TreeItem treeItem) { return treeItem == null || treeItem.getValue() == null || toText == null ? - "" : toText.call(treeItem.getValue()); + "" : toText.call(treeItem.getValue()); } @Override diff --git a/jabgui/src/main/java/org/jabref/gui/util/ZipFileChooser.java b/jabgui/src/main/java/org/jabref/gui/util/ZipFileChooser.java index dd8fd8b63e5..bdaa963932a 100644 --- a/jabgui/src/main/java/org/jabref/gui/util/ZipFileChooser.java +++ b/jabgui/src/main/java/org/jabref/gui/util/ZipFileChooser.java @@ -46,7 +46,7 @@ public ZipFileChooser(FileSystem zipFile) throws IOException { try { return new ReadOnlyStringWrapper( ZonedDateTime.ofInstant(Files.getLastModifiedTime(data.getValue()).toInstant(), - ZoneId.systemDefault()) + ZoneId.systemDefault()) .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM))); } catch (IOException e) { // Ignore diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughAction.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughAction.java index c8df1a0a76e..a630f3ac9a9 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughAction.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughAction.java @@ -70,11 +70,14 @@ private Walkthrough getWalkthrough(String name) { switch (name) { case MAIN_FILE_DIRECTORY_WALKTHROUGH_NAME -> createMainFileDirectoryWalkthrough(); - case PDF_LINK_WALKTHROUGH_NAME -> createPdfLinkWalkthrough(); + case PDF_LINK_WALKTHROUGH_NAME -> + createPdfLinkWalkthrough(); case CUSTOMIZE_ENTRY_TABLE_WALKTHROUGH_NAME -> createCustomizeEntryTableWalkthrough(); - case GROUP_WALKTHROUGH_NAME -> createGroupWalkthrough(); - case SEARCH_WALKTHROUGH_NAME -> createSearchWalkthrough(); + case GROUP_WALKTHROUGH_NAME -> + createGroupWalkthrough(); + case SEARCH_WALKTHROUGH_NAME -> + createSearchWalkthrough(); default -> throw new IllegalArgumentException("Unknown walkthrough: " + name); } @@ -449,8 +452,8 @@ private Walkthrough createSearchWalkthrough() { .predicate(GlobalSearchBar.class::isInstance) .resolve(scene) .flatMap(node -> node instanceof GlobalSearchBar bar ? - bar.getChildren().stream().filter(CustomTextField.class::isInstance).findAny() : - Optional.empty()); + bar.getChildren().stream().filter(CustomTextField.class::isInstance).findAny() : + Optional.empty()); return Walkthrough .create(stateManager) diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughHighlighter.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughHighlighter.java index 8d16ee446e8..41e67cb3b49 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughHighlighter.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughHighlighter.java @@ -28,10 +28,10 @@ public class WalkthroughHighlighter { /// Applies the specified highlight configuration. /// /// @param config The highlight configuration to apply. Default to - /// BackdropHighlight on the primary windows if null. + /// BackdropHighlight on the primary windows if null. /// @param scene The primary scene to apply the highlight to. /// @param fallbackTarget The fallback target node to use if no highlight - /// configuration is provided. + /// configuration is provided. public void applyHighlight(@Nullable WalkthroughEffect config, @NonNull Scene scene, @Nullable Node fallbackTarget) { Map newEffects = computeNewEffects(config, scene, fallbackTarget); @@ -54,8 +54,8 @@ public void applyHighlight(@Nullable WalkthroughEffect config, @NonNull Scene sc /// Sets a handler to be called when the user clicks on backdrop or darkened areas. /// /// @param handler The handler to call when the background is clicked. If null, no - /// action will be taken on background clicks. Usually used to - /// support quit walkthrough on clicking the effects. + /// action will be taken on background clicks. Usually used to + /// support quit walkthrough on clicking the effects. public void setOnBackgroundClick(@Nullable Runnable handler) { this.onBackgroundClickHandler = handler; } @@ -166,7 +166,8 @@ private void updateExistingEffect(@NonNull Window window, @NonNull EffectState n case FULL_SCREEN_DARKEN -> { // FullScreenDarken doesn't need updates as it has no target node } - case NONE -> detach(window); + case NONE -> + detach(window); } } @@ -182,8 +183,10 @@ private void applyEffect(@NonNull Window window, @NonNull HighlightEffect effect applyPulseAnimation(window, targetNode); } } - case FULL_SCREEN_DARKEN -> applyFullScreenDarken(window); - case NONE -> detach(window); + case FULL_SCREEN_DARKEN -> + applyFullScreenDarken(window); + case NONE -> + detach(window); } } diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughOverlay.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughOverlay.java index a7dd4c24b5b..f3009f8035a 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughOverlay.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughOverlay.java @@ -59,7 +59,10 @@ public void show(@NonNull WalkthroughStep step) { cleanUp(); switch (step) { - case SideEffect(String title, WalkthroughSideEffect sideEffect) -> { + case SideEffect( + String title, + WalkthroughSideEffect sideEffect + ) -> { LOGGER.debug("Executing side effect for step: {}", title); if (sideEffectExecutor.executeForward(sideEffect, walkthrough)) { @@ -142,8 +145,10 @@ private void displayWalkthroughStep(WalkthroughResult result) { w -> new WindowOverlay(w, WalkthroughPane.getInstance(w), walkthrough)); switch (component) { - case TooltipStep tooltip -> overlay.showTooltip(tooltip, resolvedNode, this::prepareForNavigation); - case PanelStep panel -> overlay.showPanel(panel, resolvedNode, this::prepareForNavigation); + case TooltipStep tooltip -> + overlay.showTooltip(tooltip, resolvedNode, this::prepareForNavigation); + case PanelStep panel -> + overlay.showPanel(panel, resolvedNode, this::prepareForNavigation); } reverter.attach(resolvedWindow, resolvedNode); diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughRenderer.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughRenderer.java index 285ef527166..622686b045d 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughRenderer.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/WalkthroughRenderer.java @@ -168,8 +168,10 @@ private VBox createContent(VisibleComponent component, Walkthrough walkthrough, contentBox.getStyleClass().add("walkthrough-content"); contentBox.getChildren().addAll(component.content().stream().map(block -> switch (block) { - case TextBlock textBlock -> render(textBlock); - case InfoBlock infoBlock -> render(infoBlock); + case TextBlock textBlock -> + render(textBlock); + case InfoBlock infoBlock -> + render(infoBlock); case ArbitraryJFXBlock arbitraryBlock -> render(arbitraryBlock, walkthrough, beforeNavigate); } diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/WindowOverlay.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/WindowOverlay.java index 835b87e1348..b74d4033b90 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/WindowOverlay.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/WindowOverlay.java @@ -78,15 +78,15 @@ public WindowOverlay(Window window, WalkthroughPane pane, Walkthrough walkthroug /// /// @param step The step to display. /// @param node The node to anchor the tooltip to, or null to show it at - /// the window. The node is expected to be positionable by - /// [WalkthroughUtils#cannotPositionNode(Node)] standard. + /// the window. The node is expected to be positionable by + /// [WalkthroughUtils#cannotPositionNode(Node)] standard. /// @param beforeNavigate A runnable to execute before navigating to the next step. - /// More precisely, the runnable to execute immediately upon - /// the button press before Walkthrough's state change to the - /// next step and before the original button/node's action is - /// executed. Usually used to prevent automatic revert from - /// unexpected reverting to the previous step when the node is - /// not yet ready to be displayed + /// More precisely, the runnable to execute immediately upon + /// the button press before Walkthrough's state change to the + /// next step and before the original button/node's action is + /// executed. Usually used to prevent automatic revert from + /// unexpected reverting to the previous step when the node is + /// not yet ready to be displayed /// @implNote The requirement for the node to be positionable by /// [WalkthroughUtils#cannotPositionNode(Node)] standard is just to make things /// easier to define. This requirement come from @@ -186,15 +186,15 @@ public void showPanel(PanelStep step, Runnable beforeNavigate) { /// /// @param step The step to display. /// @param node The node to anchor highlight to (e.g., BackdropHighlight - /// may poke a hole at the position of the node), or null to - /// use fallback effect of corresponding position. + /// may poke a hole at the position of the node), or null to + /// use fallback effect of corresponding position. /// @param beforeNavigate A runnable to execute before navigating to the next step. - /// More precisely, the runnable to execute immediately upon - /// the button press before Walkthrough's state change to the - /// next step and before the original button/node's action is - /// executed. Usually used to prevent automatic revert from - /// unexpected reverting to the previous step when the node is - /// not yet ready to be displayed + /// More precisely, the runnable to execute immediately upon + /// the button press before Walkthrough's state change to the + /// next step and before the original button/node's action is + /// executed. Usually used to prevent automatic revert from + /// unexpected reverting to the previous step when the node is + /// not yet ready to be displayed /// @see WindowOverlay#showPanel(PanelStep, Runnable) /// @see WindowOverlay#showTooltip(TooltipStep, Node, Runnable) public void showPanel(PanelStep step, @Nullable Node node, Runnable beforeNavigate) { @@ -306,11 +306,16 @@ private void listenKeybindings(EventTarget target, Scene scene) { private Optional mapToArrowLocation(TooltipPosition position) { return Optional.ofNullable(switch (position) { - case TOP -> PopOver.ArrowLocation.BOTTOM_CENTER; - case BOTTOM -> PopOver.ArrowLocation.TOP_CENTER; - case LEFT -> PopOver.ArrowLocation.RIGHT_CENTER; - case RIGHT -> PopOver.ArrowLocation.LEFT_CENTER; - case AUTO -> null; + case TOP -> + PopOver.ArrowLocation.BOTTOM_CENTER; + case BOTTOM -> + PopOver.ArrowLocation.TOP_CENTER; + case LEFT -> + PopOver.ArrowLocation.RIGHT_CENTER; + case RIGHT -> + PopOver.ArrowLocation.LEFT_CENTER; + case AUTO -> + null; }); } @@ -343,9 +348,13 @@ private QuitButtonPosition resolveQuitButtonPosition(VisibleComponent component) QuitButtonPosition position = component.quitButtonPosition(); if (position == QuitButtonPosition.AUTO && component instanceof PanelStep panelStep) { return switch (panelStep.position()) { - case LEFT, BOTTOM -> QuitButtonPosition.TOP_RIGHT; - case RIGHT -> QuitButtonPosition.TOP_LEFT; - case TOP -> QuitButtonPosition.BOTTOM_RIGHT; + case LEFT, + BOTTOM -> + QuitButtonPosition.TOP_RIGHT; + case RIGHT -> + QuitButtonPosition.TOP_LEFT; + case TOP -> + QuitButtonPosition.BOTTOM_RIGHT; }; } return position == QuitButtonPosition.AUTO ? QuitButtonPosition.BOTTOM_RIGHT : position; diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/Trigger.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/Trigger.java index 2bddc55fde8..e49993249a2 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/Trigger.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/Trigger.java @@ -96,7 +96,7 @@ private interface PredicateGenerator { /// /// @param node The node to attach the trigger to. /// @param onNavigate A function that wraps the original event handler. It takes a Supplier representing the - /// original action and returns the result of that action. + /// original action and returns the result of that action. /// @return A cleanup runnable that detaches the trigger. Runnable create(Node node, Function, ?> onNavigate); } diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/WindowResolver.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/WindowResolver.java index bbbd4710a5f..ac4e0497245 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/WindowResolver.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/WindowResolver.java @@ -35,7 +35,7 @@ static WindowResolver title(@NonNull String key) { /// Creates a resolver that finds a window that's not the window specified. /// /// @param window the window to exclude from the search. Usually this is the current - /// window. + /// window. /// @return a resolver that finds any window except the specified one static WindowResolver not(Window window) { return () -> { diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/effect/WindowEffect.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/effect/WindowEffect.java index 3fb5df99dab..6c188688e16 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/effect/WindowEffect.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/declarative/effect/WindowEffect.java @@ -8,9 +8,9 @@ import org.jspecify.annotations.NonNull; public record WindowEffect( - @NonNull Optional windowResolver, - @NonNull HighlightEffect effect, - @NonNull Optional targetNodeResolver + @NonNull Optional windowResolver, + @NonNull HighlightEffect effect, + @NonNull Optional targetNodeResolver ) { public WindowEffect(HighlightEffect effect) { this(Optional.empty(), effect, Optional.empty()); diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/effects/BaseWindowEffect.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/effects/BaseWindowEffect.java index 6f2b22d8548..8e13546762e 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/effects/BaseWindowEffect.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/effects/BaseWindowEffect.java @@ -25,7 +25,7 @@ public sealed abstract class BaseWindowEffect permits Spotlight, FullScreenDarke /// pane until [#attach(Node)] is called. /// /// @param pane The pane where the effect will be applied. Usually obtained from [Window#getScene()] and - /// [Scene#getRoot()] + /// [Scene#getRoot()] protected BaseWindowEffect(@NonNull Pane pane) { this.pane = pane; this.debouncedUpdater = WalkthroughUtils.debounced(_ -> this.updateLayout()); diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughResolver.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughResolver.java index e01bfc52893..591e39a0deb 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughResolver.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughResolver.java @@ -25,7 +25,7 @@ public class WalkthroughResolver { private static final Logger LOGGER = LoggerFactory.getLogger(WalkthroughResolver.class); private static final Duration RESOLVE_TIMEOUT = Duration.millis(2_500); -private static final Duration NODE_IDLE_TIMEOUT = Duration.millis(250); + private static final Duration NODE_IDLE_TIMEOUT = Duration.millis(250); private final WindowResolver windowResolver; private final @Nullable NodeResolver nodeResolver; diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughReverter.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughReverter.java index 02087e68f52..4269b9fc68e 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughReverter.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughReverter.java @@ -140,7 +140,8 @@ private void undoTo(int from) { return; } } - case SideEffect _ -> undo(i); + case SideEffect _ -> + undo(i); } } @@ -151,7 +152,8 @@ private void undoTo(int from) { private void undo(int stepIndex) { WalkthroughStep step = walkthrough.getStepAtIndex(stepIndex); if (step instanceof SideEffect( - String title, WalkthroughSideEffect sideEffect + String title, + WalkthroughSideEffect sideEffect )) { if (!sideEffectExecutor.executeBackward(sideEffect, walkthrough)) { LOGGER.warn("Failed to revert side effect {}: {}", title, sideEffect.description()); diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughScroller.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughScroller.java index 95c2a2b2da9..0e31256d363 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughScroller.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughScroller.java @@ -76,10 +76,14 @@ private void scrollNodeIntoViewForParent(@NonNull Node targetNode, @NonNull Node Bounds targetBounds = targetNode.localToScene(targetNode.getBoundsInLocal()); scrollIntoScrollPane(scrollPane, targetBounds); } - case ListView listView -> scrollIntoListView(targetNode, listView); - case TableView tableView -> scrollIntoTableView(targetNode, tableView); - case TreeView treeView -> scrollIntoTreeView(targetNode, treeView); - default -> LOGGER.warn("Unsupported scrollable type: {}", scrollableParent.getClass().getSimpleName()); + case ListView listView -> + scrollIntoListView(targetNode, listView); + case TableView tableView -> + scrollIntoTableView(targetNode, tableView); + case TreeView treeView -> + scrollIntoTreeView(targetNode, treeView); + default -> + LOGGER.warn("Unsupported scrollable type: {}", scrollableParent.getClass().getSimpleName()); } } catch (RuntimeException e) { LOGGER.warn("Failed to scroll node into view for parent {}", scrollableParent.getClass().getSimpleName(), e); diff --git a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughUtils.java b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughUtils.java index 30bfcd8809c..6302b6d1d08 100644 --- a/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughUtils.java +++ b/jabgui/src/main/java/org/jabref/gui/walkthrough/utils/WalkthroughUtils.java @@ -145,8 +145,8 @@ private static void scheduleExecution(Timeline timeline, long intervalMs, Runnab /// until a stop condition is met. /// /// @param stopCondition A supplier that should return true when the listener should - /// be detached (as well as run anything interesting for the - /// actual callee). + /// be detached (as well as run anything interesting for the + /// actual callee). /// @return A runnable that can be used to detach the listener prematurely. public static Runnable onWindowChangedUntil(@NonNull BooleanSupplier stopCondition) { ListChangeListener listener = new ListChangeListener<>() { diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/WelcomeTab.java b/jabgui/src/main/java/org/jabref/gui/welcome/WelcomeTab.java index edfa9f40a95..f3985aa4be2 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/WelcomeTab.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/WelcomeTab.java @@ -358,15 +358,24 @@ private Hyperlink createFooterLink(String text, StandardActions action, IconThem Hyperlink link = new Hyperlink(text); link.getStyleClass().add("welcome-community-link"); String url = switch (action) { - case HELP -> URLs.HELP_URL; - case OPEN_FORUM -> URLs.FORUM_URL; - case OPEN_MASTODON -> URLs.MASTODON_URL; - case OPEN_LINKEDIN -> URLs.LINKEDIN_URL; - case DONATE -> URLs.DONATE_URL; - case OPEN_DEV_VERSION_LINK -> URLs.DEV_VERSION_LINK_URL; - case OPEN_CHANGELOG -> URLs.CHANGELOG_URL; - case OPEN_PRIVACY_POLICY -> URLs.PRIVACY_POLICY_URL; - default -> null; + case HELP -> + URLs.HELP_URL; + case OPEN_FORUM -> + URLs.FORUM_URL; + case OPEN_MASTODON -> + URLs.MASTODON_URL; + case OPEN_LINKEDIN -> + URLs.LINKEDIN_URL; + case DONATE -> + URLs.DONATE_URL; + case OPEN_DEV_VERSION_LINK -> + URLs.DEV_VERSION_LINK_URL; + case OPEN_CHANGELOG -> + URLs.CHANGELOG_URL; + case OPEN_PRIVACY_POLICY -> + URLs.PRIVACY_POLICY_URL; + default -> + null; }; if (url != null) { link.setOnAction(_ -> new OpenBrowserAction(url, dialogService, preferences.getExternalApplicationsPreferences()).execute()); diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/components/QuickSettings.java b/jabgui/src/main/java/org/jabref/gui/welcome/components/QuickSettings.java index e3ff23fce4b..dd02329b7db 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/components/QuickSettings.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/components/QuickSettings.java @@ -88,11 +88,11 @@ private VBox createContent() { this::showEntryTableConfigurationDialog); VBox newContent = new VBox(mainFileDirButton, - themeButton, - largeLibraryButton, - entryTableButton, - pushApplicationButton, - onlineServicesButton); + themeButton, + largeLibraryButton, + entryTableButton, + pushApplicationButton, + onlineServicesButton); newContent.getStyleClass().add("quick-settings-container"); return newContent; } diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/components/ThemeWireFrame.java b/jabgui/src/main/java/org/jabref/gui/welcome/components/ThemeWireFrame.java index de560bbffdf..272b669a2be 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/components/ThemeWireFrame.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/components/ThemeWireFrame.java @@ -26,9 +26,12 @@ public void setThemeType(@NonNull ThemeTypes themeType) { styleClass.startsWith("wireframe-custom")); String themeClassName = switch (themeType) { - case LIGHT -> "wireframe-light"; - case DARK -> "wireframe-dark"; - case CUSTOM -> "wireframe-custom"; + case LIGHT -> + "wireframe-light"; + case DARK -> + "wireframe-dark"; + case CUSTOM -> + "wireframe-custom"; }; getStyleClass().add(themeClassName); } diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/ThemeDialog.java b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/ThemeDialog.java index 3deb62fbceb..8f9fe431909 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/ThemeDialog.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/ThemeDialog.java @@ -86,9 +86,12 @@ private void initialize() { private void selectInitialTheme() { switch (viewModel.getSelectedTheme()) { - case LIGHT -> lightRadio.setSelected(true); - case DARK -> darkRadio.setSelected(true); - case CUSTOM -> customRadio.setSelected(true); + case LIGHT -> + lightRadio.setSelected(true); + case DARK -> + darkRadio.setSelected(true); + case CUSTOM -> + customRadio.setSelected(true); } } diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/PushApplicationDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/PushApplicationDialogViewModel.java index 593c32a39aa..e0bcca3e793 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/PushApplicationDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/PushApplicationDialogViewModel.java @@ -99,8 +99,8 @@ private void setupPathUpdates() { } String existingPath = pushToApplicationPreferences.getCommandPaths().get(selectedApp.getDisplayName()); pathProperty.set(PushToApplicationDetector.isValidAbsolutePath(existingPath) ? - existingPath : - Objects.requireNonNullElse(detectedApplicationPaths.get(selectedApp), "")); + existingPath : + Objects.requireNonNullElse(detectedApplicationPaths.get(selectedApp), "")); }); } diff --git a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/ThemeDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/ThemeDialogViewModel.java index 5db3522814e..b755e41be63 100644 --- a/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/ThemeDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/welcome/quicksettings/viewmodel/ThemeDialogViewModel.java @@ -36,8 +36,10 @@ public ThemeDialogViewModel(GuiPreferences preferences, DialogService dialogServ private void initializeFromCurrentTheme() { Theme currentTheme = workspacePreferences.getTheme(); switch (currentTheme.getType()) { - case DEFAULT -> selectedThemeProperty.set(ThemeTypes.LIGHT); - case EMBEDDED -> selectedThemeProperty.set(ThemeTypes.DARK); + case DEFAULT -> + selectedThemeProperty.set(ThemeTypes.LIGHT); + case EMBEDDED -> + selectedThemeProperty.set(ThemeTypes.DARK); case CUSTOM -> { selectedThemeProperty.set(ThemeTypes.CUSTOM); customPathProperty.set(currentTheme.getName()); @@ -63,8 +65,8 @@ public void setCustomPath(String path) { public void browseForThemeFile() { String fileDir = customPathProperty.get().isEmpty() ? - preferences.getInternalPreferences().getLastPreferencesExportPath().toString() : - customPathProperty.get(); + preferences.getInternalPreferences().getLastPreferencesExportPath().toString() : + customPathProperty.get(); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(StandardFileType.CSS) @@ -86,9 +88,12 @@ public boolean isValidConfiguration() { public void saveSettings() { Theme newTheme = switch (selectedThemeProperty.get()) { - case LIGHT -> Theme.light(); - case DARK -> Theme.dark(); - case CUSTOM -> Theme.custom(customPathProperty.get().trim()); + case LIGHT -> + Theme.light(); + case DARK -> + Theme.dark(); + case CUSTOM -> + Theme.custom(customPathProperty.get().trim()); }; workspacePreferences.setTheme(newTheme); } diff --git a/jabgui/src/main/java/org/jabref/migrations/PerformLoadDatabaseMigrations.java b/jabgui/src/main/java/org/jabref/migrations/PerformLoadDatabaseMigrations.java index e53b5b14ecc..2fa91401f04 100644 --- a/jabgui/src/main/java/org/jabref/migrations/PerformLoadDatabaseMigrations.java +++ b/jabgui/src/main/java/org/jabref/migrations/PerformLoadDatabaseMigrations.java @@ -10,7 +10,7 @@ public class PerformLoadDatabaseMigrations { // FIXME: Should be called somewhere // Typical call: performLoadDatabaseMigrations(result, importFormatPreferences.bibEntryPreferences().getKeywordSeparator()); public static void performLoadDatabaseMigrations(ParserResult parserResult, - Character keywordDelimited) { + Character keywordDelimited) { List postOpenMigrations = Arrays.asList( new ConvertLegacyExplicitGroups(), new ConvertMarkingToGroups(), diff --git a/jabgui/src/main/java/org/jabref/migrations/PreferencesMigrations.java b/jabgui/src/main/java/org/jabref/migrations/PreferencesMigrations.java index 2d6e6aaf64d..0ac4cea86c3 100644 --- a/jabgui/src/main/java/org/jabref/migrations/PreferencesMigrations.java +++ b/jabgui/src/main/java/org/jabref/migrations/PreferencesMigrations.java @@ -272,13 +272,13 @@ static void upgradeImportFileAndDirePatterns(JabRefCliPreferences prefs, Prefere // Migrate Import patterns // Check for prefs node for Version <= 4.0 if (mainPrefsNode.get(JabRefCliPreferences.IMPORT_FILENAMEPATTERN, null) != null) { - String[] oldStylePatterns = new String[]{ + String[] oldStylePatterns = new String[] { "\\bibtexkey", "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; - String[] newStylePatterns = new String[]{"[citationkey]", + String[] newStylePatterns = new String[] {"[citationkey]", "[citationkey] - [title]"}; - String[] oldDisplayStylePattern = new String[]{"bibtexkey", "bibtexkey - title"}; + String[] oldDisplayStylePattern = new String[] {"bibtexkey", "bibtexkey - title"}; for (int i = 0; i < oldStylePatterns.length; i++) { migrateFileImportPattern(oldStylePatterns[i], newStylePatterns[i], prefs, mainPrefsNode); @@ -534,8 +534,8 @@ private static void upgradeCleanups(JabRefCliPreferences prefs) { && (FieldFormatterCleanups.ENABLED.equals(formatterCleanups.getFirst()) || FieldFormatterCleanups.DISABLED.equals(formatterCleanups.getFirst()))) { prefs.putBoolean(V6_0_CLEANUP_FIELD_FORMATTERS_ENABLED, FieldFormatterCleanups.ENABLED.equals(formatterCleanups.getFirst()) - ? Boolean.TRUE - : Boolean.FALSE); + ? Boolean.TRUE + : Boolean.FALSE); prefs.put(V6_0_CLEANUP_FIELD_FORMATTERS, String.join(OS.NEWLINE, formatterCleanups.subList(1, formatterCleanups.size() - 1))); } @@ -571,8 +571,8 @@ static void moveApiKeysToKeyring(JabRefCliPreferences preferences) { * and only then does the update. *

    * - * @implNote The default fields for the "General" tab are defined by {@link FieldFactory#getDefaultGeneralFields()}. * @param preferences the user's current preferences + * @implNote The default fields for the "General" tab are defined by {@link FieldFactory#getDefaultGeneralFields()}. */ static void addICORERankingFieldToGeneralTab(GuiPreferences preferences) { Map> entryEditorPrefs = preferences.getEntryEditorPreferences().getEntryEditorTabs(); diff --git a/jabgui/src/test/java/org/jabref/gui/autocompleter/PersonNameStringConverterTest.java b/jabgui/src/test/java/org/jabref/gui/autocompleter/PersonNameStringConverterTest.java index a2b735a81bd..7cdcbe8de7c 100644 --- a/jabgui/src/test/java/org/jabref/gui/autocompleter/PersonNameStringConverterTest.java +++ b/jabgui/src/test/java/org/jabref/gui/autocompleter/PersonNameStringConverterTest.java @@ -13,7 +13,9 @@ class PersonNameStringConverterTest { - /** The author. **/ + /** + * The author. + **/ private Author author; @BeforeEach @@ -60,9 +62,9 @@ void toStringWithoutAutoCompletePreferences(boolean autoCompFF, boolean autoComp "TRUE, BOTH, BOTH, 'Reagle, Jr., J. M.'" }) void toStringWithAutoCompletePreferences(boolean shouldAutoComplete, - AutoCompleteFirstNameMode firstNameMode, - AutoCompletePreferences.NameFormat nameFormat, - String expectedResult) { + AutoCompleteFirstNameMode firstNameMode, + AutoCompletePreferences.NameFormat nameFormat, + String expectedResult) { AutoCompletePreferences preferences = new AutoCompletePreferences( shouldAutoComplete, firstNameMode, diff --git a/jabgui/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java b/jabgui/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java index 9a4aa99cded..d2a267bef51 100644 --- a/jabgui/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java +++ b/jabgui/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java @@ -207,14 +207,22 @@ void executeOnSuccess(StandardActions action, Consumer remover, String private String expectedClipboardString(StandardActions action) { return String.join("\n", switch (action) { - case COPY_FIELD_TITLE -> titles; - case COPY_CITATION_KEY -> keys; - case COPY_DOI -> dois; - case COPY_FIELD_AUTHOR -> authors; - case COPY_FIELD_JOURNAL -> journals; - case COPY_FIELD_DATE -> dates; - case COPY_FIELD_KEYWORDS -> keywords; - case COPY_FIELD_ABSTRACT -> abstracts; + case COPY_FIELD_TITLE -> + titles; + case COPY_CITATION_KEY -> + keys; + case COPY_DOI -> + dois; + case COPY_FIELD_AUTHOR -> + authors; + case COPY_FIELD_JOURNAL -> + journals; + case COPY_FIELD_DATE -> + dates; + case COPY_FIELD_KEYWORDS -> + keywords; + case COPY_FIELD_ABSTRACT -> + abstracts; default -> throw new IllegalArgumentException("Unhandled action: " + action); }); diff --git a/jabgui/src/test/java/org/jabref/gui/edit/CopyOrMoveFieldContentTabViewModelTest.java b/jabgui/src/test/java/org/jabref/gui/edit/CopyOrMoveFieldContentTabViewModelTest.java index e8182ba5cd1..dc8b8001788 100644 --- a/jabgui/src/test/java/org/jabref/gui/edit/CopyOrMoveFieldContentTabViewModelTest.java +++ b/jabgui/src/test/java/org/jabref/gui/edit/CopyOrMoveFieldContentTabViewModelTest.java @@ -71,8 +71,8 @@ void swapValuesShouldSwapFieldValuesIfBothValuesAreNotBlank() { copyOrMoveFieldContentTabViewModel.swapValues(); assertEquals(List.of(Optional.of("2014"), Optional.of("2015")), - List.of(entryA.getField(StandardField.YEAR), entryA.getField(StandardField.DATE)), - "YEAR and DATE values didn't swap"); + List.of(entryA.getField(StandardField.YEAR), entryA.getField(StandardField.DATE)), + "YEAR and DATE values didn't swap"); } @Test diff --git a/jabgui/src/test/java/org/jabref/gui/entryeditor/FieldEditorsMultilinePropertyTest.java b/jabgui/src/test/java/org/jabref/gui/entryeditor/FieldEditorsMultilinePropertyTest.java index f98a3e48b35..db75dfbb94e 100644 --- a/jabgui/src/test/java/org/jabref/gui/entryeditor/FieldEditorsMultilinePropertyTest.java +++ b/jabgui/src/test/java/org/jabref/gui/entryeditor/FieldEditorsMultilinePropertyTest.java @@ -51,11 +51,11 @@ public static void setUp() { * 1. Use Java parser to parse FieldEditors.java and check all if statements in the getForField method. * 2. Match the conditions of if statements to extract the field properties. * 3. Match the created FieldEditor class name with field properties extracted from step 2. This creates a map where: - * - The key is the file path of the FieldEditor class (for example: ....UrlEditor.java) - * - The value is the list of properties of the FieldEditor class (for example: [FieldProperty.EXTERNAL]) + * - The key is the file path of the FieldEditor class (for example: ....UrlEditor.java) + * - The value is the list of properties of the FieldEditor class (for example: [FieldProperty.EXTERNAL]) * 4. For every class in the map, when its properties contain MULTILINE_TEXT, check whether it: - * a) Holds a TextInputControl field - * b) Has an EditorTextArea object creation + * a) Holds a TextInputControl field + * b) Has an EditorTextArea object creation */ @Test public void fieldEditorsMatchMultilineProperty() throws Exception { @@ -100,9 +100,9 @@ private static Map> getEditorsWithPropertiesInFieldEdi // Locate getForField method in FieldEditors.java MethodDeclaration getForFieldCall = cu.findAll(MethodDeclaration.class).stream() - .filter(methodDeclaration -> "getForField".equals(methodDeclaration.getNameAsString())) - .findFirst() - .orElseThrow(() -> new Exception("Failed to find getForField method in FieldEditors.java")); + .filter(methodDeclaration -> "getForField".equals(methodDeclaration.getNameAsString())) + .findFirst() + .orElseThrow(() -> new Exception("Failed to find getForField method in FieldEditors.java")); // Analyze all if statements in getForField method getForFieldCall.findAll(IfStmt.class).forEach(ifStmt -> { @@ -137,25 +137,25 @@ private static Map> getEditorsWithPropertiesInFieldEdi .map(ReturnStmt.class::cast) .findFirst() .flatMap(returnStmt -> - // Try to find the object creation in the return statement - returnStmt.stream() - .filter(ObjectCreationExpr.class::isInstance) - .map(ObjectCreationExpr.class::cast) - .findFirst()).ifPresent(creationExpr -> { - String createdClassName = creationExpr.getTypeAsString().replace("<>", ""); - cu.findAll(ImportDeclaration.class) - .stream() - .filter(importDeclaration -> importDeclaration.getNameAsString().endsWith(createdClassName)) - .findFirst() - .ifPresentOrElse(importDeclaration -> { - String classPath = importDeclaration.getNameAsString(); - Path classFilePath = Path.of("src/main/java/" + classPath.replace(".", "/") + ".java"); - result.put(classFilePath, properties); - }, () -> { - Path classFilePath = Path.of("src/main/java/org/jabref/gui/fieldeditors/" + createdClassName + ".java"); - result.put(classFilePath, properties); - }); - }); + // Try to find the object creation in the return statement + returnStmt.stream() + .filter(ObjectCreationExpr.class::isInstance) + .map(ObjectCreationExpr.class::cast) + .findFirst()).ifPresent(creationExpr -> { + String createdClassName = creationExpr.getTypeAsString().replace("<>", ""); + cu.findAll(ImportDeclaration.class) + .stream() + .filter(importDeclaration -> importDeclaration.getNameAsString().endsWith(createdClassName)) + .findFirst() + .ifPresentOrElse(importDeclaration -> { + String classPath = importDeclaration.getNameAsString(); + Path classFilePath = Path.of("src/main/java/" + classPath.replace(".", "/") + ".java"); + result.put(classFilePath, properties); + }, () -> { + Path classFilePath = Path.of("src/main/java/org/jabref/gui/fieldeditors/" + createdClassName + ".java"); + result.put(classFilePath, properties); + }); + }); }); return result; @@ -169,8 +169,8 @@ private static Map> getEditorsWithPropertiesInFieldEdi */ private static boolean implementedFieldEditorFX(CompilationUnit cu) { return cu.findAll(ClassOrInterfaceDeclaration.class).stream() - .anyMatch(classDecl -> classDecl.getImplementedTypes().stream() - .anyMatch(type -> Objects.equals("FieldEditorFX", type.getNameAsString()))); + .anyMatch(classDecl -> classDecl.getImplementedTypes().stream() + .anyMatch(type -> Objects.equals("FieldEditorFX", type.getNameAsString()))); } /** @@ -181,7 +181,7 @@ private static boolean implementedFieldEditorFX(CompilationUnit cu) { */ private static boolean hasEditorTextAreaCreationExisted(CompilationUnit cu) { return cu.findAll(ObjectCreationExpr.class).stream() - .anyMatch(creation -> Objects.equals("EditorTextArea", creation.getType().toString())); + .anyMatch(creation -> Objects.equals("EditorTextArea", creation.getType().toString())); } /** @@ -195,45 +195,45 @@ private static boolean holdTextInputControlField(CompilationUnit cu) { // establishBinding method, which should be a TextInputControl AtomicBoolean hasTextInputControlField = new AtomicBoolean(false); cu.findAll(MethodCallExpr.class) - .stream() - .filter(methodCallExpr -> "establishBinding".equals(methodCallExpr.getNameAsString())) - .findFirst() - .ifPresent(methodCallExpr -> { - if (!methodCallExpr.getArguments().isEmpty()) { - String firstArgument = methodCallExpr.getArgument(0).toString(); - cu.findAll(FieldDeclaration.class) - .stream() - .filter(fieldDeclaration -> fieldDeclaration.getVariables().stream() - .anyMatch(variableDeclarator -> variableDeclarator.getNameAsString().equals(firstArgument))) - .findFirst() - .ifPresent(fieldDeclaration -> { - String classType = fieldDeclaration.getElementType().asString(); - if ("TextInputControl".equals(classType)) { - hasTextInputControlField.set(true); - } - }); - } - }); + .stream() + .filter(methodCallExpr -> "establishBinding".equals(methodCallExpr.getNameAsString())) + .findFirst() + .ifPresent(methodCallExpr -> { + if (!methodCallExpr.getArguments().isEmpty()) { + String firstArgument = methodCallExpr.getArgument(0).toString(); + cu.findAll(FieldDeclaration.class) + .stream() + .filter(fieldDeclaration -> fieldDeclaration.getVariables().stream() + .anyMatch(variableDeclarator -> variableDeclarator.getNameAsString().equals(firstArgument))) + .findFirst() + .ifPresent(fieldDeclaration -> { + String classType = fieldDeclaration.getElementType().asString(); + if ("TextInputControl".equals(classType)) { + hasTextInputControlField.set(true); + } + }); + } + }); return hasTextInputControlField.get(); } private static boolean holdEditorTextField(CompilationUnit compilationUnit) { AtomicBoolean hasEditorTextField = new AtomicBoolean(false); compilationUnit.findAll(MethodCallExpr.class).stream() - .filter(methodCallExpr -> "establishBinding".equals(methodCallExpr.getNameAsString())) - .findFirst() - .ifPresent(establishBindingCall -> { - String firstArg = establishBindingCall.getArgument(0).toString(); - compilationUnit.findAll(FieldDeclaration.class).stream() - .filter(field -> field.getVariable(0).getNameAsString().equals(firstArg)) - .findFirst() - .ifPresent(fieldDeclaration -> { - String fieldType = fieldDeclaration.getElementType().asString(); - if ("EditorTextField".equals(fieldType)) { - hasEditorTextField.set(true); - } - }); - }); + .filter(methodCallExpr -> "establishBinding".equals(methodCallExpr.getNameAsString())) + .findFirst() + .ifPresent(establishBindingCall -> { + String firstArg = establishBindingCall.getArgument(0).toString(); + compilationUnit.findAll(FieldDeclaration.class).stream() + .filter(field -> field.getVariable(0).getNameAsString().equals(firstArg)) + .findFirst() + .ifPresent(fieldDeclaration -> { + String fieldType = fieldDeclaration.getElementType().asString(); + if ("EditorTextField".equals(fieldType)) { + hasEditorTextField.set(true); + } + }); + }); return hasEditorTextField.get(); } } diff --git a/jabgui/src/test/java/org/jabref/gui/externalfiles/AutoRenameFileOnEntryChangeTest.java b/jabgui/src/test/java/org/jabref/gui/externalfiles/AutoRenameFileOnEntryChangeTest.java index e3d9285a739..b9c6cbfd0b9 100644 --- a/jabgui/src/test/java/org/jabref/gui/externalfiles/AutoRenameFileOnEntryChangeTest.java +++ b/jabgui/src/test/java/org/jabref/gui/externalfiles/AutoRenameFileOnEntryChangeTest.java @@ -61,8 +61,8 @@ void setUp(@TempDir Path tempDir) { when(filePreferences.getFileNamePattern()).thenReturn("[bibtexkey]"); entry = new BibEntry(StandardEntryType.Article).withCitationKey("oldKey2081") - .withField(StandardField.AUTHOR, "oldKey") - .withField(StandardField.YEAR, "2081"); + .withField(StandardField.AUTHOR, "oldKey") + .withField(StandardField.YEAR, "2081"); bibDatabaseContext.getDatabase().insertEntry(entry); AutoRenameFileOnEntryChange autoRenameFileOnEntryChange = new AutoRenameFileOnEntryChange(bibDatabaseContext, guiPreferences.getFilePreferences()); diff --git a/jabgui/src/test/java/org/jabref/gui/externalfiles/FileFilterUtilsTest.java b/jabgui/src/test/java/org/jabref/gui/externalfiles/FileFilterUtilsTest.java index b746114a6ef..b76d6549bf4 100644 --- a/jabgui/src/test/java/org/jabref/gui/externalfiles/FileFilterUtilsTest.java +++ b/jabgui/src/test/java/org/jabref/gui/externalfiles/FileFilterUtilsTest.java @@ -120,40 +120,40 @@ void setUp(@TempDir Path tempDir) throws IOException { @Test void sortByDateAscendingPositiveTest() { List sortedPaths = fileFilterUtils - .sortByDateAscending(files) - .stream() - .map(Path::toString) - .collect(Collectors.toList()); + .sortByDateAscending(files) + .stream() + .map(Path::toString) + .collect(Collectors.toList()); assertEquals(sortedPaths, expectedSortByDateAscending); } @Test void sortByDateAscendingNegativeTest() { List sortedPaths = fileFilterUtils - .sortByDateAscending(files) - .stream() - .map(Path::toString) - .collect(Collectors.toList()); + .sortByDateAscending(files) + .stream() + .map(Path::toString) + .collect(Collectors.toList()); assertNotEquals(sortedPaths, wrongOrder); } @Test void sortByDateDescendingPositiveTest() { List sortedPaths = fileFilterUtils - .sortByDateDescending(files) - .stream() - .map(Path::toString) - .collect(Collectors.toList()); + .sortByDateDescending(files) + .stream() + .map(Path::toString) + .collect(Collectors.toList()); assertEquals(sortedPaths, expectedSortByDateDescending); } @Test void sortByDateDescendingNegativeTest() { List sortedPaths = fileFilterUtils - .sortByDateDescending(files) - .stream() - .map(Path::toString) - .collect(Collectors.toList()); + .sortByDateDescending(files) + .stream() + .map(Path::toString) + .collect(Collectors.toList()); assertNotEquals(sortedPaths, wrongOrder); } } diff --git a/jabgui/src/test/java/org/jabref/gui/externalfiles/ImportHandlerTest.java b/jabgui/src/test/java/org/jabref/gui/externalfiles/ImportHandlerTest.java index faa4a9845f4..7cafac1b5c1 100644 --- a/jabgui/src/test/java/org/jabref/gui/externalfiles/ImportHandlerTest.java +++ b/jabgui/src/test/java/org/jabref/gui/externalfiles/ImportHandlerTest.java @@ -39,7 +39,6 @@ class ImportHandlerTest { - private ImportHandler importHandler; private BibDatabaseContext bibDatabaseContext; private BibEntry testEntry; diff --git a/jabgui/src/test/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogViewModelTest.java b/jabgui/src/test/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogViewModelTest.java index 6225372828b..dcc9be5e2b6 100644 --- a/jabgui/src/test/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogViewModelTest.java +++ b/jabgui/src/test/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogViewModelTest.java @@ -46,8 +46,8 @@ public class UnlinkedFilesDialogViewModelTest { @Mock private BibDatabaseContext bibDatabaseContext; - private UnlinkedFilesDialogViewModel viewModel; + @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); diff --git a/jabgui/src/test/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModelTest.java b/jabgui/src/test/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModelTest.java index 166f36887b5..ed5b17854c2 100644 --- a/jabgui/src/test/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModelTest.java +++ b/jabgui/src/test/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModelTest.java @@ -41,11 +41,11 @@ void urlFieldShouldDownloadFile(@TempDir Path tempDir) { when(bibDatabaseContext.getFirstExistingFileDir(any())).thenReturn(Optional.of(tempDir)); viewModel = new LinkedFilesEditorViewModel(StandardField.FILE, new EmptySuggestionProvider(), mock(DialogService.class), bibDatabaseContext, - new CurrentThreadTaskExecutor(), mock(FieldCheckers.class), preferences, undoManager); + new CurrentThreadTaskExecutor(), mock(FieldCheckers.class), preferences, undoManager); BibEntry entry = new BibEntry().withCitationKey("test") - .withField(StandardField.URL, "https://ceur-ws.org/Vol-847/paper6.pdf"); - viewModel.entry = entry; + .withField(StandardField.URL, "https://ceur-ws.org/Vol-847/paper6.pdf"); + viewModel.entry = entry; viewModel.fetchFulltext(); assertTrue(Files.exists(tempDir.resolve("test.pdf"))); diff --git a/jabgui/src/test/java/org/jabref/gui/fieldeditors/contextmenu/ContextMenuFactoryTest.java b/jabgui/src/test/java/org/jabref/gui/fieldeditors/contextmenu/ContextMenuFactoryTest.java index 141bc6e44e5..761488c893f 100644 --- a/jabgui/src/test/java/org/jabref/gui/fieldeditors/contextmenu/ContextMenuFactoryTest.java +++ b/jabgui/src/test/java/org/jabref/gui/fieldeditors/contextmenu/ContextMenuFactoryTest.java @@ -46,7 +46,8 @@ public class ContextMenuFactoryTest { public static void initToolkit() { if (!toolkitInitialized) { try { - Platform.startup(() -> { }); + Platform.startup(() -> { + }); } catch (IllegalStateException e) { // Toolkit already initialized by another thread/test } @@ -133,12 +134,12 @@ public void removeLinkActionCallsViewModelForSingleFile() { ContextMenu menu = factory.createForSelection(files); menu.getItems().stream() - .filter(item -> { - String text = item.getText(); - return text != null && text.toLowerCase().contains("remove link"); - }) - .findFirst() - .ifPresent(item -> item.getOnAction().handle(null)); + .filter(item -> { + String text = item.getText(); + return text != null && text.toLowerCase().contains("remove link"); + }) + .findFirst() + .ifPresent(item -> item.getOnAction().handle(null)); verify(viewModel).removeFileLink(file); } @@ -152,12 +153,12 @@ public void removeLinksActionCallsViewModelForAllSelectedFiles() { ContextMenu menu = factory.createForSelection(files); menu.getItems().stream() - .filter(item -> { - String text = item.getText(); - return text != null && text.toLowerCase().contains("remove links"); - }) - .findFirst() - .ifPresent(item -> item.getOnAction().handle(null)); + .filter(item -> { + String text = item.getText(); + return text != null && text.toLowerCase().contains("remove links"); + }) + .findFirst() + .ifPresent(item -> item.getOnAction().handle(null)); verify(viewModel).removeFileLink(file1); verify(viewModel).removeFileLink(file2); diff --git a/jabgui/src/test/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModelTest.java b/jabgui/src/test/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModelTest.java index 1d7f94d11d1..ba933f63530 100644 --- a/jabgui/src/test/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModelTest.java +++ b/jabgui/src/test/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModelTest.java @@ -40,8 +40,8 @@ void falseQueryValidationStatus() { assertFalse(viewModel.queryValidationStatus().validProperty().getValue()); } - @Test - void correctQueryValidationStatus() { + @Test + void correctQueryValidationStatus() { viewModel.queryProperty().setValue("Miami AND Beach OR Houston AND Texas"); assertTrue(viewModel.queryValidationStatus().validProperty().getValue()); } diff --git a/jabgui/src/test/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModelTest.java b/jabgui/src/test/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModelTest.java index f914a5f9468..b2334cfada2 100644 --- a/jabgui/src/test/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModelTest.java +++ b/jabgui/src/test/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModelTest.java @@ -37,9 +37,9 @@ void stringsListPropertySorting() { model.setValues(); List actual = model.stringsListProperty().stream() - .map(ConstantsItemModel::labelProperty) - .map(StringProperty::getValue) - .toList(); + .map(ConstantsItemModel::labelProperty) + .map(StringProperty::getValue) + .toList(); assertEquals(expected, actual); } @@ -61,9 +61,9 @@ void stringsListPropertyResorting() { model.resortStrings(); List actual = model.stringsListProperty().stream() - .map(ConstantsItemModel::labelProperty) - .map(StringProperty::getValue) - .toList(); + .map(ConstantsItemModel::labelProperty) + .map(StringProperty::getValue) + .toList(); assertEquals(expected, actual); } diff --git a/jabgui/src/test/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FileMergerTest.java b/jabgui/src/test/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FileMergerTest.java index 653806fa1ce..0ee34ba2c70 100644 --- a/jabgui/src/test/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FileMergerTest.java +++ b/jabgui/src/test/java/org/jabref/gui/mergeentries/threewaymerge/fieldsmerger/FileMergerTest.java @@ -16,8 +16,8 @@ class FileMergerTest { * FileA and FileB are valid strings and are separated by semicolon * * @param expect Expected value - * @param fileA File string a - * @param fileB File String b + * @param fileA File string a + * @param fileB File String b */ @ParameterizedTest @CsvSource(textBlock = """ diff --git a/jabgui/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java b/jabgui/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java index 6c89ff98e0e..f58af6d8b9f 100644 --- a/jabgui/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java +++ b/jabgui/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java @@ -92,9 +92,9 @@ public String toString() { } private static String csvListOfAbbreviations(List testAbbreviations) { - return testAbbreviations.stream() - .map(TestAbbreviation::toString) - .collect(Collectors.joining("\n")); + return testAbbreviations.stream() + .map(TestAbbreviation::toString) + .collect(Collectors.joining("\n")); } private static String csvListOfAbbreviations(TestAbbreviation... testAbbreviations) { diff --git a/jabgui/src/test/java/org/jabref/gui/util/ControlHelperTest.java b/jabgui/src/test/java/org/jabref/gui/util/ControlHelperTest.java index 291893af7d1..d29f052bc09 100644 --- a/jabgui/src/test/java/org/jabref/gui/util/ControlHelperTest.java +++ b/jabgui/src/test/java/org/jabref/gui/util/ControlHelperTest.java @@ -52,8 +52,8 @@ void truncateWithDefaultMaxCharactersAndNullEllipsisAndPositionEndingReturnsTrun @NullSource void truncateWithNullEllipsisPositionThrowsNullPointerException(ControlHelper.EllipsisPosition ellipsisPosition) { assertThrows( - NullPointerException.class, - () -> ControlHelper.truncateString(TEXT, MAX_CHARACTERS, ELLIPSIS_STRING, ellipsisPosition) + NullPointerException.class, + () -> ControlHelper.truncateString(TEXT, MAX_CHARACTERS, ELLIPSIS_STRING, ellipsisPosition) ); } } diff --git a/jabgui/src/test/java/org/jabref/gui/util/IconValidationDecoratorTest.java b/jabgui/src/test/java/org/jabref/gui/util/IconValidationDecoratorTest.java index 620171c5488..b1dcb231b1d 100644 --- a/jabgui/src/test/java/org/jabref/gui/util/IconValidationDecoratorTest.java +++ b/jabgui/src/test/java/org/jabref/gui/util/IconValidationDecoratorTest.java @@ -17,7 +17,7 @@ @ExtendWith(ApplicationExtension.class) public class IconValidationDecoratorTest { static Object[][] decorationTestData() { - return new Object[][]{ + return new Object[][] { {Severity.ERROR, IconTheme.JabRefIcons.ERROR.getGraphicNode().toString()}, {Severity.WARNING, IconTheme.JabRefIcons.WARNING.getGraphicNode().toString()} }; diff --git a/jabgui/src/test/java/org/jabref/logic/journals_gui/JournalAbbreviationRepositoryTest.java b/jabgui/src/test/java/org/jabref/logic/journals_gui/JournalAbbreviationRepositoryTest.java index 5243f85effd..17fdb213e0b 100644 --- a/jabgui/src/test/java/org/jabref/logic/journals_gui/JournalAbbreviationRepositoryTest.java +++ b/jabgui/src/test/java/org/jabref/logic/journals_gui/JournalAbbreviationRepositoryTest.java @@ -213,7 +213,7 @@ void journalAbbreviateWithoutEscapedAmpersand() { UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(repository, AbbreviationType.DEFAULT, false); BibEntry entryWithoutEscapedAmpersandInJournal = new BibEntry(StandardEntryType.Article) - .withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces"); + .withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces"); undoableAbbreviator.abbreviate(bibDatabase, entryWithoutEscapedAmpersandInJournal, StandardField.JOURNAL, new CompoundEdit()); BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) @@ -226,8 +226,8 @@ void journalAbbreviateWithEmptyFJournal() { UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(repository, AbbreviationType.DEFAULT, true); BibEntry entryWithoutEscapedAmpersandInJournal = new BibEntry(StandardEntryType.Article) - .withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces") - .withField(AMSField.FJOURNAL, " "); + .withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces") + .withField(AMSField.FJOURNAL, " "); undoableAbbreviator.abbreviate(bibDatabase, entryWithoutEscapedAmpersandInJournal, StandardField.JOURNAL, new CompoundEdit()); BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) @@ -239,7 +239,7 @@ void journalAbbreviateWithEmptyFJournal() { @Test void unabbreviateWithJournalExistsAndFJournalNot() { BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) - .withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces"); + .withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces"); undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit()); BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) @@ -250,8 +250,8 @@ void unabbreviateWithJournalExistsAndFJournalNot() { @Test void unabbreviateWithJournalExistsAndFJournalExists() { BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) - .withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces") - .withField(AMSField.FJOURNAL, "ACS Applied Materials & Interfaces"); + .withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces") + .withField(AMSField.FJOURNAL, "ACS Applied Materials & Interfaces"); undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit()); BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article) diff --git a/jabgui/src/test/java/org/jabref/migrations/GuiPreferencesMigrationsTest.java b/jabgui/src/test/java/org/jabref/migrations/GuiPreferencesMigrationsTest.java index 73bcaf23187..a6bcc5e5318 100644 --- a/jabgui/src/test/java/org/jabref/migrations/GuiPreferencesMigrationsTest.java +++ b/jabgui/src/test/java/org/jabref/migrations/GuiPreferencesMigrationsTest.java @@ -29,9 +29,9 @@ class GuiPreferencesMigrationsTest { private JabRefGuiPreferences preferences; private Preferences mainPrefsNode; - private final String[] oldStylePatterns = new String[]{"\\bibtexkey", + private final String[] oldStylePatterns = new String[] {"\\bibtexkey", "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; - private final String[] newStylePatterns = new String[]{"[citationkey]", + private final String[] newStylePatterns = new String[] {"[citationkey]", "[citationkey] - [title]"}; @BeforeEach diff --git a/jabkit/src/main/java/org/jabref/cli/ArgumentProcessor.java b/jabkit/src/main/java/org/jabref/cli/ArgumentProcessor.java index e48b5e4c197..bf396e0ed81 100644 --- a/jabkit/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/jabkit/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -156,9 +156,9 @@ protected static void saveDatabase(CliPreferences cliPreferences, } protected static void saveDatabaseContext(CliPreferences cliPreferences, - BibEntryTypesManager entryTypesManager, - BibDatabaseContext bibDatabaseContext, - Path outputFile) { + BibEntryTypesManager entryTypesManager, + BibDatabaseContext bibDatabaseContext, + Path outputFile) { try { if (!FileUtil.isBibFile(outputFile)) { System.err.println(Localization.lang("Invalid output file type provided.")); diff --git a/jabkit/src/main/java/org/jabref/cli/CheckIntegrity.java b/jabkit/src/main/java/org/jabref/cli/CheckIntegrity.java index b74ed7e42b0..368f6d731fb 100644 --- a/jabkit/src/main/java/org/jabref/cli/CheckIntegrity.java +++ b/jabkit/src/main/java/org/jabref/cli/CheckIntegrity.java @@ -85,8 +85,8 @@ public Integer call() { ); List messages = databaseContext.getEntries().stream() - .flatMap(entry -> integrityCheck.checkEntry(entry).stream()) - .collect(Collectors.toList()); + .flatMap(entry -> integrityCheck.checkEntry(entry).stream()) + .collect(Collectors.toList()); messages.addAll(integrityCheck.checkDatabase(databaseContext.getDatabase())); diff --git a/jabkit/src/main/java/org/jabref/cli/Convert.java b/jabkit/src/main/java/org/jabref/cli/Convert.java index 59617349f28..dec3d2bd555 100644 --- a/jabkit/src/main/java/org/jabref/cli/Convert.java +++ b/jabkit/src/main/java/org/jabref/cli/Convert.java @@ -110,9 +110,9 @@ protected void exportFile(@NonNull ParserResult parserResult, @NonNull Path outp fileDirForDatabase, Injector.instantiateModelOrService(JournalAbbreviationRepository.class)); } catch (IOException - | SaveException - | ParserConfigurationException - | TransformerException ex) { + | SaveException + | ParserConfigurationException + | TransformerException ex) { LOGGER.error("Could not export file '{}'.", outputFile, ex); } } diff --git a/jabkit/src/main/java/org/jabref/cli/Fetch.java b/jabkit/src/main/java/org/jabref/cli/Fetch.java index 7c405211aaf..21d870dd2e4 100644 --- a/jabkit/src/main/java/org/jabref/cli/Fetch.java +++ b/jabkit/src/main/java/org/jabref/cli/Fetch.java @@ -25,7 +25,8 @@ class Fetch implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Fetch.class); - record Provider(String name, String query) { } + record Provider(String name, String query) { + } @ParentCommand private ArgumentProcessor argumentProcessor; diff --git a/jabkit/src/test/java/org/jabref/cli/ArgumentProcessorTest.java b/jabkit/src/test/java/org/jabref/cli/ArgumentProcessorTest.java index 783dc3a2da1..bd53c472cbd 100644 --- a/jabkit/src/test/java/org/jabref/cli/ArgumentProcessorTest.java +++ b/jabkit/src/test/java/org/jabref/cli/ArgumentProcessorTest.java @@ -117,7 +117,7 @@ void convertBibtexToTableRefsAsBib(@TempDir Path tempDir) throws URISyntaxExcept Path outputHtml = tempDir.resolve("output.html").toAbsolutePath(); String outputHtmlFile = outputHtml.toAbsolutePath().toString(); - when(importerPreferences.getCustomImporters()) .thenReturn(FXCollections.emptyObservableSet()); + when(importerPreferences.getCustomImporters()).thenReturn(FXCollections.emptyObservableSet()); SaveOrder saveOrder = new SaveOrder(SaveOrder.OrderType.TABLE, List.of()); ExportPreferences exportPreferences = new ExportPreferences(".html", tempDir, saveOrder, List.of()); diff --git a/jablib/src/main/java/org/jabref/logic/FilePreferences.java b/jablib/src/main/java/org/jabref/logic/FilePreferences.java index 4ff1e5fdb3e..5c1b301a250 100644 --- a/jablib/src/main/java/org/jabref/logic/FilePreferences.java +++ b/jablib/src/main/java/org/jabref/logic/FilePreferences.java @@ -13,7 +13,7 @@ import org.jabref.model.strings.StringUtil; /** - * Preferences for the linked files + * Preferences for the linked files */ public class FilePreferences { diff --git a/jablib/src/main/java/org/jabref/logic/InternalPreferences.java b/jablib/src/main/java/org/jabref/logic/InternalPreferences.java index dcd3607e16f..7583fd7083d 100644 --- a/jablib/src/main/java/org/jabref/logic/InternalPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/InternalPreferences.java @@ -75,7 +75,7 @@ public String getUserAndHost() { public StringProperty getUserAndHostProperty() { return userAndHost; } - + /** * Returns the user and host information as a UserHostInfo object. * @@ -84,7 +84,7 @@ public StringProperty getUserAndHostProperty() { public UserHostInfo getUserHostInfo() { return UserHostInfo.parse(getUserAndHost()); } - + /** * Sets the user and host information from a UserHostInfo object. * diff --git a/jablib/src/main/java/org/jabref/logic/UiCommand.java b/jablib/src/main/java/org/jabref/logic/UiCommand.java index a37f9851d66..fd7a5459b53 100644 --- a/jablib/src/main/java/org/jabref/logic/UiCommand.java +++ b/jablib/src/main/java/org/jabref/logic/UiCommand.java @@ -4,21 +4,28 @@ import java.util.List; public sealed interface UiCommand { - record BlankWorkspace() implements UiCommand { } + record BlankWorkspace() implements UiCommand { + } - record JumpToEntryKey(String citationKey) implements UiCommand { } + record JumpToEntryKey(String citationKey) implements UiCommand { + } - record OpenLibraries(List toImport) implements UiCommand { } + record OpenLibraries(List toImport) implements UiCommand { + } - record AppendToCurrentLibrary(List toAppend) implements UiCommand { } + record AppendToCurrentLibrary(List toAppend) implements UiCommand { + } - record Focus() implements UiCommand { } + record Focus() implements UiCommand { + } /// @deprecated used by the browser extension only @Deprecated - record AppendBibTeXToCurrentLibrary(String bibtex) implements UiCommand { } + record AppendBibTeXToCurrentLibrary(String bibtex) implements UiCommand { + } /// @deprecated used by the browser extension only @Deprecated - record AppendFileOrUrlToCurrentLibrary(String location) implements UiCommand { } + record AppendFileOrUrlToCurrentLibrary(String location) implements UiCommand { + } } diff --git a/jablib/src/main/java/org/jabref/logic/ai/AiDefaultPreferences.java b/jablib/src/main/java/org/jabref/logic/ai/AiDefaultPreferences.java index eaba71f44c5..ab656de2bca 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/AiDefaultPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/ai/AiDefaultPreferences.java @@ -102,15 +102,15 @@ public String toString() { #end""", AiTemplate.SUMMARIZATION_CHUNK_SYSTEM_MESSAGE, """ - Please provide an overview of the following text. It is a part of a scientific paper. - The summary should include the main objectives, methodologies used, key findings, and conclusions. - Mention any significant experiments, data, or discussions presented in the paper.""", + Please provide an overview of the following text. It is a part of a scientific paper. + The summary should include the main objectives, methodologies used, key findings, and conclusions. + Mention any significant experiments, data, or discussions presented in the paper.""", AiTemplate.SUMMARIZATION_CHUNK_USER_MESSAGE, "$text", AiTemplate.SUMMARIZATION_COMBINE_SYSTEM_MESSAGE, """ - You have written an overview of a scientific paper. You have been collecting notes from various parts - of the paper. Now your task is to combine all of the notes in one structured message.""", + You have written an overview of a scientific paper. You have been collecting notes from various parts + of the paper. Now your task is to combine all of the notes in one structured message.""", AiTemplate.SUMMARIZATION_COMBINE_USER_MESSAGE, "$chunks", diff --git a/jablib/src/main/java/org/jabref/logic/ai/AiPreferences.java b/jablib/src/main/java/org/jabref/logic/ai/AiPreferences.java index a6214b2fe83..42c3df7ba4b 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/AiPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/ai/AiPreferences.java @@ -377,11 +377,16 @@ public int getContextWindowSize() { return contextWindowSize.get(); } else { return switch (aiProvider.get()) { - case OPEN_AI -> AiDefaultPreferences.getContextWindowSize(AiProvider.OPEN_AI, openAiChatModel.get()); - case MISTRAL_AI -> AiDefaultPreferences.getContextWindowSize(AiProvider.MISTRAL_AI, mistralAiChatModel.get()); - case HUGGING_FACE -> AiDefaultPreferences.getContextWindowSize(AiProvider.HUGGING_FACE, huggingFaceChatModel.get()); - case GEMINI -> AiDefaultPreferences.getContextWindowSize(AiProvider.GEMINI, geminiChatModel.get()); - case GPT4ALL -> AiDefaultPreferences.getContextWindowSize(AiProvider.GPT4ALL, gpt4AllChatModel.get()); + case OPEN_AI -> + AiDefaultPreferences.getContextWindowSize(AiProvider.OPEN_AI, openAiChatModel.get()); + case MISTRAL_AI -> + AiDefaultPreferences.getContextWindowSize(AiProvider.MISTRAL_AI, mistralAiChatModel.get()); + case HUGGING_FACE -> + AiDefaultPreferences.getContextWindowSize(AiProvider.HUGGING_FACE, huggingFaceChatModel.get()); + case GEMINI -> + AiDefaultPreferences.getContextWindowSize(AiProvider.GEMINI, geminiChatModel.get()); + case GPT4ALL -> + AiDefaultPreferences.getContextWindowSize(AiProvider.GPT4ALL, gpt4AllChatModel.get()); }; } } diff --git a/jablib/src/main/java/org/jabref/logic/ai/AiService.java b/jablib/src/main/java/org/jabref/logic/ai/AiService.java index ff80b8f9fde..9e8d864275f 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/AiService.java +++ b/jablib/src/main/java/org/jabref/logic/ai/AiService.java @@ -27,9 +27,9 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; /** - * The main class for the AI functionality. - *

    - * Holds all the AI components: LLM and embedding model, chat history and embeddings cache. + * The main class for the AI functionality. + *

    + * Holds all the AI components: LLM and embedding model, chat history and embeddings cache. */ public class AiService implements AutoCloseable { public static final String VERSION = "1"; diff --git a/jablib/src/main/java/org/jabref/logic/ai/chatting/AiChatService.java b/jablib/src/main/java/org/jabref/logic/ai/chatting/AiChatService.java index ff70f91df3a..5506fe4a975 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/chatting/AiChatService.java +++ b/jablib/src/main/java/org/jabref/logic/ai/chatting/AiChatService.java @@ -22,10 +22,10 @@ public class AiChatService { private final AiTemplatesService aiTemplatesService; public AiChatService(AiPreferences aiPreferences, - ChatModel chatLanguageModel, - EmbeddingModel embeddingModel, - EmbeddingStore embeddingStore, - AiTemplatesService aiTemplatesService + ChatModel chatLanguageModel, + EmbeddingModel embeddingModel, + EmbeddingStore embeddingStore, + AiTemplatesService aiTemplatesService ) { this.aiPreferences = aiPreferences; this.chatLanguageModel = chatLanguageModel; diff --git a/jablib/src/main/java/org/jabref/logic/ai/chatting/ChatHistoryService.java b/jablib/src/main/java/org/jabref/logic/ai/chatting/ChatHistoryService.java index 37482d76579..0a1de1274a1 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/chatting/ChatHistoryService.java +++ b/jablib/src/main/java/org/jabref/logic/ai/chatting/ChatHistoryService.java @@ -53,7 +53,8 @@ public class ChatHistoryService implements AutoCloseable { // Note about `Optional`: it was necessary in previous version, but currently we never save an `Optional.empty()`. // However, we decided to left it here: to reduce migrations and to make possible to chat with a {@link BibEntry} without {@link BibDatabaseContext} // ({@link BibDatabaseContext} is required only for load/store of the chat). - private record ChatHistoryManagementRecord(Optional bibDatabaseContext, ObservableList chatHistory) { } + private record ChatHistoryManagementRecord(Optional bibDatabaseContext, ObservableList chatHistory) { + } // We use a {@link TreeMap} here to store {@link BibEntry} chat histories by their id. // When you compare {@link BibEntry} instances, they are compared by value, not by reference. @@ -71,19 +72,19 @@ public ChatHistoryService(CitationKeyPatternPreferences citationKeyPatternPrefer public void setupDatabase(BibDatabaseContext bibDatabaseContext) { bibDatabaseContext.getMetaData().getGroups().ifPresent(rootGroupTreeNode -> - rootGroupTreeNode.iterateOverTree().forEach(groupNode -> { - groupNode.getGroup().nameProperty().addListener((observable, oldValue, newValue) -> { - if (newValue != null && oldValue != null) { - transferGroupHistory(bibDatabaseContext, groupNode, oldValue, newValue); - } - }); - - groupNode.getGroupProperty().addListener((obs, oldValue, newValue) -> { - if (oldValue != null && newValue != null) { - transferGroupHistory(bibDatabaseContext, groupNode, oldValue.getName(), newValue.getName()); - } - }); - })); + rootGroupTreeNode.iterateOverTree().forEach(groupNode -> { + groupNode.getGroup().nameProperty().addListener((observable, oldValue, newValue) -> { + if (newValue != null && oldValue != null) { + transferGroupHistory(bibDatabaseContext, groupNode, oldValue, newValue); + } + }); + + groupNode.getGroupProperty().addListener((obs, oldValue, newValue) -> { + if (oldValue != null && newValue != null) { + transferGroupHistory(bibDatabaseContext, groupNode, oldValue.getName(), newValue.getName()); + } + }); + })); bibDatabaseContext.getDatabase().getEntries().forEach(entry -> entry.registerListener(new CitationKeyChangeListener(bibDatabaseContext))); } diff --git a/jablib/src/main/java/org/jabref/logic/ai/chatting/model/Gpt4AllModel.java b/jablib/src/main/java/org/jabref/logic/ai/chatting/model/Gpt4AllModel.java index eaa0c96ff37..7b1eccf9943 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/chatting/model/Gpt4AllModel.java +++ b/jablib/src/main/java/org/jabref/logic/ai/chatting/model/Gpt4AllModel.java @@ -42,13 +42,18 @@ public ChatResponse chat(List list) { LOGGER.debug("Generating response from Gpt4All model with {} messages: {}", list.size(), list); List messages = list.stream() - .map(chatMessage -> switch (chatMessage) { - case AiMessage aiMessage -> new Message("assistant", aiMessage.text()); - case SystemMessage systemMessage -> new Message("system", systemMessage.text()); - case ToolExecutionResultMessage toolExecutionResultMessage -> new Message("tool", toolExecutionResultMessage.text()); - case UserMessage userMessage -> new Message("user", userMessage.singleText()); - default -> throw new IllegalStateException("Unknown ChatMessage type: " + chatMessage); - }).collect(Collectors.toList()); + .map(chatMessage -> switch (chatMessage) { + case AiMessage aiMessage -> + new Message("assistant", aiMessage.text()); + case SystemMessage systemMessage -> + new Message("system", systemMessage.text()); + case ToolExecutionResultMessage toolExecutionResultMessage -> + new Message("tool", toolExecutionResultMessage.text()); + case UserMessage userMessage -> + new Message("user", userMessage.singleText()); + default -> + throw new IllegalStateException("Unknown ChatMessage type: " + chatMessage); + }).collect(Collectors.toList()); TextGenerationRequest request = TextGenerationRequest .builder() @@ -63,11 +68,11 @@ public ChatResponse chat(List list) { String baseUrl = aiPreferences.getSelectedApiBaseUrl(); String fullUrl = baseUrl.endsWith("/") ? baseUrl + "chat/completions" : baseUrl + "/chat/completions"; HttpRequest httpRequest = HttpRequest.newBuilder() - .uri(URLUtil.createUri(fullUrl)) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(requestBody)) - .timeout(Duration.ofMinutes(1)) - .build(); + .uri(URLUtil.createUri(fullUrl)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(requestBody)) + .timeout(Duration.ofMinutes(1)) + .build(); HttpResponse response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); LOGGER.info("Gpt4All response: {}", response.body()); @@ -144,9 +149,12 @@ public TextGenerationRequest build() { } } - private record TextGenerationResponse(List choices) { } + private record TextGenerationResponse(List choices) { + } - private record Choice(Message message) { } + private record Choice(Message message) { + } - private record Message(String role, String content) { } + private record Message(String role, String content) { + } } diff --git a/jablib/src/main/java/org/jabref/logic/ai/chatting/model/JabRefChatLanguageModel.java b/jablib/src/main/java/org/jabref/logic/ai/chatting/model/JabRefChatLanguageModel.java index f31e8a6e84a..f809b8f7369 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/chatting/model/JabRefChatLanguageModel.java +++ b/jablib/src/main/java/org/jabref/logic/ai/chatting/model/JabRefChatLanguageModel.java @@ -60,20 +60,23 @@ private void rebuild() { } switch (aiPreferences.getAiProvider()) { - case OPEN_AI -> langchainChatModel = Optional.of(new JvmOpenAiChatLanguageModel(aiPreferences, httpClient)); - - case GPT4ALL-> langchainChatModel = Optional.of(new Gpt4AllModel(aiPreferences, httpClient)); - - case MISTRAL_AI -> langchainChatModel = Optional.of(MistralAiChatModel - .builder() - .apiKey(apiKey) - .modelName(aiPreferences.getSelectedChatModel()) - .temperature(aiPreferences.getTemperature()) - .baseUrl(aiPreferences.getSelectedApiBaseUrl()) - .logRequests(true) - .logResponses(true) - .build() - ); + case OPEN_AI -> + langchainChatModel = Optional.of(new JvmOpenAiChatLanguageModel(aiPreferences, httpClient)); + + case GPT4ALL -> + langchainChatModel = Optional.of(new Gpt4AllModel(aiPreferences, httpClient)); + + case MISTRAL_AI -> + langchainChatModel = Optional.of(MistralAiChatModel + .builder() + .apiKey(apiKey) + .modelName(aiPreferences.getSelectedChatModel()) + .temperature(aiPreferences.getTemperature()) + .baseUrl(aiPreferences.getSelectedApiBaseUrl()) + .logRequests(true) + .logResponses(true) + .build() + ); case GEMINI -> // NOTE: {@link GoogleAiGeminiChatModel} doesn't support API base url. langchainChatModel = Optional.of(GoogleAiGeminiChatModel diff --git a/jablib/src/main/java/org/jabref/logic/ai/ingestion/LowLevelIngestor.java b/jablib/src/main/java/org/jabref/logic/ai/ingestion/LowLevelIngestor.java index 7bec5a6546a..3138dcf424b 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/ingestion/LowLevelIngestor.java +++ b/jablib/src/main/java/org/jabref/logic/ai/ingestion/LowLevelIngestor.java @@ -38,7 +38,7 @@ public LowLevelIngestor(AiPreferences aiPreferences, EmbeddingStore private void rebuild() { this.documentSplitter = DocumentSplitters .recursive(aiPreferences.getDocumentSplitterChunkSize(), - aiPreferences.getDocumentSplitterOverlapSize()); + aiPreferences.getDocumentSplitterOverlapSize()); this.ingestor = EmbeddingStoreIngestor .builder() @@ -57,7 +57,7 @@ private void setupListeningToPreferencesChanges() { * Add document to embedding store. * This method does not check if file was already ingested. * - * @param document - document to add. + * @param document - document to add. * @param stopProperty - in case you want to stop the ingestion process, set this property to true. */ public void ingestDocument(Document document, ReadOnlyBooleanProperty stopProperty, IntegerProperty workDone, IntegerProperty workMax) throws InterruptedException { diff --git a/jablib/src/main/java/org/jabref/logic/ai/ingestion/MVStoreEmbeddingStore.java b/jablib/src/main/java/org/jabref/logic/ai/ingestion/MVStoreEmbeddingStore.java index e4fdedb9e3e..70446cee9ab 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/ingestion/MVStoreEmbeddingStore.java +++ b/jablib/src/main/java/org/jabref/logic/ai/ingestion/MVStoreEmbeddingStore.java @@ -45,7 +45,8 @@ */ public class MVStoreEmbeddingStore extends MVStoreBase implements EmbeddingStore { // `file` field is nullable, because {@link Optional} can't be serialized. - private record EmbeddingRecord(@Nullable String file, String content, float[] embeddingVector) implements Serializable { } + private record EmbeddingRecord(@Nullable String file, String content, float[] embeddingVector) implements Serializable { + } private static final String EMBEDDINGS_MAP_NAME = "embeddings"; @@ -115,7 +116,6 @@ public void removeAll() { /// - [IsEqualTo] with key [FileEmbeddingsManager#LINK_METADATA_KEY] /// /// @param request embedding search request - /// /// @return an [EmbeddingSearchResult], which contains most relevant text segments @Override public EmbeddingSearchResult search(EmbeddingSearchRequest request) { @@ -160,7 +160,8 @@ public void removeAll(Collection ids) { private Stream applyFilter(@Nullable Filter filter) { return switch (filter) { - case null -> embeddingsMap.keySet().stream(); + case null -> + embeddingsMap.keySet().stream(); case IsIn isInFilter when Objects.equals(isInFilter.key(), LINK_METADATA_KEY) -> filterEntries(entry -> isInFilter.comparisonValues().contains(entry.getValue().file)); @@ -168,7 +169,8 @@ private Stream applyFilter(@Nullable Filter filter) { case IsEqualTo isEqualToFilter when Objects.equals(isEqualToFilter.key(), LINK_METADATA_KEY) -> filterEntries(entry -> isEqualToFilter.comparisonValue().equals(entry.getValue().file)); - default -> throw new IllegalArgumentException("Wrong filter passed to MVStoreEmbeddingStore"); + default -> + throw new IllegalArgumentException("Wrong filter passed to MVStoreEmbeddingStore"); }; } diff --git a/jablib/src/main/java/org/jabref/logic/ai/ingestion/model/JabRefEmbeddingModel.java b/jablib/src/main/java/org/jabref/logic/ai/ingestion/model/JabRefEmbeddingModel.java index 526ade268d1..b203ed92df9 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/ingestion/model/JabRefEmbeddingModel.java +++ b/jablib/src/main/java/org/jabref/logic/ai/ingestion/model/JabRefEmbeddingModel.java @@ -43,9 +43,11 @@ public class JabRefEmbeddingModel implements EmbeddingModel, AutoCloseable { // Used to update the tab content after the data is available private final EventBus eventBus = new EventBus(); - public static class EmbeddingModelBuiltEvent { } + public static class EmbeddingModelBuiltEvent { + } - public static class EmbeddingModelBuildingErrorEvent { } + public static class EmbeddingModelBuildingErrorEvent { + } // Empty if there is no error. private String errorWhileBuildingModel = ""; diff --git a/jablib/src/main/java/org/jabref/logic/ai/summarization/Summary.java b/jablib/src/main/java/org/jabref/logic/ai/summarization/Summary.java index f96ab60a6f6..4177af34c71 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/summarization/Summary.java +++ b/jablib/src/main/java/org/jabref/logic/ai/summarization/Summary.java @@ -5,4 +5,5 @@ import org.jabref.model.ai.AiProvider; -public record Summary(LocalDateTime timestamp, AiProvider aiProvider, String model, String content) implements Serializable { } +public record Summary(LocalDateTime timestamp, AiProvider aiProvider, String model, String content) implements Serializable { +} diff --git a/jablib/src/main/java/org/jabref/logic/ai/templates/PaperExcerpt.java b/jablib/src/main/java/org/jabref/logic/ai/templates/PaperExcerpt.java index b8fbf810650..ac4743c5c9b 100644 --- a/jablib/src/main/java/org/jabref/logic/ai/templates/PaperExcerpt.java +++ b/jablib/src/main/java/org/jabref/logic/ai/templates/PaperExcerpt.java @@ -1,3 +1,4 @@ package org.jabref.logic.ai.templates; -public record PaperExcerpt(String citationKey, String text) { } +public record PaperExcerpt(String citationKey, String text) { +} diff --git a/jablib/src/main/java/org/jabref/logic/auxparser/DefaultAuxParser.java b/jablib/src/main/java/org/jabref/logic/auxparser/DefaultAuxParser.java index ffb06b2015c..11b1e4aac7f 100644 --- a/jablib/src/main/java/org/jabref/logic/auxparser/DefaultAuxParser.java +++ b/jablib/src/main/java/org/jabref/logic/auxparser/DefaultAuxParser.java @@ -23,10 +23,10 @@ *

    * Extracts a subset of BibTeX entries from a BibDatabase that are included in an AUX file. Also supports nested AUX * files (latex \\include). - * + *

    * There exists no specification of the AUX file. Every package, class or document can write to the AUX file. The AUX * file consists of LaTeX macros and is read at the \begin{document} and again at the \end{document}. - * + *

    * BibTeX citation: \citation{x,y,z} Biblatex citation: \abx@aux@cite{x,y,z} Nested AUX files: \@input{x} */ public class DefaultAuxParser implements AuxParser { @@ -145,7 +145,7 @@ private void resolveTags(AuxParserResult result) { * Resolves and adds CrossRef entries to insert them in addition to the original entries * * @param entries Entries to check for CrossRefs - * @param result AUX file + * @param result AUX file */ private void resolveCrossReferences(List entries, AuxParserResult result) { List entriesToInsert = new ArrayList<>(); @@ -172,7 +172,7 @@ private void resolveCrossReferences(List entries, AuxParserResult resu * Insert a clone of each given entry. The clones are each given a new unique ID. * * @param entries Entries to be cloned - * @param result the parser result (representing the AUX file) + * @param result the parser result (representing the AUX file) */ private void insertEntries(List entries, AuxParserResult result) { List clonedEntries = new ArrayList<>(); diff --git a/jablib/src/main/java/org/jabref/logic/biblog/BibtexLogParser.java b/jablib/src/main/java/org/jabref/logic/biblog/BibtexLogParser.java index 65b6f0d7b5a..d1809befdee 100644 --- a/jablib/src/main/java/org/jabref/logic/biblog/BibtexLogParser.java +++ b/jablib/src/main/java/org/jabref/logic/biblog/BibtexLogParser.java @@ -46,7 +46,6 @@ public List parseBiblog(@NonNull Path blgFilePath) throws IOExceptio /// For example: `Biber.pm:123> WARN - Datamodel: article entry 'Scholey_2013' (file.bib): Invalid field 'journal'` /// /// @param line The single line from the .blg file to parse. - /// /// @returns An `Optional` containing a `BibWarning` if a match is found, or an empty `Optional` otherwise. Optional parseWarningLine(String line) { Matcher bibtexMatcher = BIBTEX_WARNING_PATTERN.matcher(line); diff --git a/jablib/src/main/java/org/jabref/logic/bibtex/FieldWriter.java b/jablib/src/main/java/org/jabref/logic/bibtex/FieldWriter.java index b069b307fe5..658291c2bd5 100644 --- a/jablib/src/main/java/org/jabref/logic/bibtex/FieldWriter.java +++ b/jablib/src/main/java/org/jabref/logic/bibtex/FieldWriter.java @@ -76,7 +76,6 @@ private static void checkBraces(String text) throws InvalidFieldValueException { * @param field the name of the field - used to trigger different serializations, e.g., turning off resolution for some strings * @param content the content of the field * @return a formatted string suitable for output - * * @throws InvalidFieldValueException if content is not a correct bibtex string, e.g., because of improperly balanced braces or using # not paired */ public String write(Field field, String content) throws InvalidFieldValueException { diff --git a/jablib/src/main/java/org/jabref/logic/bibtex/InvalidFieldValueException.java b/jablib/src/main/java/org/jabref/logic/bibtex/InvalidFieldValueException.java index 3084934bcda..a866ba8dbd2 100644 --- a/jablib/src/main/java/org/jabref/logic/bibtex/InvalidFieldValueException.java +++ b/jablib/src/main/java/org/jabref/logic/bibtex/InvalidFieldValueException.java @@ -2,8 +2,8 @@ /** * @deprecated Use only if you know what you are doing. - * Otherwise, you should implement your functionality as {@link org.jabref.logic.integrity.IntegrityCheck} instead. - * The JabRef team leaves the {@code @deprecated} annotation to have IntelliJ listing this method with a strike-through. + * Otherwise, you should implement your functionality as {@link org.jabref.logic.integrity.IntegrityCheck} instead. + * The JabRef team leaves the {@code @deprecated} annotation to have IntelliJ listing this method with a strike-through. */ @Deprecated public class InvalidFieldValueException extends Exception { diff --git a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/BibEntryCompare.java b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/BibEntryCompare.java index c53a92e8be2..f2601d8633b 100644 --- a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/BibEntryCompare.java +++ b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/BibEntryCompare.java @@ -52,11 +52,11 @@ private static boolean isSubSet(BibEntry candidateSubSet, BibEntry candidateSupe } private static boolean isSubSet(BibEntry candidateSubSet, BibEntry candidateSuperSet, Collection fields) { - for (Field field: fields) { + for (Field field : fields) { String subValue = candidateSubSet.getField(field).get(); boolean isEqualValue = candidateSuperSet.getField(field) - .filter(superValue -> superValue.equals(subValue)) - .isPresent(); + .filter(superValue -> superValue.equals(subValue)) + .isPresent(); if (!isEqualValue) { return false; } diff --git a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/EntryComparator.java b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/EntryComparator.java index f80bd483709..c6ab47480e3 100644 --- a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/EntryComparator.java +++ b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/EntryComparator.java @@ -26,10 +26,10 @@ public class EntryComparator implements Comparator { /** * - * @param binary true: the presence of fields is checked; false: the content of the fields is compared + * @param binary true: the presence of fields is checked; false: the content of the fields is compared * @param descending true: if the most different entry should get the highest score - * @param field the field to sort on - * @param next the next comparator to use (if the current comparator results in equality) + * @param field the field to sort on + * @param next the next comparator to use (if the current comparator results in equality) */ public EntryComparator(boolean binary, boolean descending, Field field, Comparator next) { this.binary = binary; diff --git a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/YearFieldValuePlausibilityComparator.java b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/YearFieldValuePlausibilityComparator.java index c3a941954ba..de593158b98 100644 --- a/jablib/src/main/java/org/jabref/logic/bibtex/comparator/YearFieldValuePlausibilityComparator.java +++ b/jablib/src/main/java/org/jabref/logic/bibtex/comparator/YearFieldValuePlausibilityComparator.java @@ -61,8 +61,8 @@ public ComparisonResult compare(String leftValue, String rightValue) { int diff = Math.abs(leftYear - rightYear); if (diff > 10) { return rightYear > leftYear - ? ComparisonResult.RIGHT_BETTER - : ComparisonResult.LEFT_BETTER; + ? ComparisonResult.RIGHT_BETTER + : ComparisonResult.LEFT_BETTER; } return ComparisonResult.UNDETERMINED; // years are close, undetermined 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 843fd38eb38..a5c93e980e4 100644 --- a/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java +++ b/jablib/src/main/java/org/jabref/logic/bst/BstFunctions.java @@ -245,7 +245,9 @@ public void execute(BstVMVisitor visitor, ParserRuleContext ctx, BstEntry bstEnt Object o1 = stack.pop(); Object o2 = stack.pop(); - if (!(o1 instanceof BstVMVisitor.Identifier(String name))) { + if (!(o1 instanceof BstVMVisitor.Identifier( + String name + ))) { throw new BstVMException("Invalid parameters (line %d)".formatted(ctx.start.getLine())); } @@ -524,7 +526,9 @@ private void bstIf(BstVMVisitor visitor, ParserRuleContext ctx) { private void callIdentifierOrTree(Object f, BstVMVisitor visitor, ParserRuleContext ctx) { if (f instanceof ParseTree tree) { visitor.visit(tree); - } else if (f instanceof BstVMVisitor.Identifier(String name)) { + } else if (f instanceof BstVMVisitor.Identifier( + String name + )) { visitor.resolveIdentifier(name, ctx); } else { stack.push(f); diff --git a/jablib/src/main/java/org/jabref/logic/bst/util/BstCaseChanger.java b/jablib/src/main/java/org/jabref/logic/bst/util/BstCaseChanger.java index 06ce483248b..d7f862f1fcf 100644 --- a/jablib/src/main/java/org/jabref/logic/bst/util/BstCaseChanger.java +++ b/jablib/src/main/java/org/jabref/logic/bst/util/BstCaseChanger.java @@ -140,7 +140,7 @@ private String doChangeCase(String s, FormatMode format) { * is other stuff, too, between braces, but it doesn't try to do anything * special with |colon|s. * - * @param start the current position. It points to the opening brace + * @param start the current position. It points to the opening brace */ private int convertSpecialChar(StringBuilder sb, char[] c, int start, FormatMode format) { int i = start; @@ -213,7 +213,8 @@ private int convertAccented(char[] c, int start, String s, StringBuilder sb, For private int convertNonControl(char[] c, int start, StringBuilder sb, FormatMode format) { int pos = start; switch (format) { - case TITLE_LOWERS, ALL_LOWERS -> { + case TITLE_LOWERS, + ALL_LOWERS -> { sb.append(Character.toLowerCase(c[pos])); pos++; } 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 b8fda0d7918..8b0a66c9a99 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 @@ -14,7 +14,7 @@ /** * From Bibtex: - * + *

    * "The |built_in| function {\.{format.name\$}} pops the * top three literals (they are a string, an integer, and a string * literal, in that order). The last string literal represents a @@ -24,7 +24,7 @@ * described in the \BibTeX\ documentation. Finally, this function * pushes the formatted name. If any of the types is incorrect, it * complains and pushes the null string." - * + *

    * Sounds easy - is a nightmare... X-( * */ @@ -102,10 +102,14 @@ public static String formatName(Author author, String format) { char type = control.charAt(0); Optional tokenS = switch (type) { - case 'f' -> author.getGivenName(); - case 'v' -> author.getNamePrefix(); - case 'l' -> author.getFamilyName(); - case 'j' -> author.getNameSuffix(); + case 'f' -> + author.getGivenName(); + case 'v' -> + author.getNamePrefix(); + case 'l' -> + author.getFamilyName(); + case 'j' -> + author.getNameSuffix(); default -> throw new BstVMException("Internal error"); }; diff --git a/jablib/src/main/java/org/jabref/logic/bst/util/BstTextPrefixer.java b/jablib/src/main/java/org/jabref/logic/bst/util/BstTextPrefixer.java index ffe123ec68e..a9d330a2a5f 100644 --- a/jablib/src/main/java/org/jabref/logic/bst/util/BstTextPrefixer.java +++ b/jablib/src/main/java/org/jabref/logic/bst/util/BstTextPrefixer.java @@ -78,6 +78,7 @@ private static class PrefixState { public int index; public int braceLevel; public int numOfChars; + public PrefixState(int index, int braceLevel, int numOfChars) { this.index = index; this.braceLevel = braceLevel; diff --git a/jablib/src/main/java/org/jabref/logic/citation/SearchCitationsRelationsService.java b/jablib/src/main/java/org/jabref/logic/citation/SearchCitationsRelationsService.java index dbd353b234b..4675ff41d92 100644 --- a/jablib/src/main/java/org/jabref/logic/citation/SearchCitationsRelationsService.java +++ b/jablib/src/main/java/org/jabref/logic/citation/SearchCitationsRelationsService.java @@ -42,7 +42,7 @@ public SearchCitationsRelationsService(ImporterPreferences importerPreferences, @VisibleForTesting SearchCitationsRelationsService(CitationFetcher citationFetcher, - BibEntryCitationsAndReferencesRepository repository + BibEntryCitationsAndReferencesRepository repository ) { this.citationFetcher = citationFetcher; this.relationsRepository = repository; @@ -51,7 +51,7 @@ public SearchCitationsRelationsService(ImporterPreferences importerPreferences, public List searchCites(BibEntry referencing) throws FetcherException { boolean isFetchingAllowed = !relationsRepository.containsReferences(referencing) || - relationsRepository.isReferencesUpdatable(referencing); + relationsRepository.isReferencesUpdatable(referencing); if (isFetchingAllowed) { List referencedBy = citationFetcher.searchCiting(referencing); relationsRepository.insertReferences(referencing, referencedBy); @@ -67,7 +67,7 @@ public List searchCites(BibEntry referencing) throws FetcherException public List searchCitedBy(BibEntry cited) throws FetcherException { boolean isFetchingAllowed = !relationsRepository.containsCitations(cited) || - relationsRepository.isCitationsUpdatable(cited); + relationsRepository.isCitationsUpdatable(cited); if (isFetchingAllowed) { List citedBy = citationFetcher.searchCitedBy(cited); relationsRepository.insertCitations(cited, citedBy); diff --git a/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShell.java b/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShell.java index 5453fa3873d..7fa9723abe5 100644 --- a/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShell.java +++ b/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShell.java @@ -18,8 +18,8 @@ public class BibEntryCitationsAndReferencesRepositoryShell implements BibEntryCi private final BibEntryRelationRepository referencesDao; public BibEntryCitationsAndReferencesRepositoryShell( - BibEntryRelationRepository citationsDao, - BibEntryRelationRepository referencesDao + BibEntryRelationRepository citationsDao, + BibEntryRelationRepository referencesDao ) { this.citationsDao = citationsDao; this.referencesDao = referencesDao; @@ -28,7 +28,7 @@ public BibEntryCitationsAndReferencesRepositoryShell( @Override public void insertCitations(BibEntry entry, List citations) { citationsDao.addRelations( - entry, Objects.requireNonNullElseGet(citations, List::of) + entry, Objects.requireNonNullElseGet(citations, List::of) ); } @@ -53,7 +53,7 @@ public boolean isCitationsUpdatable(BibEntry entry) { @Override public void insertReferences(BibEntry entry, List references) { referencesDao.addRelations( - entry, Objects.requireNonNullElseGet(references, List::of) + entry, Objects.requireNonNullElseGet(references, List::of) ); } diff --git a/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntrySerializer.java b/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntrySerializer.java index 91230d6e9fe..26b41bceeed 100644 --- a/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntrySerializer.java +++ b/jablib/src/main/java/org/jabref/logic/citation/repository/BibEntrySerializer.java @@ -83,10 +83,14 @@ public BibEntry read(ByteBuffer buff) { @Override public int compare(@NonNull BibEntry a, @NonNull BibEntry b) { return switch (BibEntryCompare.compareEntries(a, b)) { - case SUBSET -> -1; - case SUPERSET -> 1; - case EQUAL -> 0; - default -> Objects.compare(a.hashCode(), b.hashCode(), Integer::compare); + case SUBSET -> + -1; + case SUPERSET -> + 1; + case EQUAL -> + 0; + default -> + Objects.compare(a.hashCode(), b.hashCode(), Integer::compare); }; } diff --git a/jablib/src/main/java/org/jabref/logic/citationkeypattern/BracketedPattern.java b/jablib/src/main/java/org/jabref/logic/citationkeypattern/BracketedPattern.java index c5eee7acc1d..e2bcfe2ffb4 100644 --- a/jablib/src/main/java/org/jabref/logic/citationkeypattern/BracketedPattern.java +++ b/jablib/src/main/java/org/jabref/logic/citationkeypattern/BracketedPattern.java @@ -235,7 +235,8 @@ public static String expandBrackets(@NonNull String pattern, Function appendQuote(expandedPattern, parsedPattern); + case "\"" -> + appendQuote(expandedPattern, parsedPattern); case "[" -> { String fieldMarker = contentBetweenBrackets(parsedPattern, pattern); expandedPattern.append(bracketContentHandler.apply(fieldMarker)); @@ -247,7 +248,8 @@ public static String expandBrackets(@NonNull String pattern, Function expandedPattern.append(token); + default -> + expandedPattern.append(token); } } @@ -273,7 +275,8 @@ private static String contentBetweenBrackets(StringTokenizer tokenizer, final St String token = tokenizer.nextToken(); // If the beginning of a quote is found, append the content switch (token) { - case "\"" -> appendQuote(bracketContent, tokenizer); + case "\"" -> + appendQuote(bracketContent, tokenizer); case "]" -> { if (subBrackets == 0) { foundClosingBracket = true; @@ -286,7 +289,8 @@ private static String contentBetweenBrackets(StringTokenizer tokenizer, final St subBrackets++; bracketContent.append(token); } - default -> bracketContent.append(token); + default -> + bracketContent.append(token); } } @@ -531,8 +535,8 @@ private static AuthorList createAuthorList(String unparsedAuthors) { // If the author is an institution, use an institution key instead of the full name String lastName = author.getFamilyName() .map(lastPart -> isInstitution(author) ? - generateInstitutionKey(lastPart) : - LatexToUnicodeAdapter.format(lastPart)) + generateInstitutionKey(lastPart) : + LatexToUnicodeAdapter.format(lastPart)) .orElse(null); return new Author( author.getGivenName().map(LatexToUnicodeAdapter::format).orElse(null), @@ -796,7 +800,7 @@ private static String firstAuthorForenameInitials(AuthorList authorList) { */ private static String firstAuthorVonAndLast(AuthorList authorList) { return authorList.isEmpty() ? "" : - authorList.getAuthor(0).getNamePrefixAndFamilyName().replace(" ", ""); + authorList.getAuthor(0).getNamePrefixAndFamilyName().replace(" ", ""); } /** @@ -1281,8 +1285,8 @@ protected static List parseFieldAndModifiers(String arg) { *

  • null if content is null
  • * */ - @VisibleForTesting - static String generateInstitutionKey(String content) { + @VisibleForTesting + static String generateInstitutionKey(String content) { if (content == null) { return null; } diff --git a/jablib/src/main/java/org/jabref/logic/citationstyle/CSLStyleUtils.java b/jablib/src/main/java/org/jabref/logic/citationstyle/CSLStyleUtils.java index e2a9df371a4..30863e28814 100644 --- a/jablib/src/main/java/org/jabref/logic/citationstyle/CSLStyleUtils.java +++ b/jablib/src/main/java/org/jabref/logic/citationstyle/CSLStyleUtils.java @@ -114,7 +114,7 @@ private static Optional createCitationStyleFromSource(InputStream * Parses the style information from a style content using StAX. * * @param filename The filename of the style (for logging) - * @param content The XML content of the style + * @param content The XML content of the style * @return Optional containing the StyleInfo if valid, empty otherwise */ public static Optional parseStyleInfo(String filename, String content) { @@ -141,8 +141,10 @@ public static Optional parseStyleInfo(String filename, String content String hangingIndent = reader.getAttributeValue(null, "hanging-indent"); usesHangingIndent = "true".equals(hangingIndent); } - case "citation" -> hasCitation = true; - case "info" -> inInfo = true; + case "citation" -> + hasCitation = true; + case "info" -> + inInfo = true; case "title" -> { if (inInfo) { title = reader.getElementText(); diff --git a/jablib/src/main/java/org/jabref/logic/cleanup/CleanupWorker.java b/jablib/src/main/java/org/jabref/logic/cleanup/CleanupWorker.java index 1e4bd868f97..1ecf07f752a 100644 --- a/jablib/src/main/java/org/jabref/logic/cleanup/CleanupWorker.java +++ b/jablib/src/main/java/org/jabref/logic/cleanup/CleanupWorker.java @@ -50,7 +50,7 @@ private List determineCleanupActions(CleanupPreferences preset) { // Add active jobs from preset panel for (CleanupPreferences.CleanupStep action : preset.getActiveJobs()) { - jobs.add(toJob(action)); + jobs.add(toJob(action)); } if (preset.getFieldFormatterCleanups().isEnabled()) { 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 6a18f02764c..e4deb8e7dc0 100644 --- a/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java +++ b/jablib/src/main/java/org/jabref/logic/cleanup/EprintCleanup.java @@ -13,7 +13,7 @@ /** * Formats the DOI (e.g. removes http part) and also moves DOIs from note, url or ee field to the doi field. - * + *

    * Background information on tex.stackexchange. */ public class EprintCleanup implements CleanupJob { @@ -47,8 +47,8 @@ public List cleanup(BibEntry entry) { .ifPresent(changes::add); arXivIdentifier.get().getClassification() - .flatMap(classification -> entry.setField(StandardField.EPRINTCLASS, classification)) - .ifPresent(changes::add); + .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/Crawler.java b/jablib/src/main/java/org/jabref/logic/crawler/Crawler.java index ebcd0fb0cb1..c5e8446ae0b 100644 --- a/jablib/src/main/java/org/jabref/logic/crawler/Crawler.java +++ b/jablib/src/main/java/org/jabref/logic/crawler/Crawler.java @@ -18,7 +18,7 @@ /** * This class provides a service for SLR support by conducting an automated search and persistance * of studies using the queries and E-Libraries specified in the provided study definition file. - * + *

    * It composes a StudyRepository for repository management, * and a StudyFetcher that manages the crawling over the selected E-Libraries. */ @@ -56,7 +56,7 @@ public Crawler(Path studyRepositoryRoot, /** * This methods performs the crawling of the active libraries defined in the study definition file. * This method also persists the results in the same folder the study definition file is stored in. - * + *

    * The whole process works as follows: *

      *
    1. Then the search is executed
    2. diff --git a/jablib/src/main/java/org/jabref/logic/crawler/StudyCatalogToFetcherConverter.java b/jablib/src/main/java/org/jabref/logic/crawler/StudyCatalogToFetcherConverter.java index b0f0c26be4d..b1f871daea8 100644 --- a/jablib/src/main/java/org/jabref/logic/crawler/StudyCatalogToFetcherConverter.java +++ b/jablib/src/main/java/org/jabref/logic/crawler/StudyCatalogToFetcherConverter.java @@ -29,7 +29,7 @@ public StudyCatalogToFetcherConverter(List libraryEntries, /** * Returns a list of instances of all active library fetchers. - * + *

      * A fetcher is considered active if there exists an library entry of the library the fetcher is associated with that is enabled. * * @return Instances of all active fetchers defined in the study definition. diff --git a/jablib/src/main/java/org/jabref/logic/crawler/StudyRepository.java b/jablib/src/main/java/org/jabref/logic/crawler/StudyRepository.java index b539d4225fa..6f6c4db5b10 100644 --- a/jablib/src/main/java/org/jabref/logic/crawler/StudyRepository.java +++ b/jablib/src/main/java/org/jabref/logic/crawler/StudyRepository.java @@ -44,7 +44,7 @@ /** * This class manages all aspects of the study process related to the repository. - * + *

      * It includes the parsing of the study definition file (study.bib) into a Study instance, * the structured persistence of the crawling results for the study within the file based repository, * as well as the sharing, and versioning of results using git. @@ -343,17 +343,17 @@ private void createBibFile(Path file) { * Returns a string that can be used as a folder name. * This removes all characters from the query that are illegal for directory names. * Structure: ID-trimmed query - * + *

      * Examples: * Input: '(title: test-title AND abstract: Test)' as a query entry with id 12345678 * Output: '12345678 - title= test-title AND abstract= Test' - * + *

      * Input: 'abstract: Test*' as a query entry with id 87654321 * Output: '87654321 - abstract= Test' - * + *

      * Input: '"test driven"' as a query entry with id 12348765 * Output: '12348765 - test driven' - * + *

      * Note that this method might be similar to {@link org.jabref.logic.util.io.FileUtil#getValidFileName(String)} or {@link org.jabref.logic.util.io.FileNameCleaner#cleanFileName(String)} * * @param query that is trimmed and combined with its query id diff --git a/jablib/src/main/java/org/jabref/logic/database/DuplicateCheck.java b/jablib/src/main/java/org/jabref/logic/database/DuplicateCheck.java index 5c6398a8e4f..5aae78d1729 100644 --- a/jablib/src/main/java/org/jabref/logic/database/DuplicateCheck.java +++ b/jablib/src/main/java/org/jabref/logic/database/DuplicateCheck.java @@ -102,8 +102,8 @@ private static boolean haveDifferentChaptersOrPagesOfTheSameBook(final BibEntry private static double[] compareRequiredFields(final BibEntryType type, final BibEntry one, final BibEntry two) { final Set requiredFields = type.getRequiredFields(); return requiredFields.isEmpty() - ? new double[] {0., 0.} - : DuplicateCheck.compareFieldSet(requiredFields.stream().map(OrFields::getPrimary).collect(Collectors.toSet()), one, two); + ? new double[] {0., 0.} + : DuplicateCheck.compareFieldSet(requiredFields.stream().map(OrFields::getPrimary).collect(Collectors.toSet()), one, two); } private static boolean isFarFromThreshold(double value) { diff --git a/jablib/src/main/java/org/jabref/logic/exporter/BibDatabaseWriter.java b/jablib/src/main/java/org/jabref/logic/exporter/BibDatabaseWriter.java index 089d54001b1..974084db8fd 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/BibDatabaseWriter.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/BibDatabaseWriter.java @@ -88,11 +88,11 @@ public BibDatabaseWriter(BibWriter bibWriter, } public BibDatabaseWriter(Writer writer, - String newline, - SelfContainedSaveConfiguration saveConfiguration, - FieldPreferences fieldPreferences, - CitationKeyPatternPreferences citationKeyPatternPreferences, - BibEntryTypesManager entryTypesManager) { + String newline, + SelfContainedSaveConfiguration saveConfiguration, + FieldPreferences fieldPreferences, + CitationKeyPatternPreferences citationKeyPatternPreferences, + BibEntryTypesManager entryTypesManager) { this(new BibWriter(writer, newline), saveConfiguration, fieldPreferences, @@ -177,9 +177,9 @@ public List getSaveActionsFieldChanges() { */ public void saveDatabase(BibDatabaseContext bibDatabaseContext) throws IOException { List entries = bibDatabaseContext.getDatabase().getEntries() - .stream() - .filter(entry -> !entry.isEmpty()) - .toList(); + .stream() + .filter(entry -> !entry.isEmpty()) + .toList(); savePartOfDatabase(bibDatabaseContext, entries); } diff --git a/jablib/src/main/java/org/jabref/logic/exporter/CffExporter.java b/jablib/src/main/java/org/jabref/logic/exporter/CffExporter.java index ebf7199f107..8b0f35f6bef 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/CffExporter.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/CffExporter.java @@ -66,17 +66,17 @@ public class CffExporter extends Exporter { ); public static final Map TYPES_MAP = Map.ofEntries( - Map.entry(StandardEntryType.Article, "article"), - Map.entry(StandardEntryType.Book, "book"), - Map.entry(StandardEntryType.Booklet, "pamphlet"), - Map.entry(StandardEntryType.Proceedings, "conference"), - Map.entry(StandardEntryType.InProceedings, "conference-paper"), - Map.entry(StandardEntryType.Misc, "misc"), - Map.entry(StandardEntryType.Manual, "manual"), - Map.entry(StandardEntryType.Software, "software"), - Map.entry(StandardEntryType.Dataset, "dataset"), - Map.entry(StandardEntryType.Report, "report"), - Map.entry(StandardEntryType.Unpublished, "unpublished") + Map.entry(StandardEntryType.Article, "article"), + Map.entry(StandardEntryType.Book, "book"), + Map.entry(StandardEntryType.Booklet, "pamphlet"), + Map.entry(StandardEntryType.Proceedings, "conference"), + Map.entry(StandardEntryType.InProceedings, "conference-paper"), + Map.entry(StandardEntryType.Misc, "misc"), + Map.entry(StandardEntryType.Manual, "manual"), + Map.entry(StandardEntryType.Software, "software"), + Map.entry(StandardEntryType.Dataset, "dataset"), + Map.entry(StandardEntryType.Report, "report"), + Map.entry(StandardEntryType.Unpublished, "unpublished") ); public CffExporter() { diff --git a/jablib/src/main/java/org/jabref/logic/exporter/GroupSerializer.java b/jablib/src/main/java/org/jabref/logic/exporter/GroupSerializer.java index f74a6195157..d247f977b16 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/GroupSerializer.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/GroupSerializer.java @@ -129,16 +129,26 @@ public List serializeTree(GroupTreeNode node) { private String serializeGroup(AbstractGroup group) { return switch (group) { - case AllEntriesGroup _ -> serializeAllEntriesGroup(); - case SmartGroup smartGroup -> serializeSmartGroup(smartGroup); - case ExplicitGroup explicitGroup -> serializeExplicitGroup(explicitGroup); - case KeywordGroup keywordGroup -> serializeKeywordGroup(keywordGroup); - case SearchGroup searchGroup -> serializeSearchGroup(searchGroup); - case AutomaticKeywordGroup keywordGroup -> serializeAutomaticKeywordGroup(keywordGroup); - case AutomaticPersonsGroup personsGroup -> serializeAutomaticPersonsGroup(personsGroup); - case TexGroup texGroup -> serializeTexGroup(texGroup); - case null -> throw new IllegalArgumentException("Group cannot be null"); - default -> throw new UnsupportedOperationException("Don't know how to serialize group" + group.getClass().getName()); + case AllEntriesGroup _ -> + serializeAllEntriesGroup(); + case SmartGroup smartGroup -> + serializeSmartGroup(smartGroup); + case ExplicitGroup explicitGroup -> + serializeExplicitGroup(explicitGroup); + case KeywordGroup keywordGroup -> + serializeKeywordGroup(keywordGroup); + case SearchGroup searchGroup -> + serializeSearchGroup(searchGroup); + case AutomaticKeywordGroup keywordGroup -> + serializeAutomaticKeywordGroup(keywordGroup); + case AutomaticPersonsGroup personsGroup -> + serializeAutomaticPersonsGroup(personsGroup); + case TexGroup texGroup -> + serializeTexGroup(texGroup); + case null -> + throw new IllegalArgumentException("Group cannot be null"); + default -> + throw new UnsupportedOperationException("Don't know how to serialize group" + group.getClass().getName()); }; } diff --git a/jablib/src/main/java/org/jabref/logic/exporter/TemplateExporter.java b/jablib/src/main/java/org/jabref/logic/exporter/TemplateExporter.java index ab81e466238..6192060e089 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/TemplateExporter.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/TemplateExporter.java @@ -74,9 +74,9 @@ public TemplateExporter(String displayName, /** * Initialize another export format based on templates stored in dir with layoutFile lfFilename. * - * @param name to display to the user and to call this format in the console. - * @param lfFileName Name of the main layout file. - * @param extension May or may not contain the . (for instance .txt). + * @param name to display to the user and to call this format in the console. + * @param lfFileName Name of the main layout file. + * @param extension May or may not contain the . (for instance .txt). */ public TemplateExporter(String name, String lfFileName, @@ -95,11 +95,11 @@ public TemplateExporter(String name, /** * Initialize another export format based on templates stored in dir with layoutFile lfFilename. * - * @param displayName Name to display to the user. - * @param consoleName Name to call this format in the console. - * @param lfFileName Name of the main layout file. - * @param directory Directory in which to find the layout file. - * @param extension Should contain the . (for instance .txt). + * @param displayName Name to display to the user. + * @param consoleName Name to call this format in the console. + * @param lfFileName Name of the main layout file. + * @param directory Directory in which to find the layout file. + * @param extension Should contain the . (for instance .txt). */ public TemplateExporter(String displayName, String consoleName, @@ -114,12 +114,12 @@ public TemplateExporter(String displayName, /** * Initialize another export format based on templates stored in dir with layoutFile lfFilename. * - * @param displayName Name to display to the user. - * @param consoleName Name to call this format in the console. - * @param lfFileName Name of the main layout file. - * @param directory Directory in which to find the layout file. - * @param extension Should contain the . (for instance .txt). - * @param layoutPreferences Preferences for layout + * @param displayName Name to display to the user. + * @param consoleName Name to call this format in the console. + * @param lfFileName Name of the main layout file. + * @param directory Directory in which to find the layout file. + * @param extension Should contain the . (for instance .txt). + * @param layoutPreferences Preferences for layout * @param blankLineBehaviour how to behave regarding blank lines. */ public TemplateExporter(String displayName, diff --git a/jablib/src/main/java/org/jabref/logic/externalfiles/DateRange.java b/jablib/src/main/java/org/jabref/logic/externalfiles/DateRange.java index 17181a7f5bf..56f54c29eb1 100644 --- a/jablib/src/main/java/org/jabref/logic/externalfiles/DateRange.java +++ b/jablib/src/main/java/org/jabref/logic/externalfiles/DateRange.java @@ -12,7 +12,7 @@ public enum DateRange { private final String dateRange; DateRange(String dateRange) { - this.dateRange = dateRange; + this.dateRange = dateRange; } public static DateRange parse(String name) { diff --git a/jablib/src/main/java/org/jabref/logic/externalfiles/ExternalFilesContentImporter.java b/jablib/src/main/java/org/jabref/logic/externalfiles/ExternalFilesContentImporter.java index 7a868577c42..e41689b616d 100644 --- a/jablib/src/main/java/org/jabref/logic/externalfiles/ExternalFilesContentImporter.java +++ b/jablib/src/main/java/org/jabref/logic/externalfiles/ExternalFilesContentImporter.java @@ -23,7 +23,7 @@ public ParserResult importPDFContent(Path file, BibDatabaseContext context, File try { return new PdfMergeMetadataImporter(importFormatPreferences).importDatabase(file, context, filePreferences); } catch (IOException e) { - return ParserResult.fromError(e); + return ParserResult.fromError(e); } } diff --git a/jablib/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java b/jablib/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java index 52d85934c90..4f1c6311783 100644 --- a/jablib/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java +++ b/jablib/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java @@ -286,7 +286,7 @@ public String getSuggestedFileName(@NonNull String extension) { public Optional findExistingFile(LinkedFile linkedFile, BibEntry entry, String targetFileName) { // The .get() is legal without check because the method will always return a value. Path targetFilePath = linkedFile.findIn(databaseContext, filePreferences) - .get().getParent().resolve(targetFileName); + .get().getParent().resolve(targetFileName); Path oldFilePath = linkedFile.findIn(databaseContext, filePreferences).get(); // Check if file already exists in directory with different case. // This is necessary because other entries may have such a file. diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatter.java index 89a947a311c..28a7ea51fb3 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatter.java @@ -13,7 +13,7 @@ /** * Cleanup URL link. *

      - * Expose string representations URL links clean up logic. + * Expose string representations URL links clean up logic. *

      */ public class CleanupUrlFormatter extends Formatter { @@ -44,7 +44,6 @@ public String getKey() { * * @param url should not be null * @return the decoded URL as a String representation - * * @see URLDecoder#decode(String, Charset) */ @Override @@ -67,9 +66,9 @@ public String getDescription() { @Override public String getExampleInput() { return "https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=11&cad=" + - "rja&uact=8&ved=0ahUKEwjg3ZrB_ZPXAhVGuhoKHYdOBOg4ChAWCCYwAA&url=" + - "http%3A%2F%2Fwww.focus.de%2Fgesundheit%2Fratgeber%2Fherz%2Ftest%2" + - "Flebenserwartung-werden-sie-100-jahre-alt_aid_363828.html" + - "&usg=AOvVaw1G6m2jf-pTHYkXceii4hXU"; + "rja&uact=8&ved=0ahUKEwjg3ZrB_ZPXAhVGuhoKHYdOBOg4ChAWCCYwAA&url=" + + "http%3A%2F%2Fwww.focus.de%2Fgesundheit%2Fratgeber%2Fherz%2Ftest%2" + + "Flebenserwartung-werden-sie-100-jahre-alt_aid_363828.html" + + "&usg=AOvVaw1G6m2jf-pTHYkXceii4hXU"; } } diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ConvertMSCCodesFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ConvertMSCCodesFormatter.java index 85c626ba546..ddfbc037e09 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ConvertMSCCodesFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ConvertMSCCodesFormatter.java @@ -101,7 +101,8 @@ public String getName() { @Override public String getKey() { - return "MSC_codes_to_descriptions"; } + return "MSC_codes_to_descriptions"; + } @Override public String getExampleInput() { diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeDateFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeDateFormatter.java index 385b36996ca..53fddde9a22 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeDateFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeDateFormatter.java @@ -23,10 +23,10 @@ public String getKey() { /** * Format date string to yyyy-mm-dd or yyyy-mm. Keeps the existing String if it does not match one of the following * formats: - * "M/y" (covers 9/15, 9/2015, and 09/2015) - * "MMMM (dd), yyyy" (covers September 1, 2015 and September, 2015) - * "yyyy-MM-dd" (covers 2009-1-15) - * "d.M.uuuu" (covers 15.1.2015) + * "M/y" (covers 9/15, 9/2015, and 09/2015) + * "MMMM (dd), yyyy" (covers September 1, 2015 and September, 2015) + * "yyyy-MM-dd" (covers 2009-1-15) + * "d.M.uuuu" (covers 15.1.2015) */ @Override public String format(String value) { diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeUnicodeFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeUnicodeFormatter.java index 8d39cbe1c86..710efb8d76c 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeUnicodeFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeUnicodeFormatter.java @@ -6,7 +6,7 @@ /** * Clean up field values by formatting Unicode values by using the Normal form "Normalization Form Canonical Composition" (NFC): Characters are decomposed and then recomposed by canonical equivalence. - * + *

      * The {@link org.jabref.logic.integrity.UnicodeNormalFormCanonicalCompositionCheck} is for checking the presence of other Unicode representations. */ public class NormalizeUnicodeFormatter extends Formatter { diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeWhitespaceFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeWhitespaceFormatter.java index bda0735ebfe..2b779c6b5b9 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeWhitespaceFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/NormalizeWhitespaceFormatter.java @@ -10,7 +10,7 @@ /** * Replaces two subsequent whitespaces (and tabs) to one space in case of single-line fields. In case of multine fields, * the field content is kept as is. - * + *

      * Due to the distinction between single line and multiline fields, this formatter does not implement the interface {@link org.jabref.logic.cleanup.Formatter}. */ public class NormalizeWhitespaceFormatter { diff --git a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ShortenDOIFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ShortenDOIFormatter.java index b0e59354f2b..bbc43d98426 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ShortenDOIFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/bibtexfields/ShortenDOIFormatter.java @@ -32,14 +32,14 @@ public String getKey() { public String format(String value) { Objects.requireNonNull(value); return SHORT_DOI_FORMAT.test(value) ? value : DOI.parse(value) - .map(doi -> { - try { - return new ShortDOIService().getShortDOI(doi).asString(); - } catch (ShortDOIServiceException e) { - LOGGER.error(e.getMessage(), e); - return value; - } - }).orElse(value); + .map(doi -> { + try { + return new ShortDOIService().getShortDOI(doi).asString(); + } catch (ShortDOIServiceException e) { + LOGGER.error(e.getMessage(), e); + return value; + } + }).orElse(value); } @Override diff --git a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatter.java index 5f73c4839db..0b26271ebb1 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatter.java @@ -24,15 +24,15 @@ public String getKey() { @Override public String format(String input) { return StringUtil.getStringAsSentences(input) - .stream() - .map(new LowerCaseFormatter()::format) - .map(Title::new) - .map(title -> { - title.getFirstWord().ifPresent(Word::toUpperFirst); - return title; - }) - .map(Object::toString) - .collect(Collectors.joining(" ")); + .stream() + .map(new LowerCaseFormatter()::format) + .map(Title::new) + .map(title -> { + title.getFirstWord().ifPresent(Word::toUpperFirst); + return title; + }) + .map(Object::toString) + .collect(Collectors.joining(" ")); } @Override diff --git a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/ShortTitleFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/ShortTitleFormatter.java index 6e9da157286..56b1a2fc355 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/ShortTitleFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/ShortTitleFormatter.java @@ -24,7 +24,7 @@ public String format(String input) { return title.getWords().stream() .filter(Predicate.not( - Word::isSmallerWord)) + Word::isSmallerWord)) .map(Word::toString) .limit(3) .collect(Collectors.joining(" ")); diff --git a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatter.java index 857cc6a772b..1a8dde53204 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatter.java @@ -26,25 +26,25 @@ public String getKey() { @Override public String format(String input) { return StringUtil.getStringAsSentences(input) - .stream() - .map(sentence -> { - Title title = new Title(sentence); + .stream() + .map(sentence -> { + Title title = new Title(sentence); - title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase); - title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirstTitle); + title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase); + title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirstTitle); - title.getFirstWord().ifPresent(Word::toUpperFirstTitle); - title.getLastWord().ifPresent(Word::toUpperFirstTitle); + title.getFirstWord().ifPresent(Word::toUpperFirstTitle); + title.getLastWord().ifPresent(Word::toUpperFirstTitle); - for (int i = 0; i < (title.getWords().size() - 2); i++) { - if (title.getWords().get(i).endsWithColon()) { - title.getWords().get(i + 1).toUpperFirstTitle(); - } - } + for (int i = 0; i < (title.getWords().size() - 2); i++) { + if (title.getWords().get(i).endsWithColon()) { + title.getWords().get(i + 1).toUpperFirstTitle(); + } + } - return title.toString(); - }) - .collect(Collectors.joining(" ")); + return title.toString(); + }) + .collect(Collectors.joining(" ")); } @Override diff --git a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/UnprotectTermsFormatter.java b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/UnprotectTermsFormatter.java index d6dac214c65..280d772e93f 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/UnprotectTermsFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/UnprotectTermsFormatter.java @@ -7,7 +7,7 @@ /** * Remove {} braces around words in case they appear balanced - * + *

      * Related formatter: {@link ProtectTermsFormatter} */ public class UnprotectTermsFormatter extends Formatter { diff --git a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/Word.java b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/Word.java index 4d75fd1b22b..b54648c714f 100644 --- a/jablib/src/main/java/org/jabref/logic/formatter/casechanger/Word.java +++ b/jablib/src/main/java/org/jabref/logic/formatter/casechanger/Word.java @@ -88,8 +88,8 @@ public void toUpperFirst() { for (int i = 0; i < chars.length; i++) { if (!protectedChars[i]) { chars[i] = i == 0 ? - Character.toUpperCase(chars[i]) : - Character.toLowerCase(chars[i]); + Character.toUpperCase(chars[i]) : + Character.toLowerCase(chars[i]); } } } @@ -98,8 +98,8 @@ public void toUpperFirstIgnoreHyphen() { for (int i = 0; i < chars.length; i++) { if (!protectedChars[i]) { chars[i] = i == 0 || (DASHES.contains(chars[i - 1])) ? - Character.toUpperCase(chars[i]) : - Character.toLowerCase(chars[i]); + Character.toUpperCase(chars[i]) : + Character.toLowerCase(chars[i]); } } } @@ -108,18 +108,18 @@ public void toUpperFirstTitle() { for (int i = 0; i < chars.length; i++) { if (!protectedChars[i]) { chars[i] = i == 0 || (DASHES.contains(chars[i - 1]) && isConjunction(chars, i)) ? - Character.toUpperCase(chars[i]) : - Character.toLowerCase(chars[i]); + Character.toUpperCase(chars[i]) : + Character.toLowerCase(chars[i]); } } } private boolean isConjunction(char[] chars, int i) { StringBuilder word = new StringBuilder(); - while (i < chars.length && !DASHES.contains(chars[i])) { - word.append(chars[i]); - i++; - } + while (i < chars.length && !DASHES.contains(chars[i])) { + word.append(chars[i]); + i++; + } return !CONJUNCTIONS.contains(word.toString()); } @@ -127,8 +127,8 @@ public void stripConsonants() { for (int i = 0; i < chars.length; i++) { if (!protectedChars[i]) { chars[i] = i == 0 || DASHES.contains(chars[i - 1]) ? - Character.toUpperCase(chars[i]) : - Character.toLowerCase(chars[i]); + Character.toUpperCase(chars[i]) : + Character.toLowerCase(chars[i]); } } } diff --git a/jablib/src/main/java/org/jabref/logic/git/GitHandler.java b/jablib/src/main/java/org/jabref/logic/git/GitHandler.java index 7521c50ec22..1a87f19a7f5 100644 --- a/jablib/src/main/java/org/jabref/logic/git/GitHandler.java +++ b/jablib/src/main/java/org/jabref/logic/git/GitHandler.java @@ -309,8 +309,8 @@ public void pushCurrentBranchCreatingUpstream() throws IOException, GitAPIExcept String branch = repo.getBranch(); PushCommand pushCommand = git.push() - .setRemote("origin") - .setRefSpecs(new RefSpec("refs/heads/" + branch + ":refs/heads/" + branch)); + .setRemote("origin") + .setRefSpecs(new RefSpec("refs/heads/" + branch + ":refs/heads/" + branch)); if (credsOpt.isPresent()) { pushCommand.setCredentialsProvider(credsOpt.get()); @@ -319,9 +319,9 @@ public void pushCurrentBranchCreatingUpstream() throws IOException, GitAPIExcept } } - /// Pulls from the current branch’s upstream. - /// If no remote is configured, silently performs local merge. - /// This ensures SLR repositories without remotes still initialize correctly. + /// Pulls from the current branch’s upstream. + /// If no remote is configured, silently performs local merge. + /// This ensures SLR repositories without remotes still initialize correctly. public void pullOnCurrentBranch() throws IOException { try (Git git = Git.open(this.repositoryPathAsFile)) { Optional credsOpt = resolveCredentials(); diff --git a/jablib/src/main/java/org/jabref/logic/git/GitSyncService.java b/jablib/src/main/java/org/jabref/logic/git/GitSyncService.java index 780b6f7f2a9..4e2faba16fc 100644 --- a/jablib/src/main/java/org/jabref/logic/git/GitSyncService.java +++ b/jablib/src/main/java/org/jabref/logic/git/GitSyncService.java @@ -110,10 +110,10 @@ public PullResult fetchAndMerge(BibDatabaseContext localDatabaseContext, Path bi } public PullResult performSemanticMerge(Git git, - Optional baseCommitOpt, - RevCommit remoteCommit, - BibDatabaseContext localDatabaseContext, - Path bibFilePath) throws IOException, JabRefException, GitAPIException { + Optional baseCommitOpt, + RevCommit remoteCommit, + BibDatabaseContext localDatabaseContext, + Path bibFilePath) throws IOException, JabRefException, GitAPIException { Path bibPath = bibFilePath.toRealPath(); Path workTree = git.getRepository().getWorkTree().toPath().toRealPath(); @@ -200,7 +200,8 @@ public PushResult push(BibDatabaseContext localDatabaseContext, Path bibFilePath throw new JabRefException("Push aborted: Unknown Git status."); } - case BEHIND, DIVERGED -> { + case BEHIND, + DIVERGED -> { fetchAndMerge(localDatabaseContext, bibFilePath); status = GitStatusChecker.checkStatus(gitHandler); if (status.conflict()) { diff --git a/jablib/src/main/java/org/jabref/logic/git/conflicts/GitConflictResolverStrategy.java b/jablib/src/main/java/org/jabref/logic/git/conflicts/GitConflictResolverStrategy.java index 01d5135155d..4b18191898a 100644 --- a/jablib/src/main/java/org/jabref/logic/git/conflicts/GitConflictResolverStrategy.java +++ b/jablib/src/main/java/org/jabref/logic/git/conflicts/GitConflictResolverStrategy.java @@ -17,7 +17,7 @@ public interface GitConflictResolverStrategy { * * @param conflicts the list of detected three-way entry conflicts * @return the modified BibDatabaseContext containing resolved entries, - * or empty if user canceled merge or CLI refuses to merge. + * or empty if user canceled merge or CLI refuses to merge. */ List resolveConflicts(List conflicts); } diff --git a/jablib/src/main/java/org/jabref/logic/git/conflicts/SemanticConflictDetector.java b/jablib/src/main/java/org/jabref/logic/git/conflicts/SemanticConflictDetector.java index e9fabb2d21b..e5b98a2fcd3 100644 --- a/jablib/src/main/java/org/jabref/logic/git/conflicts/SemanticConflictDetector.java +++ b/jablib/src/main/java/org/jabref/logic/git/conflicts/SemanticConflictDetector.java @@ -64,8 +64,8 @@ public static List detectConflicts(BibDatabaseContext bas * Detect entry-level conflicts among base, local, and remote versions of an entry. *

      * - * @param base the entry in the common ancestor - * @param local the entry in the local version + * @param base the entry in the common ancestor + * @param local the entry in the local version * @param remote the entry in the remote version * @return optional conflict (if detected) */ @@ -179,7 +179,7 @@ private static boolean notEqual(String a, String b) { * This plan is meant to be applied to local during merge: * result = local + (remote − base) * - * @param base The base version of the database. + * @param base The base version of the database. * @param remote The remote version to be merged. * @return A {@link MergePlan} describing how to update the local copy with remote changes. */ @@ -227,8 +227,8 @@ public static MergePlan extractMergePlan(BibDatabaseContext base, BibDatabaseCon * - If both sides changed to the same value, no patch needed; * - Fallback: if a divergence is still observed, do not override local; skip this field, * - * @param base base version - * @param local local version + * @param base base version + * @param local local version * @param remote remote version * @return A map from field to new value */ diff --git a/jablib/src/main/java/org/jabref/logic/git/conflicts/ThreeWayEntryConflict.java b/jablib/src/main/java/org/jabref/logic/git/conflicts/ThreeWayEntryConflict.java index 191495a506e..b75dfb51b41 100644 --- a/jablib/src/main/java/org/jabref/logic/git/conflicts/ThreeWayEntryConflict.java +++ b/jablib/src/main/java/org/jabref/logic/git/conflicts/ThreeWayEntryConflict.java @@ -11,9 +11,9 @@ /// Constraint: At least one of {@code local} or {@code remote} must be non-null. @NullMarked public record ThreeWayEntryConflict( - @Nullable BibEntry base, - @Nullable BibEntry local, - @Nullable BibEntry remote + @Nullable BibEntry base, + @Nullable BibEntry local, + @Nullable BibEntry remote ) { public ThreeWayEntryConflict { assert !(local == null && remote == null) : "Both local and remote are null: conflict must involve at least one side."; diff --git a/jablib/src/main/java/org/jabref/logic/git/io/RevisionTriple.java b/jablib/src/main/java/org/jabref/logic/git/io/RevisionTriple.java index 973601aa5e0..957a7c4018e 100644 --- a/jablib/src/main/java/org/jabref/logic/git/io/RevisionTriple.java +++ b/jablib/src/main/java/org/jabref/logic/git/io/RevisionTriple.java @@ -9,8 +9,8 @@ * Holds the three relevant commits involved in a semantic three-way merge, * it is a helper value object used exclusively during merge resolution, not part of the domain model * - * @param base the merge base (common ancestor of local and remote) - * @param local the current local branch tip + * @param base the merge base (common ancestor of local and remote) + * @param local the current local branch tip * @param remote the tip of the remote tracking branch (typically origin/main) */ @NullMarked diff --git a/jablib/src/main/java/org/jabref/logic/git/merge/GitMergeUtil.java b/jablib/src/main/java/org/jabref/logic/git/merge/GitMergeUtil.java index e10c4d0c0a1..8b01e5527c7 100644 --- a/jablib/src/main/java/org/jabref/logic/git/merge/GitMergeUtil.java +++ b/jablib/src/main/java/org/jabref/logic/git/merge/GitMergeUtil.java @@ -13,7 +13,7 @@ public class GitMergeUtil { /** * Replace conflicting entries in the remote context with user-resolved versions. * - * @param remote the original remote BibDatabaseContext + * @param remote the original remote BibDatabaseContext * @param resolvedEntries list of entries that the user has manually resolved via GUI * @return a new BibDatabaseContext with resolved entries replacing original ones */ diff --git a/jablib/src/main/java/org/jabref/logic/git/merge/GitSemanticMergeExecutor.java b/jablib/src/main/java/org/jabref/logic/git/merge/GitSemanticMergeExecutor.java index 24a66a6aa3f..1d8681de18a 100644 --- a/jablib/src/main/java/org/jabref/logic/git/merge/GitSemanticMergeExecutor.java +++ b/jablib/src/main/java/org/jabref/logic/git/merge/GitSemanticMergeExecutor.java @@ -15,14 +15,14 @@ public interface GitSemanticMergeExecutor { * Applies semantic merge of remote into local, based on base version. * Assumes conflicts have already been resolved (if any). * - * @param base The common ancestor version - * @param local The current local version (to be updated) - * @param remote The incoming remote version (can be resolved or raw) + * @param base The common ancestor version + * @param local The current local version (to be updated) + * @param remote The incoming remote version (can be resolved or raw) * @param bibFilePath The path to the target bib file (used for write-back) * @return MergePlan object containing merge plan */ MergePlan merge(@Nullable BibDatabaseContext base, - BibDatabaseContext local, - BibDatabaseContext remote, - Path bibFilePath) throws IOException; + BibDatabaseContext local, + BibDatabaseContext remote, + Path bibFilePath) throws IOException; } diff --git a/jablib/src/main/java/org/jabref/logic/git/merge/MergePlan.java b/jablib/src/main/java/org/jabref/logic/git/merge/MergePlan.java index 438b636f8d4..b5f090b3904 100644 --- a/jablib/src/main/java/org/jabref/logic/git/merge/MergePlan.java +++ b/jablib/src/main/java/org/jabref/logic/git/merge/MergePlan.java @@ -10,8 +10,9 @@ * A data structure representing the result of semantic diffing between base and remote entries. * * @param fieldPatches contain field-level modifications per citation key. citationKey -> field -> newValue (null = delete) - * @param newEntries entries present in remote but not in base/local + * @param newEntries entries present in remote but not in base/local */ public record MergePlan( Map> fieldPatches, - List newEntries) { } + List newEntries) { +} diff --git a/jablib/src/main/java/org/jabref/logic/git/status/GitStatusSnapshot.java b/jablib/src/main/java/org/jabref/logic/git/status/GitStatusSnapshot.java index 61aa29a5529..7ddd3f8a72a 100644 --- a/jablib/src/main/java/org/jabref/logic/git/status/GitStatusSnapshot.java +++ b/jablib/src/main/java/org/jabref/logic/git/status/GitStatusSnapshot.java @@ -3,11 +3,11 @@ import java.util.Optional; public record GitStatusSnapshot( - boolean tracking, - SyncStatus syncStatus, - boolean conflict, - boolean uncommittedChanges, - Optional lastPulledCommit) { + boolean tracking, + SyncStatus syncStatus, + boolean conflict, + boolean uncommittedChanges, + Optional lastPulledCommit) { public static final boolean TRACKING = true; public static final boolean CONFLICT = true; public static final boolean UNCOMMITTED = true; diff --git a/jablib/src/main/java/org/jabref/logic/icore/ConferenceRepository.java b/jablib/src/main/java/org/jabref/logic/icore/ConferenceRepository.java index 5b71e071ea9..59d1c5f4ec9 100644 --- a/jablib/src/main/java/org/jabref/logic/icore/ConferenceRepository.java +++ b/jablib/src/main/java/org/jabref/logic/icore/ConferenceRepository.java @@ -62,10 +62,10 @@ private void loadConferenceDataFromInputStream(InputStream inputStream) throws J try (inputStream; reader) { Iterable records = CSVFormat.DEFAULT.builder() - .setHeader() - .setSkipHeaderRecord(true) - .get() - .parse(reader); + .setHeader() + .setSkipHeaderRecord(true) + .get() + .parse(reader); for (CSVRecord record : records) { String id = record.get("Id").strip(); @@ -104,10 +104,10 @@ private void loadConferenceDataFromInputStream(InputStream inputStream) throws J * of conference titles. *

      * - * @implNote see {@link ConferenceRepository#fuzzySearchConferenceTitles} for more details on matching * @param bookTitle the string to search, must not be {@code null} * @return an {@code Optional} conference entry, if found - * or {@code Optional.empty()} if no conference entry is found + * or {@code Optional.empty()} if no conference entry is found + * @implNote see {@link ConferenceRepository#fuzzySearchConferenceTitles} for more details on matching */ public Optional getConferenceFromBookTitle(@NonNull String bookTitle) { String query = bookTitle.strip().toLowerCase(); @@ -163,14 +163,14 @@ private Optional getConferenceFromAcronym(String query) { *
    3. Whenever Levenshtein similarity exceeds the threshold defined by the LEVENSHTEIN_THRESHOLD constant.
    4. *
    5. The combined weighted score of both LCS and Levenshtein similarities exceeds the COMBINED_LCS_LEV_THRESHOLD.
    6. *
    - * + *

    * The combined score is calculated as follows: * (0.6 * Levenshtein similarity) + (0.4 * LCS similarity) *

    * * @param query The query string to be searched * @return an {@code Optional} conference entry, if found - * or {@code Optional.empty()} if no conference entry is found + * or {@code Optional.empty()} if no conference entry is found */ private Optional fuzzySearchConferenceTitles(String query) { String bestMatch = ""; diff --git a/jablib/src/main/java/org/jabref/logic/icore/ConferenceUtils.java b/jablib/src/main/java/org/jabref/logic/icore/ConferenceUtils.java index ba62d4ce87b..0742c916c34 100644 --- a/jablib/src/main/java/org/jabref/logic/icore/ConferenceUtils.java +++ b/jablib/src/main/java/org/jabref/logic/icore/ConferenceUtils.java @@ -56,7 +56,7 @@ public class ConferenceUtils { * * @param input the string to search, must not be {@code null} * @return an {@code Optional} containing the extracted and trimmed string from the first set of parentheses, - * or {@code Optional.empty()} if no string is found + * or {@code Optional.empty()} if no string is found */ public static Optional extractStringFromParentheses(@NonNull String input) { if (input.indexOf('(') < 0) { @@ -95,7 +95,7 @@ public static Optional extractStringFromParentheses(@NonNull String inpu * @param input the raw string to extract acronym candidates from, must not be {@code null} * @param cutoff the maximum allowed length of each candidate substring; candidates longer than this are discarded * @return a set of acronym candidates ordered by descending length and then lexicographically, - * or an empty set if no valid candidates are found + * or an empty set if no valid candidates are found */ public static Set generateAcronymCandidates(@NonNull String input, int cutoff) { if (input.isEmpty() || cutoff <= 0) { @@ -209,7 +209,7 @@ public static String normalize(@NonNull String input) { normalizeTokenAndFlush(currentToken, normalized); return normalized.toString() - .replaceFirst("^(ofthe|of|the)+", ""); // remove any false starts + .replaceFirst("^(ofthe|of|the)+", ""); // remove any false starts } private static void normalizeTokenAndFlush(StringBuilder currentToken, StringBuilder output) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/AuthorListParser.java b/jablib/src/main/java/org/jabref/logic/importer/AuthorListParser.java index 1b9d9739b05..fcfab5e0298 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/AuthorListParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/AuthorListParser.java @@ -125,7 +125,7 @@ private static SimpleNormalFormResult getSimpleNormalForm(String listOfNames) { /** * Tries to get a simple BibTeX author list of the given string. - * + *

    * This is an intermediate step in {@link #parse}. Since parse does not work in all cases, * this method can be used to get more valid BibTeX. * diff --git a/jablib/src/main/java/org/jabref/logic/importer/FetcherServerException.java b/jablib/src/main/java/org/jabref/logic/importer/FetcherServerException.java index 2261851ed81..37878d1799b 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/FetcherServerException.java +++ b/jablib/src/main/java/org/jabref/logic/importer/FetcherServerException.java @@ -5,7 +5,7 @@ import org.jabref.model.http.SimpleHttpResponse; /** - * Should be thrown when you encounter a http status code error >= 500 + * Should be thrown when you encounter a http status code error >= 500 */ public class FetcherServerException extends FetcherException { public FetcherServerException(URL source, SimpleHttpResponse httpResponse) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/FulltextFetchers.java b/jablib/src/main/java/org/jabref/logic/importer/FulltextFetchers.java index fde45b0b135..be4b3415102 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/FulltextFetchers.java +++ b/jablib/src/main/java/org/jabref/logic/importer/FulltextFetchers.java @@ -26,7 +26,7 @@ /** * Utility class for trying to resolve URLs to full-text PDF for articles. - * + *

    * Combines multiple {@link FulltextFetcher}s together. Each fetcher is invoked, the "best" result (sorted by the fetcher trust level) is returned. */ public class FulltextFetchers { diff --git a/jablib/src/main/java/org/jabref/logic/importer/ImportCleanup.java b/jablib/src/main/java/org/jabref/logic/importer/ImportCleanup.java index 8ba167f59b1..9bd59ed3a06 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/ImportCleanup.java +++ b/jablib/src/main/java/org/jabref/logic/importer/ImportCleanup.java @@ -25,8 +25,10 @@ protected ImportCleanup(FieldPreferences fieldPreferences) { */ public static ImportCleanup targeting(BibDatabaseMode mode, @NonNull FieldPreferences fieldPreferences) { return switch (mode) { - case BIBTEX -> new ImportCleanupBibtex(fieldPreferences); - case BIBLATEX -> new ImportCleanupBiblatex(fieldPreferences); + case BIBTEX -> + new ImportCleanupBibtex(fieldPreferences); + case BIBLATEX -> + new ImportCleanupBiblatex(fieldPreferences); }; } diff --git a/jablib/src/main/java/org/jabref/logic/importer/ImportCleanupBiblatex.java b/jablib/src/main/java/org/jabref/logic/importer/ImportCleanupBiblatex.java index 269b489212a..d0d178edd5c 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/ImportCleanupBiblatex.java +++ b/jablib/src/main/java/org/jabref/logic/importer/ImportCleanupBiblatex.java @@ -21,7 +21,7 @@ public ImportCleanupBiblatex(FieldPreferences fieldPreferences) { @Override public BibEntry doPostCleanup(BibEntry entry) { entry = super.doPostCleanup(entry); - convertToBiblatexCleanup.cleanup(entry); - return entry; + convertToBiblatexCleanup.cleanup(entry); + return entry; } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/ImporterPreferences.java b/jablib/src/main/java/org/jabref/logic/importer/ImporterPreferences.java index 709b02b9005..3e1c27449e5 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/ImporterPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/importer/ImporterPreferences.java @@ -150,7 +150,7 @@ public void setCatalogs(List catalogs) { } public ObservableList getCatalogs() { - return catalogs; + return catalogs; } public PlainCitationParserChoice getDefaultPlainCitationParser() { diff --git a/jablib/src/main/java/org/jabref/logic/importer/OpenDatabase.java b/jablib/src/main/java/org/jabref/logic/importer/OpenDatabase.java index 0604fa5c85b..8012e9c27aa 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/OpenDatabase.java +++ b/jablib/src/main/java/org/jabref/logic/importer/OpenDatabase.java @@ -25,7 +25,7 @@ public static ParserResult loadDatabase(Path fileToOpen, ImportFormatPreferences } public static ParserResult loadDatabase(InputStream inputStream, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileUpdateMonitor) - throws IOException { + throws IOException { return new BibtexImporter(importFormatPreferences, fileUpdateMonitor).importDatabase(inputStream, new BibtexImporter.EncodingResult(Charset.defaultCharset(), true)); } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedFetcher.java index 2a740f74141..87a16737db2 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedFetcher.java @@ -14,8 +14,8 @@ public interface PagedSearchBasedFetcher extends SearchBasedFetcher { /** - * @param queryNode first search node - * @param pageNumber requested site number indexed from 0 + * @param queryNode first search node + * @param pageNumber requested site number indexed from 0 * @return Page with search results */ Page performSearchPaged(BaseQueryNode queryNode, int pageNumber) throws FetcherException; diff --git a/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedParserFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedParserFetcher.java index 61c83f747ad..1987b096cfe 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedParserFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/PagedSearchBasedParserFetcher.java @@ -40,8 +40,8 @@ private List getBibEntries(URL urlForQuery) throws FetcherException { /** * Constructs a URL based on the query, size and page number. * - * @param queryNode the first search node - * @param pageNumber the number of the page indexed from 0 + * @param queryNode the first search node + * @param pageNumber the number of the page indexed from 0 */ URL getURLForQuery(BaseQueryNode queryNode, int pageNumber) throws URISyntaxException, MalformedURLException; diff --git a/jablib/src/main/java/org/jabref/logic/importer/QueryParser.java b/jablib/src/main/java/org/jabref/logic/importer/QueryParser.java index 65359122ff2..2f50e5403f1 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/QueryParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/QueryParser.java @@ -17,7 +17,7 @@ /** * This class converts a query string written in lucene syntax into a complex query. - * + *

    * For simplicity this is currently limited to fielded data and the boolean AND operator. */ public class QueryParser { diff --git a/jablib/src/main/java/org/jabref/logic/importer/SearchBasedFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/SearchBasedFetcher.java index 461bf76ea23..dcc3cecfd7f 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/SearchBasedFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/SearchBasedFetcher.java @@ -13,7 +13,7 @@ * Searches web resources for bibliographic information based on a free-text query. * May return multiple search hits. *

    - * This interface is used for web resources which directly return BibTeX data ({@link BibEntry}) + * This interface is used for web resources which directly return BibTeX data ({@link BibEntry}) *

    */ public interface SearchBasedFetcher extends WebFetcher { @@ -39,7 +39,7 @@ default List performSearch(String searchQuery) throws FetcherException SearchQuery searchQueryObject = new SearchQuery(searchQuery); if (!searchQueryObject.isValid()) { - throw new FetcherException("The query is not valid"); + throw new FetcherException("The query is not valid"); } BaseQueryNode queryNode; SearchQueryVisitor visitor = new SearchQueryVisitor(searchQueryObject.getSearchFlags()); diff --git a/jablib/src/main/java/org/jabref/logic/importer/WebFetchers.java b/jablib/src/main/java/org/jabref/logic/importer/WebFetchers.java index 1e42d547311..3b8dd65bae2 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/WebFetchers.java +++ b/jablib/src/main/java/org/jabref/logic/importer/WebFetchers.java @@ -78,7 +78,8 @@ public static Optional getIdBasedFetcherForField(Field field, Im fetcher = new ArXivFetcher(importFormatPreferences); case ISSN -> fetcher = new IssnFetcher(); - case null, default -> { + case null, + default -> { return Optional.empty(); } } @@ -144,8 +145,8 @@ public static SortedSet getIdBasedFetchers(ImportFormatPreferenc set.add(new ArXivFetcher(importFormatPreferences)); set.add(new AstrophysicsDataSystem(importFormatPreferences, importerPreferences)); set.add(new IsbnFetcher(importFormatPreferences)); - // .addRetryFetcher(new EbookDeIsbnFetcher(importFormatPreferences))); - // .addRetryFetcher(new DoiToBibtexConverterComIsbnFetcher(importFormatPreferences))); + // .addRetryFetcher(new EbookDeIsbnFetcher(importFormatPreferences))); + // .addRetryFetcher(new DoiToBibtexConverterComIsbnFetcher(importFormatPreferences))); set.add(new DiVA(importFormatPreferences)); set.add(new DoiFetcher(importFormatPreferences)); set.add(new EuropePmcFetcher()); @@ -174,7 +175,7 @@ public static SortedSet getEntryBasedFetchers(ImporterPrefere set.add(new IsbnFetcher(importFormatPreferences)); set.add(new IssnFetcher()); // .addRetryFetcher(new EbookDeIsbnFetcher(importFormatPreferences))); - // .addRetryFetcher(new DoiToBibtexConverterComIsbnFetcher(importFormatPreferences))); + // .addRetryFetcher(new DoiToBibtexConverterComIsbnFetcher(importFormatPreferences))); set.add(new MathSciNet(importFormatPreferences)); set.add(new CrossRef()); set.add(new ZbMATH(importFormatPreferences)); @@ -241,7 +242,7 @@ public static Set getCustomizableKeyFetchers(ImportForma } /** - * Places "Search pre-configured" to the first of the set + * Places "Search pre-configured" to the first of the set */ class CompositeSearchFirstComparator implements Comparator { @Override diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ArXivFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ArXivFetcher.java index 2432eb8157e..f2deb5d2c95 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ArXivFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ArXivFetcher.java @@ -243,10 +243,10 @@ private static Optional waitForBibEntryRetrieval(CompletableFuture> bibEntryFuture, Set priorityFields, String id) { Optional bibEntry; @@ -286,7 +286,7 @@ private void inplaceAsyncInfuseArXivWithDoi(BibEntry arXivBibEntry) { * Infuse arXivBibEntryFuture with additional fields in an asynchronous way, accelerating the process by providing a valid ArXiv ID * * @param arXivBibEntryFuture A future entry that (if it exists) will be updated with new/modified fields - * @param arXivId An ArXiv ID for the main reference (from ArXiv), so that the retrieval of ArXiv-issued DOI metadata can be faster + * @param arXivId An ArXiv ID for the main reference (from ArXiv), so that the retrieval of ArXiv-issued DOI metadata can be faster * @throws FetcherException when failed to fetch the main ArtXiv Bibtex entry ('arXivBibEntryFuture'). */ private void inplaceAsyncInfuseArXivWithDoi(CompletableFuture> arXivBibEntryFuture, Optional arXivId) throws FetcherException { @@ -346,17 +346,17 @@ public Page performSearchPaged(BaseQueryNode queryNode, int pageNumber ExecutorService executor = Executors.newFixedThreadPool(getPageSize() * 2); Collection> futureSearchResult = result.getContent() - .stream() - .map(bibEntry -> - CompletableFuture.supplyAsync(() -> { - this.inplaceAsyncInfuseArXivWithDoi(bibEntry); - return bibEntry; - }, executor)) - .toList(); + .stream() + .map(bibEntry -> + CompletableFuture.supplyAsync(() -> { + this.inplaceAsyncInfuseArXivWithDoi(bibEntry); + return bibEntry; + }, executor)) + .toList(); Collection modifiedSearchResult = futureSearchResult.stream() - .map(CompletableFuture::join) - .collect(Collectors.toList()); + .map(CompletableFuture::join) + .collect(Collectors.toList()); return new Page<>(result.getQuery(), result.getPageNumber(), modifiedSearchResult); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ComplexSearchQuery.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ComplexSearchQuery.java index d3484e6d7f6..992d57b3eca 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ComplexSearchQuery.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ComplexSearchQuery.java @@ -41,16 +41,25 @@ public static ComplexSearchQuery fromTerms(List terms) { terms.forEach(term -> { String termText = term.text(); switch (term.field().toLowerCase()) { - case "author" -> builder.author(termText); - case "title" -> builder.titlePhrase(termText); - case "abstract" -> builder.abstractPhrase(termText); - case "journal" -> builder.journal(termText); - case "year" -> builder.singleYear(Integer.valueOf(termText)); - case "year-range" -> builder.parseYearRange(termText); - case "doi" -> builder.DOI(termText); - case "default" -> builder.defaultFieldPhrase(termText); + case "author" -> + builder.author(termText); + case "title" -> + builder.titlePhrase(termText); + case "abstract" -> + builder.abstractPhrase(termText); + case "journal" -> + builder.journal(termText); + case "year" -> + builder.singleYear(Integer.valueOf(termText)); + case "year-range" -> + builder.parseYearRange(termText); + case "doi" -> + builder.DOI(termText); + case "default" -> + builder.defaultFieldPhrase(termText); // add unknown field as default field - default -> builder.defaultFieldPhrase(termText); + default -> + builder.defaultFieldPhrase(termText); } }); return builder.build(); @@ -253,14 +262,22 @@ public ComplexSearchQueryBuilder terms(Collection terms) { terms.forEach(term -> { String termText = term.text(); switch (term.field().toLowerCase()) { - case "author" -> this.author(termText); - case "title" -> this.titlePhrase(termText); - case "abstract" -> this.abstractPhrase(termText); - case "journal" -> this.journal(termText); - case "doi" -> this.DOI(termText); - case "year" -> this.singleYear(Integer.valueOf(termText)); - case "year-range" -> this.parseYearRange(termText); - case "default" -> this.defaultFieldPhrase(termText); + case "author" -> + this.author(termText); + case "title" -> + this.titlePhrase(termText); + case "abstract" -> + this.abstractPhrase(termText); + case "journal" -> + this.journal(termText); + case "doi" -> + this.DOI(termText); + case "year" -> + this.singleYear(Integer.valueOf(termText)); + case "year-range" -> + this.parseYearRange(termText); + case "default" -> + this.defaultFieldPhrase(termText); } }); return this; diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CrossRef.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CrossRef.java index 65a97a1f1c9..ddfaf0f208e 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/CrossRef.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/CrossRef.java @@ -208,7 +208,7 @@ private String getKeywords(JSONArray jsonArray) { StringBuilder keywords = new StringBuilder(); for (int i = 0; i < jsonArray.length(); i++) { - keywords.append(jsonArray.getString(i)); + keywords.append(jsonArray.getString(i)); if (i != jsonArray.length() - 1) { keywords.append(", "); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DOABFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DOABFetcher.java index c994f34f133..c7c893c0697 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/DOABFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/DOABFetcher.java @@ -116,17 +116,21 @@ private BibEntry jsonToBibEntry(JSONArray metadataArray, JSONArray bitstreamArra switch (dataObject.getString("key")) { case "dc.contributor.author" -> { if (dataObject.getString("value").contains("(Ed.)")) { - editorsList.add(toAuthor(namePreprocessing(dataObject.getString("value")))); + editorsList.add(toAuthor(namePreprocessing(dataObject.getString("value")))); } else { authorsList.add(toAuthor(dataObject.getString("value"))); } } - case "dc.type" -> entry.setType(StandardEntryType.Book); - case "dc.date.issued" -> entry.setField(StandardField.DATE, dataObject.getString("value")); - case "oapen.identifier.doi" -> entry.setField(StandardField.DOI, - dataObject.getString("value")); - case "dc.title" -> entry.setField(StandardField.TITLE, - dataObject.getString("value")); + case "dc.type" -> + entry.setType(StandardEntryType.Book); + case "dc.date.issued" -> + entry.setField(StandardField.DATE, dataObject.getString("value")); + case "oapen.identifier.doi" -> + entry.setField(StandardField.DOI, + dataObject.getString("value")); + case "dc.title" -> + entry.setField(StandardField.TITLE, + dataObject.getString("value")); case "oapen.pages" -> { try { entry.setField(StandardField.PAGES, String.valueOf(dataObject.getInt("value"))); @@ -134,28 +138,39 @@ private BibEntry jsonToBibEntry(JSONArray metadataArray, JSONArray bitstreamArra entry.setField(StandardField.PAGES, dataObject.getString("value")); } } - case "dc.description.abstract" -> entry.setField(StandardField.ABSTRACT, - dataObject.getString("value")); - case "dc.language" -> entry.setField(StandardField.LANGUAGE, - dataObject.getString("value")); - case "publisher.name" -> entry.setField(StandardField.PUBLISHER, - dataObject.getString("value")); - case "dc.identifier.uri" -> entry.setField(StandardField.URI, - dataObject.getString("value")); + case "dc.description.abstract" -> + entry.setField(StandardField.ABSTRACT, + dataObject.getString("value")); + case "dc.language" -> + entry.setField(StandardField.LANGUAGE, + dataObject.getString("value")); + case "publisher.name" -> + entry.setField(StandardField.PUBLISHER, + dataObject.getString("value")); + case "dc.identifier.uri" -> + entry.setField(StandardField.URI, + dataObject.getString("value")); case "dc.identifier" -> { if (dataObject.getString("value").contains("http")) { - entry.setField(StandardField.URL, dataObject.getString("value")); + entry.setField(StandardField.URL, dataObject.getString("value")); } } - case "dc.subject.other" -> keywordJoiner.add(dataObject.getString("value")); - case "dc.contributor.editor" -> editorsList.add(toAuthor(dataObject.getString("value"))); - case "oapen.volume" -> entry.setField(StandardField.VOLUME, - dataObject.getString("value")); - case "oapen.relation.isbn", "dc.identifier.isbn" -> entry.setField(StandardField.ISBN, - dataObject.getString("value")); - case "dc.title.alternative" -> entry.setField(StandardField.SUBTITLE, - dataObject.getString("value")); - case "oapen.imprint" -> publisherImprint = dataObject.getString("value"); + case "dc.subject.other" -> + keywordJoiner.add(dataObject.getString("value")); + case "dc.contributor.editor" -> + editorsList.add(toAuthor(dataObject.getString("value"))); + case "oapen.volume" -> + entry.setField(StandardField.VOLUME, + dataObject.getString("value")); + case "oapen.relation.isbn", + "dc.identifier.isbn" -> + entry.setField(StandardField.ISBN, + dataObject.getString("value")); + case "dc.title.alternative" -> + entry.setField(StandardField.SUBTITLE, + dataObject.getString("value")); + case "oapen.imprint" -> + publisherImprint = dataObject.getString("value"); } } 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 e6dac8a9c7b..fe8f5964f6d 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 @@ -33,7 +33,7 @@ /** * FulltextFetcher implementation that follows the DOI resolution redirects and scans for a full-text PDF URL. - * + *

    * Note that we also have custom fetchers in place. * See {@link WebFetchers#getFullTextFetchers(ImportFormatPreferences, ImporterPreferences)}. */ diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/IEEE.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/IEEE.java index a4878bedf95..4f394813434 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/IEEE.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/IEEE.java @@ -77,10 +77,14 @@ private static BibEntry parseJsonResponse(JSONObject jsonEntry, Character keywor BibEntry entry = new BibEntry(); switch (jsonEntry.optString("content_type")) { - case "Books" -> entry.setType(StandardEntryType.Book); - case "Conferences" -> entry.setType(StandardEntryType.InProceedings); - case "Courses" -> entry.setType(StandardEntryType.Misc); - default -> entry.setType(StandardEntryType.Article); + case "Books" -> + entry.setType(StandardEntryType.Book); + case "Conferences" -> + entry.setType(StandardEntryType.InProceedings); + case "Courses" -> + entry.setType(StandardEntryType.Misc); + default -> + entry.setType(StandardEntryType.Article); } entry.setField(StandardField.ABSTRACT, jsonEntry.optString("abstract")); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/LOBIDFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/LOBIDFetcher.java index cc4edaf359f..fe9d540d133 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/LOBIDFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/LOBIDFetcher.java @@ -46,8 +46,8 @@ public class LOBIDFetcher implements PagedSearchBasedParserFetcher, IdBasedParse /** * Gets the query URL * - * @param queryNode the first parsed node - * @param pageNumber the number of the page indexed from 0 + * @param queryNode the first parsed node + * @param pageNumber the number of the page indexed from 0 * @return URL */ @Override @@ -175,9 +175,9 @@ private BibEntry parseJSONtoBibtex(JSONObject jsonEntry) { JSONArray keywordArray = jsonEntry.optJSONArray("subjectslabels"); if (keywordArray != null) { List keywordList = IntStream.range(0, keywordArray.length()) - .mapToObj(keywordArray::optString) - .filter(keyword -> !keyword.isEmpty()) - .toList(); + .mapToObj(keywordArray::optString) + .filter(keyword -> !keyword.isEmpty()) + .toList(); entry.setField(StandardField.KEYWORDS, String.join(", ", keywordList)); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/Medra.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/Medra.java index b81975cb009..c24752109d6 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/Medra.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/Medra.java @@ -89,8 +89,8 @@ private String toAuthors(JSONArray authors) { return IntStream.range(0, authors.length()) .mapToObj(authors::getJSONObject) .map(author -> author.has("literal") ? // quickly route through the literal string - new Author(author.getString("literal"), "", "", "", "") : - new Author(author.optString("given", ""), "", "", author.optString("family", ""), "")) + new Author(author.getString("literal"), "", "", "", "") : + new Author(author.optString("given", ""), "", "", author.optString("family", ""), "")) .collect(AuthorList.collect()) .getAsFirstLastNamesWithAnd(); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/OpenAccessDoi.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/OpenAccessDoi.java index 8083b22d5a9..e224fe3ebd2 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/OpenAccessDoi.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/OpenAccessDoi.java @@ -21,7 +21,7 @@ /** * A fulltext fetcher that uses oaDOI. - * + *

    * API is documented at http://unpaywall.org/api/v2 */ public class OpenAccessDoi implements FulltextFetcher { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java index 7a19dc3b91d..02fcc30bd52 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java @@ -40,8 +40,8 @@ public class ScholarArchiveFetcher implements PagedSearchBasedParserFetcher { /** * Gets the query URL by luceneQuery and pageNumber. * - * @param queryNode the first node from the parsed query - * @param pageNumber the number of the page indexed from 0 + * @param queryNode the first node from the parsed query + * @param pageNumber the number of the page indexed from 0 * @return URL */ @Override diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java index 65d2e82a234..bb46b94eacc 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java @@ -95,10 +95,10 @@ public Optional findFullText(BibEntry entry) throws IOException, FetcherExc } String source = SOURCE_ID_SEARCH + arXivString; Connection jsoupRequest = Jsoup.connect(getURLBySource(source)) - .userAgent(URLDownload.USER_AGENT) - .referrer("https://www.google.com") - .header("Accept", "text/html; charset=utf-8") - .ignoreHttpErrors(true); + .userAgent(URLDownload.USER_AGENT) + .referrer("https://www.google.com") + .header("Accept", "text/html; charset=utf-8") + .ignoreHttpErrors(true); importerPreferences.getApiKey(getName()).ifPresent( key -> jsoupRequest.header("x-api-key", key)); html = jsoupRequest.get(); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcher.java index c7cc54bcd3a..fd5b5a0d809 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcher.java @@ -175,8 +175,8 @@ public String getTestUrl() { /** * Gets the query URL * - * @param queryNode the search query - * @param pageNumber the number of the page indexed from 0 + * @param queryNode the search query + * @param pageNumber the number of the page indexed from 0 * @return URL */ @Override diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java index 0c6f76b9a32..f2ee780bb8d 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java @@ -146,11 +146,11 @@ private String fromWorksToAuthors(JSONArray works) { } List authors = IntStream.range(0, works.length()) - .mapToObj(works::getJSONObject) - .map(obj -> obj.getString("key")) - .map(worksLink -> BASE_URL + worksLink + ".json") - .flatMap(this::fromWorkToAuthors) - .collect(Collectors.toList()); + .mapToObj(works::getJSONObject) + .map(obj -> obj.getString("key")) + .map(worksLink -> BASE_URL + worksLink + ".json") + .flatMap(this::fromWorkToAuthors) + .collect(Collectors.toList()); return AuthorList.of(authors).getAsLastFirstNamesWithAnd(false); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/AbstractQueryTransformer.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/AbstractQueryTransformer.java index 524b269292c..a337c21b15b 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/AbstractQueryTransformer.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/AbstractQueryTransformer.java @@ -51,7 +51,7 @@ protected Optional transform(OperatorNode query) { /** * Returns the logical AND operator used by the library * Note: whitespaces have to be included around the operator - * + *

    * Example: " AND " */ protected abstract String getLogicalAndOperator(); @@ -59,14 +59,14 @@ protected Optional transform(OperatorNode query) { /** * Returns the logical OR operator used by the library * Note: whitespaces have to be included around the operator - * + *

    * Example: " OR " */ protected abstract String getLogicalOrOperator(); /** * Returns the logical NOT operator used by the library - * + *

    * Example: "!" */ protected abstract String getLogicalNotOperator(); @@ -158,7 +158,7 @@ protected void parseYearRange(String yearRange) { /** * Return a string representation of the year-range fielded term * Should follow the structure yyyy-yyyy - * + *

    * Example: 2015-2021 */ protected String handleYearRange(String yearRange) { @@ -210,7 +210,8 @@ protected Optional transform(BaseQueryNode query) { case NotNode notQueryNode -> { return transform(notQueryNode); } - case null, default -> { + case null, + default -> { LOGGER.error("Unsupported case when transforming the query:\n {}", query); return Optional.empty(); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformer.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformer.java index 695ac643116..23a28d5277c 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformer.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformer.java @@ -67,15 +67,15 @@ protected String handleYear(String year) { @Override protected String handleYearRange(String yearRange) { - parseYearRange(yearRange); - if (endYear == Integer.MAX_VALUE) { // invalid year range - Calendar calendar = Calendar.getInstance(); - this.getJSONPayload().put("yearEnd", calendar.get(Calendar.YEAR)); - return ""; - } - this.getJSONPayload().put("yearStart", startYear); - this.getJSONPayload().put("yearEnd", endYear); - return yearRange; + parseYearRange(yearRange); + if (endYear == Integer.MAX_VALUE) { // invalid year range + Calendar calendar = Calendar.getInstance(); + this.getJSONPayload().put("yearEnd", calendar.get(Calendar.YEAR)); + return ""; + } + this.getJSONPayload().put("yearStart", startYear); + this.getJSONPayload().put("yearEnd", endYear); + return yearRange; } /** @@ -85,11 +85,16 @@ protected String handleYearRange(String yearRange) { @Override protected Optional handleOtherField(String fieldAsString, String term) { return switch (fieldAsString) { - case "page" -> handlePage(term); - case "pageSize" -> handlePageSize(term); - case "must_have_pdf" -> handleMustHavePdf(term); - case "sortBy" -> handleSortBy(term); - default -> super.handleOtherField(fieldAsString, term); + case "page" -> + handlePage(term); + case "pageSize" -> + handlePageSize(term); + case "must_have_pdf" -> + handleMustHavePdf(term); + case "sortBy" -> + handleSortBy(term); + default -> + super.handleOtherField(fieldAsString, term); }; } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/IEEEQueryTransformer.java b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/IEEEQueryTransformer.java index 9cadd20718f..dcaa23e0234 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/IEEEQueryTransformer.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fetcher/transformers/IEEEQueryTransformer.java @@ -7,7 +7,7 @@ /** * Needs to be instantiated for each new query - * + *

    * Stop words are ignored. See ADR-0022. */ public class IEEEQueryTransformer extends YearRangeByFilteringQueryTransformer { @@ -57,8 +57,10 @@ protected String handleYear(String year) { @Override protected Optional handleOtherField(String fieldAsString, String term) { return switch (fieldAsString) { - case "article_number" -> handleArticleNumber(term); - default -> super.handleOtherField(fieldAsString, term); + case "article_number" -> + handleArticleNumber(term); + default -> + super.handleOtherField(fieldAsString, term); }; } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporter.java index bae0346b34f..ed89639fc91 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporter.java @@ -209,7 +209,7 @@ private static String getPageContents(PDDocument document, PDFTextStripper strip /** * Example: J. Knaster et al., “Overview of the IFMIF/EVEDA project”, Nucl. Fusion, vol. 57, p. 102016, 2017. doi:10.1088/ 1741-4326/aa6a6a * - * @param number The number of the reference - used for logging only + * @param number The number of the reference - used for logging only */ @VisibleForTesting BibEntry parseReference(String number, String reference) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BiblioscapeImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BiblioscapeImporter.java index 81a6d54dbf9..167ff67a562 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BiblioscapeImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BiblioscapeImporter.java @@ -154,7 +154,7 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } else if ("UR".equals(entry.getKey()) || "AT".equals(entry.getKey())) { String s = entry.getValue().toString().trim(); hm.put(s.startsWith("http://") || s.startsWith("ftp://") ? StandardField.URL - : StandardField.PDF, entry.getValue().toString()); + : StandardField.PDF, entry.getValue().toString()); } else if ("C1".equals(entry.getKey())) { comments.add("Custom1: " + entry.getValue()); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexImporter.java index 5eb0d9701c4..c634a3e7488 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexImporter.java @@ -45,7 +45,7 @@ public BibtexImporter(ImportFormatPreferences importFormatPreferences, FileUpdat /** * @return true as we have no effective way to decide whether a file is in bibtex format or not. See - * https://github.com/JabRef/jabref/pull/379#issuecomment-158685726 for more details. + * https://github.com/JabRef/jabref/pull/379#issuecomment-158685726 for more details. */ @Override public boolean isRecognizedFormat(BufferedReader reader) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CffImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CffImporter.java index 7b8ce084367..922b8d6ecc5 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CffImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CffImporter.java @@ -196,8 +196,8 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { // Select DOI to keep if ((entryMap.get(StandardField.DOI) == null) && (citation.ids != null)) { List doiIds = citation.ids.stream() - .filter(id -> "doi".equals(id.type)) - .toList(); + .filter(id -> "doi".equals(id.type)) + .toList(); if (doiIds.size() == 1) { entryMap.put(StandardField.DOI, doiIds.getFirst().value); } @@ -206,9 +206,9 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { // Select SWHID to keep if (citation.ids != null) { List swhIds = citation.ids.stream() - .filter(id -> "swh".equals(id.type)) - .map(id -> id.value) - .toList(); + .filter(id -> "swh".equals(id.type)) + .map(id -> id.value) + .toList(); if (swhIds.size() == 1) { entryMap.put(BiblatexSoftwareField.SWHID, swhIds.getFirst()); @@ -278,9 +278,9 @@ private String parseAuthors(List authors) { return authors.stream() .map(author -> author.values) .map(vals -> vals.get("name") != null ? - new Author(vals.get("name"), "", "", "", "") : - new Author(vals.get("given-names"), null, vals.get("name-particle"), - vals.get("family-names"), vals.get("name-suffix"))) + new Author(vals.get("name"), "", "", "", "") : + new Author(vals.get("given-names"), null, vals.get("name-particle"), + vals.get("family-names"), vals.get("name-suffix"))) .collect(AuthorList.collect()) .getAsFirstLastNamesWithAnd(); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CitaviXmlImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CitaviXmlImporter.java index 93c8fcb4dd4..44328888ef9 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CitaviXmlImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CitaviXmlImporter.java @@ -152,16 +152,26 @@ private void parseCitaviData(XMLStreamReader reader) throws XMLStreamException { case XMLStreamConstants.START_ELEMENT -> { String startElementName = reader.getLocalName(); switch (startElementName) { - case "Persons" -> parsePersons(reader); - case "Keywords" -> parseKeywords(reader); - case "Publishers" -> parsePublishers(reader); - case "References" -> parseReferences(reader); - case "KnowledgeItems" -> parseKnowledgeItems(reader); - case "ReferenceAuthors" -> parseReferenceIdLink(reader, "ReferenceAuthors", refIdWithAuthorIds); - case "ReferenceKeywords" -> parseReferenceIdLink(reader, "ReferenceKeywords", refIdWithKeywordsIds); - case "ReferencePublishers" -> parseReferenceIdLink(reader, "ReferencePublishers", refIdWithPublisherIds); - case "ReferenceEditors" -> parseReferenceIdLink(reader, "ReferenceEditors", refIdWithEditorIds); - default -> consumeElement(reader); + case "Persons" -> + parsePersons(reader); + case "Keywords" -> + parseKeywords(reader); + case "Publishers" -> + parsePublishers(reader); + case "References" -> + parseReferences(reader); + case "KnowledgeItems" -> + parseKnowledgeItems(reader); + case "ReferenceAuthors" -> + parseReferenceIdLink(reader, "ReferenceAuthors", refIdWithAuthorIds); + case "ReferenceKeywords" -> + parseReferenceIdLink(reader, "ReferenceKeywords", refIdWithKeywordsIds); + case "ReferencePublishers" -> + parseReferenceIdLink(reader, "ReferencePublishers", refIdWithPublisherIds); + case "ReferenceEditors" -> + parseReferenceIdLink(reader, "ReferenceEditors", refIdWithEditorIds); + default -> + consumeElement(reader); } } case XMLStreamConstants.END_ELEMENT -> { @@ -344,16 +354,26 @@ private void parseReference(XMLStreamReader reader) throws XMLStreamException { case XMLStreamConstants.START_ELEMENT -> { String elementName = reader.getLocalName(); switch (elementName) { - case "ReferenceType" -> referenceType = reader.getElementText(); - case "Title" -> title = reader.getElementText(); - case "Year" -> year = reader.getElementText(); - case "Abstract" -> abstractText = reader.getElementText(); - case "PageRange" -> pageRange = reader.getElementText(); - case "PageCount" -> pageCount = reader.getElementText(); - case "Volume" -> volume = reader.getElementText(); - case "Doi" -> doi = reader.getElementText(); - case "Isbn" -> isbn = reader.getElementText(); - default -> consumeElement(reader); + case "ReferenceType" -> + referenceType = reader.getElementText(); + case "Title" -> + title = reader.getElementText(); + case "Year" -> + year = reader.getElementText(); + case "Abstract" -> + abstractText = reader.getElementText(); + case "PageRange" -> + pageRange = reader.getElementText(); + case "PageCount" -> + pageCount = reader.getElementText(); + case "Volume" -> + volume = reader.getElementText(); + case "Doi" -> + doi = reader.getElementText(); + case "Isbn" -> + isbn = reader.getElementText(); + default -> + consumeElement(reader); } } case XMLStreamConstants.END_ELEMENT -> { @@ -400,13 +420,20 @@ private void parseKnowledgeItem(XMLStreamReader reader) throws XMLStreamExceptio case XMLStreamConstants.START_ELEMENT -> { String elementName = reader.getLocalName(); switch (elementName) { - case "ReferenceID" -> referenceId = reader.getElementText(); - case "CoreStatement" -> coreStatement = reader.getElementText(); - case "Text" -> text = reader.getElementText(); - case "PageRangeNumber" -> pageRangeNumber = reader.getElementText(); - case "QuotationType" -> quotationType = reader.getElementText(); - case "QuotationIndex" -> quotationIndex = reader.getElementText(); - default -> consumeElement(reader); + case "ReferenceID" -> + referenceId = reader.getElementText(); + case "CoreStatement" -> + coreStatement = reader.getElementText(); + case "Text" -> + text = reader.getElementText(); + case "PageRangeNumber" -> + pageRangeNumber = reader.getElementText(); + case "QuotationType" -> + quotationType = reader.getElementText(); + case "QuotationIndex" -> + quotationIndex = reader.getElementText(); + default -> + consumeElement(reader); } } case XMLStreamConstants.END_ELEMENT -> { @@ -477,7 +504,7 @@ private List buildBibItems() { .ifPresent(value -> entry.setField(StandardField.KEYWORDS, clean(value))); Optional.ofNullable(getKnowledgeItem(knowledgeItemsByRefId, reference)) - .ifPresent(value -> entry.setField(StandardField.COMMENT, StringUtil.unifyLineBreaks(value, "\n"))); + .ifPresent(value -> entry.setField(StandardField.COMMENT, StringUtil.unifyLineBreaks(value, "\n"))); bibItems.add(entry); } @@ -513,9 +540,9 @@ private Map resolvePersonMap(Map> reference List personIds = entry.getValue(); List authorsForThisReferenceId = personIds.stream() - .map(personMap::get) - .filter(Objects::nonNull) - .toList(); + .map(personMap::get) + .filter(Objects::nonNull) + .toList(); if (!authorsForThisReferenceId.isEmpty()) { String stringifiedAuthors = AuthorList.of(authorsForThisReferenceId).getAsLastFirstNamesWithAnd(false); @@ -624,12 +651,24 @@ private EntryType getType(Reference reference) { private static EntryType convertRefNameToType(String refName) { return switch (refName.toLowerCase().trim()) { - case "artwork", "generic", "musicalbum", "audioorvideodocument", "movie" -> StandardEntryType.Misc; - case "electronic article" -> IEEETranEntryType.Electronic; - case "book section" -> StandardEntryType.InBook; - case "book", "bookedited", "audiobook" -> StandardEntryType.Book; - case "report" -> StandardEntryType.Report; - default -> StandardEntryType.Article; + case "artwork", + "generic", + "musicalbum", + "audioorvideodocument", + "movie" -> + StandardEntryType.Misc; + case "electronic article" -> + IEEETranEntryType.Electronic; + case "book section" -> + StandardEntryType.InBook; + case "book", + "bookedited", + "audiobook" -> + StandardEntryType.Book; + case "report" -> + StandardEntryType.Report; + default -> + StandardEntryType.Article; }; } @@ -642,21 +681,21 @@ String cleanUpText(String text) { private String removeSpacesBeforeLineBreak(String string) { return string.replaceAll(" +\r\n", "\r\n") - .replaceAll(" +\n", "\n"); + .replaceAll(" +\n", "\n"); } @Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); throw new UnsupportedOperationException("CitaviXmlImporter does not support importDatabase(BufferedReader reader). " - + "Instead use importDatabase(Path filePath, Charset defaultEncoding)."); + + "Instead use importDatabase(Path filePath, Charset defaultEncoding)."); } @Override public List parseEntries(InputStream inputStream) { try { return importDatabase( - new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))).getDatabase().getEntries(); + new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))).getDatabase().getEntries(); } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); } @@ -684,11 +723,11 @@ private void consumeElement(XMLStreamReader reader) throws XMLStreamException { * * 113 true 113 113 * - * } + *} * Contents of {@code PageCount} after parsing above example data: * {@snippet : * 113 true 113 113 - * } + *} * Content of "ps" tag is returned by {@code getPages}. *

    * Example {@code PageRange}: @@ -700,13 +739,13 @@ private void consumeElement(XMLStreamReader reader) throws XMLStreamException { * 34165-223 * ]]> * - * } + *} * Contents of {@code PageRange} after parsing above example data: * {@snippet : * 24 true 24 24 * 31 true 31 31 * 24-31 - * } + *} * Content of "os" tag is returned by {@code getPages}. */ private String getPages(String pageRange, String pageCount) { @@ -750,16 +789,16 @@ private BufferedReader getReaderFromZip(Path filePath) throws IOException { return new BufferedReader( new InputStreamReader( new BOMInputStream.Builder() - .setInputStream(Files.newInputStream(newFile, StandardOpenOption.READ)) - .setInclude(false) - .setByteOrderMarks(ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE) - .get())); + .setInputStream(Files.newInputStream(newFile, StandardOpenOption.READ)) + .setInclude(false) + .setByteOrderMarks(ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE) + .get())); } private String clean(String input) { String result = StringUtil.unifyLineBreaks(input, " ") - .trim() - .replaceAll(" +", " "); + .trim() + .replaceAll(" +", " "); return htmlToLatexFormatter.format(result); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CustomImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CustomImporter.java index 392074470aa..66b50f2db3f 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/CustomImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/CustomImporter.java @@ -38,7 +38,7 @@ public CustomImporter(String basePath, String className) throws ImportException private static Importer load(URL basePathURL, String className) throws IOException, ReflectiveOperationException { - try (URLClassLoader cl = new URLClassLoader(new URL[]{basePathURL})) { + try (URLClassLoader cl = new URLClassLoader(new URL[] {basePathURL})) { Class clazz = Class.forName(className, true, cl); return (Importer) clazz.getDeclaredConstructor().newInstance(); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java index f356d5570f1..d53664615b6 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java @@ -181,12 +181,18 @@ private BibEntry parseRecord(XMLStreamReader reader) throws XMLStreamException { .orElse(StandardEntryType.Misc); entry.setType(entryType); } - case "contributors" -> parseContributors(reader, entry); - case "titles" -> parseTitles(reader, entry); - case "periodical" -> parsePeriodical(reader, entry); - case "keywords" -> parseKeywords(reader, entry); - case "urls" -> parseUrls(reader, entry); - case "dates" -> parseDates(reader, entry); + case "contributors" -> + parseContributors(reader, entry); + case "titles" -> + parseTitles(reader, entry); + case "periodical" -> + parsePeriodical(reader, entry); + case "keywords" -> + parseKeywords(reader, entry); + case "urls" -> + parseUrls(reader, entry); + case "dates" -> + parseDates(reader, entry); // TODO: Left for future work -- test files need to be adpated // case "accession-num" -> { // String accessionNumber = parseElementContent(reader, "accession-num"); @@ -271,10 +277,10 @@ private void parseTitles(XMLStreamReader reader, BibEntry entry) throws XMLStrea entry.setField(StandardField.BOOKTITLE, secondaryTitle); } } - case "alt-title" -> { + case "alt-title" -> { String altTitle = parseElementContent(reader, "alt-title"); entry.setField(FIELD_ALT_TITLE, altTitle); - } + } } } } @@ -296,7 +302,10 @@ private void parsePeriodical(XMLStreamReader reader, BibEntry entry) throws XMLS private void parseJournalOrBookTitle(XMLStreamReader reader, BibEntry entry) throws XMLStreamException { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "full-title", "abbr-2", "abbr-1", "abbr-3" -> { + case "full-title", + "abbr-2", + "abbr-1", + "abbr-3" -> { String title = parseElementContent(reader, elementName); if (entry.getType().equals(StandardEntryType.Article)) { entry.setField(StandardField.JOURNAL, title); @@ -388,7 +397,9 @@ private void parseDates(XMLStreamReader reader, BibEntry entry) throws XMLStream if (isStartElement(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "year", "month", "day" -> { + case "year", + "month", + "day" -> { String date = parseElementContent(reader, elementName); entry.setField(StandardField.fromName(elementName).get(), date); } 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 409e3f8ca7d..9ef27aff6e3 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 @@ -224,9 +224,11 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } case "TI" -> hm.put(StandardField.TITLE, EOL_PATTERN.matcher(value).replaceAll(" ")); - case "SO", "JA" -> + case "SO", + "JA" -> hm.put(StandardField.JOURNAL, EOL_PATTERN.matcher(value).replaceAll(" ")); - case "ID", "KW" -> { + case "ID", + "KW" -> { value = EOL_PATTERN.matcher(value).replaceAll(" "); String existingKeywords = hm.get(StandardField.KEYWORDS); if ((existingKeywords == null) || existingKeywords.contains(value)) { @@ -238,7 +240,10 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } case "AB" -> hm.put(StandardField.ABSTRACT, EOL_PATTERN.matcher(value).replaceAll(" ")); - case "BP", "BR", "SP", "AR" -> + case "BP", + "BR", + "SP", + "AR" -> pages = new StringBuilder(value); case "EP" -> { int detpos = value.indexOf(' '); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MarcXmlParser.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MarcXmlParser.java index 8ba8a8c5738..fd8bdbaceb2 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MarcXmlParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MarcXmlParser.java @@ -359,12 +359,18 @@ private void putIssue(BibEntry bibEntry, Element datafield) { if (StringUtil.isNotBlank(value)) { switch (key) { - case "number" -> bibEntry.setField(StandardField.NUMBER, value); - case "year" -> bibEntry.setField(StandardField.YEAR, value); - case "pages" -> bibEntry.setField(StandardField.PAGES, value); - case "volume" -> bibEntry.setField(StandardField.VOLUME, value); - case "day" -> bibEntry.setField(StandardField.DAY, value); - case "month" -> bibEntry.setField(StandardField.MONTH, value); + case "number" -> + bibEntry.setField(StandardField.NUMBER, value); + case "year" -> + bibEntry.setField(StandardField.YEAR, value); + case "pages" -> + bibEntry.setField(StandardField.PAGES, value); + case "volume" -> + bibEntry.setField(StandardField.VOLUME, value); + case "day" -> + bibEntry.setField(StandardField.DAY, value); + case "month" -> + bibEntry.setField(StandardField.MONTH, value); } } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlineImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlineImporter.java index 1695d90b250..87df5606776 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlineImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlineImporter.java @@ -117,8 +117,10 @@ public ParserResult importDatabase(BufferedReader input) throws IOException { if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "PubmedArticle" -> parseArticle(reader, bibItems, elementName); - case "PubmedBookArticle" -> parseBookArticle(reader, bibItems, elementName); + case "PubmedArticle" -> + parseArticle(reader, bibItems, elementName); + case "PubmedBookArticle" -> + parseBookArticle(reader, bibItems, elementName); } } } @@ -139,7 +141,8 @@ private void parseBookArticle(XMLStreamReader reader, List bibItems, S if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "BookDocument" -> parseBookDocument(reader, fields, elementName); + case "BookDocument" -> + parseBookDocument(reader, fields, elementName); case "PublicationStatus" -> { reader.next(); if (isCharacterXMLEvent(reader)) { @@ -179,10 +182,15 @@ private void parseBookDocument(XMLStreamReader reader, Map fields fields.put(StandardField.PMID, reader.getText()); } } - case "DateRevised", "ContributionDate" -> parseDate(reader, fields, elementName); - case "Abstract" -> addAbstract(reader, fields, elementName); - case "Pagination" -> addPagination(reader, fields, elementName); - case "Section" -> parseSections(reader, sectionTitleList); + case "DateRevised", + "ContributionDate" -> + parseDate(reader, fields, elementName); + case "Abstract" -> + addAbstract(reader, fields, elementName); + case "Pagination" -> + addPagination(reader, fields, elementName); + case "Section" -> + parseSections(reader, sectionTitleList); case "Keyword" -> { reader.next(); if (isCharacterXMLEvent(reader)) { @@ -201,7 +209,8 @@ private void parseBookDocument(XMLStreamReader reader, Map fields articleTitleList.add(reader.getText()); } } - case "Book" -> parseBookInformation(reader, fields, elementName); + case "Book" -> + parseBookInformation(reader, fields, elementName); } } @@ -245,9 +254,12 @@ private void parseBookInformation(XMLStreamReader reader, Map fie putIfValueNotNull(fields, new UnknownField("publocation"), reader.getText()); } } - case "BookTitle" -> handleTextElement(reader, titleList, elementName); - case "PubDate" -> addPubDate(reader, fields, elementName); - case "AuthorList" -> handleAuthorList(reader, fields, elementName); + case "BookTitle" -> + handleTextElement(reader, titleList, elementName); + case "PubDate" -> + addPubDate(reader, fields, elementName); + case "AuthorList" -> + handleAuthorList(reader, fields, elementName); case "Volume" -> { reader.next(); if (isCharacterXMLEvent(reader)) { @@ -326,7 +338,8 @@ private void parseSections(XMLStreamReader reader, List sectionTitleList sectionTitleList.add(reader.getText()); } } - case "Section" -> sectionLevel++; + case "Section" -> + sectionLevel++; } } @@ -349,8 +362,10 @@ private void parseArticle(XMLStreamReader reader, List bibItems, Strin if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "MedlineCitation" -> parseMedlineCitation(reader, fields, elementName); - case "PubmedData" -> parsePubmedData(reader, fields, elementName); + case "MedlineCitation" -> + parseMedlineCitation(reader, fields, elementName); + case "PubmedData" -> + parsePubmedData(reader, fields, elementName); } } @@ -427,8 +442,12 @@ private void parseMedlineCitation(XMLStreamReader reader, Map fie if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "DateCreated", "DateCompleted", "DateRevised" -> parseDate(reader, fields, elementName); - case "Article" -> parseArticleInformation(reader, fields); + case "DateCreated", + "DateCompleted", + "DateRevised" -> + parseDate(reader, fields, elementName); + case "Article" -> + parseArticleInformation(reader, fields); case "PMID" -> { String versionStr = reader.getAttributeValue(null, "Version"); reader.next(); @@ -440,23 +459,28 @@ private void parseMedlineCitation(XMLStreamReader reader, Map fie } } } - case "MedlineJournalInfo" -> parseMedlineJournalInfo(reader, fields, elementName); - case "ChemicalList" -> parseChemicalList(reader, fields, elementName); + case "MedlineJournalInfo" -> + parseMedlineJournalInfo(reader, fields, elementName); + case "ChemicalList" -> + parseChemicalList(reader, fields, elementName); case "CitationSubset" -> { reader.next(); if (isCharacterXMLEvent(reader)) { citationSubsets.add(reader.getText()); } } - case "GeneSymbolList" -> parseGeneSymbolList(reader, fields, elementName); - case "MeshHeading" -> parseMeshHeading(reader, meshHeadingList, elementName); + case "GeneSymbolList" -> + parseGeneSymbolList(reader, fields, elementName); + case "MeshHeading" -> + parseMeshHeading(reader, meshHeadingList, elementName); case "NumberOfReferences" -> { reader.next(); if (isCharacterXMLEvent(reader)) { putIfValueNotNull(fields, new UnknownField("references"), reader.getText()); } } - case "PersonalNameSubject" -> parsePersonalNameSubject(reader, personalNameSubjectList, elementName); + case "PersonalNameSubject" -> + parsePersonalNameSubject(reader, personalNameSubjectList, elementName); case "OtherID" -> { String otherIdSource = reader.getAttributeValue(null, "Source"); reader.next(); @@ -477,7 +501,8 @@ private void parseMedlineCitation(XMLStreamReader reader, Map fie spaceFlightMissionList.add(reader.getText()); } } - case "Investigator" -> parseInvestigator(reader, investigatorList, elementName); + case "Investigator" -> + parseInvestigator(reader, investigatorList, elementName); case "GeneralNote" -> { reader.next(); if (isCharacterXMLEvent(reader)) { @@ -713,9 +738,12 @@ private void parseArticleInformation(XMLStreamReader reader, Map if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "Journal" -> parseJournal(reader, fields); - case "ArticleTitle" -> handleTextElement(reader, titleList, elementName); - case "Pagination" -> addPagination(reader, fields, elementName); + case "Journal" -> + parseJournal(reader, fields); + case "ArticleTitle" -> + handleTextElement(reader, titleList, elementName); + case "Pagination" -> + addPagination(reader, fields, elementName); case "ELocationID" -> { String eidType = reader.getAttributeValue(null, "EIdType"); String validYN = reader.getAttributeValue(null, "ValidYN"); @@ -724,8 +752,10 @@ private void parseArticleInformation(XMLStreamReader reader, Map handleElocationId(fields, reader, eidType); } } - case "Abstract" -> addAbstract(reader, fields, elementName); - case "AuthorList" -> handleAuthorList(reader, fields, elementName); + case "Abstract" -> + addAbstract(reader, fields, elementName); + case "AuthorList" -> + handleAuthorList(reader, fields, elementName); } } @@ -769,7 +799,8 @@ private void parseJournal(XMLStreamReader reader, Map fields) thr putIfValueNotNull(fields, StandardField.ISSUE, reader.getText()); } } - case "PubDate" -> addPubDate(reader, fields, elementName); + case "PubDate" -> + addPubDate(reader, fields, elementName); } } @@ -843,9 +874,9 @@ private void addArticleIdList(Map fields, List article }); articleIdList.stream() - .filter(id -> "url".equals(id.idType())) - .findFirst() - .ifPresent(id -> fields.put(StandardField.URL, id.content())); + .filter(id -> "url".equals(id.idType())) + .findFirst() + .ifPresent(id -> fields.put(StandardField.URL, id.content())); if (!fields.containsKey(StandardField.URL) && fields.containsKey(StandardField.PMID)) { String pmid = fields.get(StandardField.PMID); @@ -1008,7 +1039,8 @@ private void addAbstract(XMLStreamReader reader, Map fields, Stri putIfValueNotNull(fields, new UnknownField("copyright"), reader.getText()); } } - case "AbstractText" -> handleAbstractTextElement(reader, abstractTextList, elementName); + case "AbstractText" -> + handleAbstractTextElement(reader, abstractTextList, elementName); } } @@ -1054,8 +1086,10 @@ private void handleText(XMLStreamReader reader, List textList, String st if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "math" -> result.append(MathMLParser.parse(reader)); - case "sup", "sub" -> { + case "math" -> + result.append(MathMLParser.parse(reader)); + case "sup", + "sub" -> { reader.next(); if (isCharacterXMLEvent(reader)) { result.append("(").append(reader.getText()).append(")"); @@ -1149,9 +1183,12 @@ private void parseAuthor(XMLStreamReader reader, List authorNames) throw if (isStartXMLEvent(reader)) { String elementName = reader.getName().getLocalPart(); switch (elementName) { - case "CollectiveName" -> parseCollectiveName(reader, collectiveNames); - case "LastName" -> authorName = parseLastName(reader, authorName); - case "ForeName" -> parseForeName(reader, authorName); + case "CollectiveName" -> + parseCollectiveName(reader, collectiveNames); + case "LastName" -> + authorName = parseLastName(reader, authorName); + case "ForeName" -> + parseForeName(reader, authorName); } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlinePlainImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlinePlainImporter.java index f9fdf48e635..a075c4844e0 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlinePlainImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/MedlinePlainImporter.java @@ -187,7 +187,8 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { switch (label) { case "IRAD", "IR", - "FIR" -> fieldConversionMap.merge(new UnknownField("investigator"), value, (a, b) -> a + ", " + b); + "FIR" -> + fieldConversionMap.merge(new UnknownField("investigator"), value, (a, b) -> a + ", " + b); case "MH", "OT" -> { if (!fieldConversionMap.containsKey(StandardField.KEYWORDS)) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java index c5ce1251d00..3fbf6ab0091 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java @@ -130,8 +130,10 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B entry.setType(EntryTypeFactory.parse(mapGenre(reader.getText()))); } } - case "language" -> parseLanguage(reader, fields); - case "location" -> parseLocationAndUrl(reader, fields); + case "language" -> + parseLanguage(reader, fields); + case "location" -> + parseLocationAndUrl(reader, fields); case "identifier" -> { String type = reader.getAttributeValue(null, "type"); reader.next(); @@ -145,12 +147,18 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B notes.add(reader.getText()); } } - case "recordInfo" -> parseRecordInfo(reader, fields); - case "titleInfo" -> parseTitle(reader, fields); - case "subject" -> parseSubject(reader, fields, keywords); - case "originInfo" -> parseOriginInfo(reader, fields); - case "name" -> parseName(reader, fields, authors); - case "relatedItem" -> parseRelatedItem(reader, fields); + case "recordInfo" -> + parseRecordInfo(reader, fields); + case "titleInfo" -> + parseTitle(reader, fields); + case "subject" -> + parseSubject(reader, fields, keywords); + case "originInfo" -> + parseOriginInfo(reader, fields); + case "name" -> + parseName(reader, fields, authors); + case "relatedItem" -> + parseRelatedItem(reader, fields); } } @@ -181,8 +189,10 @@ private void parseRelatedItem(XMLStreamReader reader, Map fields) putIfValueNotNull(fields, StandardField.JOURNAL, reader.getText()); } } - case "detail" -> handleDetail(reader, fields); - case "extent" -> handleExtent(reader, fields); + case "detail" -> + handleDetail(reader, fields); + case "extent" -> + handleExtent(reader, fields); } } @@ -323,7 +333,10 @@ private void parseOriginInfo(XMLStreamReader reader, Map fields) putIfValueNotNull(fields, StandardField.EDITION, reader.getText()); } } - case "dateIssued", "dateCreated", "dateCaptured", "dateModified" -> { + case "dateIssued", + "dateCreated", + "dateCaptured", + "dateModified" -> { reader.next(); if (isCharacterXMLEvent(reader)) { putDate(fields, elementName, reader.getText()); @@ -472,11 +485,19 @@ private void parseLocationAndUrl(XMLStreamReader reader, Map fiel private String mapGenre(String genre) { return switch (genre.toLowerCase(Locale.ROOT)) { - case "conference publication" -> "proceedings"; - case "database" -> "dataset"; - case "yearbook", "handbook" -> "book"; - case "law report or digest", "technical report", "reporting" -> "report"; - default -> genre; + case "conference publication" -> + "proceedings"; + case "database" -> + "dataset"; + case "yearbook", + "handbook" -> + "book"; + case "law report or digest", + "technical report", + "reporting" -> + "report"; + default -> + genre; }; } @@ -499,20 +520,22 @@ private void putDate(Map fields, String elementName, String date) .ifPresent(parsedDate -> fields.put(StandardField.DATE, parsedDate.getNormalized())); optionalParsedDate.flatMap(Date::getYear) - .ifPresent(year -> fields.put(StandardField.YEAR, year.toString())); + .ifPresent(year -> fields.put(StandardField.YEAR, year.toString())); optionalParsedDate.flatMap(Date::getMonth) - .ifPresent(month -> fields.put(StandardField.MONTH, month.getJabRefFormat())); + .ifPresent(month -> fields.put(StandardField.MONTH, month.getJabRefFormat())); } case "dateCreated" -> { // If there was no year in date issued, then take the year from date created fields.computeIfAbsent(StandardField.YEAR, k -> date.substring(0, 4)); fields.put(new UnknownField("created"), date); } - case "dateCaptured" -> optionalParsedDate - .ifPresent(parsedDate -> fields.put(StandardField.CREATIONDATE, parsedDate.getNormalized())); - case "dateModified" -> optionalParsedDate - .ifPresent(parsedDate -> fields.put(StandardField.MODIFICATIONDATE, parsedDate.getNormalized())); + case "dateCaptured" -> + optionalParsedDate + .ifPresent(parsedDate -> fields.put(StandardField.CREATIONDATE, parsedDate.getNormalized())); + case "dateModified" -> + optionalParsedDate + .ifPresent(parsedDate -> fields.put(StandardField.MODIFICATIONDATE, parsedDate.getNormalized())); } } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ReferImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ReferImporter.java index 3c6653a5451..677dbbd1dc3 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ReferImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ReferImporter.java @@ -111,30 +111,54 @@ private void stringToBibEntry(List bibEntryList, List allEntri String val = field.substring(2); switch (tag) { - case "0" -> type = getType(val, isEdited); - case "7" -> fieldMap.put(StandardField.EDITION, val); - case "A" -> addAuthor(author, val); - case "B" -> addTag(fieldMap, type, val, "B"); - case "C" -> fieldMap.put(StandardField.ADDRESS, val); - case "D" -> fieldMap.put(StandardField.YEAR, val); - case "E" -> addEditor(editor, val); - case "F" -> fieldMap.put(InternalField.KEY_FIELD, CitationKeyGenerator.cleanKey(val, "")); - case "G" -> fieldMap.put(StandardField.LANGUAGE, val); - case "I" -> addTag(fieldMap, type, val, "I"); - case "J" -> fieldMap.putIfAbsent(StandardField.JOURNAL, val); - case "K" -> fieldMap.put(StandardField.KEYWORDS, val); - case "N" -> fieldMap.put(StandardField.ISSUE, val); - case "O" -> fieldMap.put(StandardField.NOTE, val); - case "P" -> fieldMap.put(StandardField.PAGES, val.replaceAll("([0-9]) *- *([0-9])", "$1--$2")); - case "R" -> addTag(fieldMap, type, val, "R"); - case "S" -> fieldMap.put(StandardField.SERIES, val); - case "T" -> fieldMap.put(StandardField.TITLE, val); - case "U" -> fieldMap.put(StandardField.URL, val); - case "V" -> fieldMap.put(StandardField.VOLUME, val); - case "X" -> fieldMap.put(StandardField.ABSTRACT, val); - case "?" -> fieldMap.put(StandardField.TRANSLATOR, val); - case "@" -> fieldMap.put(StandardField.ISBN, val); - default -> addTag(fieldMap, type, val, "default"); + case "0" -> + type = getType(val, isEdited); + case "7" -> + fieldMap.put(StandardField.EDITION, val); + case "A" -> + addAuthor(author, val); + case "B" -> + addTag(fieldMap, type, val, "B"); + case "C" -> + fieldMap.put(StandardField.ADDRESS, val); + case "D" -> + fieldMap.put(StandardField.YEAR, val); + case "E" -> + addEditor(editor, val); + case "F" -> + fieldMap.put(InternalField.KEY_FIELD, CitationKeyGenerator.cleanKey(val, "")); + case "G" -> + fieldMap.put(StandardField.LANGUAGE, val); + case "I" -> + addTag(fieldMap, type, val, "I"); + case "J" -> + fieldMap.putIfAbsent(StandardField.JOURNAL, val); + case "K" -> + fieldMap.put(StandardField.KEYWORDS, val); + case "N" -> + fieldMap.put(StandardField.ISSUE, val); + case "O" -> + fieldMap.put(StandardField.NOTE, val); + case "P" -> + fieldMap.put(StandardField.PAGES, val.replaceAll("([0-9]) *- *([0-9])", "$1--$2")); + case "R" -> + addTag(fieldMap, type, val, "R"); + case "S" -> + fieldMap.put(StandardField.SERIES, val); + case "T" -> + fieldMap.put(StandardField.TITLE, val); + case "U" -> + fieldMap.put(StandardField.URL, val); + case "V" -> + fieldMap.put(StandardField.VOLUME, val); + case "X" -> + fieldMap.put(StandardField.ABSTRACT, val); + case "?" -> + fieldMap.put(StandardField.TRANSLATOR, val); + case "@" -> + fieldMap.put(StandardField.ISBN, val); + default -> + addTag(fieldMap, type, val, "default"); } } 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 2da652924c3..2b94f44af34 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 @@ -51,14 +51,14 @@ /// OverviewMessageSection /// OtherMessageSection /// -/// # we skip the overview +///# we skip the overview /// OverviewMessageSection: /// 'In this issue we have: ' SectionSeparator OtherStuff /// /// OtherMessageSection: /// SectionSeparator OtherMessageSectionContent /// -/// # we skip other stuff and read only full working paper references +///# we skip other stuff and read only full working paper references /// OtherMessageSectionContent: /// WorkingPaper EmptyLine OtherMessageSectionContent /// OtherStuff EmptyLine OtherMessageSectionContent @@ -71,8 +71,8 @@ /// NonEmptyLine: /// a non-empty String that does not start with a number followed by a '.' /// -/// # working papers are recognized by a number followed by a '.' -/// # in a non-overview section +///# working papers are recognized by a number followed by a '.' +///# in a non-overview section /// WorkingPaper: /// Number'.' WhiteSpace TitleString EmptyLine Authors EmptyLine Abstract AdditionalFields /// Number'.' WhiteSpace TitleString AdditionalFields Abstract AdditionalFields @@ -80,17 +80,17 @@ /// TitleString: /// a String that may span several lines and should be joined /// -/// # there must be at least one author +///# there must be at least one author /// Authors: /// Author '\n' Authors /// Author '\n' /// -/// # optionally, an institution is given for an author +///# optionally, an institution is given for an author /// Author: /// AuthorName /// AuthorName '(' Institution ')' /// -/// # there are no rules about the name, it may be firstname lastname or lastname, firstname or anything else +///# there are no rules about the name, it may be firstname lastname or lastname, firstname or anything else /// AuthorName: /// a non-empty String without '(' or ')' characters, not spanning more that one line /// @@ -120,7 +120,7 @@ /// Keyword: /// non-empty String that does not contain ',' (may contain whitespace) /// -/// # if no date is given, the current year as given by the system clock is assumed +///# if no date is given, the current year as given by the system clock is assumed /// DateString: /// 'yyyy-MM-dd' /// 'yyyy-MM' @@ -130,14 +130,14 @@ /// JelClassification JelClassificationList /// JelClassification /// -/// # the JEL Classifications are set into a new BIBTEX-field 'jel' -/// # they will appear if you add it as a field to one of the BIBTex Entry sections +///# the JEL Classifications are set into a new BIBTEX-field 'jel' +///# they will appear if you add it as a field to one of the BIBTex Entry sections /// JelClassification: /// one of the allowed classes, see http://ideas.repec.org/j/ /// /// SectionSeparator: /// '\n-----------------------------' -/// ``` +///``` public class RepecNepImporter extends Importer { private static final Logger LOGGER = LoggerFactory.getLogger(RepecNepImporter.class); @@ -257,9 +257,9 @@ private void parseAuthors(BibEntry be, BufferedReader in) throws IOException { institutionDone = this.lastLine.indexOf(')') >= 1; institution .append(this.lastLine.substring(this.lastLine.indexOf('(') + 1, - institutionDone && (this.lastLine - .indexOf(')') > (this.lastLine.indexOf('(') + 1)) ? this.lastLine - .indexOf(')') : this.lastLine.length()) + institutionDone && (this.lastLine + .indexOf(')') > (this.lastLine.indexOf('(') + 1)) ? this.lastLine + .indexOf(')') : this.lastLine.length()) .trim()); } else { author = this.lastLine.trim(); diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/RisImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/RisImporter.java index 8cc16b0183f..0a87899dea8 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/RisImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/RisImporter.java @@ -115,15 +115,25 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { String value = entry.substring(6).trim(); if ("TY".equals(tag)) { type = switch (value) { - case "BOOK" -> StandardEntryType.Book; - case "JOUR", "MGZN" -> StandardEntryType.Article; - case "THES" -> StandardEntryType.PhdThesis; - case "UNPB" -> StandardEntryType.Unpublished; - case "RPRT" -> StandardEntryType.TechReport; - case "CONF" -> StandardEntryType.InProceedings; - case "CHAP" -> StandardEntryType.InCollection; - case "PAT" -> IEEETranEntryType.Patent; - default -> StandardEntryType.Misc; + case "BOOK" -> + StandardEntryType.Book; + case "JOUR", + "MGZN" -> + StandardEntryType.Article; + case "THES" -> + StandardEntryType.PhdThesis; + case "UNPB" -> + StandardEntryType.Unpublished; + case "RPRT" -> + StandardEntryType.TechReport; + case "CONF" -> + StandardEntryType.InProceedings; + case "CHAP" -> + StandardEntryType.InCollection; + case "PAT" -> + IEEETranEntryType.Patent; + default -> + StandardEntryType.Misc; }; } else if ("T1".equals(tag) || "TI".equals(tag)) { String oldVal = fields.get(StandardField.TITLE); @@ -304,8 +314,8 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { return new ParserResult(bibEntries); } - private void addDoi(Map hm, String val) { - Optional parsedDoi = DOI.parse(val); - parsedDoi.ifPresent(doi -> hm.put(StandardField.DOI, doi.asString())); - } + private void addDoi(Map hm, String val) { + Optional parsedDoi = DOI.parse(val); + parsedDoi.ifPresent(doi -> hm.put(StandardField.DOI, doi.asString())); + } } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/PdfContentImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/PdfContentImporter.java index 1765085fdc9..c69dafa0c04 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/PdfContentImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/PdfContentImporter.java @@ -298,12 +298,12 @@ private boolean isThereSpace(TextPosition previous, TextPosition current) { * Parses the first page content of a PDF document and extracts bibliographic information such as title, author, * abstract, keywords, and other relevant metadata. This method processes the content line-by-line and uses * custom parsing logic to identify and assemble information blocks from academic papers. - * + *

    * idea: split[] contains the different lines, blocks are separated by empty lines, treat each block - * or do special treatment at authors (which are not broken). - * Therefore, we do a line-based and not a block-based splitting i points to the current line - * curString (mostly) contains the current block, - * the different lines are joined into one and thereby separated by " " + * or do special treatment at authors (which are not broken). + * Therefore, we do a line-based and not a block-based splitting i points to the current line + * curString (mostly) contains the current block, + * the different lines are joined into one and thereby separated by " " * *

    This method follows the structure typically found in academic paper PDFs: * - First, it attempts to detect the title by font size, if available, or by text position. @@ -320,7 +320,7 @@ private boolean isThereSpace(TextPosition previous, TextPosition current) { * @param titleByFontSize An optional title string determined by font size; if provided, this overrides the * default title parsing. * @return An {@link Optional} containing a {@link BibEntry} with the parsed bibliographic data if extraction - * is successful. Otherwise, an empty {@link Optional}. + * is successful. Otherwise, an empty {@link Optional}. */ @VisibleForTesting Optional getEntryFromPDFContent(String firstpageContents, String lineSeparator, Optional titleByFontSize) { 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 5ab21558195..983b0db8a58 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 @@ -31,10 +31,10 @@ public FileFieldParser(String value) { /** * Converts the string representation of LinkedFileData to a List of LinkedFile - * + *

    * The syntax of one element is description:path:type * Multiple elements are concatenated with ; - * + *

    * The main challenges of the implementation are: * *

      @@ -139,9 +139,9 @@ private void resetDataStructuresForNextElement() { /** * Converts the given textual representation of a LinkedFile object - * + *

      * SIDE EFFECT: The given entry list is cleared upon completion - * + *

      * Expected format is: description:link:fileType:sourceURL * fileType is an {@link org.jabref.gui.externalfiletype.ExternalFileType}, which contains a name and a mime type * diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/GrobidService.java b/jablib/src/main/java/org/jabref/logic/importer/util/GrobidService.java index 158a8f2fcbb..51d6001fb0b 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/GrobidService.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/GrobidService.java @@ -61,13 +61,13 @@ public GrobidService(GrobidPreferences grobidPreferences) { */ public Optional processCitation(String rawCitation, ImportFormatPreferences importFormatPreferences, ConsolidateCitations consolidateCitations) throws IOException, ParseException { Connection.Response response = Jsoup.connect(grobidPreferences.getGrobidURL() + "/api/processCitation") - .header("Accept", MediaTypes.APPLICATION_BIBTEX) - .data("citations", rawCitation) - .data("consolidateCitations", String.valueOf(consolidateCitations.getCode())) - .method(Connection.Method.POST) - .ignoreContentType(true) - .timeout(100_000) - .execute(); + .header("Accept", MediaTypes.APPLICATION_BIBTEX) + .data("citations", rawCitation) + .data("consolidateCitations", String.valueOf(consolidateCitations.getCode())) + .method(Connection.Method.POST) + .ignoreContentType(true) + .timeout(100_000) + .execute(); String httpResponse = response.body(); LOGGER.debug("raw citation -> response: {}, {}", rawCitation, httpResponse); @@ -80,12 +80,12 @@ public Optional processCitation(String rawCitation, ImportFormatPrefer public List processPDF(Path filePath, ImportFormatPreferences importFormatPreferences) throws IOException, ParseException { Connection.Response response = Jsoup.connect(grobidPreferences.getGrobidURL() + "/api/processHeaderDocument") - .header("Accept", MediaTypes.APPLICATION_BIBTEX) - .data("input", filePath.toString(), Files.newInputStream(filePath)) - .method(Connection.Method.POST) - .ignoreContentType(true) - .timeout(20000) - .execute(); + .header("Accept", MediaTypes.APPLICATION_BIBTEX) + .data("input", filePath.toString(), Files.newInputStream(filePath)) + .method(Connection.Method.POST) + .ignoreContentType(true) + .timeout(20000) + .execute(); String httpResponse = response.body(); @@ -94,7 +94,7 @@ public List processPDF(Path filePath, ImportFormatPreferences importFo public List processReferences(List pathList, ImportFormatPreferences importFormatPreferences) throws IOException, ParseException { List entries = new ArrayList<>(); - for (Path filePath: pathList) { + for (Path filePath : pathList) { entries.addAll(processReferences(filePath, importFormatPreferences)); } diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/MathMLParser.java b/jablib/src/main/java/org/jabref/logic/importer/util/MathMLParser.java index 735e99577e9..a8d4b92febf 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/MathMLParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/MathMLParser.java @@ -55,8 +55,8 @@ public static String parse(XMLStreamReader reader) { latexResult = writer.getBuffer().toString(); } catch (XMLStreamException - | TransformerException - | IOException e) { + | TransformerException + | IOException e) { LOGGER.error("Could not transform", e); return ""; } 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 59c9309b138..ef150e6e35e 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 @@ -167,10 +167,10 @@ public MetaData parse(MetaData metaData, Map data, Character key /** * Parse the content of the value as provided by "raw" content. - * + *

      * We do not use unescaped value (created by @link{#getAsList(java.lang.String)}), * because this leads to difficulties with UNC names. - * + *

      * No normalization is done - the library-specific file directory could be passed as Mac OS X path, but the user could sit on Windows. * * @param value the raw value (as stored in the .bib file) @@ -191,7 +191,7 @@ static String parseDirectory(String value) { private static Comparator> groupsLast() { return (s1, s2) -> MetaData.GROUPSTREE.equals(s1.getKey()) || MetaData.GROUPSTREE_LEGACY.equals(s1.getKey()) ? 1 : - MetaData.GROUPSTREE.equals(s2.getKey()) || MetaData.GROUPSTREE_LEGACY.equals(s2.getKey()) ? -1 : 0; + MetaData.GROUPSTREE.equals(s2.getKey()) || MetaData.GROUPSTREE_LEGACY.equals(s2.getKey()) ? -1 : 0; } /** @@ -270,7 +270,7 @@ public static FieldFormatterCleanups fieldFormatterCleanupsParse(List fo /** * Handles a blgFilePath-* metadata entry. Expects exactly one valid path. * - * @param entry the metadata entry containing the user-specific .blg path. + * @param entry the metadata entry containing the user-specific .blg path. * @param metaData the MetaData object to update. */ private void handleBlgFilePathEntry(Map.Entry entry, MetaData metaData) { diff --git a/jablib/src/main/java/org/jabref/logic/integrity/AmpersandChecker.java b/jablib/src/main/java/org/jabref/logic/integrity/AmpersandChecker.java index 43098173dfa..e54dd5c71c8 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/AmpersandChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/AmpersandChecker.java @@ -18,7 +18,7 @@ /** * Checks if the BibEntry contains unescaped ampersands. * This is done in nonverbatim fields. Similar to {@link HTMLCharacterChecker} - * + *

      * The {@link LatexIntegrityChecker} is not able to check unescaped ampersands. Therefore, this separate checker is required. */ public class AmpersandChecker implements EntryChecker { diff --git a/jablib/src/main/java/org/jabref/logic/integrity/HowPublishedChecker.java b/jablib/src/main/java/org/jabref/logic/integrity/HowPublishedChecker.java index 75e358732fa..73e267dec3a 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/HowPublishedChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/HowPublishedChecker.java @@ -21,9 +21,9 @@ public HowPublishedChecker(BibDatabaseContext databaseContext) { /** * Official BibTeX specification: - * HowPublished: How something strange has been published. The first word should be capitalized. + * HowPublished: How something strange has been published. The first word should be capitalized. * biblatex package documentation (Section 4.9.1): - * The biblatex package will automatically capitalize the first word when required at the beginning of a sentence. + * The biblatex package will automatically capitalize the first word when required at the beginning of a sentence. */ @Override public Optional checkValue(String value) { diff --git a/jablib/src/main/java/org/jabref/logic/integrity/IntegrityCheckResultWriter.java b/jablib/src/main/java/org/jabref/logic/integrity/IntegrityCheckResultWriter.java index 9edf3da71ff..4825411c02b 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/IntegrityCheckResultWriter.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/IntegrityCheckResultWriter.java @@ -19,5 +19,6 @@ public IntegrityCheckResultWriter(Writer writer, List messages public abstract void writeFindings() throws IOException; @Override - public void close() throws IOException { } + public void close() throws IOException { + } } diff --git a/jablib/src/main/java/org/jabref/logic/integrity/LatexIntegrityChecker.java b/jablib/src/main/java/org/jabref/logic/integrity/LatexIntegrityChecker.java index cdc092e9ddf..0629b8fcfea 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/LatexIntegrityChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/LatexIntegrityChecker.java @@ -33,7 +33,7 @@ /** * Similar check to {@link HTMLCharacterChecker}. * Here, we use SnuggleTeX, in the {@link HTMLCharacterChecker}, it is searched for HTML characters. - * + *

      * Unescaped ampersands cannot be checked by SnuggleTeX, therefore the {@link AmpersandChecker} is available additionaly. */ public class LatexIntegrityChecker implements EntryChecker { 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 e6cbc6df15e..11992e1d563 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/PagesChecker.java @@ -13,22 +13,22 @@ public class PagesChecker implements ValueChecker { 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 - + "[A-Za-z]?\\d*" // optional prefix and number - + ")?" - + "\\z"; // end String + + "[A-Za-z]?\\d*" // optional prefix and number + + "(" + + "(\\+|-{2}|\u2013)" // separator, must contain exactly two dashes + + "[A-Za-z]?\\d*" // optional prefix and number + + ")?" + + "\\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 - + "[A-Za-z]?\\d*" // optional prefix and number - + "(" - + "(\\+|-{1,2}|\u2013)" // separator - + "[A-Za-z]?\\d*" // optional prefix and number - + ")?" - + "\\z"; // end String + + "[A-Za-z]?\\d*" // optional prefix and number + + "(" + + "(\\+|-{1,2}|\u2013)" // separator + + "[A-Za-z]?\\d*" // optional prefix and number + + ")?" + + "\\z"; // end String private final Predicate isValidPageNumber; @@ -42,12 +42,12 @@ public PagesChecker(BibDatabaseContext databaseContext) { /** * From BibTex manual: - * One or more page numbers or range of numbers, such as 42--111 or 7,41,73--97 or 43+ - * (the '+' in this last example indicates pages following that don't form a simple range). - * To make it easier to maintain Scribe-compatible databases, the standard styles convert - * a single dash (as in 7-33) to the double dash used in TEX to denote number ranges (as in 7--33). + * One or more page numbers or range of numbers, such as 42--111 or 7,41,73--97 or 43+ + * (the '+' in this last example indicates pages following that don't form a simple range). + * To make it easier to maintain Scribe-compatible databases, the standard styles convert + * a single dash (as in 7-33) to the double dash used in TEX to denote number ranges (as in 7--33). * biblatex: - * same as above but allows single dash as well + * same as above but allows single dash as well */ @Override public Optional checkValue(String value) { @@ -56,8 +56,8 @@ public Optional checkValue(String value) { } if (Arrays.stream(value.split(",")) - .map(String::trim) - .anyMatch(pageRange -> !isValidPageNumber.test(pageRange))) { + .map(String::trim) + .anyMatch(pageRange -> !isValidPageNumber.test(pageRange))) { return Optional.of(Localization.lang("should contain a valid page number range")); } return Optional.empty(); diff --git a/jablib/src/main/java/org/jabref/logic/integrity/UnicodeNormalFormCanonicalCompositionCheck.java b/jablib/src/main/java/org/jabref/logic/integrity/UnicodeNormalFormCanonicalCompositionCheck.java index c8767a689c2..a23ad05c83d 100644 --- a/jablib/src/main/java/org/jabref/logic/integrity/UnicodeNormalFormCanonicalCompositionCheck.java +++ b/jablib/src/main/java/org/jabref/logic/integrity/UnicodeNormalFormCanonicalCompositionCheck.java @@ -8,7 +8,7 @@ /** * Detect any Unicode characters that is not in NFC format. NFC: Normal form "Normalization Form Canonical Composition" (NFC): Characters are decomposed and then recomposed by canonical equivalence. - * + *

      * Normalizer: {@link org.jabref.logic.formatter.bibtexfields.NormalizeUnicodeFormatter} */ public class UnicodeNormalFormCanonicalCompositionCheck implements EntryChecker { diff --git a/jablib/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java b/jablib/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java index 21734cad692..b3d04c2c718 100644 --- a/jablib/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java +++ b/jablib/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java @@ -13,12 +13,12 @@ private AbbreviationFormat() { public static CSVFormat getCSVFormatWithDelimiter(char delimiter) { return CSVFormat.DEFAULT.builder() - .setIgnoreEmptyLines(true) - .setDelimiter(delimiter) - .setEscape(ESCAPE) - .setQuote(QUOTE) - .setTrim(true) - .build(); + .setIgnoreEmptyLines(true) + .setDelimiter(delimiter) + .setEscape(ESCAPE) + .setQuote(QUOTE) + .setTrim(true) + .build(); } public static CSVFormat getCSVFormatWithDefaultDilimeter() { diff --git a/jablib/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java b/jablib/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java index 3af86c93a5e..02a4d54399b 100644 --- a/jablib/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java +++ b/jablib/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java @@ -36,7 +36,7 @@ public class JournalAbbreviationRepository { /** * Initializes the internal data based on the abbreviations found in the given MV file * - * @param journalList The path to the MV file containing the journal abbreviations. + * @param journalList The path to the MV file containing the journal abbreviations. * @param ltwaRepository The LTWA repository to use for abbreviations. */ public JournalAbbreviationRepository(Path journalList, LtwaRepository ltwaRepository) { @@ -148,9 +148,9 @@ public Optional get(String input) { } Optional abbreviation = Optional.ofNullable(fullToAbbreviationObject.get(journal)) - .or(() -> Optional.ofNullable(abbreviationToAbbreviationObject.get(journal))) - .or(() -> Optional.ofNullable(dotlessToAbbreviationObject.get(journal))) - .or(() -> Optional.ofNullable(shortestUniqueToAbbreviationObject.get(journal))); + .or(() -> Optional.ofNullable(abbreviationToAbbreviationObject.get(journal))) + .or(() -> Optional.ofNullable(dotlessToAbbreviationObject.get(journal))) + .or(() -> Optional.ofNullable(shortestUniqueToAbbreviationObject.get(journal))); if (abbreviation.isEmpty()) { abbreviation = findAbbreviationFuzzyMatched(journal); @@ -173,9 +173,9 @@ private Optional findBestFuzzyMatched(Collection abb final double SIMILARITY_THRESHOLD = 1.0; List candidates = abbreviations.stream() - .filter(abbreviation -> similarity.isSimilar(input, abbreviation.getName())) - .sorted(Comparator.comparingDouble(abbreviation -> similarity.editDistanceIgnoreCase(input, abbreviation.getName()))) - .toList(); + .filter(abbreviation -> similarity.isSimilar(input, abbreviation.getName())) + .sorted(Comparator.comparingDouble(abbreviation -> similarity.editDistanceIgnoreCase(input, abbreviation.getName()))) + .toList(); if (candidates.isEmpty()) { return Optional.empty(); diff --git a/jablib/src/main/java/org/jabref/logic/journals/ltwa/LtwaTsvParser.java b/jablib/src/main/java/org/jabref/logic/journals/ltwa/LtwaTsvParser.java index f81db7eca8f..5145869b7f0 100644 --- a/jablib/src/main/java/org/jabref/logic/journals/ltwa/LtwaTsvParser.java +++ b/jablib/src/main/java/org/jabref/logic/journals/ltwa/LtwaTsvParser.java @@ -61,7 +61,7 @@ public List parse() throws IOException { word = normalizeResult.get(); String abbreviation = NO_ABBREVIATION.equals(abbreviationStr) ? null : abbreviationStr; List languages = Arrays.stream(languageStr.split("\\s*,\\s*")).map(String::trim) - .filter(s -> !s.isEmpty()).toList(); + .filter(s -> !s.isEmpty()).toList(); entries.add(new LtwaEntry(word, abbreviation, languages)); } diff --git a/jablib/src/main/java/org/jabref/logic/l10n/Language.java b/jablib/src/main/java/org/jabref/logic/l10n/Language.java index 9d3e9958fb8..a3cc947ebae 100644 --- a/jablib/src/main/java/org/jabref/logic/l10n/Language.java +++ b/jablib/src/main/java/org/jabref/logic/l10n/Language.java @@ -42,6 +42,7 @@ public enum Language { private static final Pattern IS_NOT_LATIN = Pattern.compile("[^\\p{IsLatin}]"); private final String displayName; private final String id; + /** * @param id Typically as 639-1 code */ @@ -77,11 +78,11 @@ public String getId() { public static List getSorted() { return Arrays.stream(values()) - .sorted(Comparator.comparing(language -> removeNonLatinCharacters(language.getDisplayName()))) - .toList(); + .sorted(Comparator.comparing(language -> removeNonLatinCharacters(language.getDisplayName()))) + .toList(); } private static String removeNonLatinCharacters(String input) { - return IS_NOT_LATIN.matcher(input).replaceAll(""); + return IS_NOT_LATIN.matcher(input).replaceAll(""); } } diff --git a/jablib/src/main/java/org/jabref/logic/layout/AbstractParamLayoutFormatter.java b/jablib/src/main/java/org/jabref/logic/layout/AbstractParamLayoutFormatter.java index 44209654bb6..dc0b369317b 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/AbstractParamLayoutFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/layout/AbstractParamLayoutFormatter.java @@ -44,11 +44,16 @@ protected static List parseArgument(String arg) { private static void handleEscapedCharacter(StringBuilder current, char currentChar) { switch (currentChar) { - case 'n' -> current.append('\n'); - case 't' -> current.append('\t'); - case ',' -> current.append(','); - case '"' -> current.append('"'); - case '\\' -> current.append('\\'); + case 'n' -> + current.append('\n'); + case 't' -> + current.append('\t'); + case ',' -> + current.append(','); + case '"' -> + current.append('"'); + case '\\' -> + current.append('\\'); default -> { current.append('\\'); current.append(currentChar); diff --git a/jablib/src/main/java/org/jabref/logic/layout/LayoutEntry.java b/jablib/src/main/java/org/jabref/logic/layout/LayoutEntry.java index d6fe6dceb7f..b6df052b604 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/LayoutEntry.java +++ b/jablib/src/main/java/org/jabref/logic/layout/LayoutEntry.java @@ -165,7 +165,7 @@ public LayoutEntry(List parsedEntries, if (blockStart.equals(parsedEntry.s)) { blockEntries.add(parsedEntry); int groupType = parsedEntry.i == LayoutHelper.IS_GROUP_END ? LayoutHelper.IS_GROUP_START : - LayoutHelper.IS_FIELD_START; + LayoutHelper.IS_FIELD_START; LayoutEntry le = new LayoutEntry(blockEntries, groupType, fileDirForDatabase, preferences, abbreviationRepository); tmpEntries.add(le); blockEntries = null; @@ -414,82 +414,159 @@ private void doOptionField(String s) { private LayoutFormatter getLayoutFormatterByName(String name) { return switch (name) { // For backward compatibility - case "HTMLToLatexFormatter", "HtmlToLatex" -> new HtmlToLatexFormatter(); + case "HTMLToLatexFormatter", + "HtmlToLatex" -> + new HtmlToLatexFormatter(); // For backward compatibility - case "UnicodeToLatexFormatter", "UnicodeToLatex" -> new UnicodeToLatexFormatter(); - case "OOPreFormatter" -> new OOPreFormatter(); - case "AuthorAbbreviator" -> new AuthorAbbreviator(); - case "AuthorAndToSemicolonReplacer" -> new AuthorAndToSemicolonReplacer(); - case "AuthorAndsCommaReplacer" -> new AuthorAndsCommaReplacer(); - case "AuthorAndsReplacer" -> new AuthorAndsReplacer(); - case "AuthorFirstAbbrLastCommas" -> new AuthorFirstAbbrLastCommas(); - case "AuthorFirstAbbrLastOxfordCommas" -> new AuthorFirstAbbrLastOxfordCommas(); - case "AuthorFirstFirst" -> new AuthorFirstFirst(); - case "AuthorFirstFirstCommas" -> new AuthorFirstFirstCommas(); - case "AuthorFirstLastCommas" -> new AuthorFirstLastCommas(); - case "AuthorFirstLastOxfordCommas" -> new AuthorFirstLastOxfordCommas(); - case "AuthorLastFirst" -> new AuthorLastFirst(); - case "AuthorLastFirstAbbrCommas" -> new AuthorLastFirstAbbrCommas(); - case "AuthorLastFirstAbbreviator" -> new AuthorLastFirstAbbreviator(); - case "AuthorLastFirstAbbrOxfordCommas" -> new AuthorLastFirstAbbrOxfordCommas(); - case "AuthorLastFirstCommas" -> new AuthorLastFirstCommas(); - case "AuthorLastFirstOxfordCommas" -> new AuthorLastFirstOxfordCommas(); - case "AuthorLF_FF" -> new AuthorLF_FF(); - case "AuthorLF_FFAbbr" -> new AuthorLF_FFAbbr(); - case "AuthorNatBib" -> new AuthorNatBib(); - case "AuthorOrgSci" -> new AuthorOrgSci(); - case "CompositeFormat" -> new CompositeFormat(); - case "CreateBibORDFAuthors" -> new CreateBibORDFAuthors(); - case "CreateDocBook4Authors" -> new CreateDocBook4Authors(); - case "CreateDocBook4Editors" -> new CreateDocBook4Editors(); - case "CreateDocBook5Authors" -> new CreateDocBook5Authors(); - case "CreateDocBook5Editors" -> new CreateDocBook5Editors(); - case "CurrentDate" -> new CurrentDate(); - case "DateFormatter" -> new DateFormatter(); - case "DOICheck" -> new DOICheck(preferences.getDoiPreferences()); - case "DOIStrip" -> new DOIStrip(); - case "EntryTypeFormatter" -> new EntryTypeFormatter(); - case "FirstPage" -> new FirstPage(); - case "FormatPagesForHTML" -> new FormatPagesForHTML(); - case "FormatPagesForXML" -> new FormatPagesForXML(); - case "GetOpenOfficeType" -> new GetOpenOfficeType(); - case "HTMLChars" -> new HTMLChars(); - case "HTMLParagraphs" -> new HTMLParagraphs(); - case "Iso690FormatDate" -> new Iso690FormatDate(); - case "Iso690NamesAuthors" -> new Iso690NamesAuthors(); - case "JournalAbbreviator" -> new JournalAbbreviator(abbreviationRepository); - case "LastPage" -> new LastPage(); -// For backward compatibility - case "FormatChars", "LatexToUnicode" -> new LatexToUnicodeFormatter(); - case "NameFormatter" -> new NameFormatter(); - case "NoSpaceBetweenAbbreviations" -> new NoSpaceBetweenAbbreviations(); - case "Ordinal" -> new Ordinal(); - case "RemoveBrackets" -> new RemoveBrackets(); - case "RemoveBracketsAddComma" -> new RemoveBracketsAddComma(); - case "RemoveLatexCommands" -> new RemoveLatexCommandsFormatter(); - case "RemoveTilde" -> new RemoveTilde(); - case "RemoveWhitespace" -> new NonSpaceWhitespaceRemover(); - case "RisKeywords" -> new RisKeywords(); - case "RisMonth" -> new RisMonth(); - case "RTFChars" -> new RTFChars(); - case "ToLowerCase" -> new ToLowerCase(); - case "ToUpperCase" -> new ToUpperCase(); - case "XMLChars" -> new XMLChars(); - case "Default" -> new Default(); - case "FileLink" -> new FileLink(fileDirForDatabase, preferences.getMainFileDirectory()); - case "Number" -> new Number(); - case "RisAuthors" -> new RisAuthors(); - case "Authors" -> new Authors(); - case "IfPlural" -> new IfPlural(); - case "Replace" -> new Replace(); - case "WrapContent" -> new WrapContent(); - case "WrapFileLinks" -> new WrapFileLinks(fileDirForDatabase, preferences.getMainFileDirectory()); - case "Markdown" -> new MarkdownFormatter(); - case "CSLType" -> new CSLType(); - case "ShortMonth" -> new ShortMonthFormatter(); - case "ReplaceWithEscapedDoubleQuotes" -> new ReplaceWithEscapedDoubleQuotes(); - case "HayagrivaType" -> new HayagrivaType(); - default -> null; + case "UnicodeToLatexFormatter", + "UnicodeToLatex" -> + new UnicodeToLatexFormatter(); + case "OOPreFormatter" -> + new OOPreFormatter(); + case "AuthorAbbreviator" -> + new AuthorAbbreviator(); + case "AuthorAndToSemicolonReplacer" -> + new AuthorAndToSemicolonReplacer(); + case "AuthorAndsCommaReplacer" -> + new AuthorAndsCommaReplacer(); + case "AuthorAndsReplacer" -> + new AuthorAndsReplacer(); + case "AuthorFirstAbbrLastCommas" -> + new AuthorFirstAbbrLastCommas(); + case "AuthorFirstAbbrLastOxfordCommas" -> + new AuthorFirstAbbrLastOxfordCommas(); + case "AuthorFirstFirst" -> + new AuthorFirstFirst(); + case "AuthorFirstFirstCommas" -> + new AuthorFirstFirstCommas(); + case "AuthorFirstLastCommas" -> + new AuthorFirstLastCommas(); + case "AuthorFirstLastOxfordCommas" -> + new AuthorFirstLastOxfordCommas(); + case "AuthorLastFirst" -> + new AuthorLastFirst(); + case "AuthorLastFirstAbbrCommas" -> + new AuthorLastFirstAbbrCommas(); + case "AuthorLastFirstAbbreviator" -> + new AuthorLastFirstAbbreviator(); + case "AuthorLastFirstAbbrOxfordCommas" -> + new AuthorLastFirstAbbrOxfordCommas(); + case "AuthorLastFirstCommas" -> + new AuthorLastFirstCommas(); + case "AuthorLastFirstOxfordCommas" -> + new AuthorLastFirstOxfordCommas(); + case "AuthorLF_FF" -> + new AuthorLF_FF(); + case "AuthorLF_FFAbbr" -> + new AuthorLF_FFAbbr(); + case "AuthorNatBib" -> + new AuthorNatBib(); + case "AuthorOrgSci" -> + new AuthorOrgSci(); + case "CompositeFormat" -> + new CompositeFormat(); + case "CreateBibORDFAuthors" -> + new CreateBibORDFAuthors(); + case "CreateDocBook4Authors" -> + new CreateDocBook4Authors(); + case "CreateDocBook4Editors" -> + new CreateDocBook4Editors(); + case "CreateDocBook5Authors" -> + new CreateDocBook5Authors(); + case "CreateDocBook5Editors" -> + new CreateDocBook5Editors(); + case "CurrentDate" -> + new CurrentDate(); + case "DateFormatter" -> + new DateFormatter(); + case "DOICheck" -> + new DOICheck(preferences.getDoiPreferences()); + case "DOIStrip" -> + new DOIStrip(); + case "EntryTypeFormatter" -> + new EntryTypeFormatter(); + case "FirstPage" -> + new FirstPage(); + case "FormatPagesForHTML" -> + new FormatPagesForHTML(); + case "FormatPagesForXML" -> + new FormatPagesForXML(); + case "GetOpenOfficeType" -> + new GetOpenOfficeType(); + case "HTMLChars" -> + new HTMLChars(); + case "HTMLParagraphs" -> + new HTMLParagraphs(); + case "Iso690FormatDate" -> + new Iso690FormatDate(); + case "Iso690NamesAuthors" -> + new Iso690NamesAuthors(); + case "JournalAbbreviator" -> + new JournalAbbreviator(abbreviationRepository); + case "LastPage" -> + new LastPage(); + // For backward compatibility + case "FormatChars", + "LatexToUnicode" -> + new LatexToUnicodeFormatter(); + case "NameFormatter" -> + new NameFormatter(); + case "NoSpaceBetweenAbbreviations" -> + new NoSpaceBetweenAbbreviations(); + case "Ordinal" -> + new Ordinal(); + case "RemoveBrackets" -> + new RemoveBrackets(); + case "RemoveBracketsAddComma" -> + new RemoveBracketsAddComma(); + case "RemoveLatexCommands" -> + new RemoveLatexCommandsFormatter(); + case "RemoveTilde" -> + new RemoveTilde(); + case "RemoveWhitespace" -> + new NonSpaceWhitespaceRemover(); + case "RisKeywords" -> + new RisKeywords(); + case "RisMonth" -> + new RisMonth(); + case "RTFChars" -> + new RTFChars(); + case "ToLowerCase" -> + new ToLowerCase(); + case "ToUpperCase" -> + new ToUpperCase(); + case "XMLChars" -> + new XMLChars(); + case "Default" -> + new Default(); + case "FileLink" -> + new FileLink(fileDirForDatabase, preferences.getMainFileDirectory()); + case "Number" -> + new Number(); + case "RisAuthors" -> + new RisAuthors(); + case "Authors" -> + new Authors(); + case "IfPlural" -> + new IfPlural(); + case "Replace" -> + new Replace(); + case "WrapContent" -> + new WrapContent(); + case "WrapFileLinks" -> + new WrapFileLinks(fileDirForDatabase, preferences.getMainFileDirectory()); + case "Markdown" -> + new MarkdownFormatter(); + case "CSLType" -> + new CSLType(); + case "ShortMonth" -> + new ShortMonthFormatter(); + case "ReplaceWithEscapedDoubleQuotes" -> + new ReplaceWithEscapedDoubleQuotes(); + case "HayagrivaType" -> + new HayagrivaType(); + default -> + null; }; } diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/AuthorAndsReplacer.java b/jablib/src/main/java/org/jabref/logic/layout/format/AuthorAndsReplacer.java index 0b7bed8a9f5..a421b3ac819 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/AuthorAndsReplacer.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/AuthorAndsReplacer.java @@ -17,8 +17,10 @@ public String format(String fieldText) { String[] authors = fieldText.split(" and "); // CHECKSTYLE:OFF String s = switch (authors.length) { - case 1 -> authors[0]; // just no action - case 2 -> authors[0] + " & " + authors[1]; + case 1 -> + authors[0]; // just no action + case 2 -> + authors[0] + " & " + authors[1]; default -> { int i; int x = authors.length; diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/CSLType.java b/jablib/src/main/java/org/jabref/logic/layout/format/CSLType.java index aac863567fe..d7cc35ce5d8 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/CSLType.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/CSLType.java @@ -8,14 +8,25 @@ public class CSLType implements LayoutFormatter { @Override public String format(String value) { return switch (StandardEntryType.valueOf(value)) { - case Article -> "article"; - case Book -> "book"; - case Conference -> "paper-conference"; - case Report, TechReport -> "report"; - case Thesis, MastersThesis, PhdThesis -> "thesis"; - case WWW, Online -> "webpage"; + case Article -> + "article"; + case Book -> + "book"; + case Conference -> + "paper-conference"; + case Report, + TechReport -> + "report"; + case Thesis, + MastersThesis, + PhdThesis -> + "thesis"; + case WWW, + Online -> + "webpage"; - default -> "no-type"; + default -> + "no-type"; }; } } diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/FirstPage.java b/jablib/src/main/java/org/jabref/logic/layout/format/FirstPage.java index b5bb79c004f..feb5852e86f 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/FirstPage.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/FirstPage.java @@ -4,7 +4,7 @@ /** * Formatter that returns the first page from the "pages" field, if set. - * + *

      * For instance, if the pages field is set to "345-360" or "345--360", * this formatter will return "345". */ diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/HayagrivaType.java b/jablib/src/main/java/org/jabref/logic/layout/format/HayagrivaType.java index cbe30bf06d5..1a5c9e3d992 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/HayagrivaType.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/HayagrivaType.java @@ -8,16 +8,30 @@ public class HayagrivaType implements LayoutFormatter { @Override public String format(String value) { return switch (StandardEntryType.valueOf(value)) { - case Article, Conference -> "article"; - case Book -> "book"; - case InBook -> "chapter"; - case Report, TechReport -> "report"; - case Thesis, MastersThesis, PhdThesis -> "thesis"; - case WWW, Online -> "web"; - case Proceedings -> "proceedings"; - case Reference -> "reference"; + case Article, + Conference -> + "article"; + case Book -> + "book"; + case InBook -> + "chapter"; + case Report, + TechReport -> + "report"; + case Thesis, + MastersThesis, + PhdThesis -> + "thesis"; + case WWW, + Online -> + "web"; + case Proceedings -> + "proceedings"; + case Reference -> + "reference"; - default -> "Misc"; + default -> + "Misc"; }; } } diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/JournalAbbreviator.java b/jablib/src/main/java/org/jabref/logic/layout/format/JournalAbbreviator.java index b1dc46b7aba..12f62e0f9d9 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/JournalAbbreviator.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/JournalAbbreviator.java @@ -7,10 +7,10 @@ /** * JournalAbbreviator formats the given text in an abbreviated form according to the journal abbreviation lists. - * + *

      * The given input text is abbreviated according to the journal abbreviation lists. If no abbreviation for input is * found (e.g. not in list or already abbreviated), the input will be returned unmodified. - * + *

      * Usage: \format[JournalAbbreviator]{\journal} Example result: "Phys. Rev. Lett." instead of "Physical Review Letters" */ public class JournalAbbreviator implements LayoutFormatter { diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/LastPage.java b/jablib/src/main/java/org/jabref/logic/layout/format/LastPage.java index 1e4c1c25cfa..20432a3af4a 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/LastPage.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/LastPage.java @@ -4,7 +4,7 @@ /** * Formatter that returns the last page from the "pages" field, if set. - * + *

      * For instance, if the pages field is set to "345-360" or "345--360", * this formatter will return "360". */ diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/Ordinal.java b/jablib/src/main/java/org/jabref/logic/layout/format/Ordinal.java index 645dcae4236..d985460a048 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/Ordinal.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/Ordinal.java @@ -25,10 +25,14 @@ public String format(String fieldText) { int value = Integer.parseInt(result); // CHECKSTYLE:OFF String ordinalString = switch (value) { - case 1 -> "st"; - case 2 -> "nd"; - case 3 -> "rd"; - default -> "th"; + case 1 -> + "st"; + case 2 -> + "nd"; + case 3 -> + "rd"; + default -> + "th"; }; // CHECKSTYLE:ON m.appendReplacement(sb, result + ordinalString); 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 54f4377fb3f..81155421358 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 @@ -10,18 +10,18 @@ /** * Transform a LaTeX-String to RTF. - * + *

      * This method will: - * - * 1.) Remove LaTeX-Command sequences. - * - * 2.) Replace LaTeX-Special chars with RTF equivalents. - * - * 3.) Replace emph and textit and textbf with their RTF replacements. - * - * 4.) Take special care to save all unicode characters correctly. - * - * 5.) Replace --- by \emdash and -- by \endash. + *

      + * 1.) Remove LaTeX-Command sequences. + *

      + * 2.) Replace LaTeX-Special chars with RTF equivalents. + *

      + * 3.) Replace emph and textit and textbf with their RTF replacements. + *

      + * 4.) Take special care to save all unicode characters correctly. + *

      + * 5.) Replace --- by \emdash and -- by \endash. */ public class RTFChars implements LayoutFormatter { diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/WrapContent.java b/jablib/src/main/java/org/jabref/logic/layout/format/WrapContent.java index 097b12c7609..f7b79cc05fe 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/WrapContent.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/WrapContent.java @@ -8,7 +8,7 @@ * This formatter outputs the input value after adding a prefix and a postfix, * as long as the input value is non-empty. If the input value is empty, an * empty string is output (the prefix and postfix are not output in this case). - * + *

      * The formatter requires an argument containing the prefix and postix separated * by a comma. To include a the comma character in either, use an escape sequence * (\,). diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java b/jablib/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java index b750c11d78a..2146101f825 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java @@ -57,7 +57,7 @@ /// ``` /// 1. John's final report (/home/john/report.pdf) /// 2. An early "draft" (/home/john/draft.txt) -/// ``` +///``` /// /// If the formatter was called with a second argument, the list would be filtered. /// For instance: @@ -68,7 +68,7 @@ /// /// ``` /// 1. An early "draft" (/home/john/draft.txt) -/// ``` +///``` /// /// If we wanted this output to be part of an XML styled output, the quotes in the /// file description could cause problems. Adding two additional arguments to translate @@ -80,7 +80,7 @@ /// /// ``` /// 1. An early "draft" (/home/john/draft.txt) -/// ``` +///``` /// /// Additional pairs of replacements can be added. public class WrapFileLinks extends AbstractParamLayoutFormatter { @@ -229,7 +229,7 @@ public String format(String field) { break; case FILE_EXTENSION: FileUtil.getFileExtension(flEntry.getLink()) - .ifPresent(extension -> sb.append(replaceStrings(extension))); + .ifPresent(extension -> sb.append(replaceStrings(extension))); break; case FILE_TYPE: sb.append(replaceStrings(flEntry.getFileType())); diff --git a/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntry.java b/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntry.java index 8ab91a88a5e..15bc203dbc8 100644 --- a/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntry.java +++ b/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntry.java @@ -69,10 +69,10 @@ class MSBibEntry { /** * reduced subset, supports only "CITY , STATE, COUNTRY"
      - * \b(\w+)\s?[,]?\s?(\w+)\s?[,]?\s?(\w*)\b
      - * WORD SPACE , SPACE WORD SPACE (Can be zero or more) , SPACE WORD (Can be zero or more)
      - * Matches both single locations (only city) like Berlin and full locations like Stroudsburg, PA, USA
      - * tested using http://www.regexpal.com/ + * \b(\w+)\s?[,]?\s?(\w+)\s?[,]?\s?(\w*)\b
      + * WORD SPACE , SPACE WORD SPACE (Can be zero or more) , SPACE WORD (Can be zero or more)
      + * Matches both single locations (only city) like Berlin and full locations like Stroudsburg, PA, USA
      + * tested using http://www.regexpal.com/ */ private final Pattern ADDRESS_PATTERN = Pattern.compile("\\b(\\w+)\\s?[,]?\\s?(\\w*)\\s?[,]?\\s?(\\w*)\\b"); @@ -336,15 +336,15 @@ private void addAuthor(Document document, Element allAuthors, String entryName, private void addDateAcessedFields(Document document, Element rootNode) { Optional parsedDateAcesseField = Date.parse(dateAccessed); parsedDateAcesseField.flatMap(Date::getYear) - .map(Object::toString) - .ifPresent(yearAccessed -> addField(document, rootNode, "Year" + "Accessed", yearAccessed)); + .map(Object::toString) + .ifPresent(yearAccessed -> addField(document, rootNode, "Year" + "Accessed", yearAccessed)); parsedDateAcesseField.flatMap(Date::getMonth) .map(Month::getFullName) .ifPresent(monthAcessed -> addField(document, rootNode, "Month" + "Accessed", monthAcessed)); parsedDateAcesseField.flatMap(Date::getDay) - .map(Object::toString) - .ifPresent(dayAccessed -> addField(document, rootNode, "Day" + "Accessed", dayAccessed)); + .map(Object::toString) + .ifPresent(dayAccessed -> addField(document, rootNode, "Day" + "Accessed", dayAccessed)); } private void addAddress(Document document, Element parent, String addressToSplit) { diff --git a/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntryType.java b/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntryType.java index d4672dd5b0c..e391f6495ed 100644 --- a/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntryType.java +++ b/jablib/src/main/java/org/jabref/logic/msbib/MSBibEntryType.java @@ -6,7 +6,7 @@ * Book, BookSection, JournalArticle, ArticleInAPeriodical, ConferenceProceedings, Report, * InternetSite, DocumentFromInternetSite, ElectronicSource, Art, SoundRecording, Performance, * Film, Interview, Patent, Case, Misc - * + *

      * See BIBFORM.XML, shared-bibliography.xsd (ECMA standard) */ public enum MSBibEntryType { diff --git a/jablib/src/main/java/org/jabref/logic/msbib/MSBibMapping.java b/jablib/src/main/java/org/jabref/logic/msbib/MSBibMapping.java index ce27cdcf381..0a192ad2207 100644 --- a/jablib/src/main/java/org/jabref/logic/msbib/MSBibMapping.java +++ b/jablib/src/main/java/org/jabref/logic/msbib/MSBibMapping.java @@ -178,7 +178,7 @@ public static int getLCID(String language) { /** * All LCID codes * - * @param LCID The LCID to transform + * @param LCID The LCID to transform * @return "english" as default. Corresponding language from BiMap otherwise. */ public static String getLanguage(int LCID) { diff --git a/jablib/src/main/java/org/jabref/logic/net/URLDownload.java b/jablib/src/main/java/org/jabref/logic/net/URLDownload.java index 0ddfe1dffb0..ef68f0c60e6 100644 --- a/jablib/src/main/java/org/jabref/logic/net/URLDownload.java +++ b/jablib/src/main/java/org/jabref/logic/net/URLDownload.java @@ -369,8 +369,8 @@ public URLConnection openConnection() throws FetcherException { } if ((status == HttpURLConnection.HTTP_MOVED_TEMP) - || (status == HttpURLConnection.HTTP_MOVED_PERM) - || (status == HttpURLConnection.HTTP_SEE_OTHER)) { + || (status == HttpURLConnection.HTTP_MOVED_PERM) + || (status == HttpURLConnection.HTTP_SEE_OTHER)) { // get redirect url from "location" header field String newUrl = connection.getHeaderField("location"); // open the new connection again diff --git a/jablib/src/main/java/org/jabref/logic/net/ssl/TrustStoreManager.java b/jablib/src/main/java/org/jabref/logic/net/ssl/TrustStoreManager.java index c1304ba8f93..547840a41fc 100644 --- a/jablib/src/main/java/org/jabref/logic/net/ssl/TrustStoreManager.java +++ b/jablib/src/main/java/org/jabref/logic/net/ssl/TrustStoreManager.java @@ -169,7 +169,7 @@ public static void createTruststoreFileIfNotExist(Path storePath) { * @implNote based on https://stackoverflow.com/a/62586564/3450689 */ private static void configureTrustStore(Path myStorePath) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, - CertificateException, IOException { + CertificateException, IOException { X509TrustManager jreTrustManager = getJreTrustManager(); X509TrustManager myTrustManager = getJabRefTrustManager(myStorePath); @@ -182,7 +182,7 @@ private static X509TrustManager getJreTrustManager() throws NoSuchAlgorithmExcep } private static X509TrustManager getJabRefTrustManager(Path myStorePath) throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException { + NoSuchAlgorithmException, CertificateException { // Adapt to load your keystore try (InputStream myKeys = Files.newInputStream(myStorePath)) { KeyStore myTrustStore = KeyStore.getInstance("jks"); @@ -193,7 +193,7 @@ private static X509TrustManager getJabRefTrustManager(Path myStorePath) throws K } private static X509TrustManager findDefaultTrustManager(KeyStore keyStore) - throws NoSuchAlgorithmException, KeyStoreException { + throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); // If keyStore is null, tmf will be initialized with the default trust store @@ -235,7 +235,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) throws } private static void setSystemTrustManager(X509TrustManager mergedTrustManager) - throws NoSuchAlgorithmException, KeyManagementException { + throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] {mergedTrustManager}, null); diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/ReferenceMark.java b/jablib/src/main/java/org/jabref/logic/openoffice/ReferenceMark.java index 19eda50fce6..89a86c9ff49 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/ReferenceMark.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/ReferenceMark.java @@ -30,10 +30,10 @@ public class ReferenceMark { /** * @param name Allowed formats: - * Single entry: JABREF_{citationKey} CID_{citationNumber} {uniqueId} - * Group of entries: JABREF_{citationKey1} CID_{citationNumber1}, JABREF_{citationKey2} CID_{citationNumber2}, ..., JABREF_{citationKeyN} CID_{citationNumberN} {uniqueId} - * Disallowed: JABREF_{citationKey} CID_{citationNumber} (no unique ID at the end) - * Disallowed: JABREF_{citationKey1} CID_{citationNumber1} JABREF_{citationKey2} CID_{citationNumber2} {uniqueId} (no comma between entries) + * Single entry: JABREF_{citationKey} CID_{citationNumber} {uniqueId} + * Group of entries: JABREF_{citationKey1} CID_{citationNumber1}, JABREF_{citationKey2} CID_{citationNumber2}, ..., JABREF_{citationKeyN} CID_{citationNumberN} {uniqueId} + * Disallowed: JABREF_{citationKey} CID_{citationNumber} (no unique ID at the end) + * Disallowed: JABREF_{citationKey1} CID_{citationNumber1} JABREF_{citationKey2} CID_{citationNumber2} {uniqueId} (no comma between entries) */ public ReferenceMark(String name) { this.name = name; diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/jablib/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 1bd2f71b2ec..a5e6bc59f51 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -60,8 +60,8 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend frontend List groups = joinableGroupData.group; List newCitations = groups.stream() - .flatMap(group -> group.citationsInStorageOrder.stream()) - .collect(Collectors.toList()); + .flatMap(group -> group.citationsInStorageOrder.stream()) + .collect(Collectors.toList()); CitationType citationType = groups.getFirst().citationType; List> pageInfos = frontend.backend.combinePageInfos(groups); @@ -177,8 +177,8 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe state.prevRange.getString(), currentRange.getString(), (textOrder == 0 - ? "they start at the same position" - : "the start of the latter precedes the start of the first")); + ? "they start at the same position" + : "the start of the latter precedes the start of the first")); LOGGER.warn(msg); return false; } @@ -255,7 +255,7 @@ private static void addToCurrentGroup(ScanState state, CitationGroup group, XTex // If new group, create currentGroupCursor if (isNewGroup) { state.currentGroupCursor = currentRange.getText() - .createTextCursorByRange(currentRange.getStart()); + .createTextCursorByRange(currentRange.getStart()); } // include currentRange in currentGroupCursor @@ -289,7 +289,7 @@ private static List scan(XTextDocument doc, OOFrontend fronte for (CitationGroup group : groups) { XTextRange currentRange = frontend.getMarkRange(doc, group) - .orElseThrow(IllegalStateException::new); + .orElseThrow(IllegalStateException::new); /* * Decide if we add group to the group. False when the group is empty. diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/jablib/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 5b8bbce19d9..5c17dc5fa77 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -132,17 +132,17 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str Codec52.ParsedMarkName parsed = Codec52.parseMarkName(markName).orElseThrow(IllegalArgumentException::new); List citations = parsed.citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()); + .map(Citation::new) + .collect(Collectors.toList()); Optional pageInfo = UnoUserDefinedProperty.getStringValue(doc, markName) - .map(OOText::fromString); + .map(OOText::fromString); pageInfo = PageInfo.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); NamedRange namedRange = citationStorageManager.getNamedRangeFromDocument(doc, markName) - .orElseThrow(IllegalArgumentException::new); + .orElseThrow(IllegalArgumentException::new); CitationGroupId groupId = new CitationGroupId(markName); CitationGroup group = new CitationGroup(OODataModel.JabRef52, @@ -271,14 +271,14 @@ public CitationGroup createCitationGroup(XTextDocument doc, // Try to do something of the pageInfos. String singlePageInfo = pageInfos.stream() - .filter(Optional::isPresent) - .map(pi -> OOText.toString(pi.get())) - .distinct() - .collect(Collectors.joining("; ")); + .filter(Optional::isPresent) + .map(pi -> OOText.toString(pi.get())) + .distinct() + .collect(Collectors.joining("; ")); int totalCitations = joinableGroup.stream() - .map(CitationGroup::numberOfCitations) - .mapToInt(Integer::intValue).sum(); + .map(CitationGroup::numberOfCitations) + .mapToInt(Integer::intValue).sum(); if (singlePageInfo.isEmpty()) { singlePageInfo = null; } @@ -286,9 +286,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, case JabRef60: return joinableGroup.stream() - .flatMap(group -> (group.citationsInStorageOrder.stream() - .map(Citation::getPageInfo))) - .collect(Collectors.toList()); + .flatMap(group -> (group.citationsInStorageOrder.stream() + .map(Citation::getPageInfo))) + .collect(Collectors.toList()); default: throw new IllegalArgumentException("unhandled dataModel here"); } @@ -382,9 +382,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups .orElseThrow(IllegalStateException::new); String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = group.numberOfCitations() > 0 - ? (getPageInfoFromData(group) + ? (getPageInfoFromData(group) .map(e -> OOText.toString(e))) - : Optional.empty(); + : Optional.empty(); CitationEntry entry = new CitationEntry(name, context, pageInfo); citations.add(entry); } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/jablib/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 5d567539799..25a5bd33de3 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -57,18 +57,25 @@ public static class ParsedMarkName { */ private static CitationType citationTypeFromInt(int code) { return switch (code) { - case 1 -> CitationType.AUTHORYEAR_PAR; - case 2 -> CitationType.AUTHORYEAR_INTEXT; - case 3 -> CitationType.INVISIBLE_CIT; - default -> throw new IllegalArgumentException("Invalid CitationType code"); + case 1 -> + CitationType.AUTHORYEAR_PAR; + case 2 -> + CitationType.AUTHORYEAR_INTEXT; + case 3 -> + CitationType.INVISIBLE_CIT; + default -> + throw new IllegalArgumentException("Invalid CitationType code"); }; } private static int citationTypeToInt(CitationType type) { return switch (type) { - case AUTHORYEAR_PAR -> 1; - case AUTHORYEAR_INTEXT -> 2; - case INVISIBLE_CIT -> 3; + case AUTHORYEAR_PAR -> + 1; + case AUTHORYEAR_INTEXT -> + 2; + case INVISIBLE_CIT -> + 3; }; } @@ -131,7 +138,7 @@ public static boolean isJabRefReferenceMarkName(String name) { */ public static List filterIsJabRefReferenceMarkName(List names) { return names.stream() - .filter(Codec52::isJabRefReferenceMarkName) - .collect(Collectors.toList()); + .filter(Codec52::isJabRefReferenceMarkName) + .collect(Collectors.toList()); } } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/jablib/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index e2f0beb3cd2..ee2497ed2e8 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -98,8 +98,8 @@ private static void createReprInDocument(XTextDocument doc, final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; String bracketedContent = withoutBrackets - ? "" - : left + right; + ? "" + : left + right; cursor.getText().insertString(cursor, bracketedContent, true); DocumentAnnotation documentAnnotation = new DocumentAnnotation(doc, refMarkName, cursor, true /* absorb */); @@ -135,7 +135,7 @@ static Optional getFromDocument(XTextDocument doc, Stri NoDocumentException, WrappedTargetException { return UnoReferenceMark.getAnchor(doc, refMarkName) - .map(e -> new NamedRangeReferenceMark(refMarkName)); + .map(e -> new NamedRangeReferenceMark(refMarkName)); } /** diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/jablib/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 1aeec0d2320..a481101c827 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -168,8 +168,8 @@ private List getVisuallySortedCitationGroups(XTextDocument doc, List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); return sorted.stream() - .map(RangeSortable::getContent) - .collect(Collectors.toList()); + .map(RangeSortable::getContent) + .collect(Collectors.toList()); } /** @@ -384,13 +384,16 @@ static String rangeOverlapsToMessage(List> overlap : overlaps) { String listOfRanges = overlap.valuesForOverlappingRanges.stream() - .map(v -> "'%s'".formatted(v.format())) - .collect(Collectors.joining(", ")); + .map(v -> "'%s'".formatted(v.format())) + .collect(Collectors.joining(", ")); msg.append( switch (overlap.kind) { - case EQUAL_RANGE -> Localization.lang("Found identical ranges"); - case OVERLAP -> Localization.lang("Found overlapping ranges"); - case TOUCH -> Localization.lang("Found touching ranges"); + case EQUAL_RANGE -> + Localization.lang("Found identical ranges"); + case OVERLAP -> + Localization.lang("Found overlapping ranges"); + case TOUCH -> + Localization.lang("Found touching ranges"); }); msg.append(": "); msg.append(listOfRanges); diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/jablib/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index 1ed8747bc3c..a12d88adbec 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -34,7 +34,7 @@ private UpdateCitationMarkers() { *

      * After each fillCitationMarkInCursor call check if we lost the BIB_SECTION_NAME bookmark and recreate it if we did. * - * @param style Bibliography style to use. + * @param style Bibliography style to use. */ public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend frontend, JStyle style) throws @@ -80,8 +80,8 @@ public static void fillCitationMarkInCursor(XTextDocument doc, OOText citationText2 = style.decorateCitationMarker(citationText); String ZERO_WIDTH_SPACE = ""; if (style.spaceBeforeCitation()) { - // inject a ZERO_WIDTH_SPACE to hold the initial character format - ZERO_WIDTH_SPACE = "\u200b"; + // inject a ZERO_WIDTH_SPACE to hold the initial character format + ZERO_WIDTH_SPACE = "\u200b"; } citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.toString()); OOTextIntoOO.write(doc, cursor, citationText2); diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtils.java b/jablib/src/main/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtils.java index 465238ea6c4..aa6263fab7c 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtils.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtils.java @@ -143,8 +143,8 @@ public static String generateAlphanumericCitation(List entries, BibDat // Extract last two digits of the year String shortYear = year.get().length() >= 2 ? - year.get().substring(year.get().length() - 2) : - year.get(); + year.get().substring(year.get().length() - 2) : + year.get(); citation.append(alphaKey).append(shortYear); } else { @@ -179,7 +179,7 @@ public static String generateAlphanumericInTextCitation(BibEntry entry, BibDatab *

      * Precondition: Use ONLY with numeric citation styles.

      * - * @param citation the numeric citation with an unresolved number. + * @param citation the numeric citation with an unresolved number. * @param currentNumber the correct number to update the citation with. * @return the bibliographic citation with resolved number. */ diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyle.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyle.java index 48bdee7ddd4..46d179eeb96 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyle.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyle.java @@ -603,9 +603,9 @@ public boolean equals(Object object) { } if (object instanceof JStyle otherStyle) { return Objects.equals(path, otherStyle.path) - && Objects.equals(name, otherStyle.name) - && Objects.equals(citProperties, otherStyle.citProperties) - && Objects.equals(properties, otherStyle.properties); + && Objects.equals(name, otherStyle.name) + && Objects.equals(citProperties, otherStyle.citProperties) + && Objects.equals(properties, otherStyle.properties); } return false; } @@ -984,7 +984,7 @@ public OOText getFormattedBibliographyTitle() { OOText title = style.getReferenceHeaderText(); String parStyle = style.getReferenceHeaderParagraphFormat(); return parStyle == null - ? OOFormat.paragraph(title) - : OOFormat.paragraph(title, parStyle); + ? OOFormat.paragraph(title) + : OOFormat.paragraph(title, parStyle); } } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetCitationMarker.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetCitationMarker.java index 8553e0c6fff..e80bf9c3467 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetCitationMarker.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetCitationMarker.java @@ -31,12 +31,12 @@ private JStyleGetCitationMarker() { /** * Look up the nth author and return the "proper" last name for * citation markers. - * + *

      * Note: "proper" in the sense that it includes the "von" part - * of the name (followed by a space) if there is one. + * of the name (followed by a space) if there is one. * - * @param authorList The author list. - * @param number The number of the author to return. + * @param authorList The author list. + * @param number The number of the author to return. * @return The author name, or an empty String if inapplicable. */ private static String getAuthorLastName(AuthorList authorList, int number) { @@ -65,29 +65,26 @@ private static String markupAuthorName(JStyle style, String name) { /** * @param authorList Parsed list of authors. - * * @param maxAuthors The maximum number of authors to write out. * If there are more authors, then ET_AL_STRING is emitted * to mark their omission. * Set to -1 to write out all authors. - * + *

      * maxAuthors=0 is pointless, now throws IllegalArgumentException * (Earlier it behaved as maxAuthors=1) - * + *

      * maxAuthors less than -1 : throw IllegalArgumentException - * * @param andString For "A, B[ and ]C" - * * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" - * or "Au[etAlString][yearSep]" - * - * where AS = AUTHOR_SEPARATOR - * Au, Bu, Cu, Du are last names of authors. - * - * Note: - * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). - * - OXFORD_COMMA is only emitted if nAuthors is at least 3. - * - andString is only emitted if nAuthors is at least 2. + * or "Au[etAlString][yearSep]" + *

      + * where AS = AUTHOR_SEPARATOR + * Au, Bu, Cu, Du are last names of authors. + *

      + * Note: + * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). + * - OXFORD_COMMA is only emitted if nAuthors is at least 3. + * - andString is only emitted if nAuthors is at least 2. */ private static String formatAuthorList(JStyle style, @NonNull AuthorList authorList, @@ -215,6 +212,7 @@ private static String formatAuthorList(JStyle style, private static class FieldAndContent { Field field; String content; + FieldAndContent(Field field, String content) { this.field = field; this.content = content; @@ -242,22 +240,21 @@ private static Optional getRawCitationMarkerField(@NonNull BibE /** * This method looks up a field for an entry in a database. - * + *

      * Any number of backup fields can be used if the primary field is * empty. * - * @param fields A list of fields, to look up, using first nonempty hit. - * - * If backup fields are needed, separate field - * names by /. - * - * E.g. to use "author" with "editor" as backup, - * specify - * FieldFactory.serializeOrFields(StandardField.AUTHOR, - * StandardField.EDITOR) - * + * @param fields A list of fields, to look up, using first nonempty hit. + *

      + * If backup fields are needed, separate field + * names by /. + *

      + * E.g. to use "author" with "editor" as backup, + * specify + * FieldFactory.serializeOrFields(StandardField.AUTHOR, + * StandardField.EDITOR) * @return The resolved field content, or an empty string if the - * field(s) were empty. + * field(s) were empty. * * * @@ -266,7 +263,7 @@ private static String getCitationMarkerField(JStyle style, @NonNull CitationLookupResult db, OrFields fields) { Optional optionalFieldAndContent = - getRawCitationMarkerField(db.entry, db.database, fields); + getRawCitationMarkerField(db.entry, db.database, fields); if (optionalFieldAndContent.isEmpty()) { // No luck? Return an empty string: @@ -305,7 +302,7 @@ private enum AuthorYearMarkerPurpose { /** * How many authors would be emitted for entry, considering * style and entry.getIsFirstAppearanceOfSource() - * + *

      * If entry is unresolved, return 0. */ private static int calculateNAuthorsToEmit(JStyle style, CitationMarkerEntry entry) { @@ -315,8 +312,8 @@ private static int calculateNAuthorsToEmit(JStyle style, CitationMarkerEntry ent } int maxAuthors = entry.getIsFirstAppearanceOfSource() - ? style.getMaxAuthorsFirst() - : style.getMaxAuthors(); + ? style.getMaxAuthorsFirst() + : style.getMaxAuthors(); AuthorList authorList = getAuthorList(style, entry.getLookupResult().get()); int nAuthors = authorList.getNumberOfAuthors(); @@ -331,36 +328,32 @@ private static int calculateNAuthorsToEmit(JStyle style, CitationMarkerEntry ent /** * Produce (Author, year) or "Author (year)" style citation strings. * - * @param purpose IN_PARENTHESIS and NORMALIZED puts parentheses around the whole, - * IN_TEXT around each (year,uniqueLetter,pageInfo) part. - * - * NORMALIZED omits uniqueLetter and pageInfo, - * ignores isFirstAppearanceOfSource (always - * style.getMaxAuthors, not getMaxAuthorsFirst) - * - * @param entries The list of CitationMarkerEntry values to process. - * - * Here we do not check for duplicate entries: those - * are handled by {@code getCitationMarker} by - * omitting them from the list. - * - * Unresolved citations recognized by - * entry.getBibEntry() and/or - * entry.getDatabase() returning empty, and - * emitted as "Unresolved${citationKey}". - * - * Neither uniqueLetter nor pageInfo are emitted - * for unresolved citations. - * - * @param startsNewGroup Should have the same length as {@code entries}, and - * contain true for entries starting a new group, - * false for those that only add a uniqueLetter to - * the grouped presentation. - * + * @param purpose IN_PARENTHESIS and NORMALIZED puts parentheses around the whole, + * IN_TEXT around each (year,uniqueLetter,pageInfo) part. + *

      + * NORMALIZED omits uniqueLetter and pageInfo, + * ignores isFirstAppearanceOfSource (always + * style.getMaxAuthors, not getMaxAuthorsFirst) + * @param entries The list of CitationMarkerEntry values to process. + *

      + * Here we do not check for duplicate entries: those + * are handled by {@code getCitationMarker} by + * omitting them from the list. + *

      + * Unresolved citations recognized by + * entry.getBibEntry() and/or + * entry.getDatabase() returning empty, and + * emitted as "Unresolved${citationKey}". + *

      + * Neither uniqueLetter nor pageInfo are emitted + * for unresolved citations. + * @param startsNewGroup Should have the same length as {@code entries}, and + * contain true for entries starting a new group, + * false for those that only add a uniqueLetter to + * the grouped presentation. * @param maxAuthorsOverride If not empty, always show this number of authors. - * Added to allow NORMALIZED to use maxAuthors value that differs from - * style.getMaxAuthors() - * + * Added to allow NORMALIZED to use maxAuthors value that differs from + * style.getMaxAuthors() * @return The formatted citation. * */ @@ -371,12 +364,12 @@ private static OOText getAuthorYearParenthesisMarker2(JStyle style, Optional maxAuthorsOverride) { boolean inParenthesis = purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS - || purpose == AuthorYearMarkerPurpose.NORMALIZED; + || purpose == AuthorYearMarkerPurpose.NORMALIZED; // The String to separate authors from year, e.g. "; ". String yearSep = inParenthesis - ? style.getYearSeparator() - : style.getYearSeparatorInText(); + ? style.getYearSeparator() + : style.getYearSeparatorInText(); // The opening parenthesis. String startBrace = style.getBracketBefore(); @@ -392,8 +385,8 @@ private static OOText getAuthorYearParenthesisMarker2(JStyle style, // The String to add between the two last author names, e.g. " & ". String andString = inParenthesis - ? style.getAuthorLastSeparator() - : style.getAuthorLastSeparatorInTextWithFallBack(); + ? style.getAuthorLastSeparator() + : style.getAuthorLastSeparatorInTextWithFallBack(); String pageInfoSeparator = style.getPageInfoSeparator(); String uniquefierSeparator = style.getUniquefierSeparator(); @@ -432,7 +425,7 @@ private static OOText getAuthorYearParenthesisMarker2(JStyle style, StringBuilder pageInfoPart = new StringBuilder(); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { Optional pageInfo = - PageInfo.normalizePageInfo(entry.getPageInfo()); + PageInfo.normalizePageInfo(entry.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); pageInfoPart.append(OOText.toString(pageInfo.get())); @@ -449,8 +442,8 @@ private static OOText getAuthorYearParenthesisMarker2(JStyle style, CitationLookupResult db = entry.getLookupResult().get(); int maxAuthors = purpose == AuthorYearMarkerPurpose.NORMALIZED - ? style.getMaxAuthors() - : calculateNAuthorsToEmit(style, entry); + ? style.getMaxAuthors() + : calculateNAuthorsToEmit(style, entry); if (maxAuthorsOverride.isPresent()) { maxAuthors = maxAuthorsOverride.get(); @@ -529,13 +522,12 @@ public boolean getIsFirstAppearanceOfSource() { } /** - * @param normEntry A citation to process. - * + * @param normEntry A citation to process. * @return A normalized citation marker for deciding which - * citations need uniqueLetters. - * + * citations need uniqueLetters. + *

      * For details of what "normalized" means: See {@link JStyleGetCitationMarker#getAuthorYearParenthesisMarker2} - * + *

      * Note: now includes some markup. */ static OOText getNormalizedCitationMarker(JStyle style, @@ -544,10 +536,10 @@ static OOText getNormalizedCitationMarker(JStyle style, boolean[] startsNewGroup = {true}; CitationMarkerEntry entry = new CitationMarkerNormEntryWrap(normEntry); return getAuthorYearParenthesisMarker2(style, - AuthorYearMarkerPurpose.NORMALIZED, - List.of(entry), - startsNewGroup, - maxAuthorsOverride); + AuthorYearMarkerPurpose.NORMALIZED, + List.of(entry), + startsNewGroup, + maxAuthorsOverride); } private static List @@ -558,8 +550,8 @@ static OOText getNormalizedCitationMarker(JStyle style, List normalizedMarkers = new ArrayList<>(citationMarkerEntries.size()); for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { OOText normalized = getNormalizedCitationMarker(style, - citationMarkerEntry, - maxAuthorsOverride); + citationMarkerEntry, + maxAuthorsOverride); normalizedMarkers.add(normalized); } return normalizedMarkers; @@ -567,31 +559,29 @@ static OOText getNormalizedCitationMarker(JStyle style, /** * Produce citation marker for a citation group. - * + *

      * Attempts to join consecutive citations: if normalized citations - * markers match and no pageInfo is present, the second entry - * can be presented by appending its uniqueLetter to the - * previous. - * - * If either entry has pageInfo, join is inhibited. - * If the previous entry has more names than we need - * we check with extended normalizedMarkers if they match. - * + * markers match and no pageInfo is present, the second entry + * can be presented by appending its uniqueLetter to the + * previous. + *

      + * If either entry has pageInfo, join is inhibited. + * If the previous entry has more names than we need + * we check with extended normalizedMarkers if they match. + *

      * For consecutive identical entries, the second one is omitted. - * Identical requires same pageInfo here, we do not try to merge them. - * Note: notifying the user about them would be nice. - * - * @param citationMarkerEntries A group of citations to process. - * - * @param inParenthesis If true, put parenthesis around the whole group, - * otherwise around each (year,uniqueLetter,pageInfo) part. + * Identical requires same pageInfo here, we do not try to merge them. + * Note: notifying the user about them would be nice. * + * @param citationMarkerEntries A group of citations to process. + * @param inParenthesis If true, put parenthesis around the whole group, + * otherwise around each (year,uniqueLetter,pageInfo) part. * @param nonUniqueCitationMarkerHandling What should happen if we - * stumble upon citations with identical normalized - * citation markers which cite different sources and - * are not distinguished by uniqueLetters. - * - * Note: only consecutive citations are checked. + * stumble upon citations with identical normalized + * citation markers which cite different sources and + * are not distinguished by uniqueLetters. + *

      + * Note: only consecutive citations are checked. * */ public static OOText @@ -618,8 +608,8 @@ static OOText getNormalizedCitationMarker(JStyle style, // List normalizedMarkers = getNormalizedCitationMarkers(style, - citationMarkerEntries, - Optional.empty()); + citationMarkerEntries, + Optional.empty()); // How many authors would be emitted without grouping. int[] nAuthorsToEmit = new int[nEntries]; @@ -672,8 +662,8 @@ static OOText getNormalizedCitationMarker(JStyle style, // nAuthorsToEmitRevised[i-1] may have been indirectly increased, // we have to check that too. if (!isFirst1 && - !isFirst2 && - (nAuthorsToEmitRevised[i - 1] == nAuthorsToEmit[i - 1])) { + !isFirst2 && + (nAuthorsToEmitRevised[i - 1] == nAuthorsToEmit[i - 1])) { // we can rely on normalizedMarkers nAuthorsShownInhibitsJoin = false; } else if (style.getMaxAuthors() == style.getMaxAuthorsFirst()) { @@ -691,9 +681,9 @@ static OOText getNormalizedCitationMarker(JStyle style, // prevShown >= need // Check with extended normalizedMarkers. OOText nmx1 = - getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); + getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); OOText nmx2 = - getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); + getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); boolean extendedMarkersDiffer = !nmx2.equals(nmx1); nAuthorsShownInhibitsJoin = extendedMarkersDiffer; } @@ -714,24 +704,24 @@ static OOText getNormalizedCitationMarker(JStyle style, final boolean uniqueLettersDiffer = !ul2.equals(ul1); final boolean uniqueLetterDoesNotMakeUnique = citationKeysDiffer - && !normalizedMarkersDiffer - && !uniqueLettersDiffer; + && !normalizedMarkersDiffer + && !uniqueLettersDiffer; if (uniqueLetterDoesNotMakeUnique && nonUniqueCitationMarkerHandling == NonUniqueCitationMarker.THROWS) { throw new IllegalArgumentException("different citation keys," - + " but same normalizedMarker and uniqueLetter"); + + " but same normalizedMarker and uniqueLetter"); } final boolean pageInfoInhibitsJoin = bothPageInfosAreEmpty - ? false - : (citationKeysDiffer || pageInfosDiffer); + ? false + : (citationKeysDiffer || pageInfosDiffer); startingNewGroup = normalizedMarkersDiffer - || nAuthorsShownInhibitsJoin - || pageInfoInhibitsJoin - || uniqueLetterPresenceChanged - || uniqueLetterDoesNotMakeUnique; + || nAuthorsShownInhibitsJoin + || pageInfoInhibitsJoin + || uniqueLetterPresenceChanged + || uniqueLetterDoesNotMakeUnique; if (!startingNewGroup) { // inherit from first of group. Used at next i. @@ -739,9 +729,9 @@ static OOText getNormalizedCitationMarker(JStyle style, } sameAsPrev = !startingNewGroup - && !uniqueLettersDiffer - && !citationKeysDiffer - && !pageInfosDiffer; + && !uniqueLettersDiffer + && !citationKeysDiffer + && !pageInfosDiffer; } if (!sameAsPrev) { @@ -752,11 +742,11 @@ static OOText getNormalizedCitationMarker(JStyle style, } return getAuthorYearParenthesisMarker2(style, - inParenthesis - ? AuthorYearMarkerPurpose.IN_PARENTHESIS - : AuthorYearMarkerPurpose.IN_TEXT, - filteredCitationMarkerEntries, - startsNewGroup, - Optional.empty()); + inParenthesis + ? AuthorYearMarkerPurpose.IN_PARENTHESIS + : AuthorYearMarkerPurpose.IN_TEXT, + filteredCitationMarkerEntries, + startsNewGroup, + Optional.empty()); } } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetNumCitationMarker.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetNumCitationMarker.java index df500faa0aa..43aa3fdf4f8 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetNumCitationMarker.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/JStyleGetNumCitationMarker.java @@ -33,17 +33,17 @@ private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry } /** - * Create a numeric marker for use in the bibliography as label for the entry. + * Create a numeric marker for use in the bibliography as label for the entry. + *

      + * To support for example numbers in superscript without brackets for the text, + * but "[1]" form for the bibliography, the style can provide + * the optional "BracketBeforeInList" and "BracketAfterInList" strings + * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" * - * To support for example numbers in superscript without brackets for the text, - * but "[1]" form for the bibliography, the style can provide - * the optional "BracketBeforeInList" and "BracketAfterInList" strings - * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" - * - * @return "[${number}]" where - * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) - * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) - * "${number}" stands for the formatted number. + * @return "[${number}]" where + * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) + * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) + * "${number}" stands for the formatted number. */ public static OOText getNumCitationMarkerForBibliography(JStyle style, CitationMarkerNumericBibEntry entry) { @@ -55,8 +55,8 @@ public static OOText getNumCitationMarkerForBibliography(JStyle style, stringBuilder.append(bracketBefore); final Optional current = entry.getNumber(); stringBuilder.append(current.isPresent() - ? String.valueOf(current.get()) - : (JStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())); + ? String.valueOf(current.get()) + : (JStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())); stringBuilder.append(bracketAfter); stringBuilder.append(style.getCitationGroupMarkupAfter()); return OOText.fromString(stringBuilder.toString()); @@ -160,24 +160,22 @@ private static void emitBlock(List block, /** * Format a number-based citation marker for the given number or numbers. * - * @param entries Provide the citation numbers. - * - * An Optional.empty() number means: could not look this up - * in the databases. Positive integers are the valid numbers. - * - * Duplicate citation numbers are allowed: - * - * - If their pageInfos are identical, only a - * single instance is emitted. - * - * - If their pageInfos differ, the number is emitted with each - * distinct pageInfo. - * - * pageInfos are expected to be normalized - * + * @param entries Provide the citation numbers. + *

      + * An Optional.empty() number means: could not look this up + * in the databases. Positive integers are the valid numbers. + *

      + * Duplicate citation numbers are allowed: + *

      + * - If their pageInfos are identical, only a + * single instance is emitted. + *

      + * - If their pageInfos differ, the number is emitted with each + * distinct pageInfo. + *

      + * pageInfos are expected to be normalized * @param minGroupingCount Zero and negative means never group. - * Only used by tests to override the value in style. - * + * Only used by tests to override the value in style. * @return The text for the citation. * */ @@ -231,8 +229,8 @@ public static OOText getNumCitationMarker2(JStyle style, } else if (compareCitationMarkerNumericEntry(current, prev) == 0) { // Same as prev, just forget it. } else if ((current.getNumber().get() == (prev.getNumber().get() + 1)) - && (prev.getPageInfo().isEmpty()) - && (current.getPageInfo().isEmpty())) { + && (prev.getPageInfo().isEmpty()) + && (current.getPageInfo().isEmpty())) { // Just two consecutive numbers without pageInfo: join currentBlock.add(current); } else { diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index addc5c83728..46ff26a0b0c 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -102,9 +102,9 @@ public static OOText formatBibliographyEntryBody(CitedKey citedKey, JStyle style layout.setPostFormatter(POSTFORMATTER); return formatFullReferenceOfBibEntry(layout, - bibentry, - citedKey.getLookupResult().get().database, - citedKey.getUniqueLetter().orElse(null)); + bibentry, + citedKey.getLookupResult().get().database, + citedKey.getUniqueLetter().orElse(null)); } } @@ -115,7 +115,6 @@ public static OOText formatBibliographyEntryBody(CitedKey citedKey, JStyle style * @param entry The entry to insert. * @param database The database the entry belongs to. * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. - * * @return OOText The reference part of a bibliography entry formatted as OOText */ private static OOText formatFullReferenceOfBibEntry(Layout layout, @@ -148,11 +147,11 @@ private static OOText formatFullReferenceOfBibEntry(Layout layout, /** * Format links to citations of the source (citedKey). - * + *

      * Requires reference marks for the citation groups. - * + *

      * - The links are created as references that show page numbers of the reference marks. - * - We do not control the text shown, that is provided by OpenOffice. + * - We do not control the text shown, that is provided by OpenOffice. */ private static OOText formatCitedOnPages(CitationGroups citationGroups, CitedKey citedKey) { if (!citationGroups.citationGroupsProvideReferenceMarkNameForLinking()) { @@ -177,10 +176,10 @@ private static OOText formatCitedOnPages(CitationGroups citationGroups, CitedKey // sort the citationGroups according to their indexInGlobalOrder filteredList.sort((a, b) -> { - Integer aa = a.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); - Integer bb = b.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); - return aa.compareTo(bb); - }); + Integer aa = a.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); + Integer bb = b.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); + return aa.compareTo(bb); + }); int index = 0; for (CitationGroup group : filteredList) { diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java index caeaf8cce2a..056a34b2609 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java @@ -148,16 +148,28 @@ private String getHTMLTag(String latexCommand) { String result = ""; switch (latexCommand) { // Should really separate between emphasized and italic but since in later stages both are converted to italic... - case "textit", "it", "emph", "em" -> result = "i"; // Italic - case "textbf", "bf" -> result = "b"; // Bold font - case "textsc" -> result = "smallcaps"; // Small caps - // Not a proper HTML tag, but used here for convenience - case "underline" -> result = "u"; // Underline - case "sout" -> result = "s"; // Strikeout - // sout is the "standard" command, although it is actually based on the package ulem - case "texttt" -> result = "tt"; // Monospace font - case "textsuperscript" -> result = "sup"; // Superscript - case "textsubscript" -> result = "sub"; // Subscript + case "textit", + "it", + "emph", + "em" -> + result = "i"; // Italic + case "textbf", + "bf" -> + result = "b"; // Bold font + case "textsc" -> + result = "smallcaps"; // Small caps + // Not a proper HTML tag, but used here for convenience + case "underline" -> + result = "u"; // Underline + case "sout" -> + result = "s"; // Strikeout + // sout is the "standard" command, although it is actually based on the package ulem + case "texttt" -> + result = "tt"; // Monospace font + case "textsuperscript" -> + result = "sup"; // Superscript + case "textsubscript" -> + result = "sub"; // Subscript } return result; } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java index 68d581df341..4e5abaebaaf 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java @@ -20,26 +20,26 @@ private OOProcess() { private static Comparator makeAuthorYearTitleComparator() { List> ayt = List.of(new FieldComparator(StandardField.AUTHOR), - new FieldComparator(StandardField.YEAR), - new FieldComparator(StandardField.TITLE)); + new FieldComparator(StandardField.YEAR), + new FieldComparator(StandardField.TITLE)); return new FieldComparatorStack<>(ayt); } private static Comparator makeYearAuthorTitleComparator() { List> yat = List.of(new FieldComparator(StandardField.YEAR), - new FieldComparator(StandardField.AUTHOR), - new FieldComparator(StandardField.TITLE)); + new FieldComparator(StandardField.AUTHOR), + new FieldComparator(StandardField.TITLE)); return new FieldComparatorStack<>(yat); } /** - * The comparator used to sort within a group of merged - * citations. - * - * The term used here is "multicite". The option controlling the - * order is "MultiCiteChronological" in style files. - * - * Yes, they are always sorted one way or another. + * The comparator used to sort within a group of merged + * citations. + *

      + * The term used here is "multicite". The option controlling the + * order is "MultiCiteChronological" in style files. + *

      + * Yes, they are always sorted one way or another. */ public static Comparator comparatorForMulticite(JStyle style) { if (style.getMultiCiteChronological()) { @@ -50,8 +50,8 @@ public static Comparator comparatorForMulticite(JStyle style) { } /** - * Fill citationGroups.bibliography and cgs.citationGroupsUnordered//CitationMarker - * according to style. + * Fill citationGroups.bibliography and cgs.citationGroupsUnordered//CitationMarker + * according to style. */ public static void produceCitationMarkers(CitationGroups citationGroups, List databases, JStyle style) { if (!citationGroups.hasGlobalOrder()) { diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index a549d162429..57afb8842fb 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -25,7 +25,7 @@ private OOProcessAuthorYearMarkers() { } /** - * Fills {@code sortedCitedKeys//normCitMarker} + * Fills {@code sortedCitedKeys//normCitMarker} */ private static void createNormalizedCitationMarkers(CitedKeys sortedCitedKeys, JStyle style) { for (CitedKey ck : sortedCitedKeys.values()) { @@ -34,19 +34,19 @@ private static void createNormalizedCitationMarkers(CitedKeys sortedCitedKeys, J } /** - * For each cited source make the citation keys unique by setting - * the uniqueLetter fields to letters ("a", "b") or Optional.empty() - * + * For each cited source make the citation keys unique by setting + * the uniqueLetter fields to letters ("a", "b") or Optional.empty() + *

      * precondition: sortedCitedKeys already has normalized citation markers. * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) - * + *

      * Expects to see data for all cited sources here. * Clears uniqueLetters before filling. - * + *

      * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. - * The same values are copied to the corresponding citations in citationGroups. - * - * Depends on: style, citations and their order. + * The same values are copied to the corresponding citations in citationGroups. + *

      + * Depends on: style, citations and their order. */ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroups citationGroups) { // The entries in the clashingKeys lists preserve @@ -102,7 +102,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup /** * Set isFirstAppearanceOfSource in each citation. - * + *

      * Preconditions: globalOrder, localOrder */ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups citationGroups) { @@ -124,7 +124,7 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups citat * Produce citMarkers for normal * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. * - * @param style Bibliography style. + * @param style Bibliography style. */ static void produceCitationMarkers(CitationGroups citationGroups, JStyle style) { assert !style.isCitationKeyCiteMarkers(); @@ -147,8 +147,8 @@ static void produceCitationMarkers(CitationGroups citationGroups, JStyle style) List cits = group.getCitationsInLocalOrder(); List citationMarkerEntries = OOListUtil.map(cits, e -> e); OOText citMarker = style.createCitationMarker(citationMarkerEntries, - inParenthesis, - strictlyUnique); + inParenthesis, + strictlyUnique); group.setCitationMarker(Optional.of(citMarker)); } } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java index c7487bf30af..3cebd7c5a6e 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java @@ -14,8 +14,8 @@ private OOProcessCitationKeyMarkers() { } /** - * Produce citation markers for the case when the citation - * markers are the citation keys themselves, separated by commas. + * Produce citation markers for the case when the citation + * markers are the citation keys themselves, separated by commas. */ static void produceCitationMarkers(CitationGroups citationGroups, JStyle style) { assert style.isCitationKeyCiteMarkers(); @@ -24,9 +24,9 @@ static void produceCitationMarkers(CitationGroups citationGroups, JStyle style) for (CitationGroup group : citationGroups.getCitationGroupsInGlobalOrder()) { String citMarker = - style.getCitationGroupMarkupBefore() - + String.join(",", OOListUtil.map(group.getCitationsInLocalOrder(), Citation::getCitationKey)) - + style.getCitationGroupMarkupAfter(); + style.getCitationGroupMarkupBefore() + + String.join(",", OOListUtil.map(group.getCitationsInLocalOrder(), Citation::getCitationKey)) + + style.getCitationGroupMarkupAfter(); group.setCitationMarker(Optional.of(OOText.fromString(citMarker))); } } diff --git a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java index 0142bfd36c5..b827763ce3d 100644 --- a/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java +++ b/jablib/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java @@ -17,7 +17,7 @@ private OOProcessNumericMarkers() { /** * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. - * + *

      * Numbered citation markers for each CitationGroup. * Numbering is according to first appearance. * Assumes global order and local order are already applied. diff --git a/jablib/src/main/java/org/jabref/logic/os/OS.java b/jablib/src/main/java/org/jabref/logic/os/OS.java index 9ec0d18f6e4..3fb459703a8 100644 --- a/jablib/src/main/java/org/jabref/logic/os/OS.java +++ b/jablib/src/main/java/org/jabref/logic/os/OS.java @@ -91,7 +91,7 @@ public static String detectProgramPath(String programName, String directoryName) ShellLink link = new ShellLink(texworksLinkPath); return link.resolveTarget(); } catch (IOException | - ShellLinkException e) { + ShellLinkException e) { // Static logger instance cannot be used. See the class comment. Logger logger = LoggerFactory.getLogger(OS.class); logger.warn("Error while reading .lnk file for TeXworks", e); 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 3d071a3aa65..c0f87ed2ddb 100644 --- a/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java @@ -137,8 +137,8 @@ * contents of the defaults HashMap that are defined in this class. * There are more default parameters in this map which belong to separate preference classes. *

      - * This class is injected into formatter using reflection to avoid tight coupling and - * is easier than injecting via constructor due to amount of refactoring + * This class is injected into formatter using reflection to avoid tight coupling and + * is easier than injecting via constructor due to amount of refactoring */ @Singleton public class JabRefCliPreferences implements CliPreferences { @@ -874,7 +874,6 @@ private void storePushToApplicationPath(Map commandPair) { } // endregion - /** * @deprecated Never ever add a call to this method. There should be only one * caller. All other usages should get the preferences passed (or injected). The @@ -1284,8 +1283,8 @@ private void storeBibEntryTypes(Collection bibEntryTypes, BibDatab private static Preferences getPrefsNodeForCustomizedEntryTypes(BibDatabaseMode mode) { return mode == BibDatabaseMode.BIBTEX - ? PREFS_NODE.node(CUSTOMIZED_BIBTEX_TYPES) - : PREFS_NODE.node(CUSTOMIZED_BIBLATEX_TYPES); + ? PREFS_NODE.node(CUSTOMIZED_BIBTEX_TYPES) + : PREFS_NODE.node(CUSTOMIZED_BIBLATEX_TYPES); } //************************************************************************************************************* @@ -1857,8 +1856,10 @@ public SelfContainedSaveConfiguration getSelfContainedExportConfiguration() { LOGGER.warn("Table sort order requested, but JabRef is in CLI mode. Falling back to defeault save order"); yield SaveOrder.getDefaultSaveOrder(); } - case SPECIFIED -> SelfContainedSaveOrder.of(exportSaveOrder); - case ORIGINAL -> SaveOrder.getDefaultSaveOrder(); + case SPECIFIED -> + SelfContainedSaveOrder.of(exportSaveOrder); + case ORIGINAL -> + SaveOrder.getDefaultSaveOrder(); }; return new SelfContainedSaveConfiguration( @@ -2512,9 +2513,9 @@ private String getGitHubPat() { if (getBoolean(GITHUB_REMEMBER_PAT_KEY)) { try (final Keyring keyring = Keyring.create()) { return new Password( - keyring.getPassword("org.jabref", "github"), - getInternalPreferences().getUserAndHost()) - .decrypt(); + keyring.getPassword("org.jabref", "github"), + getInternalPreferences().getUserAndHost()) + .decrypt(); } catch (PasswordAccessException ex) { LOGGER.warn("No GitHub token stored in keyring"); } catch (Exception ex) { diff --git a/jablib/src/main/java/org/jabref/logic/pseudonymization/Pseudonymization.java b/jablib/src/main/java/org/jabref/logic/pseudonymization/Pseudonymization.java index c148dc8fe3e..abdedcc84d7 100644 --- a/jablib/src/main/java/org/jabref/logic/pseudonymization/Pseudonymization.java +++ b/jablib/src/main/java/org/jabref/logic/pseudonymization/Pseudonymization.java @@ -33,7 +33,7 @@ public Result pseudonymizeLibrary(BibDatabaseContext bibDatabaseContext) { Map valueMapping = new HashMap<>(); fieldToValueToIdMap.forEach((field, stringToIntMap) -> - stringToIntMap.forEach((value, id) -> valueMapping.put(field.getName().toLowerCase(Locale.ROOT) + "-" + id, value))); + stringToIntMap.forEach((value, id) -> valueMapping.put(field.getName().toLowerCase(Locale.ROOT) + "-" + id, value))); BibDatabase bibDatabase = new BibDatabase(newEntries); BibDatabaseContext result = new BibDatabaseContext(bibDatabase); diff --git a/jablib/src/main/java/org/jabref/logic/push/PushToApplicationDetector.java b/jablib/src/main/java/org/jabref/logic/push/PushToApplicationDetector.java index f38ca546f4a..a279a703ad1 100644 --- a/jablib/src/main/java/org/jabref/logic/push/PushToApplicationDetector.java +++ b/jablib/src/main/java/org/jabref/logic/push/PushToApplicationDetector.java @@ -151,17 +151,28 @@ private static boolean isExecutableNameMatch(String file, String name) { private static String[] getPossibleExecutableNames(String name) { return switch (name) { - case "Emacs" -> new String[] {"emacs", "emacsclient"}; - case "LyX/Kile" -> new String[] {"lyx", "kile"}; - case "Texmaker" -> new String[] {"texmaker"}; - case "TeXstudio" -> new String[] {"texstudio"}; - case "TeXworks" -> new String[] {"texworks"}; - case "Vim" -> new String[] {"vim", "nvim", "gvim"}; - case "WinEdt" -> new String[] {"winedt"}; - case "Sublime Text" -> new String[] {"subl", "sublime_text"}; - case "TeXShop" -> new String[] {"texshop"}; - case "VScode" -> new String[] {"code", "code-insiders"}; - default -> new String[] {name.replace(" ", "").toLowerCase()}; + case "Emacs" -> + new String[] {"emacs", "emacsclient"}; + case "LyX/Kile" -> + new String[] {"lyx", "kile"}; + case "Texmaker" -> + new String[] {"texmaker"}; + case "TeXstudio" -> + new String[] {"texstudio"}; + case "TeXworks" -> + new String[] {"texworks"}; + case "Vim" -> + new String[] {"vim", "nvim", "gvim"}; + case "WinEdt" -> + new String[] {"winedt"}; + case "Sublime Text" -> + new String[] {"subl", "sublime_text"}; + case "TeXShop" -> + new String[] {"texshop"}; + case "VScode" -> + new String[] {"code", "code-insiders"}; + default -> + new String[] {name.replace(" ", "").toLowerCase()}; }; } diff --git a/jablib/src/main/java/org/jabref/logic/push/PushToApplications.java b/jablib/src/main/java/org/jabref/logic/push/PushToApplications.java index 24a27fadf2e..261c514f0a4 100644 --- a/jablib/src/main/java/org/jabref/logic/push/PushToApplications.java +++ b/jablib/src/main/java/org/jabref/logic/push/PushToApplications.java @@ -17,16 +17,26 @@ public static Optional getApplicationById(String applicationI /// @param application Used by the CLI to select the application to run. public static Optional getApplication(PushApplications application, NotificationService notificationService, PushToApplicationPreferences preferences) { return Optional.of(switch (application) { - case EMACS -> new PushToEmacs(notificationService, preferences); - case LYX -> new PushToLyx(notificationService, preferences); - case SUBLIME_TEXT -> new PushToSublimeText(notificationService, preferences); - case TEXMAKER -> new PushToTexmaker(notificationService, preferences); - case TEXSTUDIO -> new PushToTeXstudio(notificationService, preferences); - case TEXWORKS -> new PushToTeXworks(notificationService, preferences); - case VIM -> new PushToVim(notificationService, preferences); - case WIN_EDT -> new PushToWinEdt(notificationService, preferences); - case TEXSHOP -> new PushToTexShop(notificationService, preferences); - case VSCODE -> new PushToVScode(notificationService, preferences); + case EMACS -> + new PushToEmacs(notificationService, preferences); + case LYX -> + new PushToLyx(notificationService, preferences); + case SUBLIME_TEXT -> + new PushToSublimeText(notificationService, preferences); + case TEXMAKER -> + new PushToTexmaker(notificationService, preferences); + case TEXSTUDIO -> + new PushToTeXstudio(notificationService, preferences); + case TEXWORKS -> + new PushToTeXworks(notificationService, preferences); + case VIM -> + new PushToVim(notificationService, preferences); + case WIN_EDT -> + new PushToWinEdt(notificationService, preferences); + case TEXSHOP -> + new PushToTexShop(notificationService, preferences); + case VSCODE -> + new PushToVScode(notificationService, preferences); }); } } diff --git a/jablib/src/main/java/org/jabref/logic/push/PushToEmacs.java b/jablib/src/main/java/org/jabref/logic/push/PushToEmacs.java index 92c055a2673..9f42da93f14 100644 --- a/jablib/src/main/java/org/jabref/logic/push/PushToEmacs.java +++ b/jablib/src/main/java/org/jabref/logic/push/PushToEmacs.java @@ -78,10 +78,10 @@ public void pushEntries(List entries) { // so sh receives: (insert "\\cite{Blah2001}") // so emacs receives: (insert "\cite{Blah2001}") com[com.length - 1] = prefix.concat("\"" - + getCitePrefix().replace("\\", "\\\\") - + keyString - + getCiteSuffix().replace("\\", "\\\\") - + "\"").concat(suffix); + + getCitePrefix().replace("\\", "\\\\") + + keyString + + getCiteSuffix().replace("\\", "\\\\") + + "\"").concat(suffix); } LOGGER.atDebug() diff --git a/jablib/src/main/java/org/jabref/logic/push/PushToTeXworks.java b/jablib/src/main/java/org/jabref/logic/push/PushToTeXworks.java index 43e9b3dfee2..48a9c3c78b1 100644 --- a/jablib/src/main/java/org/jabref/logic/push/PushToTeXworks.java +++ b/jablib/src/main/java/org/jabref/logic/push/PushToTeXworks.java @@ -12,7 +12,7 @@ public class PushToTeXworks extends AbstractPushToApplication { * Constructs a new {@code PushToTeXworks} instance. * * @param notificationService The dialog service for displaying messages to the user. - * @param preferences The service for accessing user preferences. + * @param preferences The service for accessing user preferences. */ public PushToTeXworks(NotificationService notificationService, PushToApplicationPreferences preferences) { super(notificationService, preferences); diff --git a/jablib/src/main/java/org/jabref/logic/push/PushToVim.java b/jablib/src/main/java/org/jabref/logic/push/PushToVim.java index 416f61a283b..165afb9e558 100644 --- a/jablib/src/main/java/org/jabref/logic/push/PushToVim.java +++ b/jablib/src/main/java/org/jabref/logic/push/PushToVim.java @@ -39,7 +39,7 @@ public void pushEntries(List entries) { String keyString = this.getKeyString(entries, getDelimiter()); try { - String[] com = new String[]{commandPath, "--servername", + String[] com = new String[] {commandPath, "--servername", preferences.getVimServer(), "--remote-send", "a" + getCitePrefix() + keyString + getCiteSuffix()}; @@ -99,12 +99,12 @@ public void jumpToLine(Path fileName, int line, int column) { try { String[] command = jumpToLineCommandlineArguments(fileName, line, column); if (OS.WINDOWS) { - processBuilder.command("cmd", - "/c", - "start", - "", + processBuilder.command("cmd", + "/c", + "start", + "", "\"%s\"".formatted(command[0]), - "\"%s\"".formatted(command[1]), + "\"%s\"".formatted(command[1]), "\"%s\"".formatted(command[2]), "\"+normal %s|\"".formatted(Integer.toString(column))); } else if (OS.LINUX) { diff --git a/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheck.java b/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheck.java index be6dea09eba..88e8cfbb431 100644 --- a/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheck.java +++ b/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheck.java @@ -135,14 +135,14 @@ public Result check(BibDatabaseContext bibContext, BiConsumer assert fieldsInAllEntries != null; Optional typeDefOpt = entryTypeDefinitions.stream() - .filter(def -> def.getType().equals(entryType)) - .findFirst(); + .filter(def -> def.getType().equals(entryType)) + .findFirst(); Set requiredFields = typeDefOpt.map(typeDef -> - typeDef.getRequiredFields().stream() - .flatMap(orFields -> orFields.getFields().stream()) - .collect(Collectors.toSet()) - ).orElse(Set.of()); + typeDef.getRequiredFields().stream() + .flatMap(orFields -> orFields.getFields().stream()) + .collect(Collectors.toSet()) + ).orElse(Set.of()); Set entries = entryTypeToEntriesMap.get(entryType); assert entries != null; diff --git a/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultWriter.java b/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultWriter.java index 86a43316547..d63cbe75baf 100644 --- a/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultWriter.java +++ b/jablib/src/main/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultWriter.java @@ -94,15 +94,15 @@ protected List getFindingsAsList(BibEntry bibEntry, String entryType, Se results.add(entryType); results.add(bibEntry.getCitationKey().orElse("")); allReportedFields.forEach(field -> results.add( - bibEntry.getField(field).map(value -> { - if (requiredFields.contains(field)) { - return REQUIRED_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; - } else if (optionalFields.contains(field)) { - return OPTIONAL_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; - } else { - return UNKNOWN_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; - } - }).orElse(UNSET_FIELD_AT_ENTRY_TYPE_CELL_ENTRY))); + bibEntry.getField(field).map(value -> { + if (requiredFields.contains(field)) { + return REQUIRED_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; + } else if (optionalFields.contains(field)) { + return OPTIONAL_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; + } else { + return UNKNOWN_FIELD_AT_ENTRY_TYPE_CELL_ENTRY; + } + }).orElse(UNSET_FIELD_AT_ENTRY_TYPE_CELL_ENTRY))); return results; } diff --git a/jablib/src/main/java/org/jabref/logic/remote/server/RemoteMessageHandler.java b/jablib/src/main/java/org/jabref/logic/remote/server/RemoteMessageHandler.java index b2df0207000..fdf104d0a18 100644 --- a/jablib/src/main/java/org/jabref/logic/remote/server/RemoteMessageHandler.java +++ b/jablib/src/main/java/org/jabref/logic/remote/server/RemoteMessageHandler.java @@ -4,5 +4,6 @@ public interface RemoteMessageHandler { void handleCommandLineArguments(String[] message); - default void handleFocus() { } + default void handleFocus() { + } } diff --git a/jablib/src/main/java/org/jabref/logic/search/indexing/BibFieldsIndexer.java b/jablib/src/main/java/org/jabref/logic/search/indexing/BibFieldsIndexer.java index 03544f4c48a..e7a39659310 100644 --- a/jablib/src/main/java/org/jabref/logic/search/indexing/BibFieldsIndexer.java +++ b/jablib/src/main/java/org/jabref/logic/search/indexing/BibFieldsIndexer.java @@ -412,11 +412,11 @@ private void closeIndex() { try { LOGGER.debug("Closing connection to Postgres server for library: {}", libraryName); connection.createStatement().executeUpdate(""" - DROP TABLE IF EXISTS %s - """.formatted(schemaMainTableReference)); + DROP TABLE IF EXISTS %s + """.formatted(schemaMainTableReference)); connection.createStatement().executeUpdate(""" - DROP TABLE IF EXISTS %s - """.formatted(schemaSplitValuesTableReference)); + DROP TABLE IF EXISTS %s + """.formatted(schemaSplitValuesTableReference)); connection.close(); } catch (SQLException e) { LOGGER.error("Could not drop table for library: {}", libraryName, e); @@ -429,8 +429,8 @@ public String getTable() { private void addEntryLinks(BibEntry bibEntry, Field field, PreparedStatement preparedStatementSplitValues, String entryId) { bibEntry.getEntryLinkList(field, databaseContext.getDatabase()).stream() - .distinct() - .forEach(link -> addBatch(preparedStatementSplitValues, entryId, field, link.getKey())); + .distinct() + .forEach(link -> addBatch(preparedStatementSplitValues, entryId, field, link.getKey())); } private static void addGroups(String value, PreparedStatement preparedStatementSplitValues, String entryId, Field field) { diff --git a/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryExtractorVisitor.java b/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryExtractorVisitor.java index 7a877748ff5..e9273ba6c5e 100644 --- a/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryExtractorVisitor.java +++ b/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryExtractorVisitor.java @@ -102,10 +102,14 @@ public List visitComparison(SearchParser.ComparisonContext ctx) // Pseudo-fields field = switch (field) { - case "key" -> InternalField.KEY_FIELD.getName(); - case "anykeyword" -> StandardField.KEYWORDS.getName(); - case "anyfield" -> "any"; - default -> field; + case "key" -> + InternalField.KEY_FIELD.getName(); + case "anykeyword" -> + StandardField.KEYWORDS.getName(); + case "anyfield" -> + "any"; + default -> + field; }; if (ctx.operator() != null) { diff --git a/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryVisitor.java b/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryVisitor.java index a21a828a2b1..ee072427654 100644 --- a/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryVisitor.java +++ b/jablib/src/main/java/org/jabref/logic/search/query/SearchQueryVisitor.java @@ -33,8 +33,8 @@ public BaseQueryNode visitStart(SearchParser.StartContext ctx) { @Override public BaseQueryNode visitImplicitAndExpression(SearchParser.ImplicitAndExpressionContext ctx) { List children = ctx.expression().stream() - .map(this::visit) - .collect(Collectors.toList()); + .map(this::visit) + .collect(Collectors.toList()); if (children.size() == 1) { return children.getFirst(); } @@ -86,10 +86,14 @@ public BaseQueryNode visitComparison(SearchParser.ComparisonContext ctx) { // Pseudo-fields field = switch (field) { - case "key" -> InternalField.KEY_FIELD.getName(); - case "anykeyword" -> StandardField.KEYWORDS.getName(); - case "anyfield" -> "any"; - default -> field; + case "key" -> + InternalField.KEY_FIELD.getName(); + case "anykeyword" -> + StandardField.KEYWORDS.getName(); + case "anyfield" -> + "any"; + default -> + field; }; if (ctx.operator() != null) { diff --git a/jablib/src/main/java/org/jabref/logic/search/query/SearchToLuceneVisitor.java b/jablib/src/main/java/org/jabref/logic/search/query/SearchToLuceneVisitor.java index 3ba5e40c9f6..cbb62a45892 100644 --- a/jablib/src/main/java/org/jabref/logic/search/query/SearchToLuceneVisitor.java +++ b/jablib/src/main/java/org/jabref/logic/search/query/SearchToLuceneVisitor.java @@ -112,8 +112,10 @@ private static boolean isNegationOperator(int operator) { SearchParser.NEEQUAL, SearchParser.NCEEQUAL, SearchParser.NREQUAL, - SearchParser.NCREEQUAL -> true; - default -> false; + SearchParser.NCREEQUAL -> + true; + default -> + false; }; } @@ -122,8 +124,10 @@ private static boolean isRegexOperator(int operator) { case SearchParser.REQUAL, SearchParser.CREEQUAL, SearchParser.NREQUAL, - SearchParser.NCREEQUAL -> true; - default -> false; + SearchParser.NCREEQUAL -> + true; + default -> + false; }; } } diff --git a/jablib/src/main/java/org/jabref/logic/search/query/SearchToSqlVisitor.java b/jablib/src/main/java/org/jabref/logic/search/query/SearchToSqlVisitor.java index 318e814ec57..3d3431ef888 100644 --- a/jablib/src/main/java/org/jabref/logic/search/query/SearchToSqlVisitor.java +++ b/jablib/src/main/java/org/jabref/logic/search/query/SearchToSqlVisitor.java @@ -228,10 +228,14 @@ private SqlQueryNode getFieldQueryNode(String field, String term, EnumSet InternalField.KEY_FIELD.getName(); - case "anykeyword" -> StandardField.KEYWORDS.getName(); - case "anyfield" -> "any"; - default -> field; + case "key" -> + InternalField.KEY_FIELD.getName(); + case "anykeyword" -> + StandardField.KEYWORDS.getName(); + case "anyfield" -> + "any"; + default -> + field; }; if (ENTRY_ID.toString().equals(field)) { @@ -239,22 +243,22 @@ private SqlQueryNode getFieldQueryNode(String field, String term, EnumSet flags, SearchFlags matchType, private static String getSqlOperator(EnumSet searchFlags) { return searchFlags.contains(REGULAR_EXPRESSION) - ? (searchFlags.contains(CASE_SENSITIVE) ? "~" : "~*") - : (searchFlags.contains(CASE_SENSITIVE) ? "LIKE" : "ILIKE"); + ? (searchFlags.contains(CASE_SENSITIVE) ? "~" : "~*") + : (searchFlags.contains(CASE_SENSITIVE) ? "LIKE" : "ILIKE"); } /** diff --git a/jablib/src/main/java/org/jabref/logic/shared/DBMSProcessor.java b/jablib/src/main/java/org/jabref/logic/shared/DBMSProcessor.java index af2d7a7576e..1cd77c52211 100644 --- a/jablib/src/main/java/org/jabref/logic/shared/DBMSProcessor.java +++ b/jablib/src/main/java/org/jabref/logic/shared/DBMSProcessor.java @@ -183,7 +183,7 @@ protected void insertIntoEntryTable(List bibEntries) { insertIntoEntryQuery.append(", (?)".repeat(Math.max(0, bibEntries.size() - 1))); try (PreparedStatement preparedEntryStatement = connection.prepareStatement(insertIntoEntryQuery.toString(), - new String[]{"SHARED_ID"})) { + new String[] {"SHARED_ID"})) { for (int i = 0; i < bibEntries.size(); i++) { preparedEntryStatement.setString(i + 1, bibEntries.get(i).getType().getName()); } @@ -235,7 +235,7 @@ private List getNotYetExistingEntries(List bibEntries) { LOGGER.error("SQL Error: ", e); } return bibEntries.stream().filter(entry -> - !remoteIds.contains(entry.getSharedBibEntryData().getSharedID())) + !remoteIds.contains(entry.getSharedBibEntryData().getSharedID())) .collect(Collectors.toList()); } diff --git a/jablib/src/main/java/org/jabref/logic/texparser/DefaultLatexParser.java b/jablib/src/main/java/org/jabref/logic/texparser/DefaultLatexParser.java index 1e24671c21e..6f1b9678d05 100644 --- a/jablib/src/main/java/org/jabref/logic/texparser/DefaultLatexParser.java +++ b/jablib/src/main/java/org/jabref/logic/texparser/DefaultLatexParser.java @@ -122,8 +122,8 @@ private void matchBibFile(Path file, String line, LatexParserResult latexParserR bibString = bibString.trim(); Path bibFile = file.getParent().resolve( bibString.endsWith(BIB_EXT) - ? bibString - : "%s%s".formatted(bibString, BIB_EXT)).normalize(); + ? bibString + : "%s%s".formatted(bibString, BIB_EXT)).normalize(); if (Files.exists(bibFile)) { latexParserResult.addBibFile(bibFile); @@ -141,8 +141,8 @@ private void matchNestedFile(Path texFile, String line, LatexParserResult latexP while (includeMatch.find()) { String filenamePassedToInclude = includeMatch.group(INCLUDE_GROUP); String texFileName = filenamePassedToInclude.endsWith(TEX_EXT) - ? filenamePassedToInclude - : "%s%s".formatted(filenamePassedToInclude, TEX_EXT); + ? filenamePassedToInclude + : "%s%s".formatted(filenamePassedToInclude, TEX_EXT); Path nestedFile = texFile.getParent().resolve(texFileName).normalize(); if (Files.exists(nestedFile)) { latexParserResult.addNestedFile(nestedFile); diff --git a/jablib/src/main/java/org/jabref/logic/util/BuildInfo.java b/jablib/src/main/java/org/jabref/logic/util/BuildInfo.java index 88078b43e50..72f35078132 100644 --- a/jablib/src/main/java/org/jabref/logic/util/BuildInfo.java +++ b/jablib/src/main/java/org/jabref/logic/util/BuildInfo.java @@ -10,21 +10,21 @@ public final class BuildInfo { public static final String JABREF_BANNER = """ - \u001B[35m - &&& &&&&& &&&&&&&& &&&&&&&& &&&&&&&&& &&&&&&&&& - &&& &&&&& &&& &&& &&& &&& &&& &&& - &&& &&& &&& &&& &&& &&& &&& &&& &&& - &&& && && &&&&&&& &&&&&&&& &&&&&&&& &&&&&&& - &&& &&&&&&&&& &&& &&& &&& &&& &&& &&& - &&& &&& &&& &&& &&& &&& &&& &&& &&& - &&&&& &&& &&& &&&&&&&& &&& &&& &&&&&&&&& &&& + \u001B[35m + &&& &&&&& &&&&&&&& &&&&&&&& &&&&&&&&& &&&&&&&&& + &&& &&&&& &&& &&& &&& &&& &&& &&& + &&& &&& &&& &&& &&& &&& &&& &&& &&& + &&& && && &&&&&&& &&&&&&&& &&&&&&&& &&&&&&& + &&& &&&&&&&&& &&& &&& &&& &&& &&& &&& + &&& &&& &&& &&& &&& &&& &&& &&& &&& + &&&&& &&& &&& &&&&&&&& &&& &&& &&&&&&&&& &&& - \u001B[97mVersion: %s - \u001B[0m - Staying on top of your literature since 2003 - https://www.jabref.org/ + \u001B[97mVersion: %s + \u001B[0m + Staying on top of your literature since 2003 - https://www.jabref.org/ - Please report issues at https://github.com/JabRef/jabref/issues - """; + Please report issues at https://github.com/JabRef/jabref/issues + """; public static final String UNKNOWN_VERSION = "UNKNOWN"; diff --git a/jablib/src/main/java/org/jabref/logic/util/DelayTaskThrottler.java b/jablib/src/main/java/org/jabref/logic/util/DelayTaskThrottler.java index a0fe54c34c8..39d268665f6 100644 --- a/jablib/src/main/java/org/jabref/logic/util/DelayTaskThrottler.java +++ b/jablib/src/main/java/org/jabref/logic/util/DelayTaskThrottler.java @@ -15,7 +15,7 @@ * However, if a lot of events happen in a relatively short time span, then only one task should be invoked. * * @implNote Once {@link #schedule(Runnable)} is called, the task is delayed for a given time span. - * If during this time, {@link #schedule(Runnable)} is called again, then the original task is canceled and the new one scheduled. + * If during this time, {@link #schedule(Runnable)} is called again, then the original task is canceled and the new one scheduled. */ public class DelayTaskThrottler { diff --git a/jablib/src/main/java/org/jabref/logic/util/Directories.java b/jablib/src/main/java/org/jabref/logic/util/Directories.java index 6f6816d5656..da9008fa225 100644 --- a/jablib/src/main/java/org/jabref/logic/util/Directories.java +++ b/jablib/src/main/java/org/jabref/logic/util/Directories.java @@ -48,9 +48,9 @@ public static Path getFulltextIndexBaseDirectory() { public static Path getAiFilesDirectory() { return Path.of(AppDirsFactory.getInstance() - .getUserDataDir(OS.APP_DIR_APP_NAME, - "ai" + File.separator + AiService.VERSION, - OS.APP_DIR_APP_AUTHOR)); + .getUserDataDir(OS.APP_DIR_APP_NAME, + "ai" + File.separator + AiService.VERSION, + OS.APP_DIR_APP_AUTHOR)); } public static Path getSslDirectory() { 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 e834abed595..bcf17efcd63 100644 --- a/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java +++ b/jablib/src/main/java/org/jabref/logic/util/HeadlessExecutorService.java @@ -49,7 +49,7 @@ public class HeadlessExecutorService implements Executor { private final Timer timer = new Timer("timer", true); private HeadlessExecutorService() { - } + } public void execute(Runnable command) { Objects.requireNonNull(command); diff --git a/jablib/src/main/java/org/jabref/logic/util/ProgressCounter.java b/jablib/src/main/java/org/jabref/logic/util/ProgressCounter.java index abd9b21cb1b..11e3b85915f 100644 --- a/jablib/src/main/java/org/jabref/logic/util/ProgressCounter.java +++ b/jablib/src/main/java/org/jabref/logic/util/ProgressCounter.java @@ -24,7 +24,8 @@ */ public class ProgressCounter implements Progress { - private record ProgressMessage(int maxTime, String message) { } + private record ProgressMessage(int maxTime, String message) { + } // The list should be sorted by ProgressMessage.maxTime, smaller first. private static final List PROGRESS_MESSAGES = List.of( diff --git a/jablib/src/main/java/org/jabref/logic/util/TaskExecutor.java b/jablib/src/main/java/org/jabref/logic/util/TaskExecutor.java index 23234df0298..f2ba29284d9 100644 --- a/jablib/src/main/java/org/jabref/logic/util/TaskExecutor.java +++ b/jablib/src/main/java/org/jabref/logic/util/TaskExecutor.java @@ -26,8 +26,8 @@ public interface TaskExecutor { * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter * @return a ScheduledFuture representing pending completion of - * the task and whose {@code get()} method will return - * {@code null} upon completion + * the task and whose {@code get()} method will return + * {@code null} upon completion */ Future schedule(BackgroundTask task, long delay, TimeUnit unit); diff --git a/jablib/src/main/java/org/jabref/logic/util/URLUtil.java b/jablib/src/main/java/org/jabref/logic/util/URLUtil.java index 323c2fbd523..48b7d275918 100644 --- a/jablib/src/main/java/org/jabref/logic/util/URLUtil.java +++ b/jablib/src/main/java/org/jabref/logic/util/URLUtil.java @@ -84,12 +84,12 @@ public static boolean isURL(String url) { if (url == null || url.trim().isEmpty()) { return false; } - + // Check if the URL has a protocol (http://, https://, ftp://) if (!URL_PATTERN.matcher(url).matches()) { return false; } - + try { create(url); return true; diff --git a/jablib/src/main/java/org/jabref/logic/util/io/BackupFileUtil.java b/jablib/src/main/java/org/jabref/logic/util/io/BackupFileUtil.java index a92ce7c5d45..91fda251e04 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/BackupFileUtil.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/BackupFileUtil.java @@ -86,10 +86,10 @@ public static Optional getPathOfLatestExistingBackupFile(Path targetFile, * Determines a unique file prefix. *

      *

      - * When creating a backup file, the backup file should belong to the original file. - * Just adding ".bak" suffix to the filename, does not work in all cases: - * It may be possible that the user has opened "paper.bib" twice. - * Thus, we need to create a unique prefix to distinguish these files. + * When creating a backup file, the backup file should belong to the original file. + * Just adding ".bak" suffix to the filename, does not work in all cases: + * It may be possible that the user has opened "paper.bib" twice. + * Thus, we need to create a unique prefix to distinguish these files. *

      */ public static String getUniqueFilePrefix(Path targetFile) { diff --git a/jablib/src/main/java/org/jabref/logic/util/io/FileNameCleaner.java b/jablib/src/main/java/org/jabref/logic/util/io/FileNameCleaner.java index b2ffdf82b8a..19d6f7594c7 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/FileNameCleaner.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/FileNameCleaner.java @@ -4,7 +4,7 @@ * This class is based on http://stackoverflow.com/a/5626340/873282 * extended with LEFT CURLY BRACE and RIGHT CURLY BRACE * Replaces illegal characters in given file paths. - * + *

      * Regarding the maximum length, see {@link FileUtil#getValidFileName(String)} */ public class FileNameCleaner { diff --git a/jablib/src/main/java/org/jabref/logic/util/io/FileNameUniqueness.java b/jablib/src/main/java/org/jabref/logic/util/io/FileNameUniqueness.java index 8756e2de581..e4c0f424c6f 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/FileNameUniqueness.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/FileNameUniqueness.java @@ -57,11 +57,11 @@ public static String generateUniqueFileName(Path targetDirectory, String propose * This function decide whether the newly downloaded file has the same content with other files * It returns ture when the content is duplicate, while returns false if it is not * - * @param directory The directory which saves the files (.pdf, for example) - * @param fileName Suggest name for the newly downloaded file + * @param directory The directory which saves the files (.pdf, for example) + * @param fileName Suggest name for the newly downloaded file * @param messageOnDeletion To display the error and success message * @return true when the content of the newly downloaded file is same as the file with "similar" name, - * false when there is no "similar" file name or the content is different from that of files with "similar" name + * false when there is no "similar" file name or the content is different from that of files with "similar" name * @throws IOException Fail when the file is not exist or something wrong when reading the file */ public static boolean isDuplicatedFile(@NonNull Path directory, @NonNull Path fileName, @NonNull Consumer messageOnDeletion) throws IOException { 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 4865c4b7097..25b367d2852 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 @@ -71,7 +71,7 @@ private Pattern createFileNamePattern(String[] fileParts, String extensionRegExp private static String toFileNameRegex(String expandedContent) { String cleanedContent = FileNameCleaner.cleanFileName(expandedContent); return expandedContent.equals(cleanedContent) ? Pattern.quote(expandedContent) : - "(" + Pattern.quote(expandedContent) + ")|(" + Pattern.quote(cleanedContent) + ")"; + "(" + Pattern.quote(expandedContent) + ")|(" + Pattern.quote(cleanedContent) + ")"; } /** @@ -92,17 +92,17 @@ public List findAssociatedFiles(BibEntry entry, List directories, Li /** * Searches the given directory and filename pattern for a file for the * BibTeX entry. - * + *

      * Used to fix: - * + *

      * http://sourceforge.net/tracker/index.php?func=detail&aid=1503410&group_id=92314&atid=600309 - * + *

      * Requirements: * - Be able to find the associated PDF in a set of given directories. * - Be able to return a relative path or absolute path. * - Be fast. * - Allow for flexible naming schemes in the PDFs. - * + *

      * Syntax scheme for file: *

        *
      • * Any subDir
      • diff --git a/jablib/src/main/java/org/jabref/logic/util/strings/StringManipulator.java b/jablib/src/main/java/org/jabref/logic/util/strings/StringManipulator.java index fdcb9d83cea..0097060c664 100644 --- a/jablib/src/main/java/org/jabref/logic/util/strings/StringManipulator.java +++ b/jablib/src/main/java/org/jabref/logic/util/strings/StringManipulator.java @@ -29,8 +29,7 @@ enum Direction { * @param text The text to manipulate. * @param caretPosition The index to start from. * @param targetCase The case mode the string should be changed to. - * - * @return The resulting text and caret position. + * @return The resulting text and caret position. */ private static ResultingStringState setWordCase(String text, int caretPosition, LetterCase targetCase) { int nextWordBoundary = getNextWordBoundary(caretPosition, text, Direction.NEXT); @@ -42,9 +41,12 @@ private static ResultingStringState setWordCase(String text, int caretPosition, } String result = switch (targetCase) { - case UPPER -> new UpperCaseFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); - case LOWER -> new LowerCaseFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); - case CAPITALIZED -> new CapitalizeFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); + case UPPER -> + new UpperCaseFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); + case LOWER -> + new LowerCaseFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); + case CAPITALIZED -> + new CapitalizeFormatter().format(text.substring(wordStartPosition, nextWordBoundary)); }; return new ResultingStringState( @@ -58,8 +60,7 @@ private static ResultingStringState setWordCase(String text, int caretPosition, * @param caretPosition The index to start from. * @param text The text to manipulate. * @param direction The direction to search. - * - * @return The resulting text and caret position. + * @return The resulting text and caret position. */ static ResultingStringState deleteUntilWordBoundary(int caretPosition, String text, Direction direction) { // Define cutout range @@ -67,12 +68,14 @@ static ResultingStringState deleteUntilWordBoundary(int caretPosition, String te // Construct new string without cutout return switch (direction) { - case NEXT -> new ResultingStringState( - caretPosition, - text.substring(0, caretPosition) + text.substring(nextWordBoundary)); - case PREVIOUS -> new ResultingStringState( - nextWordBoundary, - text.substring(0, nextWordBoundary) + text.substring(caretPosition)); + case NEXT -> + new ResultingStringState( + caretPosition, + text.substring(0, caretPosition) + text.substring(nextWordBoundary)); + case PREVIOUS -> + new ResultingStringState( + nextWordBoundary, + text.substring(0, nextWordBoundary) + text.substring(caretPosition)); }; } @@ -82,8 +85,7 @@ static ResultingStringState deleteUntilWordBoundary(int caretPosition, String te * @param caretPosition The current caret position * @param text The string to search in * @param direction The direction to move through string - * - * @return The position of the next whitespace after a word + * @return The position of the next whitespace after a word */ static int getNextWordBoundary(int caretPosition, String text, Direction direction) { int i = caretPosition; @@ -118,7 +120,6 @@ static int getNextWordBoundary(int caretPosition, String text, Direction directi * * @param caretPosition The position of the cursor * @param text The string to manipulate - * * @return String The resulting text and caret position. */ public static ResultingStringState capitalize(int caretPosition, String text) { @@ -130,7 +131,6 @@ public static ResultingStringState capitalize(int caretPosition, String text) { * * @param caretPosition The position of the cursor * @param text The string to manipulate - * * @return String The resulting text and caret position. */ public static ResultingStringState uppercase(int caretPosition, String text) { @@ -142,7 +142,6 @@ public static ResultingStringState uppercase(int caretPosition, String text) { * * @param caretPosition The position of the cursor * @param text The string to manipulate - * * @return String The resulting text and caret position. */ public static ResultingStringState lowercase(int caretPosition, String text) { @@ -154,7 +153,6 @@ public static ResultingStringState lowercase(int caretPosition, String text) { * * @param caretPosition The position of the cursor * @param text The string to manipulate - * * @return String The resulting text and caret position. */ public static ResultingStringState killWord(int caretPosition, String text) { @@ -166,7 +164,6 @@ public static ResultingStringState killWord(int caretPosition, String text) { * * @param caretPosition The position of the cursor * @param text The string to manipulate - * * @return String The resulting text and caret position. */ public static ResultingStringState backwardKillWord(int caretPosition, String text) { diff --git a/jablib/src/main/java/org/jabref/logic/util/strings/UnicodeLigaturesMap.java b/jablib/src/main/java/org/jabref/logic/util/strings/UnicodeLigaturesMap.java index a5466c684d4..1a3c5dc7ab8 100644 --- a/jablib/src/main/java/org/jabref/logic/util/strings/UnicodeLigaturesMap.java +++ b/jablib/src/main/java/org/jabref/logic/util/strings/UnicodeLigaturesMap.java @@ -6,7 +6,7 @@ public class UnicodeLigaturesMap extends HashMap { /** * Ligature mapping taken from https://en.wikipedia.org/wiki/Typographic_ligature#Ligatures_in_Unicode_(Latin_alphabets) - * + *

        * The mapping is bijective. In case it is ever needed to turn the extended version back to unicode ligatures, the * map can easily be reversed. */ diff --git a/jablib/src/main/java/org/jabref/logic/xmp/DocumentInformationExtractor.java b/jablib/src/main/java/org/jabref/logic/xmp/DocumentInformationExtractor.java index 098351b6c6d..2ee7cc2de36 100644 --- a/jablib/src/main/java/org/jabref/logic/xmp/DocumentInformationExtractor.java +++ b/jablib/src/main/java/org/jabref/logic/xmp/DocumentInformationExtractor.java @@ -67,13 +67,14 @@ private void extractOtherFields() { String fieldName = key.substring(XmpUtilShared.BIBTEX_DI_FIELD_NAME_PREFIX.length()); Field field = FieldFactory.parseField(fieldName); switch (field) { - case InternalField.TYPE_HEADER -> bibEntry.setType(EntryTypeFactory.parse(value)); + case InternalField.TYPE_HEADER -> + bibEntry.setType(EntryTypeFactory.parse(value)); case StandardField.MONTH -> { value = Month.parse(value).map(Month::getJabRefFormat).orElse(value); bibEntry.setField(StandardField.MONTH, value); } default -> - bibEntry.setField(field, value); + bibEntry.setField(field, value); } } } @@ -82,10 +83,10 @@ private void extractOtherFields() { /** * Function for retrieving a BibEntry from the * PDDocumentInformation in a PDF file. - * + *

        * To understand how to get hold of a PDDocumentInformation have a look in * the test cases for XMPUtilTest. - * + *

        * The BibEntry is build by mapping individual fields in the document * information (like author, title, keywords) to fields in a bibtex entry. * diff --git a/jablib/src/main/java/org/jabref/logic/xmp/DublinCoreExtractor.java b/jablib/src/main/java/org/jabref/logic/xmp/DublinCoreExtractor.java index dee939d7029..a97788a1076 100644 --- a/jablib/src/main/java/org/jabref/logic/xmp/DublinCoreExtractor.java +++ b/jablib/src/main/java/org/jabref/logic/xmp/DublinCoreExtractor.java @@ -31,7 +31,7 @@ /** * This class is used for both conversion from Dublin Core to BibTeX and conversion form BibTeX to Dublin Core - * + *

        * Related class: {@link org.jabref.logic.xmp.DocumentInformationExtractor} */ public class DublinCoreExtractor { @@ -75,7 +75,7 @@ private void extractEditor() { private void extractAuthor() { List creators = dcSchema.getCreators(); if ((creators != null) && !creators.isEmpty()) { - bibEntry.setField(StandardField.AUTHOR, String.join(" and ", creators)); + bibEntry.setField(StandardField.AUTHOR, String.join(" and ", creators)); } } @@ -87,11 +87,11 @@ private void extractDate() { if ((dates != null) && !dates.isEmpty()) { String date = dates.getFirst().trim(); Date.parse(date) - .ifPresent(dateValue -> { - dateValue.getDay().ifPresent(day -> bibEntry.setField(StandardField.DAY, Integer.toString(day))); - dateValue.getMonth().ifPresent(bibEntry::setMonth); - dateValue.getYear().ifPresent(year -> bibEntry.setField(StandardField.YEAR, Integer.toString(year))); - }); + .ifPresent(dateValue -> { + dateValue.getDay().ifPresent(day -> bibEntry.setField(StandardField.DAY, Integer.toString(day))); + dateValue.getMonth().ifPresent(bibEntry::setMonth); + dateValue.getYear().ifPresent(year -> bibEntry.setField(StandardField.YEAR, Integer.toString(year))); + }); } } @@ -181,7 +181,7 @@ private void extractRights() { try { rights = dcSchema.getRights(); } catch (BadFieldValueException e) { - LOGGER.warn("Could not extract rights", e); + LOGGER.warn("Could not extract rights", e); } if (!StringUtil.isNullOrEmpty(rights)) { bibEntry.setField(new UnknownField(DC_RIGHTS), rights); @@ -248,7 +248,7 @@ private void extractCoverage() { } /** - * Language is equivalent in both formats (BibTeX and DublinCore) + * Language is equivalent in both formats (BibTeX and DublinCore) */ private void extractLanguages() { StringBuilder builder = new StringBuilder(); @@ -378,7 +378,7 @@ private void fillCoverage(String coverage) { */ private void fillLanguages(String languages) { Arrays.stream(languages.split(",")) - .forEach(dcSchema::addLanguage); + .forEach(dcSchema::addLanguage); } /** @@ -458,7 +458,8 @@ public void fillDublinCoreSchema() { case FILE -> { // we do not write the "file" field, because the file is the PDF itself } - case DAY, MONTH -> { + case DAY, + MONTH -> { // we do not write day and month separately if dc:year can be used if (!bibEntry.hasField(StandardField.YEAR)) { this.fillCustomField(field); diff --git a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java index 4151445942d..1dec0a7d422 100644 --- a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java +++ b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java @@ -26,7 +26,7 @@ /** * Readings on XMP are available at docs/code-howtos/xmp-parsing.md - * + *

        * See also {@link org.jabref.logic.xmp.XmpUtilWriter#writeDocumentInformation} */ public class XmpUtilReader { @@ -57,7 +57,6 @@ public List readRawXmp(Path path) throws IOException { /** * @param path The path to read from. - * * @return list of a single BibEntry retrieved by merging the data from the stream */ public List readXmp(Path path, XmpPreferences xmpPreferences) throws IOException { @@ -68,13 +67,13 @@ public List readXmp(Path path, XmpPreferences xmpPreferences) throws I /** * Merges all XMP data together in one entry. - * + *

        * Try to read the given BibTexEntry from the given PDF file. *

        * Looks at the DocumentInformation and the XMP metadata. * Regarding the XMP metadata, only Dublin Core is supported. * - * @param path the path to the PDF file + * @param path the path to the PDF file * @param document the PDF document to read from (should have been created from path */ public List readXmp(Path path, PDDocument document, XmpPreferences xmpPreferences) { @@ -105,8 +104,11 @@ public List readXmp(Path path, PDDocument document, XmpPreferences xmp result.removeFirst(); result.addFirst(entry); } - case DIFFERENT -> result.addFirst(entry); - case DISJUNCT_OR_EQUAL_FIELDS, DISJUNCT -> first.mergeWith(entry); + case DIFFERENT -> + result.addFirst(entry); + case DISJUNCT_OR_EQUAL_FIELDS, + DISJUNCT -> + first.mergeWith(entry); // in all other cases (EQUAL, SUPERSET), the documentInformation is ignored } }); diff --git a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilShared.java b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilShared.java index 505d7170dbc..9b51dce89d2 100644 --- a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilShared.java +++ b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilShared.java @@ -48,7 +48,7 @@ public XMPMetadata parseXmpMetadata(InputStream is) throws IOException { /** * Will try to read XMP metadata from the given file, returning whether * metadata was found. - * + *

        * Caution: This method is as expensive as it is reading the actual metadata * itself from the PDF. * diff --git a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilWriter.java b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilWriter.java index e84e3efc893..f01e170bf98 100644 --- a/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilWriter.java +++ b/jablib/src/main/java/org/jabref/logic/xmp/XmpUtilWriter.java @@ -182,7 +182,6 @@ private String generateXmpStringWithXmpDeclaration(List entries) { * This method generates an xmp metadata string in dublin core format without the * metadata section {@code }. * - * * @param entries A list of entries, which are added to the dublin core metadata. * @return If something goes wrong (e.g. an exception is thrown), the method returns an empty string, * otherwise it returns the xmp metadata without metadata description as a string in dublin core format. @@ -233,7 +232,8 @@ private void writeDocumentInformation(PDDocument document, // do not write file field case StandardField.FILE -> { } - case null, default -> + case null, + default -> di.setCustomMetadataValue(XmpUtilShared.BIBTEX_DI_FIELD_NAME_PREFIX + field.getName(), null); } continue; @@ -256,7 +256,7 @@ private void writeDocumentInformation(PDDocument document, } case null, default -> - // We hit the case of an PDF-unsupported field --> write it directly + // We hit the case of an PDF-unsupported field --> write it directly resolvedEntry.getField(field).ifPresent(val -> di.setCustomMetadataValue(XmpUtilShared.BIBTEX_DI_FIELD_NAME_PREFIX + field.getName(), val)); } } diff --git a/jablib/src/main/java/org/jabref/model/ChainNode.java b/jablib/src/main/java/org/jabref/model/ChainNode.java index 7b0a3625254..43834981899 100644 --- a/jablib/src/main/java/org/jabref/model/ChainNode.java +++ b/jablib/src/main/java/org/jabref/model/ChainNode.java @@ -21,7 +21,8 @@ * * @param the type of the class */ -@SuppressWarnings("unchecked") // We use some explicit casts of the form "(T) this". The constructor ensures that this cast is valid. +@SuppressWarnings("unchecked") +// We use some explicit casts of the form "(T) this". The constructor ensures that this cast is valid. public abstract class ChainNode> { /** diff --git a/jablib/src/main/java/org/jabref/model/TreeNode.java b/jablib/src/main/java/org/jabref/model/TreeNode.java index 8143d190785..7234785a0a1 100644 --- a/jablib/src/main/java/org/jabref/model/TreeNode.java +++ b/jablib/src/main/java/org/jabref/model/TreeNode.java @@ -52,7 +52,7 @@ public abstract class TreeNode> { /// Constructs a tree node without parent and no children. /// /// @param derivingClass class deriving from TreeNode. It should always be "T.class". - /// We need this parameter since it is hard to get this information by other means. + /// We need this parameter since it is hard to get this information by other means. public TreeNode(Class derivingClass) { parent = null; children = FXCollections.observableArrayList(); @@ -584,11 +584,11 @@ public T copySubtree() { /** * Adds the given function to the list of subscribers which are notified when something changes in the subtree. - * + *

        * The following events are supported (the text in parentheses specifies which node is passed as the source): - * - addChild (new parent) - * - removeChild (old parent) - * - move (old parent and new parent) + * - addChild (new parent) + * - removeChild (old parent) + * - move (old parent and new parent) * * @param subscriber function to be invoked upon a change */ diff --git a/jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java b/jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java index 84202be6c0f..302743fdbac 100644 --- a/jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java +++ b/jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java @@ -166,7 +166,6 @@ public boolean isStudy() { * * * @param preferences The fileDirectory preferences - * * @return List of existing absolute paths */ public List getFileDirectories(FilePreferences preferences) { diff --git a/jablib/src/main/java/org/jabref/model/database/BibDatabaseMode.java b/jablib/src/main/java/org/jabref/model/database/BibDatabaseMode.java index 93316daaf35..d193a806fe9 100644 --- a/jablib/src/main/java/org/jabref/model/database/BibDatabaseMode.java +++ b/jablib/src/main/java/org/jabref/model/database/BibDatabaseMode.java @@ -39,8 +39,8 @@ public BibDatabaseMode getOppositeMode() { * in the string doesn't matter.If neither "bibtex" nor "biblatex" is the given string, then an * {@link IllegalArgumentException} will be thrown. * - * @return BIBTEX, if the string is bibtex
        - * BIBLATEX, if the string is biblatex
        + * @return BIBTEX, if the string is bibtex
        + * BIBLATEX, if the string is biblatex
        */ public static BibDatabaseMode parse(String data) { return BibDatabaseMode.valueOf(data.toUpperCase(Locale.ENGLISH)); diff --git a/jablib/src/main/java/org/jabref/model/database/BibDatabaseModeDetection.java b/jablib/src/main/java/org/jabref/model/database/BibDatabaseModeDetection.java index 3fa1f5745a5..82d43961b73 100644 --- a/jablib/src/main/java/org/jabref/model/database/BibDatabaseModeDetection.java +++ b/jablib/src/main/java/org/jabref/model/database/BibDatabaseModeDetection.java @@ -13,10 +13,10 @@ private BibDatabaseModeDetection() { /** * Tries to infer the database type by examining a BibDatabase database. - * + *

        * All checks are based on the case-insensitive comparison of entry tag names. * Only standard BibTex and Biblatex entry types are considered in the decision process. - * + *

        * 1. Check if any of the entries is a type exclusive to Biblatex * 2. Otherwise return BibTex * diff --git a/jablib/src/main/java/org/jabref/model/database/KeyChangeListener.java b/jablib/src/main/java/org/jabref/model/database/KeyChangeListener.java index ca4becc4e9c..60c5e2379ed 100644 --- a/jablib/src/main/java/org/jabref/model/database/KeyChangeListener.java +++ b/jablib/src/main/java/org/jabref/model/database/KeyChangeListener.java @@ -52,9 +52,9 @@ private void updateEntryLinks(String newKey, @Nullable String oldKey) { }); entry.getFields(field -> field.getProperties().contains(FieldProperty.MULTIPLE_ENTRY_LINK)) .forEach(field -> { - String fieldContent = entry.getField(field).orElseThrow(); - replaceKeyInMultiplesKeyField(newKey, oldKey, entry, field, fieldContent); - }); + String fieldContent = entry.getField(field).orElseThrow(); + replaceKeyInMultiplesKeyField(newKey, oldKey, entry, field, fieldContent); + }); } } diff --git a/jablib/src/main/java/org/jabref/model/entry/Author.java b/jablib/src/main/java/org/jabref/model/entry/Author.java index a8a24c91a56..f84f37664ff 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Author.java +++ b/jablib/src/main/java/org/jabref/model/entry/Author.java @@ -37,11 +37,11 @@ public class Author { *

        * In case only the last part is passed, enclosing braces are * - * @param givenName the first name of the author (may consist of several tokens, like "Charles Louis Xavier Joseph" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") + * @param givenName the first name of the author (may consist of several tokens, like "Charles Louis Xavier Joseph" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") * @param givenNameAbbreviated the abbreviated first name of the author (may consist of several tokens, like "C. L. X. J." in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin"). It is a responsibility of the caller to create a reasonable abbreviation of the first name. - * @param namePrefix the von part of the author's name (may consist of several tokens, like "de la" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") - * @param familyName the last name of the author (may consist of several tokens, like "Vall{\'e}e Poussin" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") - * @param nameSuffix the junior part of the author's name (may consist of several tokens, like "Jr. III" in "Smith, Jr. III, John") + * @param namePrefix the von part of the author's name (may consist of several tokens, like "de la" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") + * @param familyName the last name of the author (may consist of several tokens, like "Vall{\'e}e Poussin" in "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin") + * @param nameSuffix the junior part of the author's name (may consist of several tokens, like "Jr. III" in "Smith, Jr. III, John") */ public Author(String givenName, String givenNameAbbreviated, String namePrefix, String familyName, String nameSuffix) { boolean keepBracesAtLastPart = StringUtil.isBlank(givenName) && StringUtil.isBlank(givenNameAbbreviated) && StringUtil.isBlank(namePrefix) && !StringUtil.isBlank(familyName) && StringUtil.isBlank(nameSuffix); diff --git a/jablib/src/main/java/org/jabref/model/entry/AuthorList.java b/jablib/src/main/java/org/jabref/model/entry/AuthorList.java index 21a877b325c..30df8d27c9d 100644 --- a/jablib/src/main/java/org/jabref/model/entry/AuthorList.java +++ b/jablib/src/main/java/org/jabref/model/entry/AuthorList.java @@ -157,10 +157,14 @@ private static String andCoordinatedConjunction(List authors, boolean ox String lastDelimiter = oxfordComma ? ", and " : " and "; int lastIndex = authors.size() - 1; return switch (authors.size()) { - case 0 -> ""; - case 1 -> authors.getFirst(); - case 2 -> authors.getFirst() + " and " + authors.get(1); - default -> String.join(", ", authors.subList(0, lastIndex)) + lastDelimiter + authors.get(lastIndex); + case 0 -> + ""; + case 1 -> + authors.getFirst(); + case 2 -> + authors.getFirst() + " and " + authors.get(1); + default -> + String.join(", ", authors.subList(0, lastIndex)) + lastDelimiter + authors.get(lastIndex); }; } @@ -316,10 +320,14 @@ public AuthorList latexFree() { public String getAsNatbib() { List authors = getAuthors(); return switch (authors.size()) { - case 0 -> ""; - case 1 -> authors.getFirst().getNamePrefixAndFamilyName(); - case 2 -> authors.getFirst().getNamePrefixAndFamilyName() + " and " + authors.get(1).getNamePrefixAndFamilyName(); - default -> authors.getFirst().getNamePrefixAndFamilyName() + " et al."; + case 0 -> + ""; + case 1 -> + authors.getFirst().getNamePrefixAndFamilyName(); + case 2 -> + authors.getFirst().getNamePrefixAndFamilyName() + " and " + authors.get(1).getNamePrefixAndFamilyName(); + default -> + authors.getFirst().getNamePrefixAndFamilyName() + " et al."; }; } @@ -395,15 +403,18 @@ public String getAsLastFirstNamesWithAnd(boolean abbreviate) { */ public String getAsLastFirstFirstLastNamesWithAnd(boolean abbreviate) { return switch (authors.size()) { - case 0 -> ""; - case 1 -> authors.getFirst().getFamilyGiven(abbreviate); - default -> authors.stream() - .skip(1) - .map(author -> author.getGivenFamily(abbreviate)) - .collect(Collectors.joining( - " and ", - authors.getFirst().getFamilyGiven(abbreviate) + " and ", - "")); + case 0 -> + ""; + case 1 -> + authors.getFirst().getFamilyGiven(abbreviate); + default -> + authors.stream() + .skip(1) + .map(author -> author.getGivenFamily(abbreviate)) + .collect(Collectors.joining( + " and ", + authors.getFirst().getFamilyGiven(abbreviate) + " and ", + "")); }; } 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 55443db80ac..9e1d47596b8 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibEntry.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibEntry.java @@ -357,12 +357,13 @@ private Optional genericGetResolvedFieldOrAlias(Field field, @Nullable B } return (database == null) || result.isEmpty() ? - result : - Optional.of(database.resolveForStrings(result.get())); + result : + Optional.of(database.resolveForStrings(result.get())); } /// Returns this entry's ID. It is used internally to distinguish different BibTeX entries. // It is **not** the citation key (which is stored in the {@link InternalField#KEY_FIELD} and also known as BibTeX key). + /// /// This id changes on each run of JabRef (because it is currently generated as increasing number). /// @@ -510,7 +511,7 @@ public boolean hasField(Field field) { /** * Internal method used to get the content of a field (or its alias) - * + *

        * Used by {@link #getFieldOrAlias(Field)} and {@link #getFieldOrAliasLatexFree(Field)} * * @param field the field @@ -550,10 +551,14 @@ private Optional genericGetFieldOrAlias(Field field, BiFunction parsedDate = Date.parse(date.get()); if (parsedDate.isPresent()) { return switch (field) { - case StandardField.YEAR -> parsedDate.get().getYear().map(Object::toString); - case StandardField.MONTH -> parsedDate.get().getMonth().map(Month::getJabRefFormat); - case StandardField.DAY -> parsedDate.get().getDay().map(Object::toString); - default -> throw new IllegalStateException("Unexpected value"); + case StandardField.YEAR -> + parsedDate.get().getYear().map(Object::toString); + case StandardField.MONTH -> + parsedDate.get().getMonth().map(Month::getJabRefFormat); + case StandardField.DAY -> + parsedDate.get().getDay().map(Object::toString); + default -> + throw new IllegalStateException("Unexpected value"); }; } else { // Date field not in valid format @@ -733,7 +738,7 @@ public String getKeyAuthorTitleYear() { /** * Creates a short textual description of the entry in the format: Author1, Author2: Title (Year) - * + *

        * If 0 is passed as maxCharacters, the description is not truncated. * * @param maxCharacters The maximum number of characters (additional @@ -952,7 +957,7 @@ public boolean equals(Object o) { /** * On purpose, this hashes the "content" of the BibEntry, not the {@link #sharedBibEntryData}. - * + *

        * The content is * *

          diff --git a/jablib/src/main/java/org/jabref/model/entry/BibEntryType.java b/jablib/src/main/java/org/jabref/model/entry/BibEntryType.java index aa71197f2eb..fe6289bf7e2 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibEntryType.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibEntryType.java @@ -25,12 +25,12 @@ public class BibEntryType implements Comparable { /** * Provides an enriched EntryType with information about defined standards as mandatory fields etc. - * + *

          * A builder is available at {@link BibEntryTypeBuilder} * - * @param type The EntryType this BibEntryType is wrapped around. - * @param allFields A BibFields list of all fields, including the required fields - * @param requiredFields A OrFields list of just the required fields + * @param type The EntryType this BibEntryType is wrapped around. + * @param allFields A BibFields list of all fields, including the required fields + * @param requiredFields A OrFields list of just the required fields */ public BibEntryType(EntryType type, Collection allFields, Collection requiredFields) { this.type = Objects.requireNonNull(type); @@ -44,8 +44,8 @@ public EntryType getType() { public SequencedSet getOptionalFields() { return getAllBibFields().stream() - .filter(field -> !isRequired(field.field())) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter(field -> !isRequired(field.field())) + .collect(Collectors.toCollection(LinkedHashSet::new)); } public boolean isRequired(Field field) { @@ -136,8 +136,8 @@ public boolean equals(Object o) { } BibEntryType that = (BibEntryType) o; return type.equals(that.type) && - Objects.equals(requiredFields, that.requiredFields) && - Objects.equals(allFields, that.allFields); + Objects.equals(requiredFields, that.requiredFields) && + Objects.equals(allFields, that.allFields); } @Override diff --git a/jablib/src/main/java/org/jabref/model/entry/BibEntryTypeBuilder.java b/jablib/src/main/java/org/jabref/model/entry/BibEntryTypeBuilder.java index d873748938b..3e8c019f995 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibEntryTypeBuilder.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibEntryTypeBuilder.java @@ -106,9 +106,9 @@ public BibEntryTypeBuilder withRequiredFields(SequencedSet first, Fiel public BibEntryType build() { // Treat required fields as important ones Stream requiredAsImportant = requiredFields.stream() - .map(OrFields::getFields) - .flatMap(Set::stream) - .map(field -> new BibField(field, FieldPriority.IMPORTANT)); + .map(OrFields::getFields) + .flatMap(Set::stream) + .map(field -> new BibField(field, FieldPriority.IMPORTANT)); SequencedSet allFields = Stream.concat(optionalFields.stream(), requiredAsImportant).collect(Collectors.toCollection(LinkedHashSet::new)); return new BibEntryType(type, allFields, requiredFields); } diff --git a/jablib/src/main/java/org/jabref/model/entry/BibEntryTypesManager.java b/jablib/src/main/java/org/jabref/model/entry/BibEntryTypesManager.java index 9209e35be87..c7987aaa433 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibEntryTypesManager.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibEntryTypesManager.java @@ -45,8 +45,10 @@ public BibEntryTypesManager() { @VisibleForTesting InternalEntryTypes getEntryTypes(BibDatabaseMode mode) { return switch (mode) { - case BIBTEX -> BIBTEX_ENTRYTYPES; - case BIBLATEX -> BIBLATEX_ENTRYTYPES; + case BIBTEX -> + BIBTEX_ENTRYTYPES; + case BIBLATEX -> + BIBLATEX_ENTRYTYPES; }; } @@ -127,8 +129,8 @@ public void update(BibEntryType entryType, BibDatabaseMode mode) { // Workaround for UI not supporting OrFields Optional standardTypeOpt = entryTypes.standardTypes.stream() - .filter(InternalEntryTypes.typeEquals(entryType.getType())) - .findFirst(); + .filter(InternalEntryTypes.typeEquals(entryType.getType())) + .findFirst(); if (standardTypeOpt.isEmpty()) { LOGGER.debug("Standard type not found for {}", entryType.getType()); entryTypes.addCustomOrModifiedType(entryType); @@ -143,8 +145,8 @@ public void update(BibEntryType entryType, BibDatabaseMode mode) { Set standardOptionalFields = standardType.getOptionalFields(); Set entryTypeRequiredFields = entryType.getRequiredFields().stream() - .map(OrFields::getFields) - .flatMap(Set::stream) + .map(OrFields::getFields) + .flatMap(Set::stream) .collect(Collectors.toSet()); Set entryTypeOptionalFields = entryType.getOptionalFields(); @@ -194,8 +196,7 @@ public Optional enrich(EntryType type, BibDatabaseMode mode) { */ @VisibleForTesting static class InternalEntryTypes { - @VisibleForTesting - final Set standardTypes; + @VisibleForTesting final Set standardTypes; // TreeSet needs to be used here, because then, org.jabref.model.entry.BibEntryType.compareTo is used - instead of org.jabref.model.entry.BibEntryType.equals private final SortedSet customOrModifiedType = new TreeSet<>(); diff --git a/jablib/src/main/java/org/jabref/model/entry/BibtexString.java b/jablib/src/main/java/org/jabref/model/entry/BibtexString.java index ed7ecb52fa4..ba014e80123 100644 --- a/jablib/src/main/java/org/jabref/model/entry/BibtexString.java +++ b/jablib/src/main/java/org/jabref/model/entry/BibtexString.java @@ -81,7 +81,7 @@ public static Type get(String key) { /** * Default constructor. Use this if in doubt. - * + *

          * In case this constructor is used - and the library is eventually written, the serialization is generated from scratch (and not some null from parsedSerialization) */ public BibtexString(String name, String content) { @@ -170,7 +170,7 @@ public String getUserComments() { public Object clone() { BibtexString clone; if (parsedSerialization == null) { - clone = new BibtexString(name, content); + clone = new BibtexString(name, content); } else { clone = new BibtexString(name, content, parsedSerialization); } diff --git a/jablib/src/main/java/org/jabref/model/entry/Date.java b/jablib/src/main/java/org/jabref/model/entry/Date.java index 880035f1564..e3eda35115e 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Date.java +++ b/jablib/src/main/java/org/jabref/model/entry/Date.java @@ -106,7 +106,7 @@ public Date(TemporalAccessor date) { /** * Creates a Date from date and endDate. * - * @param date the start date + * @param date the start date * @param endDate the start date */ public Date(TemporalAccessor date, TemporalAccessor endDate) { @@ -139,15 +139,15 @@ public static Optional parse(String dateString) { // if dateString has range format, treat as date range if (dateString.matches( "\\d{4}/\\d{4}|" + // uuuu/uuuu - "\\d{4}-\\d{2}/\\d{4}-\\d{2}|" + // uuuu-mm/uuuu-mm - "\\d{4}-\\d{2}-\\d{2}/\\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd/uuuu-mm-dd - "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4})/(January|February|March|April|May|June|July|August|September|October|November" + - "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 - "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4})/(\\d{1,2})( )" + - "(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 + "\\d{4}-\\d{2}/\\d{4}-\\d{2}|" + // uuuu-mm/uuuu-mm + "\\d{4}-\\d{2}-\\d{2}/\\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd/uuuu-mm-dd + "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4})/(January|February|March|April|May|June|July|August|September|October|November" + + "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 + "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4})/(\\d{1,2})( )" + + "(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 )) { try { String[] strDates = dateString.split("/"); @@ -160,15 +160,15 @@ public static Optional parse(String dateString) { } } else if (dateString.matches( "\\d{4} / \\d{4}|" + // uuuu / uuuu - "\\d{4}-\\d{2} / \\d{4}-\\d{2}|" + // uuuu-mm / uuuu-mm - "\\d{4}-\\d{2}-\\d{2} / \\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd / uuuu-mm-dd - "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4}) / (January|February|March|April|May|June|July|August|September|October|November" + - "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 - "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4}) / (\\d{1,2})( )" + - "(January|February|March|April|May|June|July|August|September|October|November|December)" + - "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 + "\\d{4}-\\d{2} / \\d{4}-\\d{2}|" + // uuuu-mm / uuuu-mm + "\\d{4}-\\d{2}-\\d{2} / \\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd / uuuu-mm-dd + "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4}) / (January|February|March|April|May|June|July|August|September|October|November" + + "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 + "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4}) / (\\d{1,2})( )" + + "(January|February|March|April|May|June|July|August|September|October|November|December)" + + "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 )) { try { String[] strDates = dateString.split(" / "); @@ -181,11 +181,11 @@ public static Optional parse(String dateString) { } } else if (dateString.matches( "\\d{1,4} BC/\\d{1,4} AD|" + // 30 BC/5 AD and 0030 BC/0005 AD - "\\d{1,4} BC/\\d{1,4} BC|" + // 30 BC/10 BC and 0030 BC/0010 BC - "\\d{1,4} AD/\\d{1,4} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD - "\\d{1,4}-\\d{1,2} BC/\\d{1,4}-\\d{1,2} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD - "\\d{1,4}-\\d{1,2} BC/\\d{1,4}-\\d{1,2} BC|" + // 5 AD/10 AD and 0005 AD/0010 AD - "\\d{1,4}-\\d{1,2} AD/\\d{1,4}-\\d{1,2} AD" // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4} BC/\\d{1,4} BC|" + // 30 BC/10 BC and 0030 BC/0010 BC + "\\d{1,4} AD/\\d{1,4} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4}-\\d{1,2} BC/\\d{1,4}-\\d{1,2} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4}-\\d{1,2} BC/\\d{1,4}-\\d{1,2} BC|" + // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4}-\\d{1,2} AD/\\d{1,4}-\\d{1,2} AD" // 5 AD/10 AD and 0005 AD/0010 AD )) { try { String[] strDates = dateString.split("/"); @@ -198,11 +198,11 @@ public static Optional parse(String dateString) { } } else if (dateString.matches( "\\d{1,4} BC / \\d{1,4} AD|" + // 30 BC / 5 AD and 0030 BC / 0005 AD - "\\d{1,4} BC / \\d{1,4} BC|" + // 30 BC / 10 BC and 0030 BC / 0010 BC - "\\d{1,4} AD / \\d{1,4} AD|" + // 5 AD / 10 AD and 0005 AD / 0010 AD - "\\d{1,4}-\\d{1,2} BC / \\d{1,4}-\\d{1,2} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD - "\\d{1,4}-\\d{1,2} BC / \\d{1,4}-\\d{1,2} BC|" + // 5 AD/10 AD and 0005 AD/0010 AD - "\\d{1,4}-\\d{1,2} AD / \\d{1,4}-\\d{1,2} AD" // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4} BC / \\d{1,4} BC|" + // 30 BC / 10 BC and 0030 BC / 0010 BC + "\\d{1,4} AD / \\d{1,4} AD|" + // 5 AD / 10 AD and 0005 AD / 0010 AD + "\\d{1,4}-\\d{1,2} BC / \\d{1,4}-\\d{1,2} AD|" + // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4}-\\d{1,2} BC / \\d{1,4}-\\d{1,2} BC|" + // 5 AD/10 AD and 0005 AD/0010 AD + "\\d{1,4}-\\d{1,2} AD / \\d{1,4}-\\d{1,2} AD" // 5 AD/10 AD and 0005 AD/0010 AD )) { try { String[] strDates = dateString.split(" / "); @@ -230,9 +230,9 @@ public static Optional parse(String dateString) { // handle the new date formats with era indicators if (dateString.matches( "\\d{1,4} BC|" + // covers 1 BC - "\\d{1,4} AD|" + // covers 1 BC - "\\d{1,4}-\\d{1,2} BC|" + // covers 0030-01 BC - "\\d{1,4}-\\d{1,2} AD" // covers 0005-01 AD + "\\d{1,4} AD|" + // covers 1 BC + "\\d{1,4}-\\d{1,2} BC|" + // covers 0030-01 BC + "\\d{1,4}-\\d{1,2} AD" // covers 0005-01 AD )) { try { // Parse the date with era indicator diff --git a/jablib/src/main/java/org/jabref/model/entry/Keyword.java b/jablib/src/main/java/org/jabref/model/entry/Keyword.java index e87155c2813..2a9ef52f2c9 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Keyword.java +++ b/jablib/src/main/java/org/jabref/model/entry/Keyword.java @@ -39,8 +39,8 @@ public static Keyword of(List keywords) { /// Converts a raw String to a single Keyword public static Keyword ofHierarchical(String rawString) { return Keyword.of(Stream.of(rawString.split(Keyword.DEFAULT_HIERARCHICAL_DELIMITER.toString())) - .map(String::trim) - .toList()); + .map(String::trim) + .toList()); } @Override diff --git a/jablib/src/main/java/org/jabref/model/entry/Langid.java b/jablib/src/main/java/org/jabref/model/entry/Langid.java index eb94b1352e0..a4172b60aa2 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Langid.java +++ b/jablib/src/main/java/org/jabref/model/entry/Langid.java @@ -3,6 +3,7 @@ import java.util.Optional; import org.jabref.logic.bibtex.FieldWriter; + /** * Language identifiers based on BibLaTeX manual specifications. * See the BibLaTeX documentation for full details: @@ -59,7 +60,6 @@ public enum Langid { TURKISH("Turkish", "turkish"), UKRAINIAN("Ukrainian", "ukrainian"); - private final String name; private final String langid; diff --git a/jablib/src/main/java/org/jabref/model/entry/Month.java b/jablib/src/main/java/org/jabref/model/entry/Month.java index 4c5e6d06654..37362422df7 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Month.java +++ b/jablib/src/main/java/org/jabref/model/entry/Month.java @@ -114,19 +114,45 @@ public static Optional parse(String value) { static Optional parseGermanShortMonth(String value) { value = value.toLowerCase(); return switch (value) { - case "jan", "januar" -> Month.getMonthByNumber(1); - case "feb", "februar" -> Month.getMonthByNumber(2); - case "mär", "mae", "märz", "maerz" -> Month.getMonthByNumber(3); - case "apr", "april" -> Month.getMonthByNumber(4); - case "mai" -> Month.getMonthByNumber(5); - case "jun", "juni" -> Month.getMonthByNumber(6); - case "jul", "juli" -> Month.getMonthByNumber(7); - case "aug", "august" -> Month.getMonthByNumber(8); - case "sep", "september" -> Month.getMonthByNumber(9); - case "okt", "oktober" -> Month.getMonthByNumber(10); - case "nov", "november" -> Month.getMonthByNumber(11); - case "dez", "dezember" -> Month.getMonthByNumber(12); - default -> Optional.empty(); + case "jan", + "januar" -> + Month.getMonthByNumber(1); + case "feb", + "februar" -> + Month.getMonthByNumber(2); + case "mär", + "mae", + "märz", + "maerz" -> + Month.getMonthByNumber(3); + case "apr", + "april" -> + Month.getMonthByNumber(4); + case "mai" -> + Month.getMonthByNumber(5); + case "jun", + "juni" -> + Month.getMonthByNumber(6); + case "jul", + "juli" -> + Month.getMonthByNumber(7); + case "aug", + "august" -> + Month.getMonthByNumber(8); + case "sep", + "september" -> + Month.getMonthByNumber(9); + case "okt", + "oktober" -> + Month.getMonthByNumber(10); + case "nov", + "november" -> + Month.getMonthByNumber(11); + case "dez", + "dezember" -> + Month.getMonthByNumber(12); + default -> + Optional.empty(); }; } diff --git a/jablib/src/main/java/org/jabref/model/entry/Season.java b/jablib/src/main/java/org/jabref/model/entry/Season.java index f47e65d78d3..6963fbbdc6a 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Season.java +++ b/jablib/src/main/java/org/jabref/model/entry/Season.java @@ -94,11 +94,16 @@ public static Optional parse(String value) { static Optional parseGermanSeason(String value) { value = value.toLowerCase(); return switch (value) { - case "frühling" -> Optional.of(SPRING); - case "sommer" -> Optional.of(SUMMER); - case "herbst" -> Optional.of(AUTUMN); - case "winter" -> Optional.of(WINTER); - default -> Optional.empty(); + case "frühling" -> + Optional.of(SPRING); + case "sommer" -> + Optional.of(SUMMER); + case "herbst" -> + Optional.of(AUTUMN); + case "winter" -> + Optional.of(WINTER); + default -> + Optional.empty(); }; } diff --git a/jablib/src/main/java/org/jabref/model/entry/field/Field.java b/jablib/src/main/java/org/jabref/model/entry/field/Field.java index 4fca938ed28..19e551225f1 100644 --- a/jablib/src/main/java/org/jabref/model/entry/field/Field.java +++ b/jablib/src/main/java/org/jabref/model/entry/field/Field.java @@ -25,7 +25,7 @@ default String getDisplayName() { /** * Name used for writing to .bib (or as XMP data) - * + *

          * However, BibEntryWriter converts to lower case. See {@link org.jabref.logic.bibtex.BibEntryWriter#getFormattedFieldName} */ String getName(); diff --git a/jablib/src/main/java/org/jabref/model/entry/field/FieldFactory.java b/jablib/src/main/java/org/jabref/model/entry/field/FieldFactory.java index dfe0adbf3a0..ae04eb76cdc 100644 --- a/jablib/src/main/java/org/jabref/model/entry/field/FieldFactory.java +++ b/jablib/src/main/java/org/jabref/model/entry/field/FieldFactory.java @@ -67,8 +67,8 @@ public static boolean isLatexField(Field field) { */ public static Collection getNotTextFields() { Set result = Arrays.stream(StandardField.values()) - .filter(field -> !Collections.disjoint(field.getProperties(), Set.of(FieldProperty.VERBATIM, FieldProperty.NUMERIC, FieldProperty.DATE, FieldProperty.MULTIPLE_ENTRY_LINK))) - .collect(Collectors.toSet()); + .filter(field -> !Collections.disjoint(field.getProperties(), Set.of(FieldProperty.VERBATIM, FieldProperty.NUMERIC, FieldProperty.DATE, FieldProperty.MULTIPLE_ENTRY_LINK))) + .collect(Collectors.toSet()); // These fields are not marked as verbatim, because they could include LaTeX code result.add(StandardField.MONTH); @@ -116,7 +116,7 @@ public static String serializeFieldsList(Collection fields) { /** * Type T is an entry type and is used to direct the mapping to the Java field class. * This somehow acts as filter, BibLaTeX "APA" entry type has field "article", but we want to have StandardField (if not explicitly requested otherwise) - * + *

          * Supports also parsing of "UnknownField{name='rights'}" as field name (written by JabRef 5.x) */ public static Field parseField(T type, String fieldName) { @@ -133,19 +133,19 @@ public static Field parseField(T type, String fieldName) { } return OptionalUtil.orElse( - OptionalUtil.orElse( - OptionalUtil.orElse( - OptionalUtil.orElse( - OptionalUtil.orElse( - OptionalUtil.orElse( - InternalField.fromName(fieldName), - StandardField.fromName(fieldName)), - SpecialField.fromName(fieldName)), - IEEEField.fromName(fieldName)), - BiblatexSoftwareField.fromName(type, fieldName)), - BiblatexApaField.fromName(type, fieldName)), - AMSField.fromName(type, fieldName)) - .orElse(UnknownField.fromDisplayName(fieldName)); + OptionalUtil.orElse( + OptionalUtil.orElse( + OptionalUtil.orElse( + OptionalUtil.orElse( + OptionalUtil.orElse( + InternalField.fromName(fieldName), + StandardField.fromName(fieldName)), + SpecialField.fromName(fieldName)), + IEEEField.fromName(fieldName)), + BiblatexSoftwareField.fromName(type, fieldName)), + BiblatexApaField.fromName(type, fieldName)), + AMSField.fromName(type, fieldName)) + .orElse(UnknownField.fromDisplayName(fieldName)); } public static Field parseField(String fieldName) { diff --git a/jablib/src/main/java/org/jabref/model/entry/field/SpecialFieldValue.java b/jablib/src/main/java/org/jabref/model/entry/field/SpecialFieldValue.java index 6c3337b41f6..d15eefe1ef0 100644 --- a/jablib/src/main/java/org/jabref/model/entry/field/SpecialFieldValue.java +++ b/jablib/src/main/java/org/jabref/model/entry/field/SpecialFieldValue.java @@ -39,13 +39,20 @@ public enum SpecialFieldValue { public static SpecialFieldValue getRating(int ranking) { return switch (ranking) { - case 0 -> CLEAR_RANK; - case 1 -> RANK_1; - case 2 -> RANK_2; - case 3 -> RANK_3; - case 4 -> RANK_4; - case 5 -> RANK_5; - default -> throw new UnsupportedOperationException(ranking + "is not a valid ranking"); + case 0 -> + CLEAR_RANK; + case 1 -> + RANK_1; + case 2 -> + RANK_2; + case 3 -> + RANK_3; + case 4 -> + RANK_4; + case 5 -> + RANK_5; + default -> + throw new UnsupportedOperationException(ranking + "is not a valid ranking"); }; } @@ -59,13 +66,20 @@ public Optional getFieldValue() { public int toRating() { return switch (this) { - case CLEAR_RANK -> 0; - case RANK_1 -> 1; - case RANK_2 -> 2; - case RANK_3 -> 3; - case RANK_4 -> 4; - case RANK_5 -> 5; - default -> throw new UnsupportedOperationException(this + "is not a valid ranking"); + case CLEAR_RANK -> + 0; + case RANK_1 -> + 1; + case RANK_2 -> + 2; + case RANK_3 -> + 3; + case RANK_4 -> + 4; + case RANK_5 -> + 5; + default -> + throw new UnsupportedOperationException(this + "is not a valid ranking"); }; } } diff --git a/jablib/src/main/java/org/jabref/model/entry/field/UnknownField.java b/jablib/src/main/java/org/jabref/model/entry/field/UnknownField.java index 99643964c56..8ca4c3fcdd1 100644 --- a/jablib/src/main/java/org/jabref/model/entry/field/UnknownField.java +++ b/jablib/src/main/java/org/jabref/model/entry/field/UnknownField.java @@ -78,7 +78,7 @@ public int hashCode() { @Override public String toString() { return "UnknownField{" + - "name='" + name + '\'' + - '}'; + "name='" + name + '\'' + + '}'; } } diff --git a/jablib/src/main/java/org/jabref/model/entry/identifier/SSRN.java b/jablib/src/main/java/org/jabref/model/entry/identifier/SSRN.java index 0a644b6dba1..fc68d356399 100644 --- a/jablib/src/main/java/org/jabref/model/entry/identifier/SSRN.java +++ b/jablib/src/main/java/org/jabref/model/entry/identifier/SSRN.java @@ -25,7 +25,7 @@ public class SSRN extends EprintIdentifier { * Tries to parse an SSRN identifier * * @param string Either a number or a SSRN url that has the abstract ID in it - * @throws NullPointerException If you pass a null to the constructor + * @throws NullPointerException If you pass a null to the constructor * @throws IllegalArgumentException Invalid string passed to the constructor */ public SSRN(String string) { diff --git a/jablib/src/main/java/org/jabref/model/entry/types/BiblatexAPAEntryTypeDefinitions.java b/jablib/src/main/java/org/jabref/model/entry/types/BiblatexAPAEntryTypeDefinitions.java index f5c0b89b0be..709d9a0c340 100644 --- a/jablib/src/main/java/org/jabref/model/entry/types/BiblatexAPAEntryTypeDefinitions.java +++ b/jablib/src/main/java/org/jabref/model/entry/types/BiblatexAPAEntryTypeDefinitions.java @@ -35,9 +35,9 @@ public class BiblatexAPAEntryTypeDefinitions { .build(); private static final BibEntryType LEGAL = new BibEntryTypeBuilder() - .withType(BiblatexApaEntryType.Legal) - .withRequiredFields(StandardField.TITLE, StandardField.DATE, StandardField.URI, StandardField.KEYWORDS, StandardField.PART, BiblatexApaField.SECTION) - .build(); + .withType(BiblatexApaEntryType.Legal) + .withRequiredFields(StandardField.TITLE, StandardField.DATE, StandardField.URI, StandardField.KEYWORDS, StandardField.PART, BiblatexApaField.SECTION) + .build(); public static final List ALL = Arrays.asList(JURISDICTION, LEGISLATION, LEGADMINMATERIAL, CONSTITUTION, LEGAL); } diff --git a/jablib/src/main/java/org/jabref/model/groups/SearchGroup.java b/jablib/src/main/java/org/jabref/model/groups/SearchGroup.java index 71deb84c521..83ad15ccd52 100644 --- a/jablib/src/main/java/org/jabref/model/groups/SearchGroup.java +++ b/jablib/src/main/java/org/jabref/model/groups/SearchGroup.java @@ -74,9 +74,9 @@ public boolean equals(Object o) { return false; } return Objects.equals(getName(), other.getName()) - && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext()) - && Objects.equals(getSearchExpression(), other.getSearchExpression()) - && Objects.equals(getSearchFlags(), other.getSearchFlags()); + && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext()) + && Objects.equals(getSearchExpression(), other.getSearchExpression()) + && Objects.equals(getSearchFlags(), other.getSearchFlags()); } @Override diff --git a/jablib/src/main/java/org/jabref/model/http/SimpleHttpResponse.java b/jablib/src/main/java/org/jabref/model/http/SimpleHttpResponse.java index 1b650bf6983..a3c624ff080 100644 --- a/jablib/src/main/java/org/jabref/model/http/SimpleHttpResponse.java +++ b/jablib/src/main/java/org/jabref/model/http/SimpleHttpResponse.java @@ -69,8 +69,8 @@ private static String getResponseBodyDefaultEmpty(HttpURLConnection connection) * Truncates the response body to 1 KB if it exceeds that size. * Appends "... (truncated)" to indicate truncation. * - * @param responseBody the original response body - * @return the truncated response body + * @param responseBody the original response body + * @return the truncated response body */ private static String truncateResponseBody(String responseBody) { byte[] bytes = responseBody.getBytes(StandardCharsets.UTF_8); diff --git a/jablib/src/main/java/org/jabref/model/metadata/SaveOrder.java b/jablib/src/main/java/org/jabref/model/metadata/SaveOrder.java index 94e9b671bb1..b461335e037 100644 --- a/jablib/src/main/java/org/jabref/model/metadata/SaveOrder.java +++ b/jablib/src/main/java/org/jabref/model/metadata/SaveOrder.java @@ -132,7 +132,7 @@ public SortCriterion(Field field) { } /** - * @param field The field + * @param field The field * @param descending Must be a boolean value as string, e.g. "true", "false" */ public SortCriterion(Field field, String descending) { diff --git a/jablib/src/main/java/org/jabref/model/metadata/SelfContainedSaveOrder.java b/jablib/src/main/java/org/jabref/model/metadata/SelfContainedSaveOrder.java index 4b5cafc6b9c..8568e27533c 100644 --- a/jablib/src/main/java/org/jabref/model/metadata/SelfContainedSaveOrder.java +++ b/jablib/src/main/java/org/jabref/model/metadata/SelfContainedSaveOrder.java @@ -7,7 +7,7 @@ /** * With this class, the user of an instance can directly sort things. Without looking up anything in the preferences or in the UI. - * + *

          * To avoid confusion at the caller, we offer ORIGINAL and SPECIFIED only. Not TABLE. */ public class SelfContainedSaveOrder extends SaveOrder { 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 2a08c962256..002d495e112 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,7 +176,8 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); expectEnd.push("/" + tagName); break; - case "i", "em": + case "i", + "em": formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); expectEnd.push("/" + tagName); break; @@ -232,8 +233,10 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) String key = pair.a; String value = pair.b; switch (key) { - case "target" -> UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); - default -> LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); + case "target" -> + UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); + default -> + LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); } } break; @@ -249,11 +252,11 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) String value = pair.b; switch (key) { case "oo:CharStyleName" -> - // + // settings.addAll(setCharStyleName(value)); case "lang" -> - // - // + // + // settings.addAll(setCharLocale(value)); case "style" -> { // HTML-style small-caps @@ -263,7 +266,8 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) } LOGGER.warn("Unexpected value {} for attribute '{}' for <{}>", value, key, tagName); } - default -> LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); + default -> + LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName); } } formatStack.pushLayer(settings); @@ -327,8 +331,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); xPropertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | - PropertyVetoException | - WrappedTargetException ex) { + PropertyVetoException | + WrappedTargetException ex) { LOGGER.warn("exception caught", ex); } @@ -747,9 +751,9 @@ public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyl propertySet.setPropertyValue(PARA_STYLE_NAME, paragraphStyle); return PASS; } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { return FAIL; } } diff --git a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 8108befdbd3..eab7cdc2ee9 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -82,8 +82,8 @@ List> findFirst(XTextDocument doc, // // We return EQUAL_RANGE RangeOverlapKind kind = equal ? RangeOverlapKind.EQUAL_RANGE - : (touching ? RangeOverlapKind.TOUCH - : RangeOverlapKind.OVERLAP); + : (touching ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP); List valuesForOverlappingRanges = new ArrayList<>(); valuesForOverlappingRanges.add(aHolder); diff --git a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index 25ddd940176..32153678269 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -98,8 +98,8 @@ List> findOverlappingRanges(RangeSort.RangePartitions input, valuesForOverlappingRanges.add(aHolder); valuesForOverlappingRanges.add(bHolder); result.add(new RangeOverlap<>(cmpResult == 0 - ? RangeOverlapKind.TOUCH - : RangeOverlapKind.OVERLAP, + ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP, valuesForOverlappingRanges)); } if (atMost > 0 && result.size() >= atMost) { diff --git a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 074dd0bae13..e030f770954 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -31,7 +31,7 @@ private static class HolderComparatorWithinPartition implements Comparator lookup(BibDatabase database, String public static Optional lookup(List databases, String key) { return databases.stream() - .map(database -> Citation.lookup(database, key)) - .filter(Optional::isPresent) - .map(Optional::get) - .findFirst(); + .map(database -> Citation.lookup(database, key)) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); } public void lookupInDatabases(List databases) { diff --git a/jablib/src/main/java/org/jabref/model/openoffice/style/CitationType.java b/jablib/src/main/java/org/jabref/model/openoffice/style/CitationType.java index 55c1d7c50ed..2fec0f29e62 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/style/CitationType.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/style/CitationType.java @@ -11,8 +11,11 @@ public enum CitationType { public boolean inParenthesis() { return switch (this) { - case AUTHORYEAR_PAR, INVISIBLE_CIT -> true; - case AUTHORYEAR_INTEXT -> false; + case AUTHORYEAR_PAR, + INVISIBLE_CIT -> + true; + case AUTHORYEAR_INTEXT -> + false; }; } diff --git a/jablib/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java b/jablib/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java index a5afedede80..d0da2bfdbd7 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java @@ -21,7 +21,7 @@ public class CitedKeys { } /** - * The cited keys in their current order. + * The cited keys in their current order. */ public List values() { return new ArrayList<>(data.values()); diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index 2bca7a1ff19..32a7c39b5a8 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -19,8 +19,8 @@ private UnoCursor() { */ public static Optional getViewCursor(XTextDocument doc) { return UnoTextDocument.getCurrentController(doc) - .flatMap(e -> UnoCast.cast(XTextViewCursorSupplier.class, e)) - .map(XTextViewCursorSupplier::getViewCursor); + .flatMap(e -> UnoCast.cast(XTextViewCursorSupplier.class, e)) + .map(XTextViewCursorSupplier::getViewCursor); } /** diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index 702f5518171..65d13bfd8ec 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -34,12 +34,12 @@ static XNamed insertNamedTextContent(String service, DocumentAnnotation document } XNamed xNamed = UnoCast.cast(XNamed.class, xObject) - .orElseThrow(() -> new IllegalArgumentException("Service is not an XNamed")); + .orElseThrow(() -> new IllegalArgumentException("Service is not an XNamed")); xNamed.setName(documentAnnotation.name()); // get XTextContent interface XTextContent xTextContent = UnoCast.cast(XTextContent.class, xObject) - .orElseThrow(() -> new IllegalArgumentException("Service is not an XTextContent")); + .orElseThrow(() -> new IllegalArgumentException("Service is not an XTextContent")); documentAnnotation.range().getText().insertTextContent(documentAnnotation.range(), xTextContent, documentAnnotation.absorb()); return xNamed; } diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java index bca3d90ab6c..8d8e5268d64 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java @@ -28,7 +28,7 @@ public static Optional asPropertySet(XPropertyContainer propertyCo public static Optional getPropertySetInfo(XPropertySet propertySet) { return Optional.ofNullable(propertySet) - .flatMap(e -> Optional.ofNullable(e.getPropertySetInfo())); + .flatMap(e -> Optional.ofNullable(e.getPropertySetInfo())); } public static Optional getPropertySetInfo(XPropertyContainer propertyContainer) { @@ -38,8 +38,8 @@ public static Optional getPropertySetInfo(XPropertyContainer p public static List getPropertyNames(Property[] properties) { Objects.requireNonNull(properties); return Arrays.stream(properties) - .map(p -> p.Name) - .collect(Collectors.toList()); + .map(p -> p.Name) + .collect(Collectors.toList()); } public static List getPropertyNames(XPropertySetInfo propertySetInfo) { diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index 0b9f2adc6c0..446e9d1539c 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -101,7 +101,7 @@ public static Optional getAnchor(XTextDocument doc, String name) NoDocumentException, WrappedTargetException { return UnoReferenceMark.getAsTextContent(doc, name) - .map(XTextContent::getAnchor); + .map(XTextContent::getAnchor); } /** diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java index 200f7be55df..9884805d6fb 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java @@ -79,8 +79,8 @@ public static Optional getFrameTitle(XTextDocument doc) { static Optional getDocumentProperties(XTextDocument doc) { return Optional.ofNullable(doc) - .flatMap(e -> UnoCast.cast(XDocumentPropertiesSupplier.class, e)) - .map(XDocumentPropertiesSupplier::getDocumentProperties); + .flatMap(e -> UnoCast.cast(XDocumentPropertiesSupplier.class, e)) + .map(XDocumentPropertiesSupplier::getDocumentProperties); } } diff --git a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index 9de5e149130..27d55452ce2 100644 --- a/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/jablib/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -18,7 +18,7 @@ private UnoUndo() { public static Optional getXUndoManager(XTextDocument doc) { // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html return UnoCast.cast(XUndoManagerSupplier.class, doc) - .map(XUndoManagerSupplier::getUndoManager); + .map(XUndoManagerSupplier::getUndoManager); } /** 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 647208d6fe3..5551a7c23e6 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 @@ -40,8 +40,8 @@ public static Optional getPropertyContainer(XTextDocument do public static List getListOfNames(XTextDocument doc) { return UnoUserDefinedProperty.getPropertyContainer(doc) - .map(UnoProperties::getPropertyNames) - .orElse(new ArrayList<>()); + .map(UnoProperties::getPropertyNames) + .orElse(new ArrayList<>()); } /** @@ -53,7 +53,7 @@ public static Optional getStringValue(XTextDocument doc, String property throws WrappedTargetException { Optional propertySet = UnoUserDefinedProperty.getPropertyContainer(doc) - .flatMap(UnoProperties::asPropertySet); + .flatMap(UnoProperties::asPropertySet); if (propertySet.isEmpty()) { throw new java.lang.IllegalArgumentException("getting UserDefinedProperties as XPropertySet failed"); } diff --git a/jablib/src/main/java/org/jabref/model/schema/DublinCoreSchemaCustom.java b/jablib/src/main/java/org/jabref/model/schema/DublinCoreSchemaCustom.java index c9e8ca15d3d..7a9358d6fab 100644 --- a/jablib/src/main/java/org/jabref/model/schema/DublinCoreSchemaCustom.java +++ b/jablib/src/main/java/org/jabref/model/schema/DublinCoreSchemaCustom.java @@ -14,8 +14,8 @@ import org.slf4j.LoggerFactory; /** - * A DublinCoreSchema extension Class. - * In case anyone intends to alter standard behaviour. + * A DublinCoreSchema extension Class. + * In case anyone intends to alter standard behaviour. */ @StructuredType(preferedPrefix = "dc", namespace = "http://purl.org/dc/elements/1.1/") public class DublinCoreSchemaCustom extends DublinCoreSchema { @@ -44,8 +44,8 @@ public static DublinCoreSchema copyDublinCoreSchema(DublinCoreSchema dcSchema) { } /** - * Overloaded XMP Schema method - * Behaviour is same except when seqName is "Date". Will return raw value instead + * Overloaded XMP Schema method + * Behaviour is same except when seqName is "Date". Will return raw value instead */ @Override public List getUnqualifiedSequenceValueList(String seqName) { @@ -53,10 +53,10 @@ public List getUnqualifiedSequenceValueList(String seqName) { if (abstractProperty instanceof ArrayProperty property) { if ("date".equals(seqName)) { return property.getContainer() - .getAllProperties() - .stream() - .map(field -> (String) ((DateType) field).getRawValue()) - .collect(Collectors.toList()); + .getAllProperties() + .stream() + .map(field -> (String) ((DateType) field).getRawValue()) + .collect(Collectors.toList()); } return property.getElementsAsString(); } diff --git a/jablib/src/main/java/org/jabref/model/search/PostgreConstants.java b/jablib/src/main/java/org/jabref/model/search/PostgreConstants.java index 209e41de192..d2fa027ec6f 100644 --- a/jablib/src/main/java/org/jabref/model/search/PostgreConstants.java +++ b/jablib/src/main/java/org/jabref/model/search/PostgreConstants.java @@ -13,44 +13,44 @@ public enum PostgreConstants { public static final List POSTGRES_FUNCTIONS = List.of( // HTML highlighting function """ - CREATE OR REPLACE FUNCTION regexp_mark(string text, pattern text) - RETURNS text - LANGUAGE plpgsql - AS - $$ - BEGIN - RETURN regexp_replace(string, format('(%s)', pattern), '\\1', 'gi'); - END - $$; - """, + CREATE OR REPLACE FUNCTION regexp_mark(string text, pattern text) + RETURNS text + LANGUAGE plpgsql + AS + $$ + BEGIN + RETURN regexp_replace(string, format('(%s)', pattern), '\\1', 'gi'); + END + $$; + """, // Extract positions of a pattern in a string // Source: https://www.postgresql.org/message-id/flat/0aabac3c-9049-4c55-a82d-a70c5ba43d4d%40www.fastmail.com """ - CREATE OR REPLACE FUNCTION regexp_positions(string text, pattern text, OUT start_pos integer, OUT end_pos integer) - RETURNS SETOF RECORD - LANGUAGE plpgsql - AS - $$ - DECLARE - match text; - remainder text := string; - len integer; - pos integer; - BEGIN - end_pos := 0; - FOR match IN SELECT (regexp_matches(string, format('(%s)', pattern), 'gi'))[1] LOOP - len := length(match); - pos := position(match in remainder); - start_pos := pos + end_pos; - end_pos := start_pos + len - 1; - RETURN NEXT; - remainder := right(remainder, 1 - len - pos); - END LOOP; - RETURN; - END - $$; - """ + CREATE OR REPLACE FUNCTION regexp_positions(string text, pattern text, OUT start_pos integer, OUT end_pos integer) + RETURNS SETOF RECORD + LANGUAGE plpgsql + AS + $$ + DECLARE + match text; + remainder text := string; + len integer; + pos integer; + BEGIN + end_pos := 0; + FOR match IN SELECT (regexp_matches(string, format('(%s)', pattern), 'gi'))[1] LOOP + len := length(match); + pos := position(match in remainder); + start_pos := pos + end_pos; + end_pos := start_pos + len - 1; + RETURN NEXT; + remainder := right(remainder, 1 - len - pos); + END LOOP; + RETURN; + END + $$; + """ ); private final String value; 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 0b75385d9d6..ff87fb5cc72 100644 --- a/jablib/src/main/java/org/jabref/model/strings/StringUtil.java +++ b/jablib/src/main/java/org/jabref/model/strings/StringUtil.java @@ -140,7 +140,7 @@ public static String shaveString(String toShave) { * String[] s = "ab/cd/ed".split("/"); join(s, "\\", 0, s.length) -> * "ab\\cd\\ed" * - * @param to Excluding strings[to] + * @param to Excluding strings[to] */ public static String join(String[] strings, String separator, int from, int to) { if ((strings.length == 0) || (from >= to)) { diff --git a/jablib/src/main/java/org/jabref/model/study/Study.java b/jablib/src/main/java/org/jabref/model/study/Study.java index 95561cde2cc..e96e0171360 100644 --- a/jablib/src/main/java/org/jabref/model/study/Study.java +++ b/jablib/src/main/java/org/jabref/model/study/Study.java @@ -11,9 +11,9 @@ /** * This class represents a scientific study. - * + *

          * This class defines all aspects of a scientific study relevant to the application. It is a proxy for the file based study definition. - * + *

          * The file is parsed using by {@link StudyYamlParser} */ @JsonPropertyOrder({"authors", "title", "research-questions", "queries", "databases"}) diff --git a/jablib/src/main/java/org/jabref/model/texparser/Citation.java b/jablib/src/main/java/org/jabref/model/texparser/Citation.java index 87911525e5a..4aca130f01b 100644 --- a/jablib/src/main/java/org/jabref/model/texparser/Citation.java +++ b/jablib/src/main/java/org/jabref/model/texparser/Citation.java @@ -33,8 +33,8 @@ public String getContext() { int lineLength = lineText.length(); int start = Math.max(0, center + CONTEXT_WIDTH / 2 < lineLength - ? center - CONTEXT_WIDTH / 2 - : lineLength - CONTEXT_WIDTH); + ? center - CONTEXT_WIDTH / 2 + : lineLength - CONTEXT_WIDTH); int end = Math.min(lineLength, start + CONTEXT_WIDTH); // Add three dots when the string does not contain all the line. diff --git a/jablib/src/main/java/org/jabref/model/util/FileUpdateMonitor.java b/jablib/src/main/java/org/jabref/model/util/FileUpdateMonitor.java index 9575bf3a8d5..8c0d57aea07 100644 --- a/jablib/src/main/java/org/jabref/model/util/FileUpdateMonitor.java +++ b/jablib/src/main/java/org/jabref/model/util/FileUpdateMonitor.java @@ -27,7 +27,7 @@ public interface FileUpdateMonitor { boolean isActive(); /** - * stops watching for changes + * stops watching for changes */ void shutdown(); } diff --git a/jablib/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java b/jablib/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java index d68edb877c5..17152cb3ce2 100644 --- a/jablib/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java @@ -608,12 +608,12 @@ void filenameIsUnmodifiedDuringWrite() throws Exception { void addFieldWithLongerLength() throws Exception { String bibtexEntry = """ - @Article{test, - author = {BlaBla}, - journal = {International Journal of Something}, - number = {1}, - note = {some note}, - }""".replace("\n", OS.NEWLINE); + @Article{test, + author = {BlaBla}, + journal = {International Journal of Something}, + number = {1}, + note = {some note}, + }""".replace("\n", OS.NEWLINE); BibEntry entry = firstEntryFrom(bibtexEntry); // modify entry @@ -623,14 +623,14 @@ void addFieldWithLongerLength() throws Exception { bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX); String expected = """ - @Article{test, - author = {BlaBla}, - journal = {International Journal of Something}, - note = {some note}, - number = {1}, - howpublished = {asdf}, - } - """.replace("\n", OS.NEWLINE); + @Article{test, + author = {BlaBla}, + journal = {International Journal of Something}, + note = {some note}, + number = {1}, + howpublished = {asdf}, + } + """.replace("\n", OS.NEWLINE); assertEquals(expected, stringWriter.toString()); } @@ -643,10 +643,10 @@ void doNotWriteEmptyFields() throws IOException { bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX); String expected = """ - @Article{, - note = {some note}, - } - """.replace("\n", OS.NEWLINE); + @Article{, + note = {some note}, + } + """.replace("\n", OS.NEWLINE); assertEquals(expected, stringWriter.toString()); } diff --git a/jablib/src/test/java/org/jabref/logic/bibtex/FieldWriterTest.java b/jablib/src/test/java/org/jabref/logic/bibtex/FieldWriterTest.java index f9e7753232d..5728f0a47c1 100644 --- a/jablib/src/test/java/org/jabref/logic/bibtex/FieldWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/bibtex/FieldWriterTest.java @@ -45,7 +45,7 @@ static Stream keepHashSignInComment() { ), // source: https://github.com/JabRef/jabref/issues/8303 --> bug2.txt Arguments.of("Particularly, we equip SOVA – a Semantic and Ontological Variability Analysis method") - ); + ); } @BeforeEach diff --git a/jablib/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java b/jablib/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java index ff086d9b661..24644f04670 100644 --- a/jablib/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java @@ -37,10 +37,10 @@ void quoteNull() { private static Stream getEncodingTestData() { return Stream.of( - Arguments.of("a:b;c:d", new String[][]{{"a", "b"}, {"c", "d"}}), - Arguments.of("a:;c:d", new String[][]{{"a", ""}, {"c", "d"}}), - Arguments.of("a:" + null + ";c:d", new String[][]{{"a", null}, {"c", "d"}}), - Arguments.of("a:\\:b;c\\;:d", new String[][]{{"a", ":b"}, {"c;", "d"}}) + Arguments.of("a:b;c:d", new String[][] {{"a", "b"}, {"c", "d"}}), + Arguments.of("a:;c:d", new String[][] {{"a", ""}, {"c", "d"}}), + Arguments.of("a:" + null + ";c:d", new String[][] {{"a", null}, {"c", "d"}}), + Arguments.of("a:\\:b;c\\;:d", new String[][] {{"a", ":b"}, {"c;", "d"}}) ); } diff --git a/jablib/src/test/java/org/jabref/logic/bibtex/comparator/EntryComparatorTest.java b/jablib/src/test/java/org/jabref/logic/bibtex/comparator/EntryComparatorTest.java index c8c44802d81..f8085fd7df1 100644 --- a/jablib/src/test/java/org/jabref/logic/bibtex/comparator/EntryComparatorTest.java +++ b/jablib/src/test/java/org/jabref/logic/bibtex/comparator/EntryComparatorTest.java @@ -133,25 +133,25 @@ void compareWithMixedLineEndings() { @Test void withAuthorIsBeforeWithEmptyAuthorWhenSortingWithNonExistentKey() { BibEntry e1 = new BibEntry() - .withField(StandardField.AUTHOR, "Stephen King"); + .withField(StandardField.AUTHOR, "Stephen King"); BibEntry e2 = new BibEntry() - .withField(StandardField.AUTHOR, ""); + .withField(StandardField.AUTHOR, ""); assertEquals(-1, new EntryComparator(true, false, InternalField.KEY_FIELD).compare(e1, e2)); } @Test void withAuthorIsBeforeEmptyAuthorWhenSortingWithAuthor() { BibEntry e1 = new BibEntry() - .withField(StandardField.AUTHOR, "Stephen King"); + .withField(StandardField.AUTHOR, "Stephen King"); BibEntry e2 = new BibEntry() - .withField(StandardField.AUTHOR, ""); + .withField(StandardField.AUTHOR, ""); assertEquals(-1, new EntryComparator(true, false, StandardField.AUTHOR).compare(e1, e2)); } @Test void withAuthorIsBeforeWithoutAuthorWhenSortingWithAuthor() { BibEntry e1 = new BibEntry() - .withField(StandardField.AUTHOR, "Stephen King"); + .withField(StandardField.AUTHOR, "Stephen King"); BibEntry e2 = new BibEntry(); assertEquals(1, new EntryComparator(false, false, StandardField.AUTHOR).compare(e1, e2)); } diff --git a/jablib/src/test/java/org/jabref/logic/bst/util/BstTextPrefixerTest.java b/jablib/src/test/java/org/jabref/logic/bst/util/BstTextPrefixerTest.java index 8f35589c639..a11828d9b1b 100644 --- a/jablib/src/test/java/org/jabref/logic/bst/util/BstTextPrefixerTest.java +++ b/jablib/src/test/java/org/jabref/logic/bst/util/BstTextPrefixerTest.java @@ -8,22 +8,22 @@ public class BstTextPrefixerTest { @ParameterizedTest @CsvSource({ - "i, i", - "0I~ , 0I~ ", - "Hi Hi, Hi Hi ", - "{\\oe}, {\\oe}", - "Hi {\\oe }H, Hi {\\oe }Hi ", - "Jonat, Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin", - "{\\'e}, {\\'e}", - "{\\'{E}}doua, {\\'{E}}douard Masterly", - "Ulric, Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot", - "abcd{e}, abcd{efg}hi", - "ab{cd}e, ab{cd}efghi", - "ab{cd}e, ab{cd}efghi{}", - "Hi {{\\o}}, Hi {{\\oe }}Hi ", - "Hi {\\{oe }}H, Hi {\\{oe }}Hi ", - "Hi {\\\"oe }H, Hi {\\\"oe }Hi ", - "Hi {\\{\\oe }}H, Hi {\\{\\oe }}Hi " + "i, i", + "0I~ , 0I~ ", + "Hi Hi, Hi Hi ", + "{\\oe}, {\\oe}", + "Hi {\\oe }H, Hi {\\oe }Hi ", + "Jonat, Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin", + "{\\'e}, {\\'e}", + "{\\'{E}}doua, {\\'{E}}douard Masterly", + "Ulric, Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot", + "abcd{e}, abcd{efg}hi", + "ab{cd}e, ab{cd}efghi", + "ab{cd}e, ab{cd}efghi{}", + "Hi {{\\o}}, Hi {{\\oe }}Hi ", + "Hi {\\{oe }}H, Hi {\\{oe }}Hi ", + "Hi {\\\"oe }H, Hi {\\\"oe }Hi ", + "Hi {\\{\\oe }}H, Hi {\\{\\oe }}Hi " }) void assertPrefix(final String expectedResult, final String toPrefixInput) { assertEquals(expectedResult, BstTextPrefixer.textPrefix(5, toPrefixInput)); diff --git a/jablib/src/test/java/org/jabref/logic/citation/SearchCitationsRelationsServiceTest.java b/jablib/src/test/java/org/jabref/logic/citation/SearchCitationsRelationsServiceTest.java index 00ccf3a124e..ea64c42cf9f 100644 --- a/jablib/src/test/java/org/jabref/logic/citation/SearchCitationsRelationsServiceTest.java +++ b/jablib/src/test/java/org/jabref/logic/citation/SearchCitationsRelationsServiceTest.java @@ -88,7 +88,8 @@ void serviceShouldCallTheFetcherForCitationsWhenRepositoryIsUpdatable() throws F _ -> citationsToReturn, citationsDatabase::put, List::of, - (_, _) -> { }, + (_, _) -> { + }, _ -> true, _ -> false ); @@ -169,7 +170,8 @@ void serviceShouldCallTheFetcherForReferencesWhenRepositoryIsUpdatable() throws CitationFetcher fetcher = createMockFetcher(referencer, null, referencesToReturn, null); BibEntryCitationsAndReferencesRepository repository = BibEntryRelationsRepositoryTestHelpers.Mocks.from( List::of, - (_, _) -> { }, + (_, _) -> { + }, _ -> referencesToReturn, referencesDatabase::put, _ -> false, diff --git a/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShellTest.java b/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShellTest.java index a20ef003112..33fc59e7e09 100644 --- a/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShellTest.java +++ b/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryCitationsAndReferencesRepositoryShellTest.java @@ -16,22 +16,22 @@ class BibEntryCitationsAndReferencesRepositoryShellTest { private static BibEntry createBibEntry() { int i = RandomGenerator.getDefault().nextInt(); return new BibEntry() - .withCitationKey(String.valueOf(i)) - .withField(StandardField.DOI, "10.1234/5678" + i); + .withCitationKey(String.valueOf(i)) + .withField(StandardField.DOI, "10.1234/5678" + i); } private static List createRelations(BibEntry entry) { return entry - .getCitationKey() - .map(key -> RandomGenerator - .StreamableGenerator.of("L128X256MixRandom").ints(150) - .mapToObj(i -> new BibEntry() - .withCitationKey("%s relation %s".formatted(key, i)) - .withField(StandardField.DOI, "10.2345/6789" + i) + .getCitationKey() + .map(key -> RandomGenerator + .StreamableGenerator.of("L128X256MixRandom").ints(150) + .mapToObj(i -> new BibEntry() + .withCitationKey("%s relation %s".formatted(key, i)) + .withField(StandardField.DOI, "10.2345/6789" + i) + ) ) - ) - .orElseThrow() - .toList(); + .orElseThrow() + .toList(); } private static class BibEntryRelationRepositoryMock implements BibEntryRelationRepository { @@ -66,8 +66,8 @@ void repositoryShouldWriteAndReadCitationsToAndFromExpectedDAO() { List citations = createRelations(bibEntry); BibEntryRelationRepositoryMock citationsDAO = new BibEntryRelationRepositoryMock(); BibEntryCitationsAndReferencesRepositoryShell bibEntryRelationsRepository = new BibEntryCitationsAndReferencesRepositoryShell( - citationsDAO, - new BibEntryRelationRepositoryMock() + citationsDAO, + new BibEntryRelationRepositoryMock() ); Assertions.assertFalse(bibEntryRelationsRepository.containsCitations(bibEntry)); Assertions.assertFalse(citations.isEmpty()); diff --git a/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryRelationsRepositoryTestHelpers.java b/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryRelationsRepositoryTestHelpers.java index 1fe6cf42c8b..30b09e592b4 100644 --- a/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryRelationsRepositoryTestHelpers.java +++ b/jablib/src/test/java/org/jabref/logic/citation/repository/BibEntryRelationsRepositoryTestHelpers.java @@ -20,12 +20,12 @@ public class BibEntryRelationsRepositoryTestHelpers { */ public static class Mocks { public static BibEntryCitationsAndReferencesRepository from( - Function> retrieveCitations, - BiConsumer> insertCitations, - Function> retrieveReferences, - BiConsumer> insertReferences, - Function isCitationsUpdatable, - Function isReferencesUpdatable + Function> retrieveCitations, + BiConsumer> insertCitations, + Function> retrieveReferences, + BiConsumer> insertReferences, + Function isCitationsUpdatable, + Function isReferencesUpdatable ) { return new BibEntryCitationsAndReferencesRepository() { @Override @@ -76,7 +76,7 @@ public void close() { } public static BibEntryCitationsAndReferencesRepository from( - Map> citationsDB, Map> referencesDB, boolean isCitationsUpdatable + Map> citationsDB, Map> referencesDB, boolean isCitationsUpdatable ) { return new BibEntryCitationsAndReferencesRepository() { @Override diff --git a/jablib/src/test/java/org/jabref/logic/citation/repository/MVStoreBibEntryRelationRepositoryTest.java b/jablib/src/test/java/org/jabref/logic/citation/repository/MVStoreBibEntryRelationRepositoryTest.java index d7f057b97d9..36aa98d3941 100644 --- a/jablib/src/test/java/org/jabref/logic/citation/repository/MVStoreBibEntryRelationRepositoryTest.java +++ b/jablib/src/test/java/org/jabref/logic/citation/repository/MVStoreBibEntryRelationRepositoryTest.java @@ -70,14 +70,14 @@ void closeStore() { private static Stream createBibEntries() { return IntStream - .range(0, 150) - .mapToObj(MVStoreBibEntryRelationRepositoryTest::createBibEntry); + .range(0, 150) + .mapToObj(MVStoreBibEntryRelationRepositoryTest::createBibEntry); } private static BibEntry createBibEntry(int i) { return new BibEntry() - .withCitationKey(String.valueOf(i)) - .withField(StandardField.DOI, "10.1234/5678" + i); + .withCitationKey(String.valueOf(i)) + .withField(StandardField.DOI, "10.1234/5678" + i); } /** @@ -90,19 +90,19 @@ private static BibEntry createBibEntry(int i) { */ private List createRelations(BibEntry entry) { return entry - .getCitationKey() - .map(key -> RandomGenerator.StreamableGenerator - .of("L128X256MixRandom").ints(150) - .mapToObj(i -> new BibEntry(StandardEntryType.Book) - .withField(StandardField.TITLE, "A title: " + i) - .withField(StandardField.YEAR, String.valueOf(2024)) - .withField(StandardField.AUTHOR, "{A list of authors: " + i + "}") - .withField(StandardField.DOI, entry.getDOI().map(DOI::asString).orElse("") + ":" + i) - .withField(StandardField.ABSTRACT, "The Universe is expanding: " + i) + .getCitationKey() + .map(key -> RandomGenerator.StreamableGenerator + .of("L128X256MixRandom").ints(150) + .mapToObj(i -> new BibEntry(StandardEntryType.Book) + .withField(StandardField.TITLE, "A title: " + i) + .withField(StandardField.YEAR, String.valueOf(2024)) + .withField(StandardField.AUTHOR, "{A list of authors: " + i + "}") + .withField(StandardField.DOI, entry.getDOI().map(DOI::asString).orElse("") + ":" + i) + .withField(StandardField.ABSTRACT, "The Universe is expanding: " + i) + ) ) - ) - .orElseThrow() - .toList(); + .orElseThrow() + .toList(); } @ParameterizedTest @@ -123,9 +123,9 @@ void DAOShouldMergeRelationsWhenInserting(BibEntry bibEntry) { // THEN List uniqueRelations = Stream - .concat(firstRelations.stream(), secondRelations.stream()) - .distinct() - .toList(); + .concat(firstRelations.stream(), secondRelations.stream()) + .distinct() + .toList(); assertFalse(uniqueRelations.isEmpty()); assertNotSame(uniqueRelations, relationFromCache); assertEquals(uniqueRelations, relationFromCache); @@ -178,8 +178,8 @@ void shouldUpdateShouldReturnTrueAfterOneWeek(BibEntry entry) { // THEN assertFalse(dao.shouldUpdate(entry, clock)); Clock clockOneWeekAfter = Clock.fixed( - LocalDateTime.now(ZoneId.of("UTC")).plusWeeks(1).plusSeconds(1).toInstant(ZoneOffset.UTC), - ZoneId.of("UTC") + LocalDateTime.now(ZoneId.of("UTC")).plusWeeks(1).plusSeconds(1).toInstant(ZoneOffset.UTC), + ZoneId.of("UTC") ); assertTrue(dao.shouldUpdate(entry, clockOneWeekAfter)); } diff --git a/jablib/src/test/java/org/jabref/logic/citationkeypattern/BracketedPatternTest.java b/jablib/src/test/java/org/jabref/logic/citationkeypattern/BracketedPatternTest.java index 85b4e406c73..a947a1c7d66 100644 --- a/jablib/src/test/java/org/jabref/logic/citationkeypattern/BracketedPatternTest.java +++ b/jablib/src/test/java/org/jabref/logic/citationkeypattern/BracketedPatternTest.java @@ -25,7 +25,7 @@ /** * Tests based on a BibEntry are contained in {@link CitationKeyGeneratorTest} - * + *

          * "Complete" entries are tested at {@link org.jabref.logic.citationkeypattern.MakeLabelWithDatabaseTest} */ @Execution(ExecutionMode.CONCURRENT) @@ -624,7 +624,6 @@ void expandBracketsDoesNotTruncateWithoutAnArgumentToTruncateModifier() { "'CamelTitleFormatter', 'cAMEL tITLE fORMATTER'", "'C', 'c'" }) - void expandBracketsCamelTitleModifier(String expectedCitationKey, String title) { BibEntry bibEntry = new BibEntry() .withField(StandardField.TITLE, title); @@ -641,7 +640,6 @@ void expandBracketsCamelTitleModifier(String expectedCitationKey, String title) "'V', 'V'", "'V', 'A v'" }) - void expandBracketsVeryShortTitleModifier(String expectedCitationKey, String title) { BibEntry bibEntry = new BibEntry() .withField(StandardField.TITLE, title); @@ -659,7 +657,6 @@ void expandBracketsVeryShortTitleModifier(String expectedCitationKey, String tit "'Title', 'A title'", "'Title', 'A Title'" }) - void expandBracketsShortTitleModifier(String expectedCitationKey, String title) { BibEntry bibEntry = new BibEntry() .withField(StandardField.TITLE, title); @@ -853,7 +850,6 @@ void expandBracketsWithoutProtectiveBracesUsingUnprotectTermsModifier() { "'EUASA', '[editors]', '{European Union Aviation Safety Agency}'" }) - void editorFieldMarkers(String expectedCitationKey, String pattern, String editor) { BibEntry bibEntry = new BibEntry().withField(StandardField.EDITOR, editor); BracketedPattern bracketedPattern = new BracketedPattern(pattern); @@ -862,22 +858,21 @@ void editorFieldMarkers(String expectedCitationKey, String pattern, String edito @ParameterizedTest @CsvSource({ - "'', ''", - "The Attributed Graph Grammar System ({AGG}),AGG", - "'The University of Science',UniScience", - "'School of Business, Department of Management',BM", - "'Graph Systems Research Group',GSRG", - "'The Great Institute, 123 Main Street, Springfield',GreatInstitute", - "'Invalid {\\Unicode}',Invalid", - "'School of Electrical Engineering ({SEE}), Department of Computer Science',SEE", - "'{The Attributed Graph Grammar System ({AGG})}',AGG", - "'{The Attributed Graph Grammar System}',AGGS", - "'{University of Example, Department of Computer Science, Some Address}',UniExampleCS", - "'{Example School of Engineering, Department of Computer Science, Some Address}',SomeAddressEECS", - "'{Example Institute, Computer Science Department, Some Address}',ExampleInstituteCS", - "'{Short Part, Some Address}',ShortPart", - "'{Example with Several Tokens, Some Address}',EST"}) - + "'', ''", + "The Attributed Graph Grammar System ({AGG}),AGG", + "'The University of Science',UniScience", + "'School of Business, Department of Management',BM", + "'Graph Systems Research Group',GSRG", + "'The Great Institute, 123 Main Street, Springfield',GreatInstitute", + "'Invalid {\\Unicode}',Invalid", + "'School of Electrical Engineering ({SEE}), Department of Computer Science',SEE", + "'{The Attributed Graph Grammar System ({AGG})}',AGG", + "'{The Attributed Graph Grammar System}',AGGS", + "'{University of Example, Department of Computer Science, Some Address}',UniExampleCS", + "'{Example School of Engineering, Department of Computer Science, Some Address}',SomeAddressEECS", + "'{Example Institute, Computer Science Department, Some Address}',ExampleInstituteCS", + "'{Short Part, Some Address}',ShortPart", + "'{Example with Several Tokens, Some Address}',EST"}) void generateInstitutionKeyTest(String input, String expected) { assertEquals(expected, BracketedPattern.generateInstitutionKey(input)); } diff --git a/jablib/src/test/java/org/jabref/logic/citationkeypattern/CitationKeyGeneratorTest.java b/jablib/src/test/java/org/jabref/logic/citationkeypattern/CitationKeyGeneratorTest.java index 1f0d0fedf24..5283f4db933 100644 --- a/jablib/src/test/java/org/jabref/logic/citationkeypattern/CitationKeyGeneratorTest.java +++ b/jablib/src/test/java/org/jabref/logic/citationkeypattern/CitationKeyGeneratorTest.java @@ -26,7 +26,7 @@ /** * Tests whole citation key patterns such as [authorsAlpha][year]. * The concrete patterns such as authorsAlpha should better be tested at {@link BracketedPatternTest}. - * + *

          * Concurrent execution leads to issues on GitHub actions. */ class CitationKeyGeneratorTest { @@ -234,7 +234,7 @@ void university() throws ParseException { * not tested/ not in hashmap UNICODE_CHARS: * {@code * Ł ł Ő ő Ű ű Ŀ ŀ Ħ ħ Ð ð Þ þ Œ œ Æ æ Ø ø Å å Ə ə Đ đ Ů ů Ǣ ǣ ǖ ǘ ǚ ǜ - * Ǣ ǣ ǖ ǘ ǚ ǜ + * Ǣ ǣ ǖ ǘ ǚ ǜ * Đ đ Ů ů * Ł ł Ő ő Ű ű Ŀ ŀ Ħ ħ Ð ð Þ þ Œ œ Æ æ Ø ø Å å Ə ə * } diff --git a/jablib/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithoutDatabaseTest.java b/jablib/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithoutDatabaseTest.java index 61d98eccb92..024522a5a96 100644 --- a/jablib/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithoutDatabaseTest.java +++ b/jablib/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithoutDatabaseTest.java @@ -43,8 +43,8 @@ void setUp() { void makeAuthorLabelForFileSearch() { BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, "John Doe") - .withField(StandardField.YEAR, "2016") - .withField(StandardField.TITLE, "An awesome paper on JabRef"); + .withField(StandardField.YEAR, "2016") + .withField(StandardField.TITLE, "An awesome paper on JabRef"); String label = citationKeyGenerator.generateKey(entry); assertEquals("Doe", label); diff --git a/jablib/src/test/java/org/jabref/logic/citationstyle/CitationStyleCacheTest.java b/jablib/src/test/java/org/jabref/logic/citationstyle/CitationStyleCacheTest.java index faff4fe5f48..7739d13a6fa 100644 --- a/jablib/src/test/java/org/jabref/logic/citationstyle/CitationStyleCacheTest.java +++ b/jablib/src/test/java/org/jabref/logic/citationstyle/CitationStyleCacheTest.java @@ -12,20 +12,20 @@ class CitationStyleCacheTest { - private BibEntry bibEntry; - private List entries; - private BibDatabase database; - private BibDatabaseContext databaseContext; - private CitationStyleCache csCache; - - @Test - void getCitationForTest() { - BibEntry bibEntry = new BibEntry().withCitationKey("test"); - List entries = List.of(bibEntry); - BibDatabase database = new BibDatabase(entries); - BibDatabaseContext databaseContext = new BibDatabaseContext(database); - CitationStyleCache csCache = new CitationStyleCache(databaseContext); - - assertNotNull(csCache.getCitationFor(bibEntry)); - } + private BibEntry bibEntry; + private List entries; + private BibDatabase database; + private BibDatabaseContext databaseContext; + private CitationStyleCache csCache; + + @Test + void getCitationForTest() { + BibEntry bibEntry = new BibEntry().withCitationKey("test"); + List entries = List.of(bibEntry); + BibDatabase database = new BibDatabase(entries); + BibDatabaseContext databaseContext = new BibDatabaseContext(database); + CitationStyleCache csCache = new CitationStyleCache(databaseContext); + + assertNotNull(csCache.getCitationFor(bibEntry)); + } } diff --git a/jablib/src/test/java/org/jabref/logic/cleanup/DoiCleanupTest.java b/jablib/src/test/java/org/jabref/logic/cleanup/DoiCleanupTest.java index 062183766e8..3751d46cf4a 100644 --- a/jablib/src/test/java/org/jabref/logic/cleanup/DoiCleanupTest.java +++ b/jablib/src/test/java/org/jabref/logic/cleanup/DoiCleanupTest.java @@ -42,13 +42,13 @@ private static Stream provideDoiForAllLowers() { // cleanup with Doi and no URL to entries Arguments.of( new BibEntry() - .withField(StandardField.DOI, "10.1145/2594455") - .withField(StandardField.NOTE, "This is a random note to this Doi") - .withField(unknownField, "This is a random ee field for this Doi"), + .withField(StandardField.DOI, "10.1145/2594455") + .withField(StandardField.NOTE, "This is a random note to this Doi") + .withField(unknownField, "This is a random ee field for this Doi"), new BibEntry() - .withField(StandardField.DOI, "10.1145/2594455") - .withField(StandardField.NOTE, "This is a random note to this Doi") - .withField(unknownField, "This is a random ee field for this Doi")), + .withField(StandardField.DOI, "10.1145/2594455") + .withField(StandardField.NOTE, "This is a random note to this Doi") + .withField(unknownField, "This is a random ee field for this Doi")), // cleanup with spaced Doi Arguments.of(doiResult, new BibEntry() @@ -64,8 +64,8 @@ private static Stream provideDoiForAllLowers() { // cleanup of url encoded chars Arguments.of(new BibEntry() - .withField(StandardField.DOI, "10.18726/2018_3"), - new BibEntry() - .withField(unknownField, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3"))); - } + .withField(StandardField.DOI, "10.18726/2018_3"), + new BibEntry() + .withField(unknownField, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3"))); + } } diff --git a/jablib/src/test/java/org/jabref/logic/cleanup/DoiDecodeCleanupTest.java b/jablib/src/test/java/org/jabref/logic/cleanup/DoiDecodeCleanupTest.java index 17b81a8ea29..1669ffbe3c6 100644 --- a/jablib/src/test/java/org/jabref/logic/cleanup/DoiDecodeCleanupTest.java +++ b/jablib/src/test/java/org/jabref/logic/cleanup/DoiDecodeCleanupTest.java @@ -42,13 +42,13 @@ private static Stream provideDoiForAllLowers() { // cleanup with Doi and no URL to entries Arguments.of( new BibEntry() - .withField(StandardField.DOI, "10.18726/2018_3") - .withField(StandardField.NOTE, "This is a random note to this Doi") - .withField(unknownField, "This is a random ee field for this Doi"), + .withField(StandardField.DOI, "10.18726/2018_3") + .withField(StandardField.NOTE, "This is a random note to this Doi") + .withField(unknownField, "This is a random ee field for this Doi"), new BibEntry() - .withField(StandardField.DOI, "10.18726/2018_3") - .withField(StandardField.NOTE, "This is a random note to this Doi") - .withField(unknownField, "This is a random ee field for this Doi")), + .withField(StandardField.DOI, "10.18726/2018_3") + .withField(StandardField.NOTE, "This is a random note to this Doi") + .withField(unknownField, "This is a random ee field for this Doi")), // cleanup with spaced Doi Arguments.of(doiResult, new BibEntry() diff --git a/jablib/src/test/java/org/jabref/logic/cleanup/RemoveLinksToNotExistentFilesTest.java b/jablib/src/test/java/org/jabref/logic/cleanup/RemoveLinksToNotExistentFilesTest.java index 341f6679c26..069ec5dd02a 100644 --- a/jablib/src/test/java/org/jabref/logic/cleanup/RemoveLinksToNotExistentFilesTest.java +++ b/jablib/src/test/java/org/jabref/logic/cleanup/RemoveLinksToNotExistentFilesTest.java @@ -57,8 +57,8 @@ void setUp(@TempDir Path bibFolder) throws IOException { .withField(StandardField.YEAR, "2020") .withField(StandardField.DOI, "10.1109/TII.2019.2935531") .withField(StandardField.FILE, FileFieldWriter.getStringRepresentation(List.of( - new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), - fileField))) + new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), + fileField))) .withField(StandardField.ISSUE, "4") .withField(StandardField.ISSN, "1941-0050") .withField(StandardField.JOURNALTITLE, "IEEE Transactions on Industrial Informatics") @@ -77,10 +77,10 @@ void setUp(@TempDir Path bibFolder) throws IOException { void deleteFileInEntryWithMultipleFileLinks() throws IOException { LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath(), ""); FieldChange expectedChange = new FieldChange(entry, StandardField.FILE, - FileFieldWriter.getStringRepresentation(List.of( - new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), - fileField)), - FileFieldWriter.getStringRepresentation(new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF")) + FileFieldWriter.getStringRepresentation(List.of( + new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), + fileField)), + FileFieldWriter.getStringRepresentation(new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF")) ); BibEntry expectedEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Shatakshi Sharma and Bhim Singh and Sukumar Mishra") @@ -88,7 +88,7 @@ void deleteFileInEntryWithMultipleFileLinks() throws IOException { .withField(StandardField.YEAR, "2020") .withField(StandardField.DOI, "10.1109/TII.2019.2935531") .withField(StandardField.FILE, FileFieldWriter.getStringRepresentation( - new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"))) + new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"))) .withField(StandardField.ISSUE, "4") .withField(StandardField.ISSN, "1941-0050") .withField(StandardField.JOURNALTITLE, "IEEE Transactions on Industrial Informatics") @@ -114,8 +114,8 @@ void keepLinksToExistingFiles() { .withField(StandardField.YEAR, "2020") .withField(StandardField.DOI, "10.1109/TII.2019.2935531") .withField(StandardField.FILE, FileFieldWriter.getStringRepresentation(List.of( - new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), - fileField))) + new LinkedFile("", "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912", "PDF"), + fileField))) .withField(StandardField.ISSUE, "4") .withField(StandardField.ISSN, "1941-0050") .withField(StandardField.JOURNALTITLE, "IEEE Transactions on Industrial Informatics") @@ -138,8 +138,8 @@ void deleteLinkedFile() throws IOException { // There is only one linked file in entry entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); FieldChange expectedChange = new FieldChange(entry, StandardField.FILE, - FileFieldWriter.getStringRepresentation(fileField), - null); + FileFieldWriter.getStringRepresentation(fileField), + null); BibEntry expectedEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Shatakshi Sharma and Bhim Singh and Sukumar Mishra") .withField(StandardField.DATE, "April 2020") diff --git a/jablib/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java b/jablib/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java index aac51081ff8..4be9a20d8c8 100644 --- a/jablib/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/jablib/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -90,10 +90,10 @@ void cleanupRenamePdfRenamesWithMultipleFiles() throws IOException { cleanup.cleanup(entry); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation( - Arrays.asList( - new LinkedFile("", Path.of(""), ""), - new LinkedFile("", Path.of("Toot - test title.tmp"), ""), - new LinkedFile("", Path.of(""), "")))), + Arrays.asList( + new LinkedFile("", Path.of(""), ""), + new LinkedFile("", Path.of("Toot - test title.tmp"), ""), + new LinkedFile("", Path.of(""), "")))), entry.getField(StandardField.FILE)); } diff --git a/jablib/src/test/java/org/jabref/logic/cleanup/URLCleanupTest.java b/jablib/src/test/java/org/jabref/logic/cleanup/URLCleanupTest.java index 6c5ae1b247b..da47bfd2bc2 100644 --- a/jablib/src/test/java/org/jabref/logic/cleanup/URLCleanupTest.java +++ b/jablib/src/test/java/org/jabref/logic/cleanup/URLCleanupTest.java @@ -25,157 +25,157 @@ void changeURL(BibEntry expected, BibEntry urlInputField) { private static Stream provideURL() { return Stream.of( - // Input Note field has two arguments stored , with the latter being a url. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089") - .withField(StandardField.NOTE, - "this is a note"), - new BibEntry().withField(StandardField.NOTE, - "this is a note, \\url{https://hdl.handle.net/10442/hedi/6089}")), - - // Input Note field has two arguments stored, with the former being a url. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089") - .withField(StandardField.NOTE, - "this is a note"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://hdl.handle.net/10442/hedi/6089}, this is a note")), - - // Input Note field has more than one URLs stored. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089") - .withField(StandardField.NOTE, - "\\url{http://142.42.1.1:8080}"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://hdl.handle.net/10442/hedi/6089}, " + // Input Note field has two arguments stored , with the latter being a url. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089") + .withField(StandardField.NOTE, + "this is a note"), + new BibEntry().withField(StandardField.NOTE, + "this is a note, \\url{https://hdl.handle.net/10442/hedi/6089}")), + + // Input Note field has two arguments stored, with the former being a url. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089") + .withField(StandardField.NOTE, + "this is a note"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://hdl.handle.net/10442/hedi/6089}, this is a note")), + + // Input Note field has more than one URLs stored. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089") + .withField(StandardField.NOTE, + "\\url{http://142.42.1.1:8080}"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://hdl.handle.net/10442/hedi/6089}, " + "\\url{http://142.42.1.1:8080}")), - // Input entry holds the same URL both in Note and Url field. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://hdl.handle.net/10442/hedi/6089}") - .withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089")), - - // Input Note field has several values stored. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://example.org") - .withField(StandardField.NOTE, - "cited by Kramer, 2002."), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://example.org}, cited by Kramer, 2002.")), - - /* - * Several input URL types (e.g, not secure protocol, password included for - * authentication, IP address, port etc.) to be correctly identified. - */ - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://hdl.handle.net/10442/hedi/6089"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://hdl.handle.net/10442/hedi/6089}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://hdl.handle.net/10442/hedi/6089"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://hdl.handle.net/10442/hedi/6089}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://userid:password@example.com:8080"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://userid:password@example.com:8080}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://142.42.1.1:8080"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://142.42.1.1:8080}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://☺.damowmow.com"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://☺.damowmow.com}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://www.example.com/foo/?bar=baz&inga=42&quux"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://www.example.com/foo/?bar=baz&inga=42&quux}")), - - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://www.example.com/foo/?bar=baz&inga=42&quux"), - new BibEntry().withField(StandardField.NOTE, - "https://www.example.com/foo/?bar=baz&inga=42&quux")), - - // Expected entry returns formatted the url-date in the Urldate field. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://142.42.1.1:8080") - .withField(StandardField.URLDATE, - "2021-01-15"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021")), - - // Input entry doesn't hold any URL in the Note field. - Arguments.of( - new BibEntry().withField(StandardField.NOTE, - "Accessed on 2015-01-15"), - new BibEntry().withField(StandardField.NOTE, - "Accessed on 2015-01-15")), - - // Input entry has multiple url-dates stored in the Note field. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://142.42.1.1:8080") - .withField(StandardField.URLDATE, - "2021-01-15") - .withField(StandardField.NOTE, - "visited on February 12, 2017"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021, visited on February 12, 2017")), - - // Input entry holds the same url-date in both Note and Urldate field. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "http://142.42.1.1:8080") - .withField(StandardField.URLDATE, - "2015-01-15"), - new BibEntry().withField(StandardField.NOTE, - "\\url{http://142.42.1.1:8080}, visited on 2015.01.15") - .withField(StandardField.URLDATE, - "2015-01-15")), - - // Input Note field has several values stored. - Arguments.of( - new BibEntry().withField(StandardField.URL, - "https://example.org") - .withField(StandardField.URLDATE, - "2023-04-11") - .withField(StandardField.NOTE, - "cited by Kramer"), - new BibEntry().withField(StandardField.NOTE, - "\\url{https://example.org}, cited by Kramer, accessed on 2023-04-11"), - // test with no fields present - Arguments.of( - new BibEntry(), - new BibEntry()) - ) + // Input entry holds the same URL both in Note and Url field. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://hdl.handle.net/10442/hedi/6089}") + .withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089")), + + // Input Note field has several values stored. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://example.org") + .withField(StandardField.NOTE, + "cited by Kramer, 2002."), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://example.org}, cited by Kramer, 2002.")), + + /* + * Several input URL types (e.g, not secure protocol, password included for + * authentication, IP address, port etc.) to be correctly identified. + */ + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://hdl.handle.net/10442/hedi/6089"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://hdl.handle.net/10442/hedi/6089}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://hdl.handle.net/10442/hedi/6089"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://hdl.handle.net/10442/hedi/6089}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://userid:password@example.com:8080"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://userid:password@example.com:8080}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://142.42.1.1:8080"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://142.42.1.1:8080}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://☺.damowmow.com"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://☺.damowmow.com}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://www.example.com/foo/?bar=baz&inga=42&quux"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://www.example.com/foo/?bar=baz&inga=42&quux}")), + + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://www.example.com/foo/?bar=baz&inga=42&quux"), + new BibEntry().withField(StandardField.NOTE, + "https://www.example.com/foo/?bar=baz&inga=42&quux")), + + // Expected entry returns formatted the url-date in the Urldate field. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://142.42.1.1:8080") + .withField(StandardField.URLDATE, + "2021-01-15"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021")), + + // Input entry doesn't hold any URL in the Note field. + Arguments.of( + new BibEntry().withField(StandardField.NOTE, + "Accessed on 2015-01-15"), + new BibEntry().withField(StandardField.NOTE, + "Accessed on 2015-01-15")), + + // Input entry has multiple url-dates stored in the Note field. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://142.42.1.1:8080") + .withField(StandardField.URLDATE, + "2021-01-15") + .withField(StandardField.NOTE, + "visited on February 12, 2017"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021, visited on February 12, 2017")), + + // Input entry holds the same url-date in both Note and Urldate field. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "http://142.42.1.1:8080") + .withField(StandardField.URLDATE, + "2015-01-15"), + new BibEntry().withField(StandardField.NOTE, + "\\url{http://142.42.1.1:8080}, visited on 2015.01.15") + .withField(StandardField.URLDATE, + "2015-01-15")), + + // Input Note field has several values stored. + Arguments.of( + new BibEntry().withField(StandardField.URL, + "https://example.org") + .withField(StandardField.URLDATE, + "2023-04-11") + .withField(StandardField.NOTE, + "cited by Kramer"), + new BibEntry().withField(StandardField.NOTE, + "\\url{https://example.org}, cited by Kramer, accessed on 2023-04-11"), + // test with no fields present + Arguments.of( + new BibEntry(), + new BibEntry()) + ) ); } } diff --git a/jablib/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java b/jablib/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java index d761d7b2889..a4a17fcd49e 100644 --- a/jablib/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java +++ b/jablib/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java @@ -107,10 +107,10 @@ void mergeBibTexStringsWithSameNameAreImportedWithModifiedName() { new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeStrings(target, source2); // Use string representation to compare since the id will not match List resultStringsSorted = target.getStringValues() - .stream() - .map(BibtexString::toString) - .sorted() - .collect(Collectors.toList()); + .stream() + .map(BibtexString::toString) + .sorted() + .collect(Collectors.toList()); assertEquals(List.of(targetString.toString(), importedBibTeXString1.toString(), importedBibTeXString2.toString()), resultStringsSorted); @@ -134,9 +134,9 @@ void mergeBibTexStringsWithSameNameAndContentAreIgnored() { new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeStrings(target, source); List resultStringsSorted = target.getStringValues() - .stream() - .sorted(new BibtexStringComparator(false)::compare) - .collect(Collectors.toList()); + .stream() + .sorted(new BibtexStringComparator(false)::compare) + .collect(Collectors.toList()); assertEquals(List.of(targetString1, targetString2), resultStringsSorted); } diff --git a/jablib/src/test/java/org/jabref/logic/exporter/ExporterTest.java b/jablib/src/test/java/org/jabref/logic/exporter/ExporterTest.java index 28602d4cc84..970cefe8f74 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/ExporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/ExporterTest.java @@ -40,7 +40,7 @@ private static Stream exportFormats() { Collection result = new ArrayList<>(); for (Exporter format : exporterFactory.getExporters()) { - result.add(new Object[]{format, format.getName()}); + result.add(new Object[] {format, format.getName()}); } return result.stream(); } diff --git a/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java b/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java index 54a4ff17135..beb6b0a7f72 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java @@ -78,7 +78,7 @@ void serializeSingleExplicitGroupWithIconAndDescription() { } @Test - // For https://github.com/JabRef/jabref/issues/1681 + // For https://github.com/JabRef/jabref/issues/1681 void serializeSingleExplicitGroupWithEscapedSlash() { ExplicitGroup group = new ExplicitGroup("B{\\\"{o}}hmer", GroupHierarchyType.INDEPENDENT, ','); List serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); diff --git a/jablib/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java b/jablib/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java index 4ebddab3509..9c30035f73a 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java @@ -83,40 +83,40 @@ void writeMultipleEntriesInASingleFile(@TempDir Path testFolder) throws IOExcept String actual = String.join("\n", Files.readAllLines(file)); // we are using \n to join, so we need it in the expected string as well, \r\n would fail String expected = """ - - - - - Alan Turing - - - application/pdf - - - Misc - - - - - - - Michael Armbrust - - - - - bibtex/citationkey/Armbrust2010 - - - application/pdf - - - Misc - - - - - """.stripTrailing(); + + + + + Alan Turing + + + application/pdf + + + Misc + + + + + + + Michael Armbrust + + + + + bibtex/citationkey/Armbrust2010 + + + application/pdf + + + Misc + + + + + """.stripTrailing(); assertEquals(expected, actual); } @@ -143,22 +143,22 @@ void writeMultipleEntriesInDifferentFiles(@TempDir Path testFolder) throws IOExc // we are using \n to join, so we need it in the expected string as well, \r\n would fail String actualTuring = String.join("\n", Files.readAllLines(fileTuring)); String expectedTuring = """ - - - - - Alan Turing - - - application/pdf - - - Misc - - - - - """.stripTrailing(); + + + + + Alan Turing + + + application/pdf + + + Misc + + + + + """.stripTrailing(); assertEquals(expectedTuring, actualTuring); // armbrust contains the armbrust entry only diff --git a/jablib/src/test/java/org/jabref/logic/exporter/YamlExporterTest.java b/jablib/src/test/java/org/jabref/logic/exporter/YamlExporterTest.java index 0ab80c9b70e..a1daeb0bceb 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/YamlExporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/YamlExporterTest.java @@ -111,11 +111,11 @@ final void formatsContentCorrect(@TempDir Path tempFile) throws IOException, Sav @Test void passesModifiedCharset(@TempDir Path tempFile) throws IOException, SaveException, ParserConfigurationException, TransformerException { BibEntry entry = new BibEntry(StandardEntryType.Article) - .withCitationKey("test") - .withField(StandardField.AUTHOR, "谷崎 潤一郎") - .withField(StandardField.TITLE, "細雪") - .withField(StandardField.URL, "http://example.com") - .withField(StandardField.DATE, "2020-10-14"); + .withCitationKey("test") + .withField(StandardField.AUTHOR, "谷崎 潤一郎") + .withField(StandardField.TITLE, "細雪") + .withField(StandardField.URL, "http://example.com") + .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); @@ -139,11 +139,11 @@ void passesModifiedCharset(@TempDir Path tempFile) throws IOException, SaveExcep @Test void passesModifiedCharsetNull(@TempDir Path tempFile) throws IOException, SaveException, ParserConfigurationException, TransformerException { BibEntry entry = new BibEntry(StandardEntryType.Article) - .withCitationKey("test") - .withField(StandardField.AUTHOR, "谷崎 潤一郎") - .withField(StandardField.TITLE, "細雪") - .withField(StandardField.URL, "http://example.com") - .withField(StandardField.DATE, "2020-10-14"); + .withCitationKey("test") + .withField(StandardField.AUTHOR, "谷崎 潤一郎") + .withField(StandardField.TITLE, "細雪") + .withField(StandardField.URL, "http://example.com") + .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); diff --git a/jablib/src/test/java/org/jabref/logic/formatter/FormatterTest.java b/jablib/src/test/java/org/jabref/logic/formatter/FormatterTest.java index d551426beda..4f21e8a6343 100644 --- a/jablib/src/test/java/org/jabref/logic/formatter/FormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/formatter/FormatterTest.java @@ -43,7 +43,7 @@ void allFormatterKeysAreUnique() { assertEquals(List.of(), getFormatters().collect(Collectors.groupingBy( Formatter::getKey, - Collectors.counting())) + Collectors.counting())) .entrySet().stream() .filter(e -> e.getValue() > 1) .map(Map.Entry::getKey) diff --git a/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java b/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java index 05f49c7639c..5649a45cd46 100644 --- a/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java @@ -15,16 +15,16 @@ class HtmlToUnicodeFormatterTest { private static Stream data() { return Stream.of( - Arguments.of("abc", "abc"), - Arguments.of("åäö", "åäö"), - Arguments.of("í", "í"), - Arguments.of("Ε", "Ε"), - Arguments.of("ä", "ä"), - Arguments.of("ä", "ä"), - Arguments.of("ä", "ä"), - Arguments.of("ñ", "ñ"), - Arguments.of("aaa", "

          aaa

          "), - Arguments.of("bread & butter", "bread & butter")); + Arguments.of("abc", "abc"), + Arguments.of("åäö", "åäö"), + Arguments.of("í", "í"), + Arguments.of("Ε", "Ε"), + Arguments.of("ä", "ä"), + Arguments.of("ä", "ä"), + Arguments.of("ä", "ä"), + Arguments.of("ñ", "ñ"), + Arguments.of("aaa", "

          aaa

          "), + Arguments.of("bread & butter", "bread & butter")); } @BeforeEach diff --git a/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeToLatexFormatterTest.java b/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeToLatexFormatterTest.java index 6784d6985e3..42c4c5470da 100644 --- a/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeToLatexFormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeToLatexFormatterTest.java @@ -20,16 +20,16 @@ void setUp() { private static Stream testCases() { return Stream.of( - Arguments.of("", ""), // empty string input - Arguments.of("abc", "abc"), // non unicode input - Arguments.of("{{\\aa}}{\\\"{a}}{\\\"{o}}", "\u00E5\u00E4\u00F6"), // multiple unicodes input - Arguments.of("", "\u0081"), // high code point unicode, boundary case: cp = 129 - Arguments.of("€", "\u0080"), // high code point unicode, boundary case: cp = 128 < 129 - Arguments.of("M{\\\"{o}}nch", new UnicodeToLatexFormatter().getExampleInput()), - Arguments.of("{\\i}", "ı"), - Arguments.of("{\\i} {\\={\\i}}", "ı ī"), - Arguments.of("{\\={\\i}}{\\={\\i}}", "\u0069\u0304\u0069\u0304"), - Arguments.of("Pu{\\d{n}}ya-pattana-vidy{\\={a}}-p{\\={\\i}}{\\d{t}}h{\\={a}}dhi-k{\\d{r}}tai{\\d{h}} pr{\\={a}}-ka{{\\'{s}}}ya{\\d{m}} n{\\={\\i}}ta{\\d{h}}", "Puṇya-pattana-vidyā-pīṭhādhi-kṛtaiḥ prā-kaśyaṃ nītaḥ") + Arguments.of("", ""), // empty string input + Arguments.of("abc", "abc"), // non unicode input + Arguments.of("{{\\aa}}{\\\"{a}}{\\\"{o}}", "\u00E5\u00E4\u00F6"), // multiple unicodes input + Arguments.of("", "\u0081"), // high code point unicode, boundary case: cp = 129 + Arguments.of("€", "\u0080"), // high code point unicode, boundary case: cp = 128 < 129 + Arguments.of("M{\\\"{o}}nch", new UnicodeToLatexFormatter().getExampleInput()), + Arguments.of("{\\i}", "ı"), + Arguments.of("{\\i} {\\={\\i}}", "ı ī"), + Arguments.of("{\\={\\i}}{\\={\\i}}", "\u0069\u0304\u0069\u0304"), + Arguments.of("Pu{\\d{n}}ya-pattana-vidy{\\={a}}-p{\\={\\i}}{\\d{t}}h{\\={a}}dhi-k{\\d{r}}tai{\\d{h}} pr{\\={a}}-ka{{\\'{s}}}ya{\\d{m}} n{\\={\\i}}ta{\\d{h}}", "Puṇya-pattana-vidyā-pīṭhādhi-kṛtaiḥ prā-kaśyaṃ nītaḥ") ); } diff --git a/jablib/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java b/jablib/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java index d3d8f9a24cc..04097b4dc67 100644 --- a/jablib/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java @@ -35,6 +35,6 @@ private static Stream provideAuthorNames() { Arguments.of("Simon Harrer and others", "Simon Harrer and Jörg Lenhard and Guido Wirtz"), Arguments.of("Simon Harrer and others", "Simon Harrer and Jörg Lenhard and Guido Wirtz and others"), Arguments.of("Stefan Kolb and others", new MinifyNameListFormatter().getExampleInput()) - ); + ); } } diff --git a/jablib/src/test/java/org/jabref/logic/git/GitHandlerTest.java b/jablib/src/test/java/org/jabref/logic/git/GitHandlerTest.java index d96e9a1a73e..9a18acf29eb 100644 --- a/jablib/src/test/java/org/jabref/logic/git/GitHandlerTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/GitHandlerTest.java @@ -46,10 +46,10 @@ void setUpGitHandler() throws IOException, GitAPIException, URISyntaxException { SystemReader.setInstance(new NoopGitSystemReader()); try (Git remoteGit = Git.init() - .setBare(true) - .setDirectory(remoteRepoPath.toFile()) - .setInitialBranch("main") - .call()) { + .setBare(true) + .setDirectory(remoteRepoPath.toFile()) + .setInitialBranch("main") + .call()) { // This ensures the remote repository is initialized and properly closed } diff --git a/jablib/src/test/java/org/jabref/logic/git/GitSyncServiceTest.java b/jablib/src/test/java/org/jabref/logic/git/GitSyncServiceTest.java index 8fb6bc07ff1..995066147b3 100644 --- a/jablib/src/test/java/org/jabref/logic/git/GitSyncServiceTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/GitSyncServiceTest.java @@ -74,29 +74,29 @@ class GitSyncServiceTest { // In the future, consider replacing with structured BibEntry construction // to improve semantic robustness and avoid syntax errors. private final String initialContent = """ - @article{a, - author = {don't know the author}, - doi = {xya}, - } - - @article{b, - author = {don't know the author}, - doi = {xyz}, - } - """; + @article{a, + author = {don't know the author}, + doi = {xya}, + } + + @article{b, + author = {don't know the author}, + doi = {xyz}, + } + """; // Alice modifies a private final String aliceUpdatedContent = """ - @article{a, - author = {author-a}, - doi = {xya}, - } - - @article{b, - author = {don't know the author}, - doi = {xyz}, - } - """; + @article{a, + author = {author-a}, + doi = {xya}, + } + + @article{b, + author = {don't know the author}, + doi = {xyz}, + } + """; // Bob reorders a and b private final String bobUpdatedContent = """ @@ -131,10 +131,10 @@ void aliceBobSimple(@TempDir Path tempDir) throws Exception { // create fake remote repo remoteDir = tempDir.resolve("remote.git"); remoteGit = Git.init() - .setBare(true) - .setInitialBranch("main") - .setDirectory(remoteDir.toFile()) - .call(); + .setBare(true) + .setInitialBranch("main") + .setDirectory(remoteDir.toFile()) + .call(); // Alice init local repository aliceDir = tempDir.resolve("alice"); @@ -154,20 +154,20 @@ void aliceBobSimple(@TempDir Path tempDir) throws Exception { .call(); aliceGit.push() - .setRemote("origin") - .setRefSpecs(new RefSpec("refs/heads/main:refs/heads/main")) - .call(); + .setRemote("origin") + .setRefSpecs(new RefSpec("refs/heads/main:refs/heads/main")) + .call(); configureTracking(aliceGit, "main", "origin"); // Bob clone remote bobDir = tempDir.resolve("bob"); bobGit = Git.cloneRepository() - .setURI(remoteDir.toUri().toString()) - .setDirectory(bobDir.toFile()) - .setBranchesToClone(List.of("refs/heads/main")) - .setBranch("main") - .call(); + .setURI(remoteDir.toUri().toString()) + .setDirectory(bobDir.toFile()) + .setBranchesToClone(List.of("refs/heads/main")) + .setBranch("main") + .call(); Path bobLibrary = bobDir.resolve("library.bib"); bobCommit = writeAndCommit(bobUpdatedContent, "Exchange a with b", bob, bobLibrary, bobGit); @@ -214,16 +214,16 @@ void pullTriggersSemanticMergeWhenNoConflicts() throws Exception { String merged = Files.readString(library); String expected = """ - @article{a, - author = {author-a}, - doi = {xya}, - } + @article{a, + author = {author-a}, + doi = {xya}, + } - @article{b, - author = {author-b}, - doi = {xyz}, - } - """; + @article{b, + author = {author-b}, + doi = {xyz}, + } + """; assertEquals(normalize(expected), normalize(merged)); } @@ -237,16 +237,16 @@ void pushTriggersMergeAndPushWhenNoConflicts() throws Exception { .readFileFromCommit(aliceGit, aliceGit.log().setMaxCount(1).call().iterator().next(), Path.of("library.bib")) .orElseThrow(() -> new IllegalStateException("Expected file 'library.bib' not found in commit")); String expected = """ - @article{a, - author = {author-a}, - doi = {xya}, - } + @article{a, + author = {author-a}, + doi = {xya}, + } - @article{b, - author = {author-b}, - doi = {xyz}, - } - """; + @article{b, + author = {author-b}, + doi = {xyz}, + } + """; assertEquals(normalize(expected), normalize(pushedContent)); } @@ -255,39 +255,39 @@ void pushTriggersMergeAndPushWhenNoConflicts() throws Exception { void mergeConflictOnSameFieldTriggersDialogAndUsesUserResolution() throws Exception { Path bobLibrary = bobDir.resolve("library.bib"); String bobEntry = """ - @article{b, - author = {author-b}, - doi = {xyz}, - } - - @article{a, - author = {don't know the author}, - doi = {xya}, - } - - @article{c, - author = {bob-c}, - title = {Title C}, - } - """; + @article{b, + author = {author-b}, + doi = {xyz}, + } + + @article{a, + author = {don't know the author}, + doi = {xya}, + } + + @article{c, + author = {bob-c}, + title = {Title C}, + } + """; writeAndCommit(bobEntry, "Bob adds article-c", bob, bobLibrary, bobGit); bobGit.push().setRemote("origin").call(); String aliceEntry = """ - @article{a, - author = {author-a}, - doi = {xya}, - } - - @article{b, - author = {don't know the author}, - doi = {xyz}, - } - - @article{c, - author = {alice-c}, - title = {Title C}, - } - """; + @article{a, + author = {author-a}, + doi = {xya}, + } + + @article{b, + author = {don't know the author}, + doi = {xyz}, + } + + @article{c, + author = {alice-c}, + title = {Title C}, + } + """; writeAndCommit(aliceEntry, "Alice adds conflicting article-c", alice, library, aliceGit); aliceGit.fetch().setRemote("origin").call(); diff --git a/jablib/src/test/java/org/jabref/logic/git/status/GitStatusCheckerTest.java b/jablib/src/test/java/org/jabref/logic/git/status/GitStatusCheckerTest.java index 5160280f59f..f65c73855d1 100644 --- a/jablib/src/test/java/org/jabref/logic/git/status/GitStatusCheckerTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/status/GitStatusCheckerTest.java @@ -36,40 +36,40 @@ class GitStatusCheckerTest { private final PersonIdent author = new PersonIdent("Tester", "tester@example.org"); private final String baseContent = """ - @article{a, - author = {initial-author}, - doi = {xya}, - } + @article{a, + author = {initial-author}, + doi = {xya}, + } - @article{b, - author = {initial-author}, - doi = {xyz}, - } - """; + @article{b, + author = {initial-author}, + doi = {xyz}, + } + """; private final String remoteUpdatedContent = """ - @article{a, - author = {initial-author}, - doi = {xya}, - } + @article{a, + author = {initial-author}, + doi = {xya}, + } - @article{b, - author = {remote-update}, - doi = {xyz}, - } - """; + @article{b, + author = {remote-update}, + doi = {xyz}, + } + """; private final String localUpdatedContent = """ - @article{a, - author = {local-update}, - doi = {xya}, - } + @article{a, + author = {local-update}, + doi = {xya}, + } - @article{b, - author = {initial-author}, - doi = {xyz}, - } - """; + @article{b, + author = {initial-author}, + doi = {xyz}, + } + """; @BeforeEach void setup(@TempDir Path tempDir) throws Exception { @@ -79,9 +79,9 @@ void setup(@TempDir Path tempDir) throws Exception { Path seedDir = tempDir.resolve("seed"); seedGit = Git.init() - .setInitialBranch("main") - .setDirectory(seedDir.toFile()) - .call(); + .setInitialBranch("main") + .setDirectory(seedDir.toFile()) + .call(); Path seedFile = seedDir.resolve("library.bib"); Files.writeString(seedFile, baseContent, StandardCharsets.UTF_8); @@ -155,11 +155,11 @@ void upToDateStatusAfterInitialSync() { void behindStatusWhenRemoteHasNewCommit(@TempDir Path tempDir) throws Exception { Path remoteWork = tempDir.resolve("remoteWork"); try (Git remoteClone = Git.cloneRepository() - .setURI(remoteGit.getRepository().getDirectory().toURI().toString()) - .setDirectory(remoteWork.toFile()) - .setBranchesToClone(List.of("refs/heads/main")) - .setBranch("main") - .call()) { + .setURI(remoteGit.getRepository().getDirectory().toURI().toString()) + .setDirectory(remoteWork.toFile()) + .setBranchesToClone(List.of("refs/heads/main")) + .setBranch("main") + .call()) { commitFile(remoteClone, remoteUpdatedContent, "Remote update"); remoteClone.push() .setRemote("origin") @@ -187,11 +187,11 @@ void divergedStatusWhenBothSidesHaveCommits(@TempDir Path tempDir) throws Except Path remoteWork = tempDir.resolve("remoteWork"); try (Git remoteClone = Git.cloneRepository() - .setURI(remoteGit.getRepository().getDirectory().toURI().toString()) - .setDirectory(remoteWork.toFile()) - .setBranchesToClone(List.of("refs/heads/main")) - .setBranch("main") - .call()) { + .setURI(remoteGit.getRepository().getDirectory().toURI().toString()) + .setDirectory(remoteWork.toFile()) + .setBranchesToClone(List.of("refs/heads/main")) + .setBranch("main") + .call()) { commitFile(remoteClone, remoteUpdatedContent, "Remote update"); remoteClone.push() .setRemote("origin") diff --git a/jablib/src/test/java/org/jabref/logic/git/util/GitFileWriterTest.java b/jablib/src/test/java/org/jabref/logic/git/util/GitFileWriterTest.java index a53a832324b..7e7b42c4c39 100644 --- a/jablib/src/test/java/org/jabref/logic/git/util/GitFileWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/util/GitFileWriterTest.java @@ -22,6 +22,7 @@ class GitFileWriterTest { private ImportFormatPreferences importFormatPreferences; + @BeforeEach void setUp() { SystemReader.setInstance(new NoopGitSystemReader()); @@ -33,11 +34,11 @@ void setUp() { @Test void writeThenReadBack() throws Exception { BibDatabaseContext inputDatabaseContext = BibDatabaseContext.of(""" - @article{a, - author = {Alice}, - title = {Test}, - } - """, importFormatPreferences); + @article{a, + author = {Alice}, + title = {Test}, + } + """, importFormatPreferences); Path tempFile = Files.createTempFile("tempgitwriter", ".bib"); GitFileWriter.write(tempFile, inputDatabaseContext, importFormatPreferences); diff --git a/jablib/src/test/java/org/jabref/logic/git/util/NoopGitSystemReader.java b/jablib/src/test/java/org/jabref/logic/git/util/NoopGitSystemReader.java index 260ee21e1a1..bc4bdca1581 100644 --- a/jablib/src/test/java/org/jabref/logic/git/util/NoopGitSystemReader.java +++ b/jablib/src/test/java/org/jabref/logic/git/util/NoopGitSystemReader.java @@ -10,10 +10,12 @@ public class NoopGitSystemReader extends SystemReader.Delegate { private static final StoredConfig NOP = new StoredConfig() { @Override - public void load() { } + public void load() { + } @Override - public void save() { } + public void save() { + } }; public NoopGitSystemReader() { diff --git a/jablib/src/test/java/org/jabref/logic/git/util/SemanticConflictDetectorTest.java b/jablib/src/test/java/org/jabref/logic/git/util/SemanticConflictDetectorTest.java index 3b5893b7bed..f3bfbf8e6c7 100644 --- a/jablib/src/test/java/org/jabref/logic/git/util/SemanticConflictDetectorTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/util/SemanticConflictDetectorTest.java @@ -112,742 +112,742 @@ static Stream semanticConflicts() { "", "", """ - @article{a, - author = {remote}, - title = {A}, - } - """, + @article{a, + author = {remote}, + title = {A}, + } + """, false), Arguments.of("E03 - entry a added locally only", "", """ - @article{a, - author = {local}, - title = {A}, - } - """, + @article{a, + author = {local}, + title = {A}, + } + """, "", false), Arguments.of("E04 - entry a added on both sides with different content", "", """ - @article{a, - author = {local}, - title = {A}, - } - """, - """ - @article{a, - author = {remote}, - title = {A}, - } - """, + @article{a, + author = {local}, + title = {A}, + } + """, + """ + @article{a, + author = {remote}, + title = {A}, + } + """, true), Arguments.of("E04a - both sides added entry a with identical content", "", """ - @article{a, - author = {same}, - title = {A}, - } - """, - """ - @article{a, - author = {same}, - title = {A}, - } - """, + @article{a, + author = {same}, + title = {A}, + } + """, + """ + @article{a, + author = {same}, + title = {A}, + } + """, false ), Arguments.of("E04b - both added entry a but changed different fields", "", """ - @article{a, - author = {local}, - } - """, + @article{a, + author = {local}, + } + """, """ - @article{a, - journal = {Remote Journal}, - } - """, + @article{a, + journal = {Remote Journal}, + } + """, false ), Arguments.of("E04c - both added entry a with conflicting field values", "", """ - @article{a, - author = {local}, - title = {A}, - } - """, - """ - @article{a, - author = {remote}, - title = {A}, - } - """, + @article{a, + author = {local}, + title = {A}, + } + """, + """ + @article{a, + author = {remote}, + title = {A}, + } + """, true ), Arguments.of("E05 - entry a was deleted by both", """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, "", "", false), Arguments.of("E06 - local deleted entry a, remote kept it unchanged", """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, "", """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, false), Arguments.of("E07 - local deleted entry a, remote modified it", """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, "", """ - @article{a, - author = {remote}, - title = {A}, - } - """, + @article{a, + author = {remote}, + title = {A}, + } + """, true), Arguments.of("E08 - remote deleted entry a, local kept it unchanged", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {A}, + } + """, "", false), Arguments.of("E09 - entry a unchanged in all three", """ - @article{a, - author = {base}, - title = {A}, - }""", - """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + }""", + """ + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {A}, + } + """, false), Arguments.of("E10a - remote modified a different field, local unchanged", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - year = {2025}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + year = {2025}, + } + """, false ), Arguments.of("E10b - remote modified the same field, local unchanged", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {remote}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {remote}, + title = {A}, + } + """, false ), Arguments.of("E11 - remote deleted entry a, local modified it", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {local}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {local}, + title = {A}, + } + """, "", true), Arguments.of("E12 - local modified entry a, remote unchanged", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {local}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {A}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {local}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {A}, + } + """, false), Arguments.of("E13a - both modified entry a but changed different fields", """ - @article{a, - author = {base}, - title = {A}, - } - """, - """ - @article{a, - author = {local}, - title = {A}, - } - """, - """ - @article{a, - author = {base}, - title = {B}, - } - """, + @article{a, + author = {base}, + title = {A}, + } + """, + """ + @article{a, + author = {local}, + title = {A}, + } + """, + """ + @article{a, + author = {base}, + title = {B}, + } + """, false ), Arguments.of("E13b - both changed same field to same value", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {common}, - } - """, + @article{a, + author = {common}, + } + """, """ - @article{a, - author = {common}, - } - """, + @article{a, + author = {common}, + } + """, false ), Arguments.of("E13c - both changed same field differently", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {local}, - } - """, + @article{a, + author = {local}, + } + """, """ - @article{a, - author = {remote}, - } - """, + @article{a, + author = {remote}, + } + """, true ), Arguments.of("E14a - citationKey changed in local", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{b, - author = {base}, - } - """, + @article{b, + author = {base}, + } + """, """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, false ), Arguments.of("E14b - citationKey changed in remote", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{b, - author = {base}, - } - """, + @article{b, + author = {base}, + } + """, false ), Arguments.of("E14c - citationKey renamed differently in local and remote", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{b, - author = {base}, - } - """, + @article{b, + author = {base}, + } + """, """ - @article{c, - author = {base}, - } - """, + @article{c, + author = {base}, + } + """, false ), Arguments.of("E15 - both added same citationKey with different content", """ - """, + """, """ - @article{a, - title = {local}, - } - """, + @article{a, + title = {local}, + } + """, """ - @article{a, - title = {remote}, - } - """, + @article{a, + title = {remote}, + } + """, true ), Arguments.of("F01 - identical field value on all sides", """ - @article{a, - author = {same}, - } - """, + @article{a, + author = {same}, + } + """, """ - @article{a, - author = {same}, - } - """, + @article{a, + author = {same}, + } + """, """ - @article{a, - author = {same}, - } - """, + @article{a, + author = {same}, + } + """, false ), Arguments.of("F02 - remote changed, local same as base", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {remote}, - } - """, + @article{a, + author = {remote}, + } + """, false ), Arguments.of("F03 - local changed, remote same as base", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {local}, - } - """, + @article{a, + author = {local}, + } + """, """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, false ), Arguments.of("F04 - both changed to same value", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {common}, - } - """, + @article{a, + author = {common}, + } + """, """ - @article{a, - author = {common}, - } - """, + @article{a, + author = {common}, + } + """, false ), Arguments.of("F05 - both changed same field differently", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @article{a, - author = {local}, - } - """, + @article{a, + author = {local}, + } + """, """ - @article{a, - author = {remote}, - } - """, + @article{a, + author = {remote}, + } + """, true ), Arguments.of("F06 - Local deleted, remote unchanged", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, false ), Arguments.of("F07 - Remote deleted, local unchanged", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, false ), Arguments.of("F08 - Both deleted", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - } - """, + @article{a, + } + """, false ), Arguments.of("F09 - Local changed, remote deleted", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - author = {local} - } - """, + @article{a, + author = {local} + } + """, """ - @article{a, - }""", + @article{a, + }""", true ), Arguments.of("F10 - Local deleted, remote changed", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {remote} - } - """, + @article{a, + author = {remote} + } + """, true ), Arguments.of("F11 - All missing", """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - } - """, + @article{a, + } + """, false ), Arguments.of("F12 - Local added", """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {local} - } - """, + @article{a, + author = {local} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, false ), Arguments.of("F13 - Remote added", """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {remote} - } - """, + @article{a, + author = {remote} + } + """, false ), Arguments.of("F14 - Both added same value", """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {same} - } - """, + @article{a, + author = {same} + } + """, """ - @article{a, - author = {same} - } - """, + @article{a, + author = {same} + } + """, false ), Arguments.of("F15 - Both added different values", """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {local} - } - """, + @article{a, + author = {local} + } + """, """ - @article{a, - author = {remote} - } - """, + @article{a, + author = {remote} + } + """, true ), Arguments.of("F16 - Local modified, remote deleted (conflict)", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - author = {local} - } - """, + @article{a, + author = {local} + } + """, """ - @article{a, - }""", + @article{a, + }""", true ), Arguments.of("F17 - Local deleted and remote modified (conflict)", """ - @article{a, - author = {base} - } - """, + @article{a, + author = {base} + } + """, """ - @article{a, - } - """, + @article{a, + } + """, """ - @article{a, - author = {remote} - } - """, + @article{a, + author = {remote} + } + """, true ), Arguments.of("F18 - No base, both added different", """ - @article{a, - }""", + @article{a, + }""", """ - @article{a, - author = {local} - } - """, + @article{a, + author = {local} + } + """, """ - @article{a, - author = {remote} - } - """, + @article{a, + author = {remote} + } + """, true ), Arguments.of("F19 - field order changed, same content", """ - @article{a, - title = {Hello}, - author = {Alice}, - } - """, - """ - @article{a, - author = {Alice}, - title = {Hello}, - } - """, - """ - @article{a, - title = {Hello}, - author = {Alice}, - } - """, + @article{a, + title = {Hello}, + author = {Alice}, + } + """, + """ + @article{a, + author = {Alice}, + title = {Hello}, + } + """, + """ + @article{a, + title = {Hello}, + author = {Alice}, + } + """, false ), Arguments.of("F20 - entryType changed in local", """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, """ - @book{a, - author = {base}, - } - """, + @book{a, + author = {base}, + } + """, """ - @article{a, - author = {base}, - } - """, + @article{a, + author = {base}, + } + """, false ), Arguments.of("F21 - entryType changed differently on both sides", """ - """, + """, """ - @book{a, - author = {base}, - } - """, + @book{a, + author = {base}, + } + """, """ - @inproceedings{a, - author = {base}, - } - """, + @inproceedings{a, + author = {base}, + } + """, true ) ); @@ -856,26 +856,26 @@ static Stream semanticConflicts() { @Test void extractMergePlanOnlyRemoteChangedEntryB() throws Exception { String base = """ - @article{a, - author = {Test Author}, - doi = {xya}, - } - @article{b, - author = {Test Author}, - doi = {xyz}, - } - """; + @article{a, + author = {Test Author}, + doi = {xya}, + } + @article{b, + author = {Test Author}, + doi = {xyz}, + } + """; String local = base; String remote = """ - @article{b, - author = {author-b}, - doi = {xyz}, - } - @article{a, - author = {Test Author}, - doi = {xya}, - } - """; + @article{b, + author = {author-b}, + doi = {xyz}, + } + @article{a, + author = {Test Author}, + doi = {xya}, + } + """; RevCommit baseCommit = writeAndCommit(base, "base", alice); RevCommit localCommit = writeAndCommit(base, "local", alice); @@ -896,19 +896,19 @@ void extractMergePlanOnlyRemoteChangedEntryB() throws Exception { @Test void extractMergePlanRemoteAddsField() throws Exception { String base = """ - @article{a, - author = {Test Author}, - doi = {xya}, - } - """; + @article{a, + author = {Test Author}, + doi = {xya}, + } + """; String local = base; String remote = """ - @article{a, - author = {Test Author}, - doi = {xya}, - year = {2025}, - } - """; + @article{a, + author = {Test Author}, + doi = {xya}, + year = {2025}, + } + """; RevCommit baseCommit = writeAndCommit(base, "base", alice); RevCommit localCommit = writeAndCommit(base, "local", alice); @@ -927,20 +927,20 @@ void extractMergePlanRemoteAddsField() throws Exception { @Test void noConflictWhenOnlyLineEndingsDiffer() throws Exception { String base = """ - @article{a, - comment = {line1\n\nline3\n\nline5}, - } - """; + @article{a, + comment = {line1\n\nline3\n\nline5}, + } + """; String local = """ - @article{a, - comment = {line1\r\n\r\nline3\r\n\r\nline5}, - } - """; + @article{a, + comment = {line1\r\n\r\nline3\r\n\r\nline5}, + } + """; String remote = """ - @article{a, - comment = {line1\n\nline3\n\nline5}, - } - """; + @article{a, + comment = {line1\n\nline3\n\nline5}, + } + """; RevCommit baseCommit = writeAndCommit(base, "base", alice); RevCommit localCommit = writeAndCommit(local, "local", alice); diff --git a/jablib/src/test/java/org/jabref/logic/git/util/SemanticMergerTest.java b/jablib/src/test/java/org/jabref/logic/git/util/SemanticMergerTest.java index 88116a8fcfd..bdcfb210209 100644 --- a/jablib/src/test/java/org/jabref/logic/git/util/SemanticMergerTest.java +++ b/jablib/src/test/java/org/jabref/logic/git/util/SemanticMergerTest.java @@ -57,85 +57,85 @@ static Stream patchDatabase() { return Stream.of( Arguments.of("T1 - remote changed a field, local unchanged", """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {bob}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {bob}, + doi = {ExampleDoi} + } + """, "bob" ), Arguments.of("T2 - local changed a field, remote unchanged", """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {alice}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {alice}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi} + } + """, "alice" ), Arguments.of("T3 - both changed to same value", """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {bob}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {bob}, + doi = {ExampleDoi} + } + """, """ - @article{a, - author = {bob}, - doi = {ExampleDoi} - } - """, + @article{a, + author = {bob}, + doi = {ExampleDoi} + } + """, "bob" ), Arguments.of("T4 - field removed in remote, unchanged in local", """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi}, - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi}, + } + """, """ - @article{a, - author = {TestAuthor}, - doi = {ExampleDoi}, - } - """, + @article{a, + author = {TestAuthor}, + doi = {ExampleDoi}, + } + """, """ - @article{a, - doi = {ExampleDoi}, - } - """, + @article{a, + doi = {ExampleDoi}, + } + """, null ) ); diff --git a/jablib/src/test/java/org/jabref/logic/icore/ConferenceRepositoryTest.java b/jablib/src/test/java/org/jabref/logic/icore/ConferenceRepositoryTest.java index 5b6b3753b76..4172ef0bfe1 100644 --- a/jablib/src/test/java/org/jabref/logic/icore/ConferenceRepositoryTest.java +++ b/jablib/src/test/java/org/jabref/logic/icore/ConferenceRepositoryTest.java @@ -26,38 +26,38 @@ static void loadTestConferenceDataIntoRepo() throws JabRefException { static Stream generateConferenceTestData() { return Stream.of( - // Acronym match tests - Arguments.of("HCOMP", "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), // acronym only exact match - Arguments.of("BBBBB", null, null, null, null), // no match found in conference data - Arguments.of("''", null, null, null, null), // empty string should return empty - Arguments.of("(iiWAS 2010)", "822", "Information Integration and Web-based Applications and Services", "IIWAS", "C"), // acronym with other text separated by space; acronym first - Arguments.of("(2010 iiWAS)", "822", "Information Integration and Web-based Applications and Services", "IIWAS", "C"), // acronym with other text separated by space; acronym second - Arguments.of("(CLOSER'12)", "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), // acronym with other text separated by quote - Arguments.of("(IEEE CCNC)", "616", "IEEE Consumer Communications and Networking Conference", "IEEE CCNC", "B"), // acronym with space in it - Arguments.of("(ACM_WiSec 2019)", "2313", "ACM Conference on Security and Privacy in Wireless and Mobile Networks", "ACM_WiSec", "B"), // acronym with special character with extra text separated by space - Arguments.of("(EC-TEL'2023)", "2262", "European Conference on Technology Enhanced Learning", "EC-TEL", "B"), // acronym with special character and quote - Arguments.of("(IEEE-IV'2023)", "2062", "Intelligent Vehicles Conference", "IEEE-IV", "B"), // longer acronym with delimiter matches (IEEE-IV) instead of nested one (IV) - Arguments.of("CoopIS 2009 (OTM 2009)", "979", "International Conference on Cooperative Information Systems", "CoopIS", "B"), // acronym outside parentheses matches post-normalization - Arguments.of("Cloud Computing and Services Science (CLOSER 2016): 6th International Conference", // Acronym in middle of title - "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), + // Acronym match tests + Arguments.of("HCOMP", "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), // acronym only exact match + Arguments.of("BBBBB", null, null, null, null), // no match found in conference data + Arguments.of("''", null, null, null, null), // empty string should return empty + Arguments.of("(iiWAS 2010)", "822", "Information Integration and Web-based Applications and Services", "IIWAS", "C"), // acronym with other text separated by space; acronym first + Arguments.of("(2010 iiWAS)", "822", "Information Integration and Web-based Applications and Services", "IIWAS", "C"), // acronym with other text separated by space; acronym second + Arguments.of("(CLOSER'12)", "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), // acronym with other text separated by quote + Arguments.of("(IEEE CCNC)", "616", "IEEE Consumer Communications and Networking Conference", "IEEE CCNC", "B"), // acronym with space in it + Arguments.of("(ACM_WiSec 2019)", "2313", "ACM Conference on Security and Privacy in Wireless and Mobile Networks", "ACM_WiSec", "B"), // acronym with special character with extra text separated by space + Arguments.of("(EC-TEL'2023)", "2262", "European Conference on Technology Enhanced Learning", "EC-TEL", "B"), // acronym with special character and quote + Arguments.of("(IEEE-IV'2023)", "2062", "Intelligent Vehicles Conference", "IEEE-IV", "B"), // longer acronym with delimiter matches (IEEE-IV) instead of nested one (IV) + Arguments.of("CoopIS 2009 (OTM 2009)", "979", "International Conference on Cooperative Information Systems", "CoopIS", "B"), // acronym outside parentheses matches post-normalization + Arguments.of("Cloud Computing and Services Science (CLOSER 2016): 6th International Conference", // Acronym in middle of title + "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), - // Title match tests - Arguments.of("AAAI Conference on Human Computation and Crowdsourcing", // Exact match without normalization - "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), - Arguments.of("Proceedings of the 2nd AAAI Conference on Human Computation and Crowdsourcing", // Exact match post-normalization - "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), - Arguments.of( - // Long booktitle with lots of filler text has conference title as a substring; an exact LCS match - "22nd IEEE International Enterprise Distributed Object Computing Conference, EDOC 2018, Stockholm, Sweden, October 16-19, 2018", - "682", "IEEE International Enterprise Distributed Object Computing Conference", "EDOC", "B"), - Arguments.of( - // Long misspelled booktitle with lots of filler text matches on combined Lev+LCS score above threshold - "Proceedings of the 3\\textsuperscript{rd} International Conference on Cloud Computing and Service Science, CLOSER 2013, 8-10 May 2013, Aachen, Germany", - "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), - Arguments.of( - // Long booktitle with lots of filler text and jumbled conference title does not match due to low combined score - "Advances in Information Retrieval - 41st European Conference on IR Research, ECIR 2019, Cologne, Germany, April 14-18, 2019, Proceedings, Part II", - null, null, null, null) + // Title match tests + Arguments.of("AAAI Conference on Human Computation and Crowdsourcing", // Exact match without normalization + "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), + Arguments.of("Proceedings of the 2nd AAAI Conference on Human Computation and Crowdsourcing", // Exact match post-normalization + "2264", "AAAI Conference on Human Computation and Crowdsourcing", "HCOMP", "B"), + Arguments.of( + // Long booktitle with lots of filler text has conference title as a substring; an exact LCS match + "22nd IEEE International Enterprise Distributed Object Computing Conference, EDOC 2018, Stockholm, Sweden, October 16-19, 2018", + "682", "IEEE International Enterprise Distributed Object Computing Conference", "EDOC", "B"), + Arguments.of( + // Long misspelled booktitle with lots of filler text matches on combined Lev+LCS score above threshold + "Proceedings of the 3\\textsuperscript{rd} International Conference on Cloud Computing and Service Science, CLOSER 2013, 8-10 May 2013, Aachen, Germany", + "2300", "International Conference on Cloud Computing and Services Science", "CLOSER", "C"), + Arguments.of( + // Long booktitle with lots of filler text and jumbled conference title does not match due to low combined score + "Advances in Information Retrieval - 41st European Conference on IR Research, ECIR 2019, Cologne, Germany, April 14-18, 2019, Proceedings, Part II", + null, null, null, null) ); } @@ -71,7 +71,7 @@ void getConferenceFromBookTitle( String expectedRank ) { Optional expectedResult = Optional.ofNullable(expectedId) - .map(_ -> new ConferenceEntry(expectedId, expectedTitle.toLowerCase(), expectedAcronym.toLowerCase(), expectedRank)); + .map(_ -> new ConferenceEntry(expectedId, expectedTitle.toLowerCase(), expectedAcronym.toLowerCase(), expectedRank)); assertEquals(expectedResult, TEST_REPO.getConferenceFromBookTitle(testBookTitle)); } diff --git a/jablib/src/test/java/org/jabref/logic/icore/ConferenceUtilsTest.java b/jablib/src/test/java/org/jabref/logic/icore/ConferenceUtilsTest.java index c88d439643a..1c109a5317b 100644 --- a/jablib/src/test/java/org/jabref/logic/icore/ConferenceUtilsTest.java +++ b/jablib/src/test/java/org/jabref/logic/icore/ConferenceUtilsTest.java @@ -18,16 +18,16 @@ public class ConferenceUtilsTest { @ParameterizedTest(name = "Extract from \"{0}\" should return \"{1}\"") @CsvSource({ - "(SERA), SERA", // Simple acronym extraction - "Extract conference from full title (SERA), SERA", // Acronym in a conference title - "This (SERA) has multiple (CONF) acronyms, SERA", // Extract only the first acronym encountered - "This (C++SER@-20_26) has special characters, C++SER@-20_26", // Special characters in acronym - "Input with whitespace ( ACR )', ACR", // Extract strips whitespace around acronym - "(Nested (parentheses (SERA))), SERA", // Extract the acronym in the deepest parentheses - "This open paren ((SERA) is never closed, SERA", // Extract acronym from incomplete parentheses - "Input with empty () parentheses, ", // Empty acronym inside parentheses - "Input with empty ( ) whitespace in parens, ", // Only whitespace inside parentheses - "'', " // Empty string + "(SERA), SERA", // Simple acronym extraction + "Extract conference from full title (SERA), SERA", // Acronym in a conference title + "This (SERA) has multiple (CONF) acronyms, SERA", // Extract only the first acronym encountered + "This (C++SER@-20_26) has special characters, C++SER@-20_26", // Special characters in acronym + "Input with whitespace ( ACR )', ACR", // Extract strips whitespace around acronym + "(Nested (parentheses (SERA))), SERA", // Extract the acronym in the deepest parentheses + "This open paren ((SERA) is never closed, SERA", // Extract acronym from incomplete parentheses + "Input with empty () parentheses, ", // Empty acronym inside parentheses + "Input with empty ( ) whitespace in parens, ", // Only whitespace inside parentheses + "'', " // Empty string }) void acronymExtraction(String input, String expectedResult) { assertEquals(Optional.ofNullable(expectedResult), extractStringFromParentheses(input)); @@ -35,17 +35,17 @@ void acronymExtraction(String input, String expectedResult) { @ParameterizedTest(name = "RemoveParentheses for \"{0}\" should return \"{1}\"") @CsvSource({ - "'', ''", // Empty string - "(removed), ''", // only parentheses string in input returns empty - "(Everything (here is (removed))), ''", // removes only nested parentheses string - "This is not removed (this is), 'This is not removed '", // single parentheses string is removed - "Removes (one) both (CONF) parens, Removes both parens", // multiple parentheses strings are removed - "Removes (this is (deep)) nested parens, Removes nested parens", // nested parentheses strings are removed - "Doesn't remove (this, Doesn't remove (this", // open with missing close paren is not removed - "Doesn't remove )this either, Doesn't remove )this either", // close with missing open paren is not removed - "Remove (this) but not )this, Remove but not )this", // matched paren pair is removed while close with missing open paren is not removed - "Multiple (one (two)) parens are (three) removed, Multiple parens are removed", // combination of single and nested parens - "Empty () parentheses, Empty parentheses" // empty parentheses are removed + "'', ''", // Empty string + "(removed), ''", // only parentheses string in input returns empty + "(Everything (here is (removed))), ''", // removes only nested parentheses string + "This is not removed (this is), 'This is not removed '", // single parentheses string is removed + "Removes (one) both (CONF) parens, Removes both parens", // multiple parentheses strings are removed + "Removes (this is (deep)) nested parens, Removes nested parens", // nested parentheses strings are removed + "Doesn't remove (this, Doesn't remove (this", // open with missing close paren is not removed + "Doesn't remove )this either, Doesn't remove )this either", // close with missing open paren is not removed + "Remove (this) but not )this, Remove but not )this", // matched paren pair is removed while close with missing open paren is not removed + "Multiple (one (two)) parens are (three) removed, Multiple parens are removed", // combination of single and nested parens + "Empty () parentheses, Empty parentheses" // empty parentheses are removed }) void removeParenthesesWithContent(String input, String expectedResult) { assertEquals(expectedResult, removeAllParenthesesWithContent(input)); @@ -59,105 +59,105 @@ void acronymCandidateGeneration(String input, int cutoff, Set expectedRe static Stream generateAcronymCandidateTestData() { return Stream.of( - // Edge cases - Arguments.of("", 2, Set.of()), // Empty string returns empty set - Arguments.of("foo", -1, Set.of()), // Negative cutoff returns empty set - Arguments.of("foo", 0, Set.of()), // Zero cutoff returns empty set - Arguments.of("foo", 1, Set.of()), // Cutoff too small - Arguments.of("bar", 3, Set.of("bar")), // Cutoff same as input length - Arguments.of("bar", 15, Set.of("bar")), // Cutoff larger than input length - Arguments.of("a", 1, Set.of("a")), // Single character - Arguments.of(" ", 3, Set.of()), // Only whitespace in input - - // Basic delimiter cases (space) - Arguments.of("ACR NYM", 3, Set.of("ACR", "NYM")), // Two acronyms, exact cutoff - Arguments.of("ACR NYM", 2, Set.of()), // Cutoff too small for acronyms - Arguments.of("ACR NYM", 7, Set.of("ACR NYM", "ACR", "NYM")), // Includes full string for large enough cutoff - Arguments.of("A B C", 1, Set.of("A", "B", "C")), // Single chars - Arguments.of("A B C", 3, Set.of("A", "B", "C", "A B", "B C")), // Partial subset combinations - Arguments.of("A B C", 5, Set.of("A B C", "A B", "B C", "A", "B", "C")), // All subset combinations - - // Multiple delimiter types - Arguments.of("ACRO_2012", 4, Set.of("ACRO", "2012")), // Underscore delimiter - Arguments.of("ACRO.2012", 4, Set.of("ACRO", "2012")), // Dot delimiter - Arguments.of("ACRO'2012", 4, Set.of("ACRO", "2012")), // Apostrophe delimiter - Arguments.of("ACRO:NYM", 4, Set.of("ACRO", "NYM")), // Colon delimiter - Arguments.of("ACRO-NYM", 4, Set.of("ACRO", "NYM")), // Hyphen delimiter - Arguments.of("ACRO,NYM", 4, Set.of("ACRO", "NYM")), // Comma delimiter - - Arguments.of("ACRO+NYM@CONF#2018", 20, Set.of("ACRO+NYM@CONF#2018")), // Does not split non-delimiters - - // Delimiter trimming cases - Arguments.of("____ACRO", 6, Set.of("ACRO")), // trim delimiter on beginning - Arguments.of("ACRO____", 6, Set.of("ACRO")), // trim delimiter on end - Arguments.of("____ACRO____", 6, Set.of("ACRO")), // trim delimiter on both sides - Arguments.of("_,-:.ACRO.:-,_", 6, Set.of("ACRO")), // trim different adjacent delimiters on both sides - Arguments.of("' _ : . , ", 9, Set.of()), // delimiter only string returns empty - Arguments.of("_,-:.ACRO_-NYM.:-,_", 10, Set.of("ACRO_-NYM", "ACRO", "NYM")), // trimming keeps delimiters between acronym but strips other subsets - Arguments.of("a.b_c:d", 3, Set.of("a.b", "b_c", "c:d", "a", "b", "c", "d")), // interleaved delimiters between valid characters preserves middle-delimiters in subsets - - // Subset generation with real-world examples - Arguments.of("CLOSER'2022", 11, Set.of("CLOSER'2022", "CLOSER", "2022")), // keeps original string at the head if below cutoff - Arguments.of("CLOSER'2022", 6, Set.of("CLOSER", "2022")), // discards original string if above cutoff - Arguments.of("ACM_WiSec'2022", 11, Set.of("WiSec'2022", "ACM_WiSec", "WiSec", "2022", "ACM")), // keeps longer candidates as well - Arguments.of("IEEE-IV'2022", 11, Set.of("IEEE-IV", "IV'2022", "2022", "IEEE", "IV")) // composite acronyms are pushed ahead for better matching + // Edge cases + Arguments.of("", 2, Set.of()), // Empty string returns empty set + Arguments.of("foo", -1, Set.of()), // Negative cutoff returns empty set + Arguments.of("foo", 0, Set.of()), // Zero cutoff returns empty set + Arguments.of("foo", 1, Set.of()), // Cutoff too small + Arguments.of("bar", 3, Set.of("bar")), // Cutoff same as input length + Arguments.of("bar", 15, Set.of("bar")), // Cutoff larger than input length + Arguments.of("a", 1, Set.of("a")), // Single character + Arguments.of(" ", 3, Set.of()), // Only whitespace in input + + // Basic delimiter cases (space) + Arguments.of("ACR NYM", 3, Set.of("ACR", "NYM")), // Two acronyms, exact cutoff + Arguments.of("ACR NYM", 2, Set.of()), // Cutoff too small for acronyms + Arguments.of("ACR NYM", 7, Set.of("ACR NYM", "ACR", "NYM")), // Includes full string for large enough cutoff + Arguments.of("A B C", 1, Set.of("A", "B", "C")), // Single chars + Arguments.of("A B C", 3, Set.of("A", "B", "C", "A B", "B C")), // Partial subset combinations + Arguments.of("A B C", 5, Set.of("A B C", "A B", "B C", "A", "B", "C")), // All subset combinations + + // Multiple delimiter types + Arguments.of("ACRO_2012", 4, Set.of("ACRO", "2012")), // Underscore delimiter + Arguments.of("ACRO.2012", 4, Set.of("ACRO", "2012")), // Dot delimiter + Arguments.of("ACRO'2012", 4, Set.of("ACRO", "2012")), // Apostrophe delimiter + Arguments.of("ACRO:NYM", 4, Set.of("ACRO", "NYM")), // Colon delimiter + Arguments.of("ACRO-NYM", 4, Set.of("ACRO", "NYM")), // Hyphen delimiter + Arguments.of("ACRO,NYM", 4, Set.of("ACRO", "NYM")), // Comma delimiter + + Arguments.of("ACRO+NYM@CONF#2018", 20, Set.of("ACRO+NYM@CONF#2018")), // Does not split non-delimiters + + // Delimiter trimming cases + Arguments.of("____ACRO", 6, Set.of("ACRO")), // trim delimiter on beginning + Arguments.of("ACRO____", 6, Set.of("ACRO")), // trim delimiter on end + Arguments.of("____ACRO____", 6, Set.of("ACRO")), // trim delimiter on both sides + Arguments.of("_,-:.ACRO.:-,_", 6, Set.of("ACRO")), // trim different adjacent delimiters on both sides + Arguments.of("' _ : . , ", 9, Set.of()), // delimiter only string returns empty + Arguments.of("_,-:.ACRO_-NYM.:-,_", 10, Set.of("ACRO_-NYM", "ACRO", "NYM")), // trimming keeps delimiters between acronym but strips other subsets + Arguments.of("a.b_c:d", 3, Set.of("a.b", "b_c", "c:d", "a", "b", "c", "d")), // interleaved delimiters between valid characters preserves middle-delimiters in subsets + + // Subset generation with real-world examples + Arguments.of("CLOSER'2022", 11, Set.of("CLOSER'2022", "CLOSER", "2022")), // keeps original string at the head if below cutoff + Arguments.of("CLOSER'2022", 6, Set.of("CLOSER", "2022")), // discards original string if above cutoff + Arguments.of("ACM_WiSec'2022", 11, Set.of("WiSec'2022", "ACM_WiSec", "WiSec", "2022", "ACM")), // keeps longer candidates as well + Arguments.of("IEEE-IV'2022", 11, Set.of("IEEE-IV", "IV'2022", "2022", "IEEE", "IV")) // composite acronyms are pushed ahead for better matching ); } @ParameterizedTest(name = "normalize(\"{0}\") should return \"{1}\"") @CsvSource({ - "'', ''", // empty string - "title, title", // nothing to normalize - "' hello world ', helloworld", // removes all space - - // Parentheses removal - "'conference (icml 2018)', conference", // removes parentheses with content and strip - "'(start) middle (end)', middle", // removes all parentheses with content - "'nested (inner (deep) content) text', nestedtext", // removes all parentheses with content regardless of depth - "'multiple (first) (second) (third)', multiple", // removes multiple consecutive parentheses with content - "'keep this (but (not this)) (but do keep this', keepthisbutdokeepthis", // doesn't remove content if open paren is never closed - "'keep this (but (not this)) )but do keep this', keepthisbutdokeepthis", // doesn't remove content for isolated close paren - - // Year removal (19XX and 20XX) - "'conference 2018 workshop 1999', conferenceworkshop", // removes years on their own - "'start-2019end', startend", // removes years between strings - "'conference 1800 keeps old years', conference1800keepsoldyears", // keeps non-matching years - "'health conference 42 test', healthconference42test", // does not remove non-matching numbers on their own - "conference201workshop, conference201workshop", // does not remove other numbers between string - - // Ordinal removal (simple and LaTeX) - "'1st 2nd 3rd 4th 21st 22nd 23rd 101st conference', conference", - "'3\\textsuperscript{rd} 17\\textsuperscript{th} 1\\textsuperscript{st} meeting', meeting", // need to escape \t otherwise it is read as tab - - // Stopword removal - "'proceedings volume part papers combined', combined", // regular stopwords - "'proceedings of the conference volume part', conference", // interleaved with a false start - "'january february march april may june july august september october november december conference', conference", // all months - "'conference january workshop february meeting', conferenceworkshopmeeting", // months interleaved - - // False start removal - "'of the conference', conference", - "'of machine learning', machinelearning", - "'the big conference', bigconference", - "'ofthe combined', combined", - "'the proceedings of the 25th international conference on machine learning', internationalconferenceonmachinelearning", // removes multiple false starts weaved between stopwords - - // Special characters and punctuation - "'conference & workshop - machine learning: ai @ home # 1 . test _ more', conferenceworkshopmachinelearningaihome1testmore", - "'symbols !@#$%^&*()_+-=[]{}|;:,.<>?', symbols", - - // Edge cases leading to empty string output - "2018, ''", // only year - "'(only parentheses)', ''", // only parentheses content - "'proceedings volume part papers', ''", // only stop words - "'1st 2nd 3rd', ''", // only ordinals - "'january february march', ''", // only months - "'2018 (removed) 1st proceedings march', ''", // combination of above - - // Some real-world examples with cases interleaved - "'proceedings of the 3rd international conference on machine learning (icml 2018)', internationalconferenceonmachinelearning", - "'21st annual conference on neural information processing (nips 2019)', annualconferenceonneuralinformationprocessing", - "'part i: the 15th conference (2020) & workshop proceedings, january edition', itheconferenceworkshopedition" + "'', ''", // empty string + "title, title", // nothing to normalize + "' hello world ', helloworld", // removes all space + + // Parentheses removal + "'conference (icml 2018)', conference", // removes parentheses with content and strip + "'(start) middle (end)', middle", // removes all parentheses with content + "'nested (inner (deep) content) text', nestedtext", // removes all parentheses with content regardless of depth + "'multiple (first) (second) (third)', multiple", // removes multiple consecutive parentheses with content + "'keep this (but (not this)) (but do keep this', keepthisbutdokeepthis", // doesn't remove content if open paren is never closed + "'keep this (but (not this)) )but do keep this', keepthisbutdokeepthis", // doesn't remove content for isolated close paren + + // Year removal (19XX and 20XX) + "'conference 2018 workshop 1999', conferenceworkshop", // removes years on their own + "'start-2019end', startend", // removes years between strings + "'conference 1800 keeps old years', conference1800keepsoldyears", // keeps non-matching years + "'health conference 42 test', healthconference42test", // does not remove non-matching numbers on their own + "conference201workshop, conference201workshop", // does not remove other numbers between string + + // Ordinal removal (simple and LaTeX) + "'1st 2nd 3rd 4th 21st 22nd 23rd 101st conference', conference", + "'3\\textsuperscript{rd} 17\\textsuperscript{th} 1\\textsuperscript{st} meeting', meeting", // need to escape \t otherwise it is read as tab + + // Stopword removal + "'proceedings volume part papers combined', combined", // regular stopwords + "'proceedings of the conference volume part', conference", // interleaved with a false start + "'january february march april may june july august september october november december conference', conference", // all months + "'conference january workshop february meeting', conferenceworkshopmeeting", // months interleaved + + // False start removal + "'of the conference', conference", + "'of machine learning', machinelearning", + "'the big conference', bigconference", + "'ofthe combined', combined", + "'the proceedings of the 25th international conference on machine learning', internationalconferenceonmachinelearning", // removes multiple false starts weaved between stopwords + + // Special characters and punctuation + "'conference & workshop - machine learning: ai @ home # 1 . test _ more', conferenceworkshopmachinelearningaihome1testmore", + "'symbols !@#$%^&*()_+-=[]{}|;:,.<>?', symbols", + + // Edge cases leading to empty string output + "2018, ''", // only year + "'(only parentheses)', ''", // only parentheses content + "'proceedings volume part papers', ''", // only stop words + "'1st 2nd 3rd', ''", // only ordinals + "'january february march', ''", // only months + "'2018 (removed) 1st proceedings march', ''", // combination of above + + // Some real-world examples with cases interleaved + "'proceedings of the 3rd international conference on machine learning (icml 2018)', internationalconferenceonmachinelearning", + "'21st annual conference on neural information processing (nips 2019)', annualconferenceonneuralinformationprocessing", + "'part i: the 15th conference (2020) & workshop proceedings, january edition', itheconferenceworkshopedition" }) void titleNormalization(String input, String expected) { assertEquals(expected, normalize(input)); diff --git a/jablib/src/test/java/org/jabref/logic/importer/AuthorListParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/AuthorListParserTest.java index ee3617406e3..625deb8075c 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/AuthorListParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/AuthorListParserTest.java @@ -95,10 +95,10 @@ private static Stream parseMultipleCorrectly() { new Author("J. M.", "J. M.", null, "Carmona", null) ), """ - Alexander Artemenko - I. Podadera - J. M. Carmona - """), + Alexander Artemenko + I. Podadera + J. M. Carmona + """), Arguments.of( AuthorList.of( new Author("First1", "F.", null, "Last1", null), @@ -106,10 +106,10 @@ private static Stream parseMultipleCorrectly() { new Author("First3", "F.", null, "Last3", null) ), """ - First1 Last1 - First2 Last2 - First3 Last3 - """) + First1 Last1 + First2 Last2 + First3 Last3 + """) ); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java b/jablib/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java index c8daed64745..403305748ef 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java @@ -62,14 +62,14 @@ void importUnknownFormatFromString(String resource, String format, int count) th private static Stream importFormats() { Collection result = new ArrayList<>(); - result.add(new Object[]{"fileformat/RisImporterTest1.ris", "ris", 1}); - result.add(new Object[]{"fileformat/IsiImporterTest1.isi", "isi", 1}); - result.add(new Object[]{"fileformat/RepecNepImporterTest2.txt", "repecnep", 1}); - result.add(new Object[]{"fileformat/OvidImporterTest3.txt", "ovid", 1}); - result.add(new Object[]{"fileformat/Endnote.entries.enw", "refer", 5}); - result.add(new Object[]{"fileformat/MsBibImporterTest4.xml", "msbib", 1}); - result.add(new Object[]{"fileformat/MsBibImporterTest4.bib", "bibtex", 1}); - result.add(new Object[]{"fileformat/refer.bibIX.ref", "refer-bibIX", 4}); + result.add(new Object[] {"fileformat/RisImporterTest1.ris", "ris", 1}); + result.add(new Object[] {"fileformat/IsiImporterTest1.isi", "isi", 1}); + result.add(new Object[] {"fileformat/RepecNepImporterTest2.txt", "repecnep", 1}); + result.add(new Object[] {"fileformat/OvidImporterTest3.txt", "ovid", 1}); + result.add(new Object[] {"fileformat/Endnote.entries.enw", "refer", 5}); + result.add(new Object[] {"fileformat/MsBibImporterTest4.xml", "msbib", 1}); + result.add(new Object[] {"fileformat/MsBibImporterTest4.bib", "bibtex", 1}); + result.add(new Object[] {"fileformat/refer.bibIX.ref", "refer-bibIX", 4}); return result.stream(); } } diff --git a/jablib/src/test/java/org/jabref/logic/importer/ParserResultTest.java b/jablib/src/test/java/org/jabref/logic/importer/ParserResultTest.java index 0e14f538ac8..ff32092d9a1 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/ParserResultTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/ParserResultTest.java @@ -78,15 +78,15 @@ void warningAddedForWhitespaceInCitationKeyImport(@TempDir Path tmpDir) throws I void warningAddedForMissingCommaInCitationKeyImport(@TempDir Path tmpDir) throws IOException { // Comma replaced by whitespace instead in citation key "myArticle " String bibtexEntry = """ - @article{myArticle\s - author = "Author Name", - title = "Title of the Article", - journal = "Journal Name", - year = "2024", - pages = "1-10", - publisher = "Publisher Name" - } - """; + @article{myArticle\s + author = "Author Name", + title = "Title of the Article", + journal = "Journal Name", + year = "2024", + pages = "1-10", + publisher = "Publisher Name" + } + """; Path tempFile = tmpDir.resolve("invalidBibTex.bib"); Files.write(tempFile, bibtexEntry.getBytes()); ParserResult parserResult = OpenDatabase.loadDatabase(tempFile, mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); @@ -96,15 +96,15 @@ void warningAddedForMissingCommaInCitationKeyImport(@TempDir Path tmpDir) throws @Test void warningAddedForCorruptedCitationKeyInImport(@TempDir Path tmpDir) throws IOException { String bibtexEntry = """ - @article{myArticle - author = "Author Name", - title = "Title of the Article", - journal = "Journal Name", - year = "2024", - pages = "1-10", - publisher = "Publisher Name" - } - """; + @article{myArticle + author = "Author Name", + title = "Title of the Article", + journal = "Journal Name", + year = "2024", + pages = "1-10", + publisher = "Publisher Name" + } + """; Path tempFile = tmpDir.resolve("invalidBibTex.bib"); Files.write(tempFile, bibtexEntry.getBytes()); @@ -116,15 +116,15 @@ void warningAddedForCorruptedCitationKeyInImport(@TempDir Path tmpDir) throws IO void skipsImportEntryForImproperSyntax(@TempDir Path tmpDir) throws IOException { // Comma after '=' character on line 2 throws error String bibtexEntry = """ - @article{myArticle, - author =, "Author Name", - title = "Title of the Article", - journal = "Journal Name", - year = "2024", - pages = "1-10", - publisher = "Publisher Name" - } - """; + @article{myArticle, + author =, "Author Name", + title = "Title of the Article", + journal = "Journal Name", + year = "2024", + pages = "1-10", + publisher = "Publisher Name" + } + """; Path tempFile = tmpDir.resolve("invalidBibTex.bib"); Files.write(tempFile, bibtexEntry.getBytes()); ParserResult parserResult = OpenDatabase.loadDatabase(tempFile, mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); diff --git a/jablib/src/test/java/org/jabref/logic/importer/WebFetchersTest.java b/jablib/src/test/java/org/jabref/logic/importer/WebFetchersTest.java index 97aa81b43b6..f5c106f3b02 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/WebFetchersTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/WebFetchersTest.java @@ -57,14 +57,14 @@ void setUp() { private Set> getIgnoredInaccessibleClasses() { return IGNORED_INACCESSIBLE_FETCHERS.stream() - .map(classPath -> { - try { - return Class.forName(classPath); - } catch (ClassNotFoundException e) { - LOGGER.error("Some of the ignored classes were not found", e); - return null; - } - }).filter(Objects::nonNull).collect(Collectors.toSet()); + .map(classPath -> { + try { + return Class.forName(classPath); + } catch (ClassNotFoundException e) { + LOGGER.error("Some of the ignored classes were not found", e); + return null; + } + }).filter(Objects::nonNull).collect(Collectors.toSet()); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java index 735fee29f99..6a856fa5e59 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java @@ -34,22 +34,22 @@ void setUp() { @Test void searchByQueryFindsEntry() throws FetcherException { BibEntry searchEntry = new BibEntry(StandardEntryType.Conference) - .withField(StandardField.AUTHOR, "Olsson, Tobias and Ericsson, Morgan and Wingkvist, Anna") - .withField(StandardField.YEAR, "2017") - .withField(StandardField.MONTH, "9") - .withField(StandardField.DAY, "11") - .withField(StandardField.SERIES, "ECSA '17") - .withField(StandardField.BOOKTITLE, "Proceedings of the 11th European Conference on Software Architecture: Companion Proceedings") - .withField(StandardField.DOI, "10.1145/3129790.3129810") - .withField(StandardField.LOCATION, "Canterbury, United Kingdom") - .withField(StandardField.ISBN, "9781450352178") - .withField(StandardField.KEYWORDS, "conformance checking, repository data mining, software architecture") - .withField(StandardField.PUBLISHER, "Association for Computing Machinery") - .withField(StandardField.ADDRESS, "New York, NY, USA") - .withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef") - .withField(StandardField.URL, "https://doi.org/10.1145/3129790.3129810") - .withField(StandardField.PAGETOTAL, "7") - .withField(StandardField.PAGES, "152–158"); + .withField(StandardField.AUTHOR, "Olsson, Tobias and Ericsson, Morgan and Wingkvist, Anna") + .withField(StandardField.YEAR, "2017") + .withField(StandardField.MONTH, "9") + .withField(StandardField.DAY, "11") + .withField(StandardField.SERIES, "ECSA '17") + .withField(StandardField.BOOKTITLE, "Proceedings of the 11th European Conference on Software Architecture: Companion Proceedings") + .withField(StandardField.DOI, "10.1145/3129790.3129810") + .withField(StandardField.LOCATION, "Canterbury, United Kingdom") + .withField(StandardField.ISBN, "9781450352178") + .withField(StandardField.KEYWORDS, "conformance checking, repository data mining, software architecture") + .withField(StandardField.PUBLISHER, "Association for Computing Machinery") + .withField(StandardField.ADDRESS, "New York, NY, USA") + .withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef") + .withField(StandardField.URL, "https://doi.org/10.1145/3129790.3129810") + .withField(StandardField.PAGETOTAL, "7") + .withField(StandardField.PAGES, "152–158"); List fetchedEntries = fetcher.performSearch("The relationship of code churn and architectural violations in the open source software JabRef"); // we clear the abstract due to copyright reasons (JabRef's code should not contain copyrighted abstracts) diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ArXivFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ArXivFetcherTest.java index 426453b58aa..5afeba01ea7 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ArXivFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ArXivFetcherTest.java @@ -86,7 +86,7 @@ void eachSetUp() { mainResultPaper = new BibEntry(StandardEntryType.Article) // ArXiv-original fields -// .withField(StandardField.AUTHOR, "Joeran Beel and Andrew Collins and Akiko Aizawa") + // .withField(StandardField.AUTHOR, "Joeran Beel and Andrew Collins and Akiko Aizawa") .withField(StandardField.TITLE, "The Architecture of Mr. DLib's Scientific Recommender-System API") .withField(StandardField.DATE, "2018-11-26") .withField(StandardField.ABSTRACT, "Recommender systems in academia are not widely available. This may be in part due to the difficulty and cost of developing and maintaining recommender systems. Many operators of academic products such as digital libraries and reference managers avoid this effort, although a recommender system could provide significant benefits to their users. In this paper, we introduce Mr. DLib's \"Recommendations as-a-Service\" (RaaS) API that allows operators of academic products to easily integrate a scientific recommender system into their products. Mr. DLib generates recommendations for research articles but in the future, recommendations may include call for papers, grants, etc. Operators of academic products can request recommendations from Mr. DLib and display these recommendations to their users. Mr. DLib can be integrated in just a few hours or days; creating an equivalent recommender system from scratch would require several months for an academic operator. Mr. DLib has been used by GESIS Sowiport and by the reference manager JabRef. Mr. DLib is open source and its goal is to facilitate the application of, and research on, scientific recommender systems. In this paper, we present the motivation for Mr. DLib, the architecture and details about the effectiveness. Mr. DLib has delivered 94m recommendations over a span of two years with an average click-through rate of 0.12%.") @@ -94,7 +94,7 @@ void eachSetUp() { .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1811.10364v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "cs.IR") -// .withField(StandardField.KEYWORDS, "cs.IR, cs.AI, cs.DL, cs.LG") + // .withField(StandardField.KEYWORDS, "cs.IR, cs.AI, cs.DL, cs.LG") // Unavailable info: // StandardField.JOURNALTITLE // INFO NOT APPLICABLE TO THIS ENTRY // ArXiv-issue DOI fields @@ -359,7 +359,7 @@ void searchEntryByIdWith4DigitsAndPrefixAndNotTrimmed() throws FetcherException @Test void searchEntryByIdWith5Digits() throws FetcherException { assertEquals(Optional.of( - "An Optimal Convergence Theorem for Mean Curvature Flow of Arbitrary Codimension in Hyperbolic Spaces"), + "An Optimal Convergence Theorem for Mean Curvature Flow of Arbitrary Codimension in Hyperbolic Spaces"), fetcher.performSearchById("1503.06747").flatMap(entry -> entry.getField(StandardField.TITLE))); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/BiodiversityLibraryTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/BiodiversityLibraryTest.java index 502b92e80f7..5cc43b94ac6 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/BiodiversityLibraryTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/BiodiversityLibraryTest.java @@ -94,16 +94,16 @@ void getItemMetadaUrl(String id) throws MalformedURLException, URISyntaxExceptio @Test void performSearch() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) - .withField(StandardField.AUTHOR, "Clark, John L. (John Littner) and Neill, David A. ") - .withField(StandardField.JOURNALTITLE, "PhytoKeys") - .withField(StandardField.LANGUAGE, "English") - .withField(StandardField.PUBLISHER, "Pensoft Publishers") - .withField(StandardField.TITLE, "\uFEFFAmanoa condorensis (Phyllanthaceae), a new shrubby species from the Cordillera del Condor in southern Ecuador") - .withField(StandardField.URL, "https://www.biodiversitylibrary.org/part/356490") - .withField(StandardField.DATE, "2023") - .withField(StandardField.VOLUME, "227") - .withField(StandardField.PAGES, "89--97") - .withField(StandardField.DOI, "10.3897/phytokeys.227.104703"); + .withField(StandardField.AUTHOR, "Clark, John L. (John Littner) and Neill, David A. ") + .withField(StandardField.JOURNALTITLE, "PhytoKeys") + .withField(StandardField.LANGUAGE, "English") + .withField(StandardField.PUBLISHER, "Pensoft Publishers") + .withField(StandardField.TITLE, "\uFEFFAmanoa condorensis (Phyllanthaceae), a new shrubby species from the Cordillera del Condor in southern Ecuador") + .withField(StandardField.URL, "https://www.biodiversitylibrary.org/part/356490") + .withField(StandardField.DATE, "2023") + .withField(StandardField.VOLUME, "227") + .withField(StandardField.PAGES, "89--97") + .withField(StandardField.DOI, "10.3897/phytokeys.227.104703"); assertEquals(expected, fetcher.performSearch("Amanoa condorensis (Phyllanthaceae)").getFirst()); } @@ -141,7 +141,7 @@ void jsonResultToBibEntry() { "Genre": "Book", "Title": "Potatoes : the poor man's own crop : illustrated with plates, showing the decay and disease of the potatoe [sic] : with hints to improve the land and life of the poor man : published to aid the Industrial Marlborough Exhibition" }"""); - expected = new BibEntry(StandardEntryType.Book) + expected = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Potatoes : the poor man's own crop : illustrated with plates, showing the decay and disease of the potatoe [sic] : with hints to improve the land and life of the poor man : published to aid the Industrial Marlborough Exhibition") .withField(StandardField.AUTHOR, "George, George ") .withField(StandardField.YEAR, "1861") diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/BvbFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/BvbFetcherTest.java index 9c2eacf86b3..2faffa615ef 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/BvbFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/BvbFetcherTest.java @@ -55,10 +55,10 @@ void performTest() throws FetcherException { List result = fetcher.performSearch(searchquery); assertFalse(result.isEmpty()); -// System.out.println("Query:\n"); -// System.out.println(fetcher.getURLForQuery(new StandardSyntaxParser().parse(searchquery, NO_EXPLICIT_FIELD))); -// System.out.println("Test result:\n"); -// result.forEach(entry -> System.out.println(entry.toString())); + // System.out.println("Query:\n"); + // System.out.println(fetcher.getURLForQuery(new StandardSyntaxParser().parse(searchquery, NO_EXPLICIT_FIELD))); + // System.out.println("Test result:\n"); + // result.forEach(entry -> System.out.println(entry.toString())); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/CiteSeerTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/CiteSeerTest.java index 92e59439f4c..fe787fc4e50 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/CiteSeerTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/CiteSeerTest.java @@ -72,7 +72,7 @@ void searchByQueryFindsEntryCopingTheoryAndResearch() throws FetcherException { void searchWithSortingByYear() throws FetcherException { Optional expected = Optional.of("1552"); List fetchedEntries = fetcher.performSearch("title:Theory AND year:1552 AND sortBy:Year"); - for (BibEntry actual: fetchedEntries) { + for (BibEntry actual : fetchedEntries) { if (actual.hasField(StandardField.YEAR)) { assertEquals(expected, actual.getField(StandardField.YEAR)); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/DOAJFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/DOAJFetcherTest.java index 0c92eb57e9d..896101fb1f2 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/DOAJFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/DOAJFetcherTest.java @@ -36,19 +36,19 @@ void setUp() { @Test void searchByQueryFindsEntry() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) - .withField(StandardField.AUTHOR, "Nísea de A. Corrêa and Maria P. Foss and Paula R. B. Diniz") - .withField(StandardField.DOI, "10.11606/issn.2176-7262.v49i6p533-548") - .withField(StandardField.ISSN, "2176-7262") - .withField(StandardField.JOURNAL, "Medicina") - .withField(StandardField.PUBLISHER, "Universidade de São Paulo") - .withField(StandardField.TITLE, "Structural and functional changes related to memory deficit in non-demential elderly individuals") - .withField(StandardField.URL, "http://www.revistas.usp.br/rmrp/article/view/127443") - .withField(StandardField.VOLUME, "49") - .withField(StandardField.NUMBER, "6") - .withField(StandardField.YEAR, "2016") - .withField(StandardField.MONTH, "December") - .withField(StandardField.KEYWORDS, "Central Nervous System. Structural Changes. Functional Changes. Memory deficits. Aging. Normal Aging. Magnetic Resonance Imaging") - .withField(StandardField.ABSTRACT, "Objective: Based on Magnetic Resonance Imaging (MRI), verify the structural and functional changes related to memory deficits in non-demented elderly individuals in comparison with young adults. Methodology: Proceeded a systematic review based on Preferred Reporting Items for Systematic Review and Meta-Analysis (PRISMA) fluxogram. The search was done on PubMed, Scopus and EBSCO databases using JabRef 2.10, and Web of Science. It was included in the analysis quasi-experimental, cross-sectional, cohort and case-control studies published between 2005 and 2014 in national and international indexed periodicals that had as sample: non-demented individuals older than 60 years old, who were submitted to MRI investigation of their for any brain structural and functional changes associated with memory deficits, identified in neuropsychologicals tests. Results: About the imaging technique, we reviewed studies that used structural MRIs (two articles), functional MRIs (six articles), both techniques (four articles). In the 12 studies, 38 distinct neuropsychological tests were used, an average of five different tests for each study (variation of 1-12). The most used tests were WAIS Digit Span Backwards (seven articles), Trail Making Test A and B (four articles) and Wechsler Memory Scale (four articles). Conclusion: The review showed that in normal aging the parahippocampal white substance, the hippocampus volume and entorhinal cortex slightly shrink, causing verbal memory reduction, possibly due to fiber demyelination; reduced connections between temporal and frontal lobes contributing to an impairement of episodic, working memory and verbal fluency; reduction suppression of irrelevant information, affecting the register of information; changes on frontal and parietal areas, compromising recognition memory; modifications in activity and connectivity of the default mode network; reorganization of cognitive functions and also a slower response, probably due to reduction of pre-frontal cortex activation"); + .withField(StandardField.AUTHOR, "Nísea de A. Corrêa and Maria P. Foss and Paula R. B. Diniz") + .withField(StandardField.DOI, "10.11606/issn.2176-7262.v49i6p533-548") + .withField(StandardField.ISSN, "2176-7262") + .withField(StandardField.JOURNAL, "Medicina") + .withField(StandardField.PUBLISHER, "Universidade de São Paulo") + .withField(StandardField.TITLE, "Structural and functional changes related to memory deficit in non-demential elderly individuals") + .withField(StandardField.URL, "http://www.revistas.usp.br/rmrp/article/view/127443") + .withField(StandardField.VOLUME, "49") + .withField(StandardField.NUMBER, "6") + .withField(StandardField.YEAR, "2016") + .withField(StandardField.MONTH, "December") + .withField(StandardField.KEYWORDS, "Central Nervous System. Structural Changes. Functional Changes. Memory deficits. Aging. Normal Aging. Magnetic Resonance Imaging") + .withField(StandardField.ABSTRACT, "Objective: Based on Magnetic Resonance Imaging (MRI), verify the structural and functional changes related to memory deficits in non-demented elderly individuals in comparison with young adults. Methodology: Proceeded a systematic review based on Preferred Reporting Items for Systematic Review and Meta-Analysis (PRISMA) fluxogram. The search was done on PubMed, Scopus and EBSCO databases using JabRef 2.10, and Web of Science. It was included in the analysis quasi-experimental, cross-sectional, cohort and case-control studies published between 2005 and 2014 in national and international indexed periodicals that had as sample: non-demented individuals older than 60 years old, who were submitted to MRI investigation of their for any brain structural and functional changes associated with memory deficits, identified in neuropsychologicals tests. Results: About the imaging technique, we reviewed studies that used structural MRIs (two articles), functional MRIs (six articles), both techniques (four articles). In the 12 studies, 38 distinct neuropsychological tests were used, an average of five different tests for each study (variation of 1-12). The most used tests were WAIS Digit Span Backwards (seven articles), Trail Making Test A and B (four articles) and Wechsler Memory Scale (four articles). Conclusion: The review showed that in normal aging the parahippocampal white substance, the hippocampus volume and entorhinal cortex slightly shrink, causing verbal memory reduction, possibly due to fiber demyelination; reduced connections between temporal and frontal lobes contributing to an impairement of episodic, working memory and verbal fluency; reduction suppression of irrelevant information, affecting the register of information; changes on frontal and parietal areas, compromising recognition memory; modifications in activity and connectivity of the default mode network; reorganization of cognitive functions and also a slower response, probably due to reduction of pre-frontal cortex activation"); List fetchedEntries = fetcher.performSearch("JabRef MRI"); assertEquals(List.of(expected), fetchedEntries); diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java index 10221a85ec2..78eab452854 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java @@ -136,7 +136,7 @@ void performSearchWithTitleWithCurlyBraces() throws FetcherException { .withField(StandardField.DOI, "10.13140/RG.2.2.36822.78406")); Optional actual = fetcher.performSearch(entryInput) - .stream().findFirst(); + .stream().findFirst(); assertEquals(expected, actual); } } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ScienceDirectTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ScienceDirectTest.java index 0419e3d5aaa..5418f5f2767 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/ScienceDirectTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/ScienceDirectTest.java @@ -26,6 +26,7 @@ class ScienceDirectTest { private final ImporterPreferences importerPreferences = mock(ImporterPreferences.class); private ScienceDirect finder; private BibEntry entry; + @BeforeEach void setUp() { Optional apiKey = Optional.of(new BuildInfo().scienceDirectApiKey); diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SearchBasedFetcherCapabilityTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SearchBasedFetcherCapabilityTest.java index ef8c313b148..96d36d84dcb 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SearchBasedFetcherCapabilityTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SearchBasedFetcherCapabilityTest.java @@ -97,7 +97,7 @@ default void supportsYearRangeSearch() throws FetcherException { /** * Test whether the library API supports journal based search. - * + *

          * WARNING: the error while merging information from user-assigned DOI (more specifically, "10.1016/j.geomphys.2012.09.009") * is related to a failed read by the Bibtex Parser (title is formatted in a weird way) */ diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SemanticScholarTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SemanticScholarTest.java index 7351f45473a..c85ec096019 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SemanticScholarTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SemanticScholarTest.java @@ -102,7 +102,7 @@ void fullTextNotFoundByDOI() throws IOException, FetcherException { @DisabledOnCIServer("CI server is unreliable") void fullTextFindByArXiv() throws URISyntaxException, IOException, FetcherException { BibEntry entry = new BibEntry().withField(StandardField.EPRINT, "1407.3561") - .withField(StandardField.ARCHIVEPREFIX, "arXiv"); + .withField(StandardField.ARCHIVEPREFIX, "arXiv"); assertEquals( Optional.of(new URI("https://arxiv.org/pdf/1407.3561.pdf").toURL()), fetcher.findFullText(entry) diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcherTest.java index 9744f18a2a4..a702f883234 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/SpringerNatureWebFetcherTest.java @@ -76,20 +76,20 @@ void searchByQueryFindsEntry() throws FetcherException { .withField(StandardField.ABSTRACT, "Labeling issues with the skills required to complete them can help contributors to choose tasks in Open Source Software projects. However, manually labeling issues is time-consuming and error-prone, and current automated approaches are mostly limited to classifying issues as bugs/non-bugs. We investigate the feasibility and relevance of automatically labeling issues with what we call “API-domains,” which are high-level categories of APIs. Therefore, we posit that the APIs used in the source code affected by an issue can be a proxy for the type of skills (e.g., DB, security, UI) needed to work on the issue. We ran a user study (n=74) to assess API-domain labels’ relevancy to potential contributors, leveraged the issues’ descriptions and the project history to build prediction models, and validated the predictions with contributors (n=20) of the projects. Our results show that (i) newcomers to the project consider API-domain labels useful in choosing tasks, (ii) labels can be predicted with a precision of 84% and a recall of 78.6% on average, (iii) the results of the predictions reached up to 71.3% in precision and 52.5% in recall when training with a project and testing in another (transfer learning), and (iv) project contributors consider most of the predictions helpful in identifying needed skills. These findings suggest our approach can be applied in practice to automatically label issues, assisting developers in finding tasks that better match their skills."); BibEntry firstArticle = new BibEntry(StandardEntryType.Article) - .withField(StandardField.AUTHOR, "Steinmacher, Igor and Balali, Sogol and Trinkenreich, Bianca and Guizani, Mariam and Izquierdo-Cortazar, Daniel and Cuevas Zambrano, Griselda G. and Gerosa, Marco Aurelio and Sarma, Anita") - .withField(StandardField.DATE, "2021-09-09") - .withField(StandardField.DOI, "10.1186/s13174-021-00140-z") - .withField(StandardField.ISSN, "1867-4828") - .withField(StandardField.JOURNAL, "Journal of Internet Services and Applications") - .withField(StandardField.MONTH, "#sep#") - .withField(StandardField.PAGES, "1--33") - .withField(StandardField.NUMBER, "1") - .withField(StandardField.VOLUME, "12") - .withField(StandardField.PUBLISHER, "Springer") - .withField(StandardField.TITLE, "Being a Mentor in open source projects") - .withField(StandardField.YEAR, "2021") - .withField(StandardField.FILE, ":https\\://www.biomedcentral.com/openurl/pdf?id=doi\\:10.1186/s13174-021-00140-z:PDF") - .withField(StandardField.ABSTRACT, "Mentoring is a well-known way to help newcomers to Open Source Software (OSS) projects overcome initial contribution barriers. Through mentoring, newcomers learn to acquire essential technical, social, and organizational skills. Despite the importance of OSS mentors, they are understudied in the literature. Understanding who OSS project mentors are, the challenges they face, and the strategies they use can help OSS projects better support mentors’ work. In this paper, we employ a two-stage study to comprehensively investigate mentors in OSS. First, we identify the characteristics of mentors in the Apache Software Foundation, a large OSS community, using an online survey. We found that less experienced volunteer contributors are less likely to take on the mentorship role. Second, through interviews with OSS mentors (n=18), we identify the challenges that mentors face and how they mitigate them. In total, we identified 25 general mentorship challenges and 7 sub-categories of challenges regarding task recommendation. We also identified 13 strategies to overcome the challenges related to task recommendation. Our results provide insights for OSS communities, formal mentorship programs, and tool builders who design automated support for task assignment and internship."); + .withField(StandardField.AUTHOR, "Steinmacher, Igor and Balali, Sogol and Trinkenreich, Bianca and Guizani, Mariam and Izquierdo-Cortazar, Daniel and Cuevas Zambrano, Griselda G. and Gerosa, Marco Aurelio and Sarma, Anita") + .withField(StandardField.DATE, "2021-09-09") + .withField(StandardField.DOI, "10.1186/s13174-021-00140-z") + .withField(StandardField.ISSN, "1867-4828") + .withField(StandardField.JOURNAL, "Journal of Internet Services and Applications") + .withField(StandardField.MONTH, "#sep#") + .withField(StandardField.PAGES, "1--33") + .withField(StandardField.NUMBER, "1") + .withField(StandardField.VOLUME, "12") + .withField(StandardField.PUBLISHER, "Springer") + .withField(StandardField.TITLE, "Being a Mentor in open source projects") + .withField(StandardField.YEAR, "2021") + .withField(StandardField.FILE, ":https\\://www.biomedcentral.com/openurl/pdf?id=doi\\:10.1186/s13174-021-00140-z:PDF") + .withField(StandardField.ABSTRACT, "Mentoring is a well-known way to help newcomers to Open Source Software (OSS) projects overcome initial contribution barriers. Through mentoring, newcomers learn to acquire essential technical, social, and organizational skills. Despite the importance of OSS mentors, they are understudied in the literature. Understanding who OSS project mentors are, the challenges they face, and the strategies they use can help OSS projects better support mentors’ work. In this paper, we employ a two-stage study to comprehensively investigate mentors in OSS. First, we identify the characteristics of mentors in the Apache Software Foundation, a large OSS community, using an online survey. We found that less experienced volunteer contributors are less likely to take on the mentorship role. Second, through interviews with OSS mentors (n=18), we identify the challenges that mentors face and how they mitigate them. In total, we identified 25 general mentorship challenges and 7 sub-categories of challenges regarding task recommendation. We also identified 13 strategies to overcome the challenges related to task recommendation. Our results provide insights for OSS communities, formal mentorship programs, and tool builders who design automated support for task assignment and internship."); BibEntry secondArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Steinmacher, Igor and Gerosa, Marco and Conte, Tayana U. and Redmiles, David F.") @@ -108,33 +108,33 @@ void searchByQueryFindsEntry() throws FetcherException { .withField(StandardField.ABSTRACT, "An influx of newcomers is critical to the survival, long-term success, and continuity of many Open Source Software (OSS) community-based projects. However, newcomers face many barriers when making their first contribution, leading in many cases to dropouts. Due to the collaborative nature of community-based OSS projects, newcomers may be susceptible to social barriers, such as communication breakdowns and reception issues. In this article, we report a two-phase study aimed at better understanding social barriers faced by newcomers. In the first phase, we qualitatively analyzed the literature and data collected from practitioners to identify barriers that hinder newcomers’ first contribution. We designed a model composed of 58 barriers, including 13 social barriers. In the second phase, based on the barriers model, we developed FLOSScoach, a portal to support newcomers making their first contribution. We evaluated the portal in a diary-based study and found that the portal guided the newcomers and reduced the need for communication. Our results provide insights for communities that want to support newcomers and lay a foundation for building better onboarding tools. The contributions of this paper include identifying and gathering empirical evidence of social barriers faced by newcomers; understanding how social barriers can be reduced or avoided by using a portal that organizes proper information for newcomers (FLOSScoach); presenting guidelines for communities and newcomers on how to reduce or avoid social barriers; and identifying new streams of research."); BibEntry thirdArticle = new BibEntry(StandardEntryType.InCollection) - .withField(StandardField.AUTHOR, "Serrano Alves, Luiz Philipe and Wiese, Igor Scaliante and Chaves, Ana Paula and Steinmacher, Igor") - .withField(StandardField.BOOKTITLE, "Chatbot Research and Design") - .withField(StandardField.DATE, "2022-01-01") - .withField(StandardField.DOI, "10.1007/978-3-030-94890-0_6") - .withField(StandardField.ISBN, "978-3-030-94889-4") - .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/978-3-030-94890-0_6:PDF") - .withField(StandardField.MONTH, "#jan#") - .withField(StandardField.PUBLISHER, "Springer") - .withField(StandardField.YEAR, "2022") - .withField(StandardField.TITLE, "How to Find My Task? Chatbot to Assist Newcomers in Choosing Tasks in OSS Projects") - .withField(StandardField.ABSTRACT, "Open Source Software (OSS) is making a meteoric rise in the software industry since several big companies have entered this market. Unfortunately, newcomers enter these projects and usually lose interest in contributing because of several factors. This paper aims to reduce the problems users face when they walk their first steps into OSS projects: finding the appropriate task. This paper presents a chatbot that filters tasks to help newcomers choose a task that fits their skills. We performed a quantitative and a qualitative study comparing the chatbot with the current GitHub issue tracker interface, which uses labels to categorize and identify tasks. The results show that users perceived the chatbot as easier to use than the GitHub issue tracker. Additionally, users tend to interpret the use of chatbots as situational, helping mainly newcomers and inexperienced contributors."); + .withField(StandardField.AUTHOR, "Serrano Alves, Luiz Philipe and Wiese, Igor Scaliante and Chaves, Ana Paula and Steinmacher, Igor") + .withField(StandardField.BOOKTITLE, "Chatbot Research and Design") + .withField(StandardField.DATE, "2022-01-01") + .withField(StandardField.DOI, "10.1007/978-3-030-94890-0_6") + .withField(StandardField.ISBN, "978-3-030-94889-4") + .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/978-3-030-94890-0_6:PDF") + .withField(StandardField.MONTH, "#jan#") + .withField(StandardField.PUBLISHER, "Springer") + .withField(StandardField.YEAR, "2022") + .withField(StandardField.TITLE, "How to Find My Task? Chatbot to Assist Newcomers in Choosing Tasks in OSS Projects") + .withField(StandardField.ABSTRACT, "Open Source Software (OSS) is making a meteoric rise in the software industry since several big companies have entered this market. Unfortunately, newcomers enter these projects and usually lose interest in contributing because of several factors. This paper aims to reduce the problems users face when they walk their first steps into OSS projects: finding the appropriate task. This paper presents a chatbot that filters tasks to help newcomers choose a task that fits their skills. We performed a quantitative and a qualitative study comparing the chatbot with the current GitHub issue tracker interface, which uses labels to categorize and identify tasks. The results show that users perceived the chatbot as easier to use than the GitHub issue tracker. Additionally, users tend to interpret the use of chatbots as situational, helping mainly newcomers and inexperienced contributors."); BibEntry fourthArticle = new BibEntry(StandardEntryType.Article) - .withField(StandardField.AUTHOR, "Calefato, Fabio and Gerosa, Marco Aurélio and Iaffaldano, Giuseppe and Lanubile, Filippo and Steinmacher, Igor") - .withField(StandardField.DATE, "2022-03-19") - .withField(StandardField.DOI, "10.1007/s10664-021-10012-6") - .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/s10664-021-10012-6:PDF") - .withField(StandardField.ISSN, "1382-3256") - .withField(StandardField.JOURNAL, "Empirical Software Engineering") - .withField(StandardField.MONTH, "#mar#") - .withField(StandardField.NUMBER, "3") - .withField(StandardField.PAGES, "1--41") - .withField(StandardField.PUBLISHER, "Springer") - .withField(StandardField.TITLE, "Will you come back to contribute? Investigating the inactivity of OSS core developers in GitHub") - .withField(StandardField.VOLUME, "27") - .withField(StandardField.YEAR, "2022") - .withField(StandardField.ABSTRACT, "Several Open-Source Software (OSS) projects depend on the continuity of their development communities to remain sustainable. Understanding how developers become inactive or why they take breaks can help communities prevent abandonment and incentivize developers to come back. In this paper, we propose a novel method to identify developers’ inactive periods by analyzing the individual rhythm of contributions to the projects. Using this method, we quantitatively analyze the inactivity of core developers in 18 OSS organizations hosted on GitHub. We also survey core developers to receive their feedback about the identified breaks and transitions. Our results show that our method was effective for identifying developers’ breaks. About 94% of the surveyed core developers agreed with our state model of inactivity; 71% and 79% of them acknowledged their breaks and state transition, respectively. We also show that all core developers take breaks (at least once) and about a half of them (~45%) have completely disengaged from a project for at least one year. We also analyzed the probability of transitions to/from inactivity and found that developers who pause their activity have a ~35 to ~55% chance to return to an active state; yet, if the break lasts for a year or longer, then the probability of resuming activities drops to ~21–26%, with a ~54% chance of complete disengagement. These results may support the creation of policies and mechanisms to make OSS community managers aware of breaks and potential project abandonment."); + .withField(StandardField.AUTHOR, "Calefato, Fabio and Gerosa, Marco Aurélio and Iaffaldano, Giuseppe and Lanubile, Filippo and Steinmacher, Igor") + .withField(StandardField.DATE, "2022-03-19") + .withField(StandardField.DOI, "10.1007/s10664-021-10012-6") + .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/s10664-021-10012-6:PDF") + .withField(StandardField.ISSN, "1382-3256") + .withField(StandardField.JOURNAL, "Empirical Software Engineering") + .withField(StandardField.MONTH, "#mar#") + .withField(StandardField.NUMBER, "3") + .withField(StandardField.PAGES, "1--41") + .withField(StandardField.PUBLISHER, "Springer") + .withField(StandardField.TITLE, "Will you come back to contribute? Investigating the inactivity of OSS core developers in GitHub") + .withField(StandardField.VOLUME, "27") + .withField(StandardField.YEAR, "2022") + .withField(StandardField.ABSTRACT, "Several Open-Source Software (OSS) projects depend on the continuity of their development communities to remain sustainable. Understanding how developers become inactive or why they take breaks can help communities prevent abandonment and incentivize developers to come back. In this paper, we propose a novel method to identify developers’ inactive periods by analyzing the individual rhythm of contributions to the projects. Using this method, we quantitatively analyze the inactivity of core developers in 18 OSS organizations hosted on GitHub. We also survey core developers to receive their feedback about the identified breaks and transitions. Our results show that our method was effective for identifying developers’ breaks. About 94% of the surveyed core developers agreed with our state model of inactivity; 71% and 79% of them acknowledged their breaks and state transition, respectively. We also show that all core developers take breaks (at least once) and about a half of them (~45%) have completely disengaged from a project for at least one year. We also analyzed the probability of transitions to/from inactivity and found that developers who pause their activity have a ~35 to ~55% chance to return to an active state; yet, if the break lasts for a year or longer, then the probability of resuming activities drops to ~21–26%, with a ~54% chance of complete disengagement. These results may support the creation of policies and mechanisms to make OSS community managers aware of breaks and potential project abandonment."); List fetchedEntries = fetcher.performSearch("JabRef Social Barriers Steinmacher"); assertEquals(List.of(articleSupportingIdentification, articleTagThatIssue, fourthArticle, thirdArticle, firstArticle, secondArticle), fetchedEntries); @@ -233,8 +233,8 @@ void supportsBooleanANDSearch() throws FetcherException { assertTrue(resultJustByAuthor.containsAll(result)); List allEntriesFromCSCW = result.stream() .filter(bibEntry -> "Computer Supported Cooperative Work (CSCW)" - .equals(bibEntry.getField(StandardField.JOURNAL) - .orElse(""))) + .equals(bibEntry.getField(StandardField.JOURNAL) + .orElse(""))) .toList(); allEntriesFromCSCW.stream() .map(bibEntry -> bibEntry.getField(StandardField.AUTHOR)) diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/citation/CitationFetcherHelpersForTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/citation/CitationFetcherHelpersForTest.java index 3092048f1f0..8061d0c0ef5 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/citation/CitationFetcherHelpersForTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/citation/CitationFetcherHelpersForTest.java @@ -10,9 +10,9 @@ public class CitationFetcherHelpersForTest { public static class Mocks { public static CitationFetcher from( - Function> retrieveCitedBy, - Function> retrieveCiting, - Function> retrieveCitationCount + Function> retrieveCitedBy, + Function> retrieveCiting, + Function> retrieveCitationCount ) { return new CitationFetcher() { @Override diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/GVKIsbnFetcherTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/GVKIsbnFetcherTest.java index a56b62436c1..5c4ef46bf67 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/GVKIsbnFetcherTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/GVKIsbnFetcherTest.java @@ -99,7 +99,7 @@ public void authorsAreCorrectlyFormatted() throws FetcherException { void isbnNeitherAvailableOnEbookDeNorOrViaOpenLibrary() throws FetcherException { // In this test, the ISBN needs to be a valid (syntax+checksum) ISBN number // However, the ISBN number must not be assigned to a real book - assertEquals(Optional.empty(), fetcher.performSearchById("9785646216541")); + assertEquals(Optional.empty(), fetcher.performSearchById("9785646216541")); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformerTest.java b/jablib/src/test/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformerTest.java index 89788e8e0bc..865f752f17f 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformerTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformerTest.java @@ -109,8 +109,8 @@ void convertMultipleAuthors() throws ParseCancellationException { private static Stream getJSONWithYearVariations() { String baseString = "title=Ericksen-Leslie page=1 pageSize=20 must_have_pdf=false sortBy=relevance"; List withYearAndYearRange = List.of( - StringUtil.join(new String[]{baseString, "year=2020"}, " ", 0, 2), - StringUtil.join(new String[]{baseString, "year-range=2019-2023"}, " ", 0, 2) + StringUtil.join(new String[] {baseString, "year=2020"}, " ", 0, 2), + StringUtil.join(new String[] {baseString, "year-range=2019-2023"}, " ", 0, 2) ); JSONObject expectedJson = new JSONObject(); diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java index 198c7ffff38..cbbe365cf99 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java @@ -117,22 +117,22 @@ void parseBibEntry() { void parseBibEntryWithFamilyAuthorOnly() { String json = "{\"id\":\"10.1145/3011077.3011113\",\"type\":\"PAPER_CONFERENCE\",\"author\":[{\"family\":\"Ngo-Thi-Thu-Trang\"},{\"family\":\"Bui\",\"given\":\"Hieu T.\"},{\"family\":\"Nguyen\",\"given\":\"Nhan D.\"}],\"accessed\":{\"date-parts\":[[2023,8,4]]},\"issued\":{\"date-parts\":[[2016,12,8]]},\"original-date\":{\"date-parts\":[[2016,12,8]]},\"abstract\":\"\",\"call-number\":\"10.1145/3011077.3011113\",\"collection-title\":\"SoICT '16\",\"container-title\":\"Proceedings of the 7th Symposium on Information and Communication Technology\",\"DOI\":\"10.1145/3011077.3011113\",\"event-place\":\"Ho Chi Minh City, Vietnam\",\"ISBN\":\"9781450348157\",\"keyword\":\"orthogonal frequency division multiplexing (OFDM), long-range passive optical network (LR PON), four-wave mixing (FWM), wavelength division multiplexing (WDM)\",\"number-of-pages\":\"6\",\"page\":\"216–221\",\"publisher\":\"Association for Computing Machinery\",\"publisher-place\":\"New York, NY, USA\",\"title\":\"A simple performance analysis of IM-DD OFDM WDM systems in long range PON application\",\"URL\":\"https://doi.org/10.1145/3011077.3011113\"}"; BibEntry expectedEntry = new BibEntry(StandardEntryType.Conference) - .withField(StandardField.AUTHOR, "Ngo-Thi-Thu-Trang and Bui, Hieu T. and Nguyen, Nhan D.") - .withField(StandardField.TITLE, "A simple performance analysis of IM-DD OFDM WDM systems in long range PON application") - .withField(StandardField.BOOKTITLE, "Proceedings of the 7th Symposium on Information and Communication Technology") - .withField(StandardField.YEAR, "2016") - .withField(StandardField.SERIES, "SoICT '16") - .withField(StandardField.PAGES, "216–221") - .withField(StandardField.ADDRESS, "New York, NY, USA") - .withField(StandardField.MONTH, "12") - .withField(StandardField.PUBLISHER, "Association for Computing Machinery") - .withField(StandardField.LOCATION, "Ho Chi Minh City, Vietnam") - .withField(StandardField.ISBN, "9781450348157") - .withField(StandardField.DAY, "8") - .withField(StandardField.PAGETOTAL, "6") - .withField(StandardField.DOI, "10.1145/3011077.3011113") - .withField(StandardField.KEYWORDS, "four-wave mixing (FWM), long-range passive optical network (LR PON), orthogonal frequency division multiplexing (OFDM), wavelength division multiplexing (WDM)") - .withField(StandardField.URL, "https://doi.org/10.1145/3011077.3011113"); + .withField(StandardField.AUTHOR, "Ngo-Thi-Thu-Trang and Bui, Hieu T. and Nguyen, Nhan D.") + .withField(StandardField.TITLE, "A simple performance analysis of IM-DD OFDM WDM systems in long range PON application") + .withField(StandardField.BOOKTITLE, "Proceedings of the 7th Symposium on Information and Communication Technology") + .withField(StandardField.YEAR, "2016") + .withField(StandardField.SERIES, "SoICT '16") + .withField(StandardField.PAGES, "216–221") + .withField(StandardField.ADDRESS, "New York, NY, USA") + .withField(StandardField.MONTH, "12") + .withField(StandardField.PUBLISHER, "Association for Computing Machinery") + .withField(StandardField.LOCATION, "Ho Chi Minh City, Vietnam") + .withField(StandardField.ISBN, "9781450348157") + .withField(StandardField.DAY, "8") + .withField(StandardField.PAGETOTAL, "6") + .withField(StandardField.DOI, "10.1145/3011077.3011113") + .withField(StandardField.KEYWORDS, "four-wave mixing (FWM), long-range passive optical network (LR PON), orthogonal frequency division multiplexing (OFDM), wavelength division multiplexing (WDM)") + .withField(StandardField.URL, "https://doi.org/10.1145/3011077.3011113"); BibEntry parsedEntry = parser.parseBibEntry(json); assertEquals(expectedEntry, parsedEntry); diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporterTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporterTest.java index 0f99beccf90..be59e972cba 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibliographyFromPdfImporterTest.java @@ -192,13 +192,13 @@ void tua3i2refpage() throws URISyntaxException { BibEntry entry09 = new BibEntry(StandardEntryType.InProceedings) .withCitationKey("9") .withField(StandardField.AUTHOR, "A. De Franco and others") - .withField(StandardField.BOOKTITLE, "Proc. IPAC’23, Venice, Italy") + .withField(StandardField.BOOKTITLE, "Proc. IPAC’23, Venice, Italy") .withField(StandardField.TITLE, "RF conditioning towards continuous wave of the FRQ of the Linear IFMIF Prototype Accelerator") .withField(StandardField.PAGES, "2345-2348") .withField(StandardField.MONTH, "#may#") .withField(StandardField.YEAR, "2023") - .withField(StandardField.DOI, "10.18429/JACoW-IPAC2023-TUPM065") - .withField(StandardField.COMMENT, "[9] A. De Franco et al., “RF conditioning towards continuous wave of the FRQ of the Linear IFMIF Prototype Accelerator”, in Proc. IPAC’23, Venice, Italy, May 2023, pp. 2345-2348. doi:10.18429/JACoW-IPAC2023-TUPM065"); + .withField(StandardField.DOI, "10.18429/JACoW-IPAC2023-TUPM065") + .withField(StandardField.COMMENT, "[9] A. De Franco et al., “RF conditioning towards continuous wave of the FRQ of the Linear IFMIF Prototype Accelerator”, in Proc. IPAC’23, Venice, Italy, May 2023, pp. 2345-2348. doi:10.18429/JACoW-IPAC2023-TUPM065"); BibEntry entry10 = new BibEntry(StandardEntryType.InProceedings) .withCitationKey("10") @@ -281,13 +281,13 @@ static Stream references() { AKAGI_2023, INTERNAL_NOTE, new BibEntry(StandardEntryType.InProceedings) - .withCitationKey("18") - .withField(StandardField.AUTHOR, "Z. Yao and D. S. Weld and W-P. Chen and H. Sun") - .withField(StandardField.BOOKTITLE, "Proceedings of the 2018 World Wide Web Conference") - .withField(StandardField.COMMENT, "[18] Z. Yao, D. S. Weld, W.-P. Chen, and H. Sun, “Staqc: A systematically mined question-code dataset from stack overflow,” in Proceedings of the 2018 World Wide Web Conference, 2018, pp. 1693–1703.") - .withField(StandardField.TITLE, "Staqc: A systematically mined question-code dataset from stack overflow") - .withField(StandardField.PAGES, "1693-1703") - .withField(StandardField.YEAR, "2018") + .withCitationKey("18") + .withField(StandardField.AUTHOR, "Z. Yao and D. S. Weld and W-P. Chen and H. Sun") + .withField(StandardField.BOOKTITLE, "Proceedings of the 2018 World Wide Web Conference") + .withField(StandardField.COMMENT, "[18] Z. Yao, D. S. Weld, W.-P. Chen, and H. Sun, “Staqc: A systematically mined question-code dataset from stack overflow,” in Proceedings of the 2018 World Wide Web Conference, 2018, pp. 1693–1703.") + .withField(StandardField.TITLE, "Staqc: A systematically mined question-code dataset from stack overflow") + .withField(StandardField.PAGES, "1693-1703") + .withField(StandardField.YEAR, "2018") ); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java index 76b5c4edf81..e482d3a4870 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java @@ -106,12 +106,12 @@ void importMultipleEntriesInSingleFile() throws IOException, URISyntaxException BibEntry expectedEntry5 = new BibEntry(StandardEntryType.Proceedings) .withField(StandardField.KEYWORDS, "Female") - .withField(StandardField.PMID, "96578310"); + .withField(StandardField.PMID, "96578310"); assertEquals(expectedEntry5, entries.get(5)); BibEntry expectedEntry6 = new BibEntry(StandardEntryType.Misc) .withField(StandardField.KEYWORDS, "Female") - .withField(StandardField.PMID, "45984220"); + .withField(StandardField.PMID, "45984220"); assertEquals(expectedEntry6, entries.get(6)); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ReferImporterTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ReferImporterTest.java index 76eb9f6127c..4737473bf43 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ReferImporterTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ReferImporterTest.java @@ -106,9 +106,9 @@ void editorNameInAuthorField() throws IOException { """; BibEntry entry = referImporter.importDatabase(new BufferedReader(Reader.of(refEntry))) - .getDatabase() - .getEntries() - .getFirst(); + .getDatabase() + .getEntries() + .getFirst(); assertEquals(StandardEntryType.Book, entry.getType()); assertEquals(Optional.empty(), entry.getField(StandardField.AUTHOR)); diff --git a/jablib/src/test/java/org/jabref/logic/importer/plaincitation/GrobidPlainCitationParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/plaincitation/GrobidPlainCitationParserTest.java index 91d03311703..015e2c001cf 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/plaincitation/GrobidPlainCitationParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/plaincitation/GrobidPlainCitationParserTest.java @@ -63,16 +63,16 @@ public class GrobidPlainCitationParserTest { static String example3 = "Turk, J., Graham, P., & Verhulst, F. (2007). Child and adolescent psychiatry : A developmental approach. Oxford, England: Oxford University Press."; static BibEntry example3AsBibEntry = new BibEntry(StandardEntryType.InBook).withCitationKey("-1") - .withField(StandardField.AUTHOR, "Turk, Jeremy and Graham, Philip and Verhulst, Frank") - .withField(StandardField.TITLE, "Developmental psychopathology") - .withField(StandardField.BOOKTITLE, "Child and Adolescent Psychiatry") - .withField(StandardField.PUBLISHER, "Oxford University Press") - .withField(StandardField.DATE, "2007-02") - .withField(StandardField.YEAR, "2007") - .withField(StandardField.MONTH, "2") - .withField(StandardField.PAGES, "191-264") - .withField(StandardField.DOI, "10.1093/med/9780199216697.003.0004") - .withField(StandardField.ADDRESS, "Oxford, England"); + .withField(StandardField.AUTHOR, "Turk, Jeremy and Graham, Philip and Verhulst, Frank") + .withField(StandardField.TITLE, "Developmental psychopathology") + .withField(StandardField.BOOKTITLE, "Child and Adolescent Psychiatry") + .withField(StandardField.PUBLISHER, "Oxford University Press") + .withField(StandardField.DATE, "2007-02") + .withField(StandardField.YEAR, "2007") + .withField(StandardField.MONTH, "2") + .withField(StandardField.PAGES, "191-264") + .withField(StandardField.DOI, "10.1093/med/9780199216697.003.0004") + .withField(StandardField.ADDRESS, "Oxford, England"); static String example4 = "Carr, I., & Kidner, R. (2003). Statutes and conventions on international trade law (4th ed.). London, England: Cavendish."; static BibEntry example4AsBibEntry = new BibEntry(StandardEntryType.InBook).withCitationKey("-1") diff --git a/jablib/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java index c6f1f1dd48b..cede695444d 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java @@ -50,7 +50,7 @@ private static Stream stringsToParseTest() throws MalformedURLExcepti List.of(), "" ), - + // URL starting with www. (without protocol) Arguments.of( List.of(new LinkedFile("A test", URLUtil.create("https://www.yahoo.com/abc/cde.htm"), "URL")), @@ -171,24 +171,24 @@ private static Stream stringsToParseTest() throws MalformedURLExcepti // url Arguments.of( List.of(new LinkedFile(URLUtil.create("https://books.google.de/"), "")), - "https://books.google.de/" + "https://books.google.de/" ), // url with www Arguments.of( List.of(new LinkedFile(URLUtil.create("https://www.google.de/"), "")), - "https://www.google.de/" + "https://www.google.de/" ), // url as file Arguments.of( List.of(new LinkedFile("", URLUtil.create("http://ceur-ws.org/Vol-438"), "URL")), - ":http\\://ceur-ws.org/Vol-438:URL" + ":http\\://ceur-ws.org/Vol-438:URL" ), // url as file with desc Arguments.of( - List.of(new LinkedFile("desc", URLUtil.create("http://ceur-ws.org/Vol-438"), "URL")), - "desc:http\\://ceur-ws.org/Vol-438:URL" + List.of(new LinkedFile("desc", URLUtil.create("http://ceur-ws.org/Vol-438"), "URL")), + "desc:http\\://ceur-ws.org/Vol-438:URL" ), // link with source url Arguments.of( diff --git a/jablib/src/test/java/org/jabref/logic/integrity/DoiDuplicationCheckerTest.java b/jablib/src/test/java/org/jabref/logic/integrity/DoiDuplicationCheckerTest.java index c5c163f8af3..b377509b298 100644 --- a/jablib/src/test/java/org/jabref/logic/integrity/DoiDuplicationCheckerTest.java +++ b/jablib/src/test/java/org/jabref/logic/integrity/DoiDuplicationCheckerTest.java @@ -28,7 +28,7 @@ void onePairDuplicateDOI() { List entries = List.of(doiA_entry1, doiA_entry2, doiC_entry1); BibDatabase database = new BibDatabase(entries); List results = List.of(new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry1, StandardField.DOI), - new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry2, StandardField.DOI)); + new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry2, StandardField.DOI)); assertEquals(results, checker.check(database)); } diff --git a/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBiblatexTest.java b/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBiblatexTest.java index 13ffba0fb58..7aea2020270 100644 --- a/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBiblatexTest.java +++ b/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBiblatexTest.java @@ -38,7 +38,7 @@ public static Stream bibtexAccepts() { "43+", // bibTexAcceptsMorePageNumbersWithRangeOfNumbers "7+,41--43,73" - ); + ); } @ParameterizedTest @@ -55,7 +55,7 @@ public static Stream bibtexRejects() { "1 2", // bibTexDoesNotAcceptBrackets "{1}-{2}" - ); + ); } @ParameterizedTest diff --git a/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBibtexTest.java b/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBibtexTest.java index d9cdac14197..8997634ed6b 100644 --- a/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBibtexTest.java +++ b/jablib/src/test/java/org/jabref/logic/integrity/PagesCheckerBibtexTest.java @@ -36,7 +36,7 @@ public static Stream bibtexAccepts() { "43+", // bibTexAcceptsMorePageNumbersWithRangeOfNumbers "7+,41--43,73" - ); + ); } @ParameterizedTest @@ -55,7 +55,7 @@ public static Stream bibtexRejects() { "1 2", // bibTexDoesNotAcceptBrackets "{1}-{2}" - ); + ); } @ParameterizedTest diff --git a/jablib/src/test/java/org/jabref/logic/integrity/UTF8CheckerTest.java b/jablib/src/test/java/org/jabref/logic/integrity/UTF8CheckerTest.java index 12c72565291..ed22c2fc708 100644 --- a/jablib/src/test/java/org/jabref/logic/integrity/UTF8CheckerTest.java +++ b/jablib/src/test/java/org/jabref/logic/integrity/UTF8CheckerTest.java @@ -52,7 +52,7 @@ void fieldDoesNotAcceptUmlauts() { @Test void NonUTF8EncodingCheckerTest() { String NonUTF8 = new String("你好,这条语句使用GBK字符集".getBytes(StandardCharsets.UTF_8), GBK); - assertFalse(UTF8Checker.UTF8EncodingChecker(NonUTF8.getBytes(GBK))); + assertFalse(UTF8Checker.UTF8EncodingChecker(NonUTF8.getBytes(GBK))); } /** @@ -62,6 +62,6 @@ void NonUTF8EncodingCheckerTest() { @Test void UTF8EncodingCheckerTest() { String UTF8Demo = new String("你好,这条语句使用GBK字符集".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); - assertTrue(UTF8Checker.UTF8EncodingChecker(UTF8Demo.getBytes(StandardCharsets.UTF_8))); + assertTrue(UTF8Checker.UTF8EncodingChecker(UTF8Demo.getBytes(StandardCharsets.UTF_8))); } } diff --git a/jablib/src/test/java/org/jabref/logic/layout/LayoutTest.java b/jablib/src/test/java/org/jabref/logic/layout/LayoutTest.java index 37a1e40f1aa..93aa6ba4ba2 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/LayoutTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/LayoutTest.java @@ -130,7 +130,7 @@ void beginConditionals() throws IOException { // combined (!a&&b) layoutText = layout( "\\begin{!editor&&author}\\format[HTMLChars]{\\author}\\end{!editor&&author}" + - "\\begin{editor&&!author}\\format[HTMLChars]{\\editor} (eds.)\\end{editor&&!author}", entry); + "\\begin{editor&&!author}\\format[HTMLChars]{\\editor} (eds.)\\end{editor&&!author}", entry); assertEquals("Author", layoutText); } @@ -177,8 +177,8 @@ void customNameFormatter() throws IOException { void annotatedField() throws IOException { UnknownField annotatedField = new UnknownField("author+an"); BibEntry entry = new BibEntry(StandardEntryType.Article) - .withField(annotatedField, "1:corresponding,2:highlight") - .withField(StandardField.AUTHOR, "Joe Doe and Mary Jane"); + .withField(annotatedField, "1:corresponding,2:highlight") + .withField(StandardField.AUTHOR, "Joe Doe and Mary Jane"); String layoutText = layout("\\author: \\author \\author+an", entry); diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/AbstractParamLayoutFormatterTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/AbstractParamLayoutFormatterTest.java index 6cc2ede6ed0..e10c66bf7ef 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/AbstractParamLayoutFormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/AbstractParamLayoutFormatterTest.java @@ -29,7 +29,7 @@ void simpleArguments() { String input = "arg1,arg2,arg3"; List result = ParseArgumentTester.callParseArgument(input); assertEquals(List.of("arg1", "arg2", "arg3"), result, - "Simple arguments should be split correctly by commas"); + "Simple arguments should be split correctly by commas"); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java index a682dcbfadd..9b6009e56d5 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java @@ -16,7 +16,7 @@ void emptyComposite() { @Test void arrayComposite() { - LayoutFormatter f = new CompositeFormat(new LayoutFormatter[]{fieldText -> fieldText + fieldText, + LayoutFormatter f = new CompositeFormat(new LayoutFormatter[] {fieldText -> fieldText + fieldText, fieldText -> "A" + fieldText, fieldText -> "B" + fieldText}); assertEquals("BAff", f.format("f")); diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java index 019886ab5a7..85ae09faf96 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java @@ -12,24 +12,24 @@ class DOIStripTest { - LayoutFormatter layoutFormatter = new DOIStrip(); + LayoutFormatter layoutFormatter = new DOIStrip(); @ParameterizedTest @MethodSource("provideDOI") void formatDOIStrip(String formattedDOI, String originalDOI) { - assertEquals(formattedDOI, layoutFormatter.format(originalDOI)); - } - - private static Stream provideDOI() { - return Stream.of( - Arguments.of("", ""), - Arguments.of(null, null), - Arguments.of("10.1000/ISBN1-900512-44-0", "10.1000/ISBN1-900512-44-0"), - Arguments.of("10.1000/ISBN1-900512-44-0", "http://dx.doi.org/10.1000/ISBN1-900512-44-0"), - Arguments.of("10.1000/ISBN1-900512-44-0", "http://doi.acm.org/10.1000/ISBN1-900512-44-0"), - Arguments.of("10.1145/354401.354407", "http://doi.acm.org/10.1145/354401.354407"), - Arguments.of("10", "10"), - Arguments.of("1", "1") - ); - } + assertEquals(formattedDOI, layoutFormatter.format(originalDOI)); + } + + private static Stream provideDOI() { + return Stream.of( + Arguments.of("", ""), + Arguments.of(null, null), + Arguments.of("10.1000/ISBN1-900512-44-0", "10.1000/ISBN1-900512-44-0"), + Arguments.of("10.1000/ISBN1-900512-44-0", "http://dx.doi.org/10.1000/ISBN1-900512-44-0"), + Arguments.of("10.1000/ISBN1-900512-44-0", "http://doi.acm.org/10.1000/ISBN1-900512-44-0"), + Arguments.of("10.1145/354401.354407", "http://doi.acm.org/10.1145/354401.354407"), + Arguments.of("10", "10"), + Arguments.of("1", "1") + ); + } } diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java index da6acd50c16..98ec3c0e61c 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java @@ -152,14 +152,14 @@ void hTMLEntityFormatting(String expected, String input) { private static Stream provideBracesKeepFormattingData() { return Stream.of( - Arguments.of("{ä}", "{\\\"{a}}"), - Arguments.of("{ä}", "{\\\"a}"), - Arguments.of("{Ç}", "{\\c{C}}"), - Arguments.of("{hallo}", "{\\emph hallo}"), - Arguments.of("{hallo}", "{\\textbf hallo}"), - Arguments.of("{hallo}", "{\\bf hallo}"), - Arguments.of("{'}", "{\\textquotesingle}"), - Arguments.of("{{ test }}", "{{ test }}") + Arguments.of("{ä}", "{\\\"{a}}"), + Arguments.of("{ä}", "{\\\"a}"), + Arguments.of("{Ç}", "{\\c{C}}"), + Arguments.of("{hallo}", "{\\emph hallo}"), + Arguments.of("{hallo}", "{\\textbf hallo}"), + Arguments.of("{hallo}", "{\\bf hallo}"), + Arguments.of("{'}", "{\\textquotesingle}"), + Arguments.of("{{ test }}", "{{ test }}") ); } diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/MarkdownFormatterTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/MarkdownFormatterTest.java index 2bfb5ef4caa..37372401c67 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/MarkdownFormatterTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/MarkdownFormatterTest.java @@ -30,57 +30,57 @@ private static Stream provideMarkdownAndHtml() { return Stream.of( Arguments.of("Hello World", "

          Hello World

          "), Arguments.of(""" - Markup - - * list item one - * list item two - - rest - """, + Markup + + * list item one + * list item two + + rest + """, "

          Markup

          • list item one
          • list item two

          rest

          " ), Arguments.of(""" - ``` - Hello World - ``` - """, + ``` + Hello World + ``` + """, "
          Hello World 
          " ), Arguments.of(""" - First line - - Second line - - ```java - String test; - ``` - """, - "

          First line

          Second line

          String test; 
          " + First line + + Second line + + ```java + String test; + ``` + """, + "

          First line

          Second line

          String test; 
          " ), Arguments.of(""" - Some text. - ```javascript - let test = "Hello World"; - ``` - - ```java - String test = "Hello World"; - ``` - Some more text. - """, - "

          Some text.

          let test = "Hello World"; " +
          -                            "
          String test = "Hello World"; " +
          -                            "

          Some more text.

          " + Some text. + ```javascript + let test = "Hello World"; + ``` + + ```java + String test = "Hello World"; + ``` + Some more text. + """, + "

          Some text.

          let test = "Hello World"; " +
          +                                "
          String test = "Hello World"; " +
          +                                "

          Some more text.

          " ), Arguments.of(""" - Some text. - - ```java - int foo = 0; - foo = 1; - - ``` - """, + Some text. + + ```java + int foo = 0; + foo = 1; + + ``` + """, "

          Some text.

          int foo = 0; foo = 1;  
          " ) ); diff --git a/jablib/src/test/java/org/jabref/logic/net/ProxyTest.java b/jablib/src/test/java/org/jabref/logic/net/ProxyTest.java index 36a8869ff49..e12215e7c50 100644 --- a/jablib/src/test/java/org/jabref/logic/net/ProxyTest.java +++ b/jablib/src/test/java/org/jabref/logic/net/ProxyTest.java @@ -12,32 +12,32 @@ class ProxyTest { */ @Test void proxyPreferencesStorePassword() { - // mock data - boolean useProxy = true; - String hostname = "testName"; - String port = "8080"; - boolean useAuthentication = true; - String username = "testUserName"; - String password = "testPassword"; - boolean persist = false; + // mock data + boolean useProxy = true; + String hostname = "testName"; + String port = "8080"; + boolean useAuthentication = true; + String username = "testUserName"; + String password = "testPassword"; + boolean persist = false; - // Creates proxy preference - ProxyPreferences proxyPref = new ProxyPreferences( - useProxy, - hostname, - port, - useAuthentication, - username, - password, - persist); + // Creates proxy preference + ProxyPreferences proxyPref = new ProxyPreferences( + useProxy, + hostname, + port, + useAuthentication, + username, + password, + persist); - // Check if mock data is stored in object memory and can be extracted - assertTrue(proxyPref.shouldUseProxy()); - assertEquals(proxyPref.getHostname(), hostname); - assertEquals(proxyPref.getPort(), port); - assertTrue(proxyPref.shouldUseAuthentication()); - assertEquals(proxyPref.getUsername(), username); - assertEquals(proxyPref.getPassword(), password); - assertEquals(proxyPref.shouldPersistPassword(), persist); - } + // Check if mock data is stored in object memory and can be extracted + assertTrue(proxyPref.shouldUseProxy()); + assertEquals(proxyPref.getHostname(), hostname); + assertEquals(proxyPref.getPort(), port); + assertTrue(proxyPref.shouldUseAuthentication()); + assertEquals(proxyPref.getUsername(), username); + assertEquals(proxyPref.getPassword(), password); + assertEquals(proxyPref.shouldPersistPassword(), persist); + } } diff --git a/jablib/src/test/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtilsTest.java b/jablib/src/test/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtilsTest.java index 99dd0d4f2d9..39bd9290299 100644 --- a/jablib/src/test/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtilsTest.java +++ b/jablib/src/test/java/org/jabref/logic/openoffice/oocsltext/CSLFormatUtilsTest.java @@ -490,8 +490,7 @@ static Stream ooHTMLTransformFromCitationWithMultipleEntries() { * The numeric index should change to the provided "current number". * The rest of the citation should stay as it is (other numbers in the body shouldn't be affected). * - * @implSpec - *
            + * @implSpec
              *
            1. Assumes that {@link CitationStyleGenerator#generateBibliography(List, String, CitationStyleOutputFormat, BibDatabaseContext, BibEntryTypesManager) generateBibliography} works as expected.
            2. *
            3. Assumes that the method {@link CSLFormatUtils#transformHTML(String) transformHTML} works as expected.
            4. *
            5. Run this test ONLY on numeric Citation Styles.
            6. diff --git a/jablib/src/test/java/org/jabref/logic/openoffice/style/JStyleTest.java b/jablib/src/test/java/org/jabref/logic/openoffice/style/JStyleTest.java index 27826c49e34..7d0186be34d 100644 --- a/jablib/src/test/java/org/jabref/logic/openoffice/style/JStyleTest.java +++ b/jablib/src/test/java/org/jabref/logic/openoffice/style/JStyleTest.java @@ -260,14 +260,14 @@ void getCitationMarker() throws IOException { assertEquals("Boström et al. [2006]", getCitationMarker2(style, List.of(entry), entryDBMap, - false, null, new Boolean[]{false}, null)); + false, null, new Boolean[] {false}, null)); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, List.of(entry), entryDBMap, true, null, - new Boolean[]{true}, + new Boolean[] {true}, null)); } @@ -489,8 +489,8 @@ void getCitationMarkerInParenthesisUniquefiers() throws IOException { getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, + new String[] {"a", "b", ""}, + new Boolean[] {false, false, false}, null)); } @@ -533,8 +533,8 @@ void getCitationMarkerInTextUniquefiers() throws IOException { getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, + new String[] {"a", "b", ""}, + new Boolean[] {false, false, false}, null)); } @@ -576,8 +576,8 @@ void getCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExcepti assertEquals("[Beta, 2000a,b,c]", getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, + new String[] {"a", "b", "c"}, + new Boolean[] {false, false, false}, null)); } @@ -619,8 +619,8 @@ void getCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException { assertEquals("Beta [2000a,b,c]", getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, + new String[] {"a", "b", "c"}, + new Boolean[] {false, false, false}, null)); } diff --git a/jablib/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/jablib/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 7ec50d9189e..5e807ace39a 100644 --- a/jablib/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/jablib/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -39,8 +39,8 @@ static class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntr public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { this.citationKey = citationKey; this.num = num == UNRESOLVED_ENTRY_NUMBER - ? Optional.empty() - : Optional.of(num); + ? Optional.empty() + : Optional.of(num); this.pageInfo = PageInfo.normalizePageInfo(pageInfo); } diff --git a/jablib/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java b/jablib/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java index bbf0bc8f18c..3b7420bb5dc 100644 --- a/jablib/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java +++ b/jablib/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java @@ -34,7 +34,7 @@ void getProtectedTerms() throws URISyntaxException { } assertTrue(loader.getProtectedTermsLists().isEmpty()); Path path = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") - .toURI()); + .toURI()); loader.addProtectedTermsListFromFile(path, true); assertEquals(List.of("Einstein"), loader.getProtectedTerms()); } @@ -42,7 +42,7 @@ void getProtectedTerms() throws URISyntaxException { @Test void addProtectedTermsListFromFile() throws URISyntaxException { Path path = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") - .toURI()); + .toURI()); assertEquals(ProtectedTermsLoader.getInternalLists().size(), loader.getProtectedTermsLists().size()); loader.addProtectedTermsListFromFile(path, false); assertEquals(ProtectedTermsLoader.getInternalLists().size() + 1, loader.getProtectedTermsLists().size()); diff --git a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultCsvWriterTest.java b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultCsvWriterTest.java index 0d9707b7521..e740d3e53cb 100644 --- a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultCsvWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultCsvWriterTest.java @@ -42,7 +42,8 @@ void checkSimpleLibrary(@TempDir Path tempDir) throws IOException { database.insertEntry(second); BibDatabaseContext bibContext = new BibDatabaseContext(database); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); Path csvFile = tempDir.resolve("checkSimpleLibrary-result.csv"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(csvFile)); @@ -72,7 +73,8 @@ void checkDifferentOutputSymbols(@TempDir Path tempDir) throws IOException { BibDatabaseContext bibContext = new BibDatabaseContext(database); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); Path csvFile = tempDir.resolve("checkDifferentOutputSymbols-result.csv"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(csvFile)); @@ -117,7 +119,8 @@ void checkComplexLibrary(@TempDir Path tempDir) throws IOException { database.insertEntry(fifth); BibDatabaseContext bibContext = new BibDatabaseContext(database); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); Path csvFile = tempDir.resolve("checkSimpleLibrary-result.csv"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(csvFile)); @@ -148,7 +151,8 @@ void checkLibraryWithoutIssues(@TempDir Path tempDir) throws IOException { BibDatabaseContext bibContext = new BibDatabaseContext(database); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); Path csvFile = tempDir.resolve("checkLibraryWithoutIssues-result.csv"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(csvFile)); @@ -166,7 +170,8 @@ void checkManualInput() throws IOException { Path file = Path.of("C:\\TEMP\\JabRef\\biblio-anon.bib"); Path csvFile = file.resolveSibling("biblio-cited.csv"); BibDatabaseContext databaseContext = importer.importDatabase(file).getDatabaseContext(); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(databaseContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(databaseContext, (_, _) -> { + }); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(csvFile)); BibliographyConsistencyCheckResultCsvWriter paperConsistencyCheckResultCsvWriter = new BibliographyConsistencyCheckResultCsvWriter(result, writer, true)) { paperConsistencyCheckResultCsvWriter.writeFindings(); diff --git a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultTxtWriterTest.java b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultTxtWriterTest.java index 754eb94525d..ac57bee4ba7 100644 --- a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultTxtWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckResultTxtWriterTest.java @@ -44,7 +44,8 @@ void checkSimpleLibrary(@TempDir Path tempDir) throws IOException { BibDatabaseContext bibContext = new BibDatabaseContext(database); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); Path txtFile = tempDir.resolve("checkSimpleLibrary-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -130,7 +131,8 @@ void checkDifferentOutputSymbols(@TempDir Path tempDir) throws IOException { BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); Path txtFile = tempDir.resolve("checkDifferentOutputSymbols-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -169,7 +171,8 @@ void checkVeryLongCitationKey(@TempDir Path tempDir) throws IOException { bibDatabase.insertEntries(bibEntriesList); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); Path txtFile = tempDir.resolve("checkDifferentOutputSymbols-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -225,7 +228,8 @@ void checkComplexLibrary(@TempDir Path tempDir) throws IOException { bibDatabase.insertEntries(bibEntriesList); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); Path txtFile = tempDir.resolve("checkSimpleLibrary-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -266,7 +270,8 @@ void checkLibraryWithoutIssuesWithOutPorcelain(@TempDir Path tempDir) throws IOE bibDatabase.insertEntries(bibEntriesList); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); Path txtFile = tempDir.resolve("checkLibraryWithoutIssues-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -293,7 +298,8 @@ void checkLibraryWithoutIssuesWithPorcelain(@TempDir Path tempDir) throws IOExce bibDatabase.insertEntries(bibEntriesList); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); Path txtFile = tempDir.resolve("checkLibraryWithoutIssues-result.txt"); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); @@ -309,7 +315,8 @@ void checkManualInput() throws IOException { Path file = Path.of("C:\\TEMP\\JabRef\\biblio-anon.bib"); Path txtFile = file.resolveSibling("biblio-cited.txt"); BibDatabaseContext databaseContext = importer.importDatabase(file).getDatabaseContext(); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(databaseContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(databaseContext, (_, _) -> { + }); try (Writer writer = new OutputStreamWriter(Files.newOutputStream(txtFile)); BibliographyConsistencyCheckResultTxtWriter txtWriter = new BibliographyConsistencyCheckResultTxtWriter(result, writer, true)) { txtWriter.writeFindings(); diff --git a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckTest.java b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckTest.java index 1eb1debd0ac..12987b2cf40 100644 --- a/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckTest.java +++ b/jablib/src/test/java/org/jabref/logic/quality/consistency/BibliographyConsistencyCheckTest.java @@ -34,7 +34,8 @@ void checkSimpleLibrary(@TempDir Path tempDir) { BibDatabase database = new BibDatabase(List.of(first, second)); BibDatabaseContext bibContext = new BibDatabaseContext(database); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (count, total) -> { + }); BibliographyConsistencyCheck.EntryTypeResult entryTypeResult = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.PUBLISHER), List.of(first, second)); BibliographyConsistencyCheck.Result expected = new BibliographyConsistencyCheck.Result(Map.of(StandardEntryType.Article, entryTypeResult)); @@ -54,7 +55,8 @@ void checkDifferentOutputSymbols(@TempDir Path tempDir) { BibDatabase bibDatabase = new BibDatabase(List.of(first, second)); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); bibContext.setMode(BibDatabaseMode.BIBTEX); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult entryTypeResult = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.TITLE, customField), List.of(first, second)); BibliographyConsistencyCheck.Result expected = new BibliographyConsistencyCheck.Result(Map.of(StandardEntryType.Article, entryTypeResult)); @@ -86,7 +88,8 @@ void checkComplexLibrary(@TempDir Path tempDir) { BibDatabase bibDatabase = new BibDatabase(List.of(first, second, third, fourth, fifth)); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult articleResult = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.PUBLISHER), List.of(first, second)); BibliographyConsistencyCheck.EntryTypeResult inProceedingsResult = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.PUBLISHER, StandardField.LOCATION), List.of(fifth, fourth, third)); @@ -108,7 +111,8 @@ void checkLibraryWithoutIssues(@TempDir Path tempDir) { BibDatabase bibDatabase = new BibDatabase(List.of(first, second)); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.Result expected = new BibliographyConsistencyCheck.Result(Map.of()); assertEquals(expected, result); @@ -129,7 +133,8 @@ void filteredFieldsAreIgnored() { BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck() - .check(bibContext, (_, _) -> { }); + .check(bibContext, (_, _) -> { + }); assertEquals(Map.of(), result.entryTypeToResultMap(), "Differences only in filtered fields must be ignored"); @@ -145,7 +150,8 @@ void nonFilteredFieldDifferenceIsReported() { BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck() - .check(bibContext, (_, _) -> { }); + .check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult typeResult = result.entryTypeToResultMap().get(StandardEntryType.Misc); @@ -168,7 +174,8 @@ void unsetRequriedFieldsReported() { bibContext.setMode(BibDatabaseMode.BIBLATEX); BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck() - .check(bibContext, (_, _) -> { }); + .check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult typeResult = result.entryTypeToResultMap().get(StandardEntryType.Online); @@ -191,7 +198,8 @@ void unsetFieldsReportedInBibtexMode() { BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); bibContext.setMode(BibDatabaseMode.BIBTEX); BibliographyConsistencyCheck.Result result = new BibliographyConsistencyCheck() - .check(bibContext, (_, _) -> { }); + .check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult typeResult = result.entryTypeToResultMap().get(StandardEntryType.Online); @@ -260,7 +268,8 @@ void checkComplexLibraryWithAdditionalEntry(@TempDir Path tempDir) { BibDatabase bibDatabase = new BibDatabase(List.of(first, second, third, fourth, fifth, sixth)); BibDatabaseContext bibContext = new BibDatabaseContext(bibDatabase); - BibliographyConsistencyCheck.Result actualResult = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { }); + BibliographyConsistencyCheck.Result actualResult = new BibliographyConsistencyCheck().check(bibContext, (_, _) -> { + }); BibliographyConsistencyCheck.EntryTypeResult articleResult = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.PUBLISHER), List.of(first, second)); BibliographyConsistencyCheck.EntryTypeResult expectedInProceedings = new BibliographyConsistencyCheck.EntryTypeResult(Set.of(StandardField.PAGES, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.YEAR), List.of(fifth, fourth, sixth, third)); diff --git a/jablib/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java b/jablib/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java index bb2cdc8dc90..168571c7f92 100644 --- a/jablib/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java +++ b/jablib/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java @@ -49,7 +49,7 @@ void pingReturnsTrue() throws IOException, InterruptedException { @Test void commandLineArgumentSinglePassedToServer() { - final String[] message = new String[]{"my message"}; + final String[] message = new String[] {"my message"}; client.sendCommandLineArguments(message); @@ -58,7 +58,7 @@ void commandLineArgumentSinglePassedToServer() { @Test void commandLineArgumentTwoPassedToServer() { - final String[] message = new String[]{"my message", "second"}; + final String[] message = new String[] {"my message", "second"}; client.sendCommandLineArguments(message); @@ -67,7 +67,7 @@ void commandLineArgumentTwoPassedToServer() { @Test void commandLineArgumentMultiLinePassedToServer() { - final String[] message = new String[]{"my message\n second line", "second \r and third"}; + final String[] message = new String[] {"my message\n second line", "second \r and third"}; client.sendCommandLineArguments(message); @@ -76,7 +76,7 @@ void commandLineArgumentMultiLinePassedToServer() { @Test void commandLineArgumentEncodingAndDecoding() { - final String[] message = new String[]{"D:\\T EST\\测试te st.bib"}; + final String[] message = new String[] {"D:\\T EST\\测试te st.bib"}; // will be encoded as "D%3A%5CT+EST%5C%E6%B5%8B%E8%AF%95te+st.bib" client.sendCommandLineArguments(message); diff --git a/jablib/src/test/java/org/jabref/logic/remote/RemoteSetupTest.java b/jablib/src/test/java/org/jabref/logic/remote/RemoteSetupTest.java index 6db9a4c9541..e2e73cd3920 100644 --- a/jablib/src/test/java/org/jabref/logic/remote/RemoteSetupTest.java +++ b/jablib/src/test/java/org/jabref/logic/remote/RemoteSetupTest.java @@ -36,7 +36,7 @@ void setUp() { @Test void goodCase() { final int port = 34567; - final String[] message = new String[]{"MYMESSAGE"}; + final String[] message = new String[] {"MYMESSAGE"}; try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { assertFalse(server.isOpen()); @@ -52,7 +52,7 @@ void goodCase() { @Test void goodCaseWithAllLifecycleMethods() { final int port = 34567; - final String[] message = new String[]{"MYMESSAGE"}; + final String[] message = new String[] {"MYMESSAGE"}; try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { assertFalse(server.isOpen()); @@ -98,7 +98,7 @@ void clientTimeout() { final int port = 34567; final String message = "MYMESSAGE"; - assertFalse(new RemoteClient(port).sendCommandLineArguments(new String[]{message})); + assertFalse(new RemoteClient(port).sendCommandLineArguments(new String[] {message})); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/search/DatabaseSearcherWithBibFilesTest.java b/jablib/src/test/java/org/jabref/logic/search/DatabaseSearcherWithBibFilesTest.java index 9e3a1597c85..7854494c618 100644 --- a/jablib/src/test/java/org/jabref/logic/search/DatabaseSearcherWithBibFilesTest.java +++ b/jablib/src/test/java/org/jabref/logic/search/DatabaseSearcherWithBibFilesTest.java @@ -124,14 +124,14 @@ private static Stream searchLibrary() { Arguments.of(List.of(), "test-library-title-casing.bib", "title = NotExisting", false), Arguments.of(List.of(TITLE_SENTENCE_CASED, TITLE_MIXED_CASED, TITLE_UPPER_CASED), "test-library-title-casing.bib", "title = Title", false), - Arguments.of(List.of(), "test-library-title-casing.bib", "title =! TiTLE", false), - Arguments.of(List.of(TITLE_SENTENCE_CASED), "test-library-title-casing.bib", "title =! Title", false), + Arguments.of(List.of(), "test-library-title-casing.bib", "title =! TiTLE", false), + Arguments.of(List.of(TITLE_SENTENCE_CASED), "test-library-title-casing.bib", "title =! Title", false), - Arguments.of(List.of(), "test-library-title-casing.bib", "any =! TiTLE", false), - Arguments.of(List.of(TITLE_MIXED_CASED), "test-library-title-casing.bib", "any =! TiTle", false), + Arguments.of(List.of(), "test-library-title-casing.bib", "any =! TiTLE", false), + Arguments.of(List.of(TITLE_MIXED_CASED), "test-library-title-casing.bib", "any =! TiTle", false), - Arguments.of(List.of(), "test-library-title-casing.bib", "title =! NotExisting", false), - Arguments.of(List.of(TITLE_MIXED_CASED), "test-library-title-casing.bib", "title =! TiTle", false), + Arguments.of(List.of(), "test-library-title-casing.bib", "title =! NotExisting", false), + Arguments.of(List.of(TITLE_MIXED_CASED), "test-library-title-casing.bib", "title =! TiTle", false), Arguments.of(List.of(), "test-library-title-casing.bib", "any =~ [Y]", false), diff --git a/jablib/src/test/java/org/jabref/logic/search/query/SearchQuerySQLConversionTest.java b/jablib/src/test/java/org/jabref/logic/search/query/SearchQuerySQLConversionTest.java index 755171768ec..04746c9ce61 100644 --- a/jablib/src/test/java/org/jabref/logic/search/query/SearchQuerySQLConversionTest.java +++ b/jablib/src/test/java/org/jabref/logic/search/query/SearchQuerySQLConversionTest.java @@ -40,693 +40,693 @@ public static Stream searchConversion() { Arguments.of( "author CONTAINS smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author = smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author =! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%smith%')) OR (main_table.field_value_transformed LIKE ('%smith%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%smith%')) OR (main_table.field_value_transformed LIKE ('%smith%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author != smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ILIKE ('%smith%')) OR (inner_table.field_value_transformed ILIKE ('%smith%'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ILIKE ('%smith%')) OR (inner_table.field_value_transformed ILIKE ('%smith%'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author !=! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name = 'author') AND ((inner_table.field_value_literal LIKE ('%smith%')) OR (inner_table.field_value_transformed LIKE ('%smith%'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name = 'author') AND ((inner_table.field_value_literal LIKE ('%smith%')) OR (inner_table.field_value_transformed LIKE ('%smith%'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author MATCHES smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) - WHERE ( - ((main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith')))) - OR - ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) + WHERE ( + ((main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith')))) + OR + ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author == smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) - WHERE ( - ((main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith')))) - OR - ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) + WHERE ( + ((main_table.field_name = 'author') AND ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith')))) + OR + ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author ==! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) - WHERE ( - ((main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('smith')) OR (main_table.field_value_transformed LIKE ('smith')))) - OR - ((split_table.field_name = 'author') AND ((split_table.field_value_literal LIKE ('smith')) OR (split_table.field_value_transformed LIKE ('smith')))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) + WHERE ( + ((main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('smith')) OR (main_table.field_value_transformed LIKE ('smith')))) + OR + ((split_table.field_name = 'author') AND ((split_table.field_value_literal LIKE ('smith')) OR (split_table.field_value_transformed LIKE ('smith')))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author !== smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (inner_table.entryid = split_table.entryid AND inner_table.field_name = split_table.field_name) - WHERE ( - ((inner_table.field_name = 'author') AND ((inner_table.field_value_literal ILIKE ('smith')) OR (inner_table.field_value_transformed ILIKE ('smith')))) - OR - ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (inner_table.entryid = split_table.entryid AND inner_table.field_name = split_table.field_name) + WHERE ( + ((inner_table.field_name = 'author') AND ((inner_table.field_value_literal ILIKE ('smith')) OR (inner_table.field_value_transformed ILIKE ('smith')))) + OR + ((split_table.field_name = 'author') AND ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith')))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author !==! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (inner_table.entryid = split_table.entryid AND inner_table.field_name = split_table.field_name) - WHERE ( - ((inner_table.field_name = 'author') AND ((inner_table.field_value_literal LIKE ('smith')) OR (inner_table.field_value_transformed LIKE ('smith')))) - OR - ((split_table.field_name = 'author') AND ((split_table.field_value_literal LIKE ('smith')) OR (split_table.field_value_transformed LIKE ('smith')))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (inner_table.entryid = split_table.entryid AND inner_table.field_name = split_table.field_name) + WHERE ( + ((inner_table.field_name = 'author') AND ((inner_table.field_value_literal LIKE ('smith')) OR (inner_table.field_value_transformed LIKE ('smith')))) + OR + ((split_table.field_name = 'author') AND ((split_table.field_value_literal LIKE ('smith')) OR (split_table.field_value_transformed LIKE ('smith')))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author =~ smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal ~* ('smith')) OR (main_table.field_value_transformed ~* ('smith'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal ~* ('smith')) OR (main_table.field_value_transformed ~* ('smith'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author =~! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal ~ ('smith')) OR (main_table.field_value_transformed ~ ('smith'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal ~ ('smith')) OR (main_table.field_value_transformed ~ ('smith'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author !=~ smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ~* ('smith')) OR (inner_table.field_value_transformed ~* ('smith'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ~* ('smith')) OR (inner_table.field_value_transformed ~* ('smith'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "author !=~! smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ~ ('smith')) OR (inner_table.field_value_transformed ~ ('smith'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name = 'author') AND ((inner_table.field_value_literal ~ ('smith')) OR (inner_table.field_value_transformed ~ ('smith'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%smith%')) OR (main_table.field_value_transformed ILIKE ('%smith%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "any == smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - LEFT JOIN bib_fields."tableName_split_values" AS split_table - ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) - WHERE ( - (main_table.field_name != 'groups') - AND ( - ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith'))) - OR - ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + LEFT JOIN bib_fields."tableName_split_values" AS split_table + ON (main_table.entryid = split_table.entryid AND main_table.field_name = split_table.field_name) + WHERE ( + (main_table.field_name != 'groups') + AND ( + ((main_table.field_value_literal ILIKE ('smith')) OR (main_table.field_value_transformed ILIKE ('smith'))) + OR + ((split_table.field_value_literal ILIKE ('smith')) OR (split_table.field_value_transformed ILIKE ('smith'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "anyfield != smith", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name != 'groups') AND ((inner_table.field_value_literal ILIKE ('%smith%')) OR (inner_table.field_value_transformed ILIKE ('%smith%'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name != 'groups') AND ((inner_table.field_value_literal ILIKE ('%smith%')) OR (inner_table.field_value_transformed ILIKE ('%smith%'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "title = \"computer science\"", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'title') AND ((main_table.field_value_literal ILIKE ('%computer science%')) OR (main_table.field_value_transformed ILIKE ('%computer science%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'title') AND ((main_table.field_value_literal ILIKE ('%computer science%')) OR (main_table.field_value_transformed ILIKE ('%computer science%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "term1 term2 term3", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term1%')) OR (main_table.field_value_transformed ILIKE ('%term1%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term2%')) OR (main_table.field_value_transformed ILIKE ('%term2%'))) - ) - ) - , - cte2 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term3%')) OR (main_table.field_value_transformed ILIKE ('%term3%'))) - ) - ) - , - cte3 AS ( - SELECT entryid FROM cte0 - INTERSECT - SELECT entryid FROM cte1 - INTERSECT - SELECT entryid FROM cte2 - ) - SELECT * FROM cte3 GROUP BY entryid""" - ), - - Arguments.of( - "a OR b AND c", - """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte3 AS ( - SELECT entryid - FROM cte1 - INTERSECT - SELECT entryid - FROM cte2 - ) - , - cte4 AS ( - SELECT entryid - FROM cte0 - UNION - SELECT entryid - FROM cte3 - ) - SELECT * FROM cte4 GROUP BY entryid""" - ), - - Arguments.of( - "a AND b OR c", - """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - INTERSECT - SELECT entryid - FROM cte1 - ) - , - cte3 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte4 AS ( - SELECT entryid - FROM cte2 - UNION - SELECT entryid - FROM cte3 - ) - SELECT * FROM cte4 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term1%')) OR (main_table.field_value_transformed ILIKE ('%term1%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term2%')) OR (main_table.field_value_transformed ILIKE ('%term2%'))) + ) + ) + , + cte2 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%term3%')) OR (main_table.field_value_transformed ILIKE ('%term3%'))) + ) + ) + , + cte3 AS ( + SELECT entryid FROM cte0 + INTERSECT + SELECT entryid FROM cte1 + INTERSECT + SELECT entryid FROM cte2 + ) + SELECT * FROM cte3 GROUP BY entryid""" + ), + + Arguments.of( + "a OR b AND c", + """ + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte3 AS ( + SELECT entryid + FROM cte1 + INTERSECT + SELECT entryid + FROM cte2 + ) + , + cte4 AS ( + SELECT entryid + FROM cte0 + UNION + SELECT entryid + FROM cte3 + ) + SELECT * FROM cte4 GROUP BY entryid""" + ), + + Arguments.of( + "a AND b OR c", + """ + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + INTERSECT + SELECT entryid + FROM cte1 + ) + , + cte3 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte4 AS ( + SELECT entryid + FROM cte2 + UNION + SELECT entryid + FROM cte3 + ) + SELECT * FROM cte4 GROUP BY entryid""" ), Arguments.of( "(a OR b) AND c", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - UNION - SELECT entryid - FROM cte1 - ) - , - cte3 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte4 AS ( - SELECT entryid - FROM cte2 - INTERSECT - SELECT entryid - FROM cte3 - ) - SELECT * FROM cte4 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + UNION + SELECT entryid + FROM cte1 + ) + , + cte3 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte4 AS ( + SELECT entryid + FROM cte2 + INTERSECT + SELECT entryid + FROM cte3 + ) + SELECT * FROM cte4 GROUP BY entryid""" ), Arguments.of( "a OR (b AND c)", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte3 AS ( - SELECT entryid - FROM cte1 - INTERSECT - SELECT entryid - FROM cte2 - ) - , - cte4 AS ( - SELECT entryid - FROM cte0 - UNION - SELECT entryid - FROM cte3 - ) - SELECT * FROM cte4 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte3 AS ( + SELECT entryid + FROM cte1 + INTERSECT + SELECT entryid + FROM cte2 + ) + , + cte4 AS ( + SELECT entryid + FROM cte0 + UNION + SELECT entryid + FROM cte3 + ) + SELECT * FROM cte4 GROUP BY entryid""" ), Arguments.of( "(a OR b) AND (c OR d)", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - UNION - SELECT entryid - FROM cte1 - ) - , - cte3 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte4 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%d%')) OR (main_table.field_value_transformed ILIKE ('%d%'))) - ) - ) - , - cte5 AS ( - SELECT entryid - FROM cte3 - UNION - SELECT entryid - FROM cte4 - ) - , - cte6 AS ( - SELECT entryid - FROM cte2 - INTERSECT - SELECT entryid - FROM cte5 - ) - SELECT * FROM cte6 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + UNION + SELECT entryid + FROM cte1 + ) + , + cte3 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte4 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%d%')) OR (main_table.field_value_transformed ILIKE ('%d%'))) + ) + ) + , + cte5 AS ( + SELECT entryid + FROM cte3 + UNION + SELECT entryid + FROM cte4 + ) + , + cte6 AS ( + SELECT entryid + FROM cte2 + INTERSECT + SELECT entryid + FROM cte5 + ) + SELECT * FROM cte6 GROUP BY entryid""" ), Arguments.of( "a AND NOT (b OR c)", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) - ) - ) - , - cte2 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) - ) - ) - , - cte3 AS ( - SELECT entryid - FROM cte1 - UNION - SELECT entryid - FROM cte2 - ) - , - cte4 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT entryid - FROM cte3 - ) - ) - , - cte5 AS ( - SELECT entryid - FROM cte0 - INTERSECT - SELECT entryid - FROM cte4 - ) - SELECT * FROM cte5 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a%')) OR (main_table.field_value_transformed ILIKE ('%a%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%b%')) OR (main_table.field_value_transformed ILIKE ('%b%'))) + ) + ) + , + cte2 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%c%')) OR (main_table.field_value_transformed ILIKE ('%c%'))) + ) + ) + , + cte3 AS ( + SELECT entryid + FROM cte1 + UNION + SELECT entryid + FROM cte2 + ) + , + cte4 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT entryid + FROM cte3 + ) + ) + , + cte5 AS ( + SELECT entryid + FROM cte0 + INTERSECT + SELECT entryid + FROM cte4 + ) + SELECT * FROM cte5 GROUP BY entryid""" ), Arguments.of( "a'b", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a''b%')) OR (main_table.field_value_transformed ILIKE ('%a''b%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%a''b%')) OR (main_table.field_value_transformed ILIKE ('%a''b%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "file = \"\"", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE main_table.entryid NOT IN ( - SELECT inner_table.entryid - FROM bib_fields."tableName" AS inner_table - WHERE ( - (inner_table.field_name = 'file') AND ((inner_table.field_value_literal ILIKE ('%%')) OR (inner_table.field_value_transformed ILIKE ('%%'))) + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE main_table.entryid NOT IN ( + SELECT inner_table.entryid + FROM bib_fields."tableName" AS inner_table + WHERE ( + (inner_table.field_name = 'file') AND ((inner_table.field_value_literal ILIKE ('%%')) OR (inner_table.field_value_transformed ILIKE ('%%'))) + ) + ) ) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "file != \"\"", """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'file') AND ((main_table.field_value_literal ILIKE ('%%')) OR (main_table.field_value_transformed ILIKE ('%%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'file') AND ((main_table.field_value_literal ILIKE ('%%')) OR (main_table.field_value_transformed ILIKE ('%%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ) ); } @@ -752,153 +752,153 @@ public static Stream unFieldedTermsWithSearchBarFlags() { "Test", EnumSet.noneOf(SearchFlags.class), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%Test%')) OR (main_table.field_value_transformed ILIKE ('%Test%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%Test%')) OR (main_table.field_value_transformed ILIKE ('%Test%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "Test", EnumSet.of(CASE_SENSITIVE), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal LIKE ('%Test%')) OR (main_table.field_value_transformed LIKE ('%Test%'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal LIKE ('%Test%')) OR (main_table.field_value_transformed LIKE ('%Test%'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "Test", EnumSet.of(REGULAR_EXPRESSION), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~* ('Test')) OR (main_table.field_value_transformed ~* ('Test'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~* ('Test')) OR (main_table.field_value_transformed ~* ('Test'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "Test", EnumSet.of(CASE_SENSITIVE, REGULAR_EXPRESSION), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~ ('Test')) OR (main_table.field_value_transformed ~ ('Test'))) - ) - ) - SELECT * FROM cte0 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~ ('Test')) OR (main_table.field_value_transformed ~ ('Test'))) + ) + ) + SELECT * FROM cte0 GROUP BY entryid""" ), Arguments.of( "Test AND author =! Smith", EnumSet.noneOf(SearchFlags.class), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%Test%')) OR (main_table.field_value_transformed ILIKE ('%Test%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - INTERSECT - SELECT entryid - FROM cte1 - ) - SELECT * FROM cte2 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ILIKE ('%Test%')) OR (main_table.field_value_transformed ILIKE ('%Test%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + INTERSECT + SELECT entryid + FROM cte1 + ) + SELECT * FROM cte2 GROUP BY entryid""" ), Arguments.of( "Test AND author =! Smith", EnumSet.of(CASE_SENSITIVE), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal LIKE ('%Test%')) OR (main_table.field_value_transformed LIKE ('%Test%'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - INTERSECT - SELECT entryid - FROM cte1 - ) - SELECT * FROM cte2 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal LIKE ('%Test%')) OR (main_table.field_value_transformed LIKE ('%Test%'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + INTERSECT + SELECT entryid + FROM cte1 + ) + SELECT * FROM cte2 GROUP BY entryid""" ), Arguments.of( "any =~ Test AND author =! Smith", EnumSet.of(CASE_SENSITIVE), """ - WITH - cte0 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~* ('Test')) OR (main_table.field_value_transformed ~* ('Test'))) - ) - ) - , - cte1 AS ( - SELECT main_table.entryid - FROM bib_fields."tableName" AS main_table - WHERE ( - (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) - ) - ) - , - cte2 AS ( - SELECT entryid - FROM cte0 - INTERSECT - SELECT entryid - FROM cte1 - ) - SELECT * FROM cte2 GROUP BY entryid""" + WITH + cte0 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name != 'groups') AND ((main_table.field_value_literal ~* ('Test')) OR (main_table.field_value_transformed ~* ('Test'))) + ) + ) + , + cte1 AS ( + SELECT main_table.entryid + FROM bib_fields."tableName" AS main_table + WHERE ( + (main_table.field_name = 'author') AND ((main_table.field_value_literal LIKE ('%Smith%')) OR (main_table.field_value_transformed LIKE ('%Smith%'))) + ) + ) + , + cte2 AS ( + SELECT entryid + FROM cte0 + INTERSECT + SELECT entryid + FROM cte1 + ) + SELECT * FROM cte2 GROUP BY entryid""" ) ); } diff --git a/jablib/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java b/jablib/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java index 28fa5b70360..31ca72358d9 100644 --- a/jablib/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java +++ b/jablib/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java @@ -419,7 +419,7 @@ void insertMultipleEntries() throws SQLException { Map> expectedFieldMap = entries.stream() .collect(Collectors.toMap(bibEntry -> bibEntry.getSharedBibEntryData().getSharedID(), bibEntry -> bibEntry.getFieldMap().entrySet().stream() - .collect(Collectors.toMap(entry -> entry.getKey().getName(), Map.Entry::getValue)))); + .collect(Collectors.toMap(entry -> entry.getKey().getName(), Map.Entry::getValue)))); assertEquals(expectedFieldMap, actualFieldMap); } diff --git a/jablib/src/test/java/org/jabref/logic/util/ExternalLinkCreatorTest.java b/jablib/src/test/java/org/jabref/logic/util/ExternalLinkCreatorTest.java index 2e291106936..2f1165f84cf 100644 --- a/jablib/src/test/java/org/jabref/logic/util/ExternalLinkCreatorTest.java +++ b/jablib/src/test/java/org/jabref/logic/util/ExternalLinkCreatorTest.java @@ -34,7 +34,7 @@ private boolean urlIsValid(String url) { static Stream specialCharactersProvider() { return Stream.of( - Arguments.of("!*'();:@&=+$,/?#[]") + Arguments.of("!*'();:@&=+$,/?#[]") ); } @@ -50,10 +50,10 @@ void getShortScienceSearchURLEncodesSpecialCharacters(String title) { @ParameterizedTest @CsvSource({ - "'歷史書 📖 📚', 'https://www.shortscience.org/internalsearch?q=%E6%AD%B7%E5%8F%B2%E6%9B%B8%20%F0%9F%93%96%20%F0%9F%93%9A'", - "' History Textbook ', 'https://www.shortscience.org/internalsearch?q=History%20Textbook'", - "'History%20Textbook', 'https://www.shortscience.org/internalsearch?q=History%2520Textbook'", - "'JabRef bibliography management', 'https://www.shortscience.org/internalsearch?q=JabRef%20bibliography%20management'" + "'歷史書 📖 📚', 'https://www.shortscience.org/internalsearch?q=%E6%AD%B7%E5%8F%B2%E6%9B%B8%20%F0%9F%93%96%20%F0%9F%93%9A'", + "' History Textbook ', 'https://www.shortscience.org/internalsearch?q=History%20Textbook'", + "'History%20Textbook', 'https://www.shortscience.org/internalsearch?q=History%2520Textbook'", + "'JabRef bibliography management', 'https://www.shortscience.org/internalsearch?q=JabRef%20bibliography%20management'" }) void getShortScienceSearchURLEncodesCharacters(String title, String expectedUrl) { BibEntry entry = new BibEntry().withField(StandardField.TITLE, title); diff --git a/jablib/src/test/java/org/jabref/logic/util/FileNameCleanerTest.java b/jablib/src/test/java/org/jabref/logic/util/FileNameCleanerTest.java index 1193075cd8b..91ccb630081 100644 --- a/jablib/src/test/java/org/jabref/logic/util/FileNameCleanerTest.java +++ b/jablib/src/test/java/org/jabref/logic/util/FileNameCleanerTest.java @@ -11,11 +11,11 @@ class FileNameCleanerTest { @ParameterizedTest @CsvSource({ - "legalFilename.txt, legalFilename.txt", - "illegalFilename______.txt, illegalFilename/?*<>|.txt", - "illegalFileName_.txt, illegalFileName{.txt", - "_The Evolution of Sentiment_ Analysis_.PDF, ?The Evolution of Sentiment} Analysis}.PDF", - "'The Evolution of Sentiment_ Analysis_A Review of Research Topics, Venues, and Top Cited Papers.PDF', 'The Evolution of Sentiment} Analysis}A Review of Research Topics, Venues, and Top Cited Papers.PDF'" + "legalFilename.txt, legalFilename.txt", + "illegalFilename______.txt, illegalFilename/?*<>|.txt", + "illegalFileName_.txt, illegalFileName{.txt", + "_The Evolution of Sentiment_ Analysis_.PDF, ?The Evolution of Sentiment} Analysis}.PDF", + "'The Evolution of Sentiment_ Analysis_A Review of Research Topics, Venues, and Top Cited Papers.PDF', 'The Evolution of Sentiment} Analysis}A Review of Research Topics, Venues, and Top Cited Papers.PDF'" }) void cleanFileName(String expected, String input) { assertEquals(expected, FileNameCleaner.cleanFileName(input)); @@ -23,9 +23,9 @@ void cleanFileName(String expected, String input) { @ParameterizedTest @CsvSource({ - "legalFilename.txt, legalFilename.txt", - "subdir/legalFilename.txt, subdir/legalFilename.txt", - "illegalFilename/_____.txt, illegalFilename/?*<>|.txt" + "legalFilename.txt, legalFilename.txt", + "subdir/legalFilename.txt, subdir/legalFilename.txt", + "illegalFilename/_____.txt, illegalFilename/?*<>|.txt" }) void cleanDirectoryName(String expected, String input) { assertEquals(expected, FileNameCleaner.cleanDirectoryName(input)); @@ -33,9 +33,9 @@ void cleanDirectoryName(String expected, String input) { @ParameterizedTest @CsvSource({ - "legalFilename.txt, legalFilename.txt", - "subdir\\legalFilename.txt, subdir\\legalFilename.txt", - "illegalFilename\\_____.txt, illegalFilename\\?*<>|.txt" + "legalFilename.txt, legalFilename.txt", + "subdir\\legalFilename.txt, subdir\\legalFilename.txt", + "illegalFilename\\_____.txt, illegalFilename\\?*<>|.txt" }) void cleanDirectoryNameForWindows(String expected, String input) { assertEquals(expected, FileNameCleaner.cleanDirectoryName(input)); diff --git a/jablib/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTest.java b/jablib/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTest.java index 29640c29af2..b4ccc2b1731 100644 --- a/jablib/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTest.java +++ b/jablib/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTest.java @@ -26,7 +26,7 @@ class RegExpBasedFileFinderTest { "directory/subdirectory/2017_Gražulis_726.pdf", "directory/subdirectory/pdfInSubdirectory.pdf", "directory/subdirectory/GUO ea - INORG CHEM COMMUN 2010 - Ferroelectric Metal Organic Framework (MOF).pdf" - ); + ); private Path directory; private BibEntry entry; @@ -110,10 +110,10 @@ void findAssociatedFilesFindCleanedFileFromBracketedExpression() throws IOExcept @Test void findAssociatedFilesFindFileContainingParenthesizesFromBracketedExpression() throws IOException { BibEntry bibEntry = new BibEntry().withCitationKey("Guo_ICC_2010") - .withField(StandardField.TITLE, "Ferroelectric Metal Organic Framework (MOF)") - .withField(StandardField.AUTHOR, "Guo, M. and Cai, H.-L. and Xiong, R.-G.") - .withField(StandardField.JOURNAL, "Inorganic Chemistry Communications") - .withField(StandardField.YEAR, "2010"); + .withField(StandardField.TITLE, "Ferroelectric Metal Organic Framework (MOF)") + .withField(StandardField.AUTHOR, "Guo, M. and Cai, H.-L. and Xiong, R.-G.") + .withField(StandardField.JOURNAL, "Inorganic Chemistry Communications") + .withField(StandardField.YEAR, "2010"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/.*[TITLE].*\\\\.[extension]", ','); diff --git a/jablib/src/test/java/org/jabref/logic/util/strings/StringSimilarityTest.java b/jablib/src/test/java/org/jabref/logic/util/strings/StringSimilarityTest.java index 9229cb0b3d1..ba6bff0edc5 100644 --- a/jablib/src/test/java/org/jabref/logic/util/strings/StringSimilarityTest.java +++ b/jablib/src/test/java/org/jabref/logic/util/strings/StringSimilarityTest.java @@ -43,24 +43,24 @@ void stringSimilarity(String a, String b, String expectedResult) { @ParameterizedTest(name = "\"{0}\" should match \"{1}\" with LCS similarity rating of \"{2}\".") @CsvSource({ - "'', '', 1.0", // Both empty strings - "'', test, 0.0", // First empty - "test, '', 0.0", // Second empty - "a, a, 1.0", // Single character identical strings - "test, test, 1.0", // Identical strings - "hellotheregeneralkenobi, hellotheregeneralkenobi, 1.0", // Longer identical strings - "abc, xyz, 0.0", // No common characters - "a, ab, 1.0", // Single char match, shorter string length used - "ab, a, 1.0", // Single char match, reverse argument order - "axc, ayc, 0.3333333", // Single char difference - "hello, help, 0.75", // Common 'hel' (3 chars) / min(5,4) = 0.75 - "abcd, dcba, 0.25", // Only single chars match at a time, longest common substring is of size 1 - "prefix123, prefixabc, 0.6666666", // substring is 'prefix' (6 chars) / min(9,9) = 0.666... - "123suffix, abcsuffix, 0.6666666", // substring is 'suffix' (6 chars) / min(9,9) = 0.666... - "efgh, abcdefgh, 1.0", // Exact match at end of string - "cde, abcdefgh, 1.0", // Exact match in the middle of string - "123abc456, xyzabcpqr, 0.3333333", // common substring in the middle - "ABC, abc, 1.0", // Matching ignores case + "'', '', 1.0", // Both empty strings + "'', test, 0.0", // First empty + "test, '', 0.0", // Second empty + "a, a, 1.0", // Single character identical strings + "test, test, 1.0", // Identical strings + "hellotheregeneralkenobi, hellotheregeneralkenobi, 1.0", // Longer identical strings + "abc, xyz, 0.0", // No common characters + "a, ab, 1.0", // Single char match, shorter string length used + "ab, a, 1.0", // Single char match, reverse argument order + "axc, ayc, 0.3333333", // Single char difference + "hello, help, 0.75", // Common 'hel' (3 chars) / min(5,4) = 0.75 + "abcd, dcba, 0.25", // Only single chars match at a time, longest common substring is of size 1 + "prefix123, prefixabc, 0.6666666", // substring is 'prefix' (6 chars) / min(9,9) = 0.666... + "123suffix, abcsuffix, 0.6666666", // substring is 'suffix' (6 chars) / min(9,9) = 0.666... + "efgh, abcdefgh, 1.0", // Exact match at end of string + "cde, abcdefgh, 1.0", // Exact match in the middle of string + "123abc456, xyzabcpqr, 0.3333333", // common substring in the middle + "ABC, abc, 1.0", // Matching ignores case }) void LCSSimilarity(String a, String b, String expectedResult) { assertEquals(Double.parseDouble(expectedResult), StringSimilarity.LCSSimilarity(a, b), EPSILON_SIMILARITY); diff --git a/jablib/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java b/jablib/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java index 6444a4fbd4d..b4f61c9e1b7 100644 --- a/jablib/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java +++ b/jablib/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java @@ -174,12 +174,12 @@ void getFullTextIndexPathWhenPathIsNotNull() { @Test void ofParsesValidBibtexStringCorrectly() throws Exception { String bibContent = """ - @article{Alice2023, - author = {Alice}, - title = {Test Title}, - year = {2023} - } - """; + @article{Alice2023, + author = {Alice}, + title = {Test Title}, + year = {2023} + } + """; BibDatabaseContext context = BibDatabaseContext.of(bibContent, importPrefs); BibEntry expected = new BibEntry(StandardEntryType.Article) @@ -194,12 +194,12 @@ void ofParsesValidBibtexStringCorrectly() throws Exception { @Test void ofParsesValidBibtexStreamCorrectly() throws Exception { String bibContent = """ - @article{Alice2023, - author = {Alice}, - title = {Test Title}, - year = {2023} - } - """; + @article{Alice2023, + author = {Alice}, + title = {Test Title}, + year = {2023} + } + """; try (InputStream bibContentStream = new ByteArrayInputStream(bibContent.getBytes(StandardCharsets.UTF_8))) { BibDatabaseContext context = BibDatabaseContext.of(bibContentStream, importPrefs); diff --git a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java index 592f84f9923..45f16edd674 100644 --- a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java @@ -27,10 +27,10 @@ void addDotIfAbbreviationDoesNotAddMultipleSpaces() { @ParameterizedTest @ValueSource(strings = {"O.", "A. O.", "A.-O.", - "O. Moore", "A. O. Moore", "O. von Moore", "A.-O. Moore", - "Moore, O.", "Moore, O., Jr.", "Moore, A. O.", "Moore, A.-O.", - "MEmre", "{\\'{E}}douard", "J{\\\"o}rg", "Moore, O. and O. Moore", - "Moore, O. and O. Moore and Moore, O. O."}) + "O. Moore", "A. O. Moore", "O. von Moore", "A.-O. Moore", + "Moore, O.", "Moore, O., Jr.", "Moore, A. O.", "Moore, A.-O.", + "MEmre", "{\\'{E}}douard", "J{\\\"o}rg", "Moore, O. and O. Moore", + "Moore, O. and O. Moore and Moore, O. O."}) void addDotIfAbbreviationDoNotAddDot(String input) { assertEquals(input, Author.addDotIfAbbreviation(input)); } diff --git a/jablib/src/test/java/org/jabref/model/entry/BibEntryTypeBuilderTest.java b/jablib/src/test/java/org/jabref/model/entry/BibEntryTypeBuilderTest.java index fa4b10dffff..de7f8e7722c 100644 --- a/jablib/src/test/java/org/jabref/model/entry/BibEntryTypeBuilderTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/BibEntryTypeBuilderTest.java @@ -17,10 +17,10 @@ class BibEntryTypeBuilderTest { @Disabled("There is just a log message written, but no exception thrown") void fieldAlreadySeenSameCategory() { assertThrows(IllegalArgumentException.class, () -> - new BibEntryTypeBuilder() - .withImportantFields(StandardField.AUTHOR) - .withImportantFields(StandardField.AUTHOR) - .build()); + new BibEntryTypeBuilder() + .withImportantFields(StandardField.AUTHOR) + .withImportantFields(StandardField.AUTHOR) + .build()); } @Test @@ -36,9 +36,9 @@ void detailOptionalWorks() { @Disabled("There is just a log message written, but no exception thrown") void fieldAlreadySeenDifferentCategories() { assertThrows(IllegalArgumentException.class, () -> - new BibEntryTypeBuilder() - .withRequiredFields(StandardField.AUTHOR) - .withImportantFields(StandardField.AUTHOR) - .build()); + new BibEntryTypeBuilder() + .withRequiredFields(StandardField.AUTHOR) + .withImportantFields(StandardField.AUTHOR) + .build()); } } diff --git a/jablib/src/test/java/org/jabref/model/entry/BibEntryTypesManagerTest.java b/jablib/src/test/java/org/jabref/model/entry/BibEntryTypesManagerTest.java index 22b3749fac2..fa06b377cce 100644 --- a/jablib/src/test/java/org/jabref/model/entry/BibEntryTypesManagerTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/BibEntryTypesManagerTest.java @@ -172,12 +172,12 @@ void resettingArticleWithUpdate(BibDatabaseMode mode) { @EnumSource(BibDatabaseMode.class) void modifyingArticle(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( - StandardEntryType.Article, - List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), - new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), - new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), - new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), - Set.of()); + StandardEntryType.Article, + List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), + new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), + new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), + new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), + Set.of()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertEquals(List.of(overwrittenStandardType), entryTypesManager.getAllTypes(mode).stream().filter(t -> "article".equals(t.getType().getName())).collect(Collectors.toList())); @@ -187,12 +187,12 @@ void modifyingArticle(BibDatabaseMode mode) { @EnumSource(BibDatabaseMode.class) void modifyingArticleWithParsing(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( - StandardEntryType.Article, - List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), - new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), - new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), - new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), - Set.of()); + StandardEntryType.Article, + List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), + new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), + new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), + new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), + Set.of()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); String serialized = MetaDataSerializer.serializeCustomEntryTypes(overwrittenStandardType); @@ -205,12 +205,12 @@ void modifyingArticleWithParsing(BibDatabaseMode mode) { @EnumSource(BibDatabaseMode.class) void modifyingArticleWithParsingKeepsListOrder(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( - StandardEntryType.Article, - List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), - new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), - new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), - new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), - Set.of()); + StandardEntryType.Article, + List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), + new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), + new BibField(StandardField.LANGUAGEID, FieldPriority.IMPORTANT), + new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), + Set.of()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); String serialized = MetaDataSerializer.serializeCustomEntryTypes(overwrittenStandardType); diff --git a/jablib/src/test/java/org/jabref/model/entry/DateTest.java b/jablib/src/test/java/org/jabref/model/entry/DateTest.java index adf2b2cce22..dc6976c5e4b 100644 --- a/jablib/src/test/java/org/jabref/model/entry/DateTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/DateTest.java @@ -66,21 +66,21 @@ void parseByDatePattern(Temporal expected, String provided) { private static Stream validDateRanges() { return Stream.of( - Arguments.of(Year.of(2014), Year.of(2017), "2014/2017"), - Arguments.of(YearMonth.of(2015, Month.JANUARY), YearMonth.of(2015, Month.FEBRUARY), "2015-01/2015-02"), - Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15/2015-02-25"), - Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15 / 2015-02-25"), - Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015/25 February 2015"), - Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015 / 25 February 2015"), - Arguments.of(Year.of(-29), Year.of(5), "30 BC/5 AD"), - Arguments.of(Year.of(-29), Year.of(5), "30 BC / 5 AD"), - Arguments.of(Year.of(-29), Year.of(5), "0030 BC/0005 AD"), - Arguments.of(Year.of(-29), Year.of(-9), "0030 BC/0010 BC"), - Arguments.of(Year.of(5), Year.of(10), "0005 AD/0010 AD"), - Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(5, Month.FEBRUARY), "0030-01 BC/0005-02 AD"), - Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(5, Month.FEBRUARY), "0030-01 BC / 0005-02 AD"), - Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(-9, Month.FEBRUARY), "0030-01 BC / 0010-02 BC"), - Arguments.of(YearMonth.of(5, Month.JANUARY), YearMonth.of(20, Month.FEBRUARY), "0005-01 AD / 0020-02 AD") + Arguments.of(Year.of(2014), Year.of(2017), "2014/2017"), + Arguments.of(YearMonth.of(2015, Month.JANUARY), YearMonth.of(2015, Month.FEBRUARY), "2015-01/2015-02"), + Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15/2015-02-25"), + Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15 / 2015-02-25"), + Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015/25 February 2015"), + Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015 / 25 February 2015"), + Arguments.of(Year.of(-29), Year.of(5), "30 BC/5 AD"), + Arguments.of(Year.of(-29), Year.of(5), "30 BC / 5 AD"), + Arguments.of(Year.of(-29), Year.of(5), "0030 BC/0005 AD"), + Arguments.of(Year.of(-29), Year.of(-9), "0030 BC/0010 BC"), + Arguments.of(Year.of(5), Year.of(10), "0005 AD/0010 AD"), + Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(5, Month.FEBRUARY), "0030-01 BC/0005-02 AD"), + Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(5, Month.FEBRUARY), "0030-01 BC / 0005-02 AD"), + Arguments.of(YearMonth.of(-29, Month.JANUARY), YearMonth.of(-9, Month.FEBRUARY), "0030-01 BC / 0010-02 BC"), + Arguments.of(YearMonth.of(5, Month.JANUARY), YearMonth.of(20, Month.FEBRUARY), "0005-01 AD / 0020-02 AD") ); } diff --git a/jablib/src/test/java/org/jabref/model/entry/EntryLinkListTest.java b/jablib/src/test/java/org/jabref/model/entry/EntryLinkListTest.java index 83729e7dd3a..6dfa9de42a2 100644 --- a/jablib/src/test/java/org/jabref/model/entry/EntryLinkListTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/EntryLinkListTest.java @@ -62,8 +62,8 @@ void givenFieldValueAndDatabaseWhenParsingThenExpectLink() { @Test void givenBibEntryWhenParsingThenExpectLink() { - ParsedEntryLink expected = new ParsedEntryLink(new BibEntry().withCitationKey("key")); - assertFalse(expected.getLinkedEntry().isEmpty()); + ParsedEntryLink expected = new ParsedEntryLink(new BibEntry().withCitationKey("key")); + assertFalse(expected.getLinkedEntry().isEmpty()); } @Test diff --git a/jablib/src/test/java/org/jabref/model/entry/identifier/DOITest.java b/jablib/src/test/java/org/jabref/model/entry/identifier/DOITest.java index 51c9b8f9d3a..8aa03e4c836 100644 --- a/jablib/src/test/java/org/jabref/model/entry/identifier/DOITest.java +++ b/jablib/src/test/java/org/jabref/model/entry/identifier/DOITest.java @@ -300,9 +300,9 @@ void rejectInvalidDirectoryIndicatorInShortDoi() { @Test void emptyOrUndescoreOnlyReturnsEmpty() { - assertEquals(Optional.empty(), DOI.parse("_")); - assertEquals(Optional.empty(), DOI.parse("\t_")); - assertEquals(Optional.empty(), DOI.parse("___")); + assertEquals(Optional.empty(), DOI.parse("_")); + assertEquals(Optional.empty(), DOI.parse("\t_")); + assertEquals(Optional.empty(), DOI.parse("___")); } @Test diff --git a/jablib/src/test/java/org/jabref/model/entry/identifier/SSRNTest.java b/jablib/src/test/java/org/jabref/model/entry/identifier/SSRNTest.java index 62f5e2a5bd6..85e6689a7cd 100644 --- a/jablib/src/test/java/org/jabref/model/entry/identifier/SSRNTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/identifier/SSRNTest.java @@ -32,7 +32,7 @@ private static Stream provideTestData() { /** * @param findInText if the input should be found when passing through "find in text" - * @param input the input to be checked + * @param input the input to be checked */ @ParameterizedTest @MethodSource("provideTestData") diff --git a/jablib/src/test/java/org/jabref/model/entry/types/BibtexEntryTypeDefinitionsTest.java b/jablib/src/test/java/org/jabref/model/entry/types/BibtexEntryTypeDefinitionsTest.java index 05aef2a503f..999c3487f3f 100644 --- a/jablib/src/test/java/org/jabref/model/entry/types/BibtexEntryTypeDefinitionsTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/types/BibtexEntryTypeDefinitionsTest.java @@ -18,9 +18,9 @@ void all() { @Test void languageContained() { BibEntryType articleEntryType = BiblatexEntryTypeDefinitions.ALL.stream() - .filter(type -> type.getType().equals(StandardEntryType.Article)) - .findFirst() - .get(); + .filter(type -> type.getType().equals(StandardEntryType.Article)) + .findFirst() + .get(); assertTrue(articleEntryType.getDetailOptionalFields().contains(StandardField.LANGUAGE)); } } diff --git a/jablib/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java b/jablib/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java index ea9d473a941..f3bcaad066e 100644 --- a/jablib/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java +++ b/jablib/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java @@ -28,9 +28,9 @@ public class GroupTreeNodeTest { /** * Gets the marked node in the following tree of explicit groups: * Root - * A ExplicitA, Including - * A ExplicitParent, Independent (= parent) - * B ExplicitNode, Refining (<-- this) + * A ExplicitA, Including + * A ExplicitParent, Independent (= parent) + * B ExplicitNode, Refining (<-- this) */ public static GroupTreeNode getNodeInSimpleTree(GroupTreeNode root) { root.addSubgroup(new ExplicitGroup("ExplicitA", GroupHierarchyType.INCLUDING, ',')); @@ -42,19 +42,19 @@ public static GroupTreeNode getNodeInSimpleTree(GroupTreeNode root) { /** * Gets the marked node in the following tree: * Root - * A SearchA - * A ExplicitA, Including - * A ExplicitGrandParent (= grand parent) - * B ExplicitB - * B KeywordParent (= parent) - * C KeywordNode (<-- this) - * D ExplicitChild (= child) - * C SearchC - * C ExplicitC - * C KeywordC - * B SearchB - * B KeywordB - * A KeywordA + * A SearchA + * A ExplicitA, Including + * A ExplicitGrandParent (= grand parent) + * B ExplicitB + * B KeywordParent (= parent) + * C KeywordNode (<-- this) + * D ExplicitChild (= child) + * C SearchC + * C ExplicitC + * C KeywordC + * B SearchB + * B KeywordB + * A KeywordA */ public static GroupTreeNode getNodeInComplexTree(GroupTreeNode root) { root.addSubgroup(getSearchGroup("SearchA")); @@ -92,10 +92,10 @@ private static AbstractGroup getExplict(String name) { /** * Gets the marked in the following tree: * Root - * A - * A - * A (<- this) - * A + * A + * A + * A (<- this) + * A */ /* GroupTreeNode getNodeAsChild(TreeNodeMock root) { diff --git a/jablib/src/test/java/org/jabref/model/metadata/UserHostInfoTest.java b/jablib/src/test/java/org/jabref/model/metadata/UserHostInfoTest.java index a6af353eeda..6303b2e4e47 100644 --- a/jablib/src/test/java/org/jabref/model/metadata/UserHostInfoTest.java +++ b/jablib/src/test/java/org/jabref/model/metadata/UserHostInfoTest.java @@ -41,43 +41,43 @@ void parse(String userHostString, String expectedUser, String expectedHost) { void hasSameHostReturnsTrueForSameNonEmptyHost() { UserHostInfo userHost1 = new UserHostInfo("user1", "host"); UserHostInfo userHost2 = new UserHostInfo("user2", "host"); - + assertTrue(userHost1.hasSameHost(userHost2)); assertTrue(userHost2.hasSameHost(userHost1)); } - + @Test void hasSameHostReturnsFalseForDifferentHosts() { UserHostInfo userHost1 = new UserHostInfo("user", "host1"); UserHostInfo userHost2 = new UserHostInfo("user", "host2"); - + assertFalse(userHost1.hasSameHost(userHost2)); assertFalse(userHost2.hasSameHost(userHost1)); } - + @Test void hasSameHostReturnsFalseForEmptyHost() { UserHostInfo userHostWithEmptyHost = new UserHostInfo("user", ""); UserHostInfo userHostWithHost = new UserHostInfo("user", "host"); - + assertFalse(userHostWithEmptyHost.hasSameHost(userHostWithHost)); assertFalse(userHostWithHost.hasSameHost(userHostWithEmptyHost)); } - + @Test void hasSameHostReturnsFalseForBothEmptyHosts() { UserHostInfo userHost1 = new UserHostInfo("user1", ""); UserHostInfo userHost2 = new UserHostInfo("user2", ""); - + assertFalse(userHost1.hasSameHost(userHost2)); assertFalse(userHost2.hasSameHost(userHost1)); } - + @Test void toStringReturnsUserHostString() { UserHostInfo userHostInfo = new UserHostInfo("user", "host"); assertEquals("user-host", userHostInfo.toString()); - + UserHostInfo userHostInfoWithEmptyHost = new UserHostInfo("user", ""); assertEquals("user", userHostInfoWithEmptyHost.toString()); } diff --git a/jablib/src/test/java/org/jabref/model/strings/StringUtilTest.java b/jablib/src/test/java/org/jabref/model/strings/StringUtilTest.java index 293218df064..201ca23b35e 100644 --- a/jablib/src/test/java/org/jabref/model/strings/StringUtilTest.java +++ b/jablib/src/test/java/org/jabref/model/strings/StringUtilTest.java @@ -138,7 +138,7 @@ void join() { assertEquals("", StringUtil.join(s, "\\", 3, s.length)); - assertEquals("", StringUtil.join(new String[]{}, "\\", 0, 0)); + assertEquals("", StringUtil.join(new String[] {}, "\\", 0, 0)); } @Test @@ -189,11 +189,11 @@ void wrap() { @Test void decodeStringDoubleArray() { - assertArrayEquals(new String[][]{{"a", "b"}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:b;c:d")); - assertArrayEquals(new String[][]{{"a", ""}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:;c:d")); + assertArrayEquals(new String[][] {{"a", "b"}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:b;c:d")); + assertArrayEquals(new String[][] {{"a", ""}, {"c", "d"}}, StringUtil.decodeStringDoubleArray("a:;c:d")); // arrays first differed at element [0][1]; expected: null but was: java.lang.String // assertArrayEquals(stringArray2res, StringUtil.decodeStringDoubleArray(encStringArray2)); - assertArrayEquals(new String[][]{{"a", ":b"}, {"c;", "d"}}, StringUtil.decodeStringDoubleArray("a:\\:b;c\\;:d")); + assertArrayEquals(new String[][] {{"a", ":b"}, {"c;", "d"}}, StringUtil.decodeStringDoubleArray("a:\\:b;c\\;:d")); } @Test diff --git a/jabls/src/main/java/org/jabref/languageserver/BibtexTextDocumentService.java b/jabls/src/main/java/org/jabref/languageserver/BibtexTextDocumentService.java index 10cd45abb1a..3fbb072b28b 100644 --- a/jabls/src/main/java/org/jabref/languageserver/BibtexTextDocumentService.java +++ b/jabls/src/main/java/org/jabref/languageserver/BibtexTextDocumentService.java @@ -42,10 +42,12 @@ public void didChange(DidChangeTextDocumentParams params) { } @Override - public void didClose(DidCloseTextDocumentParams params) { } + public void didClose(DidCloseTextDocumentParams params) { + } @Override - public void didSave(DidSaveTextDocumentParams params) { } + public void didSave(DidSaveTextDocumentParams params) { + } @Override public CompletableFuture, CompletionList>> completion(CompletionParams position) { diff --git a/jabls/src/main/java/org/jabref/languageserver/util/LspDiagnosticBuilder.java b/jabls/src/main/java/org/jabref/languageserver/util/LspDiagnosticBuilder.java index fe0d49eef23..628811eeffa 100644 --- a/jabls/src/main/java/org/jabref/languageserver/util/LspDiagnosticBuilder.java +++ b/jabls/src/main/java/org/jabref/languageserver/util/LspDiagnosticBuilder.java @@ -32,7 +32,8 @@ public final class LspDiagnosticBuilder { @Nullable private Range explicitRange; - private LspDiagnosticBuilder() { } + private LspDiagnosticBuilder() { + } public static LspDiagnosticBuilder create(ParserResult parserResult, String message) { return new LspDiagnosticBuilder().setMessage(message).setParserResult(parserResult); diff --git a/jabsrv-cli/src/main/java/org/jabref/http/server/cli/ServerCli.java b/jabsrv-cli/src/main/java/org/jabref/http/server/cli/ServerCli.java index e73ee273955..c590639aebb 100644 --- a/jabsrv-cli/src/main/java/org/jabref/http/server/cli/ServerCli.java +++ b/jabsrv-cli/src/main/java/org/jabref/http/server/cli/ServerCli.java @@ -50,9 +50,9 @@ public Void call() throws InterruptedException { // Additionally, files can be provided as args if (files != null) { List filesToAdd = files.stream() - .filter(Files::exists) - .filter(path -> !filesToServe.contains(path)) - .toList(); + .filter(Files::exists) + .filter(path -> !filesToServe.contains(path)) + .toList(); LOGGER.info("Adding following files to the list of opened libraries: {}", filesToAdd); filesToServe.addAll(0, filesToAdd); } diff --git a/jabsrv/src/main/java/org/jabref/http/dto/BibEntryDTO.java b/jabsrv/src/main/java/org/jabref/http/dto/BibEntryDTO.java index 1e36564072d..b8305f22f33 100644 --- a/jabsrv/src/main/java/org/jabref/http/dto/BibEntryDTO.java +++ b/jabsrv/src/main/java/org/jabref/http/dto/BibEntryDTO.java @@ -20,9 +20,9 @@ * The data transfer object (DTO) for an BibEntry * * @param sharingMetadata the data used for sharing - * @param userComments the comments before the BibTeX entry - * @param citationKey the citation key (duplicated from BibEntry to ease processing by the client) - * @param bibtex the BibEntry as BibTeX string (see ADR-0027 for more information, why we don't use a HashMap / JSON) + * @param userComments the comments before the BibTeX entry + * @param citationKey the citation key (duplicated from BibEntry to ease processing by the client) + * @param bibtex the BibEntry as BibTeX string (see ADR-0027 for more information, why we don't use a HashMap / JSON) */ public record BibEntryDTO(SharedBibEntryData sharingMetadata, String userComments, String citationKey, String bibtex) implements Comparable { diff --git a/jabsrv/src/main/java/org/jabref/http/server/LibraryResource.java b/jabsrv/src/main/java/org/jabref/http/server/LibraryResource.java index 1d53dcc9ba0..0db9294d281 100644 --- a/jabsrv/src/main/java/org/jabref/http/server/LibraryResource.java +++ b/jabsrv/src/main/java/org/jabref/http/server/LibraryResource.java @@ -77,7 +77,7 @@ public String getJson(@PathParam("id") String id) throws IOException { /** * At http://localhost:23119/libraries/{id}/map

              - * + *

              * Looks for the .jmp file in the directory of the given library ({id}.bib file). * * @param id The given library @@ -123,11 +123,10 @@ public String getJabMapJson(@PathParam("id") String id) throws IOException { /** * At http://localhost:23119/libraries/{id}/map

              - * + *

              * Saves the mindmap next to its associated library. * * @param id The given library - * * @throws IOException */ @PUT @@ -204,10 +203,10 @@ private BibDatabaseContext getDatabaseContext(String id) throws IOException { /** * At http://localhost:23119/libraries/{id}/entries/{entryId}

              - * + *

              * Combines attributes of a given BibEntry into a basic entry preview for as plain text. * - * @param id The name of the library + * @param id The name of the library * @param entryId The CitationKey of the BibEntry * @return a basic entry preview as plain text * @throws IOException @@ -253,10 +252,10 @@ public String getPlainRepresentation(@PathParam("id") String id, @PathParam("ent /** * At http://localhost:23119/libraries/{id}/entries/{entryId}

              - * + *

              * Combines attributes of a given BibEntry into a basic entry preview for as HTML text. * - * @param id The name of the library + * @param id The name of the library * @param entryId The CitationKey of the BibEntry * @return a basic entry preview as HTML text * @throws IOException @@ -300,7 +299,7 @@ public String getHTMLRepresentation(@PathParam("id") String id, @PathParam("entr /** * At http://localhost:23119/libraries/{id}/entries/pdffiles

              - * + *

              * Loops through all entries in the specified library and adds attached files of type "PDF" to * a list and JSON serialises it. */ diff --git a/jabsrv/src/main/java/org/jabref/http/server/RootResource.java b/jabsrv/src/main/java/org/jabref/http/server/RootResource.java index c55f2583db3..5c3c9753ec5 100644 --- a/jabsrv/src/main/java/org/jabref/http/server/RootResource.java +++ b/jabsrv/src/main/java/org/jabref/http/server/RootResource.java @@ -11,12 +11,12 @@ public class RootResource { @Produces(MediaType.TEXT_HTML) public String get() { return """ - - -

              - JabRef http API runs. Please navigate to libraries. -

              - -"""; + + +

              + JabRef http API runs. Please navigate to libraries. +

              + + """; } } diff --git a/jabsrv/src/main/java/org/jabref/http/server/cayw/format/BibLatexFormatter.java b/jabsrv/src/main/java/org/jabref/http/server/cayw/format/BibLatexFormatter.java index 73c41b6236c..6a5078bc566 100644 --- a/jabsrv/src/main/java/org/jabref/http/server/cayw/format/BibLatexFormatter.java +++ b/jabsrv/src/main/java/org/jabref/http/server/cayw/format/BibLatexFormatter.java @@ -30,8 +30,8 @@ public String format(CAYWQueryParams queryParams, List caywEntries) { String command = queryParams.getCommand().orElse(defaultCommand); List bibEntries = caywEntries.stream() - .map(CAYWEntry::bibEntry) - .toList(); + .map(CAYWEntry::bibEntry) + .toList(); return "\\%s{%s}".formatted(command, bibEntries.stream() diff --git a/jabsrv/src/main/java/org/jabref/http/server/cayw/format/SimpleJsonFormatter.java b/jabsrv/src/main/java/org/jabref/http/server/cayw/format/SimpleJsonFormatter.java index a08be38c6b5..e05f9fa97a5 100644 --- a/jabsrv/src/main/java/org/jabref/http/server/cayw/format/SimpleJsonFormatter.java +++ b/jabsrv/src/main/java/org/jabref/http/server/cayw/format/SimpleJsonFormatter.java @@ -28,8 +28,8 @@ public MediaType getMediaType() { @Override public String format(CAYWQueryParams queryParams, List caywEntries) { List simpleJsons = caywEntries.stream() - .map(caywEntry -> SimpleJson.fromBibEntry(caywEntry.bibEntry())) - .toList(); + .map(caywEntry -> SimpleJson.fromBibEntry(caywEntry.bibEntry())) + .toList(); return gson.toJson(simpleJsons); } } diff --git a/jabsrv/src/main/java/org/jabref/http/server/services/ServerUtils.java b/jabsrv/src/main/java/org/jabref/http/server/services/ServerUtils.java index 79a388c4318..d695564eda2 100644 --- a/jabsrv/src/main/java/org/jabref/http/server/services/ServerUtils.java +++ b/jabsrv/src/main/java/org/jabref/http/server/services/ServerUtils.java @@ -26,10 +26,10 @@ public class ServerUtils { private static java.nio.file.Path getLibraryPath(String id, FilesToServe filesToServe) { return filesToServe.getFilesToServe() - .stream() - .filter(p -> (p.getFileName() + "-" + BackupFileUtil.getUniqueFilePrefix(p)).equals(id)) - .findAny() - .orElseThrow(NotFoundException::new); + .stream() + .filter(p -> (p.getFileName() + "-" + BackupFileUtil.getUniqueFilePrefix(p)).equals(id)) + .findAny() + .orElseThrow(NotFoundException::new); } private static java.nio.file.Path getLibraryPath(String id, SrvStateManager srvStateManager) { diff --git a/jabsrv/src/test/java/org/jabref/http/server/cayw/CAYWResourceTest.java b/jabsrv/src/test/java/org/jabref/http/server/cayw/CAYWResourceTest.java index 0786268c341..24a2b4196bc 100644 --- a/jabsrv/src/test/java/org/jabref/http/server/cayw/CAYWResourceTest.java +++ b/jabsrv/src/test/java/org/jabref/http/server/cayw/CAYWResourceTest.java @@ -25,7 +25,8 @@ protected Application configure() { addFormatterServiceToResourceConfig(resourceConfig); resourceConfig.register(new AbstractBinder() { - @Override protected void configure() { + @Override + protected void configure() { SrvStateManager mockSrv = Mockito.mock(SrvStateManager.class); BibEntry bibEntry = new BibEntry().withCitationKey("Author2023test"); Mockito.when(mockSrv.getSelectedEntries()).thenReturn(FXCollections.observableArrayList(bibEntry));