From 3ca461e74042232c5a690ab668a62cbc6caa4f4d Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 16:51:30 +0200 Subject: [PATCH 01/16] Move information generator for AUX import to logic Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com> --- src/main/java/org/jabref/cli/AuxCommandLine.java | 4 ++-- .../org/jabref/gui/auximport/FromAuxDialogViewModel.java | 3 ++- .../auxparser/AuxParserStatisticsProvider.java} | 7 +++---- 3 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/org/jabref/{gui/auximport/AuxParserResultViewModel.java => logic/auxparser/AuxParserStatisticsProvider.java} (90%) diff --git a/src/main/java/org/jabref/cli/AuxCommandLine.java b/src/main/java/org/jabref/cli/AuxCommandLine.java index 61f4c133008..ea566f44e24 100644 --- a/src/main/java/org/jabref/cli/AuxCommandLine.java +++ b/src/main/java/org/jabref/cli/AuxCommandLine.java @@ -2,9 +2,9 @@ import java.nio.file.Path; -import org.jabref.gui.auximport.AuxParserResultViewModel; import org.jabref.logic.auxparser.AuxParser; import org.jabref.logic.auxparser.AuxParserResult; +import org.jabref.logic.auxparser.AuxParserStatisticsProvider; import org.jabref.logic.auxparser.DefaultAuxParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.strings.StringUtil; @@ -26,7 +26,7 @@ public BibDatabase perform() { AuxParserResult result = auxParser.parse(Path.of(auxFile)); subDatabase = result.getGeneratedBibDatabase(); // print statistics - System.out.println(new AuxParserResultViewModel(result).getInformation(true)); + System.out.println(new AuxParserStatisticsProvider(result).getInformation(true)); } return subDatabase; } diff --git a/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java b/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java index eb871f44a22..4f197767dde 100644 --- a/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java +++ b/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java @@ -20,6 +20,7 @@ import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.auxparser.AuxParser; import org.jabref.logic.auxparser.AuxParserResult; +import org.jabref.logic.auxparser.AuxParserStatisticsProvider; import org.jabref.logic.auxparser.DefaultAuxParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.preferences.CliPreferences; @@ -96,7 +97,7 @@ public void parse() { AuxParser auxParser = new DefaultAuxParser(referenceDatabase); auxParserResult = auxParser.parse(Path.of(auxName)); notFoundList.setAll(auxParserResult.getUnresolvedKeys()); - statusTextProperty.set(new AuxParserResultViewModel(auxParserResult).getInformation(false)); + statusTextProperty.set(new AuxParserStatisticsProvider(auxParserResult).getInformation(false)); if (!auxParserResult.getGeneratedBibDatabase().hasEntries()) { // The generated database contains no entries -> no active generate-button diff --git a/src/main/java/org/jabref/gui/auximport/AuxParserResultViewModel.java b/src/main/java/org/jabref/logic/auxparser/AuxParserStatisticsProvider.java similarity index 90% rename from src/main/java/org/jabref/gui/auximport/AuxParserResultViewModel.java rename to src/main/java/org/jabref/logic/auxparser/AuxParserStatisticsProvider.java index 511ef2d168a..8509eb4cc86 100644 --- a/src/main/java/org/jabref/gui/auximport/AuxParserResultViewModel.java +++ b/src/main/java/org/jabref/logic/auxparser/AuxParserStatisticsProvider.java @@ -1,15 +1,14 @@ -package org.jabref.gui.auximport; +package org.jabref.logic.auxparser; import java.util.stream.Collectors; -import org.jabref.logic.auxparser.AuxParserResult; import org.jabref.logic.l10n.Localization; -public class AuxParserResultViewModel { +public class AuxParserStatisticsProvider { private AuxParserResult auxParserResult; - public AuxParserResultViewModel(AuxParserResult auxParserResult) { + public AuxParserStatisticsProvider(AuxParserResult auxParserResult) { this.auxParserResult = auxParserResult; } From ec9c347abd9e44459c649a61113d66509624d340 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 16:59:26 +0200 Subject: [PATCH 02/16] Add "static" to de-facto static methods --- src/main/java/org/jabref/cli/ArgumentProcessor.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/cli/ArgumentProcessor.java b/src/main/java/org/jabref/cli/ArgumentProcessor.java index 64edddac7a4..e87b7bd61d7 100644 --- a/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -300,7 +300,7 @@ public void processArguments() { } } - private void writeMetadataToPdf(List loaded, + private static void writeMetadataToPdf(List loaded, String filesAndCiteKeys, XmpPreferences xmpPreferences, FilePreferences filePreferences, @@ -366,7 +366,7 @@ private void writeMetadataToPdf(List loaded, embeddBibfile); } - private void writeMetadataToPDFsOfEntry(BibDatabaseContext databaseContext, + private static void writeMetadataToPDFsOfEntry(BibDatabaseContext databaseContext, String citeKey, BibEntry entry, FilePreferences filePreferences, @@ -395,7 +395,7 @@ private void writeMetadataToPDFsOfEntry(BibDatabaseContext databaseContext, } } - private void writeMetadataToPdfByCitekey(BibDatabaseContext databaseContext, + private static void writeMetadataToPdfByCitekey(BibDatabaseContext databaseContext, List citeKeys, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, @@ -415,7 +415,7 @@ private void writeMetadataToPdfByCitekey(BibDatabaseContext databaseContext, } } - private void writeMetadataToPdfByFileNames(BibDatabaseContext databaseContext, + private static void writeMetadataToPdfByFileNames(BibDatabaseContext databaseContext, List pdfs, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, From 52e267f3155f3c71aa18f4f5395bdc9a9c35252a Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 17:05:06 +0200 Subject: [PATCH 03/16] Use BibEntryTypesManager from preferences --- src/main/java/org/jabref/cli/ArgumentProcessor.java | 10 +++------- src/main/java/org/jabref/cli/JabRefCLI.java | 5 +---- .../java/org/jabref/gui/exporter/ExportCommand.java | 4 +--- .../jabref/gui/exporter/ExportToClipboardAction.java | 5 +---- .../org/jabref/logic/exporter/ExporterFactory.java | 7 ++----- .../java/org/jabref/logic/exporter/ExporterTest.java | 5 ++--- 6 files changed, 10 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/cli/ArgumentProcessor.java b/src/main/java/org/jabref/cli/ArgumentProcessor.java index e87b7bd61d7..ebac484faa1 100644 --- a/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -258,7 +258,7 @@ public void processArguments() { cliPreferences.getXmpPreferences(), cliPreferences.getFilePreferences(), cliPreferences.getLibraryPreferences().getDefaultBibDatabaseMode(), - Injector.instantiateModelOrService(BibEntryTypesManager.class), + cliPreferences.getCustomEntryTypesRepository(), cliPreferences.getFieldPreferences(), Injector.instantiateModelOrService(JournalAbbreviationRepository.class), cli.isWriteXmpToPdf() || cli.isWriteMetadataToPdf(), @@ -499,9 +499,7 @@ private boolean exportMatches(List loaded) { LOGGER.debug("Finished export"); } else { // export new database - ExporterFactory exporterFactory = ExporterFactory.create( - cliPreferences, - Injector.instantiateModelOrService(BibEntryTypesManager.class)); + ExporterFactory exporterFactory = ExporterFactory.create(cliPreferences); Optional exporter = exporterFactory.getExporterByName(formatName); if (exporter.isEmpty()) { System.err.println(Localization.lang("Unknown export format %0", formatName)); @@ -679,9 +677,7 @@ private void exportFile(List loaded, String[] data) { List fileDirForDatabase = databaseContext .getFileDirectories(cliPreferences.getFilePreferences()); System.out.println(Localization.lang("Exporting %0", data[0])); - ExporterFactory exporterFactory = ExporterFactory.create( - cliPreferences, - Injector.instantiateModelOrService(BibEntryTypesManager.class)); + ExporterFactory exporterFactory = ExporterFactory.create(cliPreferences); Optional exporter = exporterFactory.getExporterByName(data[1]); if (exporter.isEmpty()) { System.err.println(Localization.lang("Unknown export format %0", data[1])); diff --git a/src/main/java/org/jabref/cli/JabRefCLI.java b/src/main/java/org/jabref/cli/JabRefCLI.java index 0cd74a0bba4..795288f8638 100644 --- a/src/main/java/org/jabref/cli/JabRefCLI.java +++ b/src/main/java/org/jabref/cli/JabRefCLI.java @@ -11,7 +11,6 @@ import org.jabref.logic.os.OS; import org.jabref.logic.preferences.CliPreferences; import org.jabref.logic.util.BuildInfo; -import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.DummyFileUpdateMonitor; @@ -325,9 +324,7 @@ public static void printUsage(CliPreferences preferences) { String importFormatsIntro = Localization.lang("Available import formats"); String importFormatsList = "%s:%n%s%n".formatted(importFormatsIntro, alignStringTable(importFormats)); - ExporterFactory exporterFactory = ExporterFactory.create( - preferences, - Injector.instantiateModelOrService(BibEntryTypesManager.class)); + ExporterFactory exporterFactory = ExporterFactory.create(preferences); List> exportFormats = exporterFactory .getExporters().stream() .map(format -> new Pair<>(format.getName(), format.getId())) diff --git a/src/main/java/org/jabref/gui/exporter/ExportCommand.java b/src/main/java/org/jabref/gui/exporter/ExportCommand.java index 4cadba61f5b..5cf0024cb9b 100644 --- a/src/main/java/org/jabref/gui/exporter/ExportCommand.java +++ b/src/main/java/org/jabref/gui/exporter/ExportCommand.java @@ -79,9 +79,7 @@ public ExportCommand(ExportMethod exportMethod, @Override public void execute() { // Get list of exporters and sort before adding to file dialog - ExporterFactory exporterFactory = ExporterFactory.create( - preferences, - entryTypesManager); + ExporterFactory exporterFactory = ExporterFactory.create(preferences); List exporters = exporterFactory.getExporters().stream() .sorted(Comparator.comparing(Exporter::getName)) .collect(Collectors.toList()); diff --git a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java index 5fb8cb1fe0c..57551c8298a 100644 --- a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java +++ b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java @@ -27,7 +27,6 @@ import org.jabref.logic.util.StandardFileType; import org.jabref.logic.util.TaskExecutor; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.BibEntryTypesManager; import com.airhacks.afterburner.injection.Injector; import org.slf4j.Logger; @@ -75,9 +74,7 @@ public void execute() { return; } - ExporterFactory exporterFactory = ExporterFactory.create( - preferences, - Injector.instantiateModelOrService(BibEntryTypesManager.class)); + ExporterFactory exporterFactory = ExporterFactory.create(preferences); List exporters = exporterFactory.getExporters().stream() .sorted(Comparator.comparing(Exporter::getName)) .filter(exporter -> SUPPORTED_FILETYPES.contains(exporter.getFileType())) diff --git a/src/main/java/org/jabref/logic/exporter/ExporterFactory.java b/src/main/java/org/jabref/logic/exporter/ExporterFactory.java index 8f5f61afdf3..28a89ebfe7c 100644 --- a/src/main/java/org/jabref/logic/exporter/ExporterFactory.java +++ b/src/main/java/org/jabref/logic/exporter/ExporterFactory.java @@ -13,7 +13,6 @@ import org.jabref.logic.util.StandardFileType; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.database.BibDatabaseMode; -import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.metadata.SelfContainedSaveOrder; public class ExporterFactory { @@ -24,9 +23,7 @@ private ExporterFactory(List exporters) { this.exporters = Objects.requireNonNull(exporters); } - public static ExporterFactory create(CliPreferences preferences, - BibEntryTypesManager entryTypesManager) { - + public static ExporterFactory create(CliPreferences preferences) { List customFormats = preferences.getExportPreferences().getCustomExporters(); LayoutFormatterPreferences layoutPreferences = preferences.getLayoutFormatterPreferences(); SelfContainedSaveOrder saveOrder = SelfContainedSaveOrder.of(preferences.getSelfContainedExportConfiguration().getSaveOrder()); @@ -61,7 +58,7 @@ public static ExporterFactory create(CliPreferences preferences, exporters.add(new ModsExporter()); exporters.add(new XmpExporter(xmpPreferences)); exporters.add(new XmpPdfExporter(xmpPreferences)); - exporters.add(new EmbeddedBibFilePdfExporter(bibDatabaseMode, entryTypesManager, fieldPreferences)); + exporters.add(new EmbeddedBibFilePdfExporter(bibDatabaseMode, preferences.getCustomEntryTypesRepository(), fieldPreferences)); exporters.add(new CffExporter()); exporters.add(new EndnoteXmlExporter(preferences.getBibEntryPreferences())); diff --git a/src/test/java/org/jabref/logic/exporter/ExporterTest.java b/src/test/java/org/jabref/logic/exporter/ExporterTest.java index b3490f8a0f2..fbd95cdd7d7 100644 --- a/src/test/java/org/jabref/logic/exporter/ExporterTest.java +++ b/src/test/java/org/jabref/logic/exporter/ExporterTest.java @@ -42,10 +42,9 @@ private static Stream exportFormats() { CliPreferences preferences = mock(CliPreferences.class, Answers.RETURNS_DEEP_STUBS); when(preferences.getExportPreferences().getExportSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); when(preferences.getExportPreferences().getCustomExporters()).thenReturn(FXCollections.emptyObservableList()); + when(preferences.getCustomEntryTypesRepository()).thenReturn(mock(BibEntryTypesManager.class)); - ExporterFactory exporterFactory = ExporterFactory.create( - preferences, - mock(BibEntryTypesManager.class)); + ExporterFactory exporterFactory = ExporterFactory.create(preferences); Collection result = new ArrayList<>(); for (Exporter format : exporterFactory.getExporters()) { From 3e2573aefa1a3c7addce55cf705f5ae401e10782 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 17:05:46 +0200 Subject: [PATCH 04/16] Inline variables --- .../org/jabref/logic/exporter/ExporterTest.java | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/test/java/org/jabref/logic/exporter/ExporterTest.java b/src/test/java/org/jabref/logic/exporter/ExporterTest.java index fbd95cdd7d7..206a07b96b2 100644 --- a/src/test/java/org/jabref/logic/exporter/ExporterTest.java +++ b/src/test/java/org/jabref/logic/exporter/ExporterTest.java @@ -12,11 +12,9 @@ import org.jabref.logic.preferences.CliPreferences; import org.jabref.model.database.BibDatabaseContext; -import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.metadata.SaveOrder; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -29,15 +27,6 @@ public class ExporterTest { - public BibDatabaseContext databaseContext; - public List entries; - - @BeforeEach - void setUp() { - databaseContext = new BibDatabaseContext(); - entries = Collections.emptyList(); - } - private static Stream exportFormats() { CliPreferences preferences = mock(CliPreferences.class, Answers.RETURNS_DEEP_STUBS); when(preferences.getExportPreferences().getExportSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); @@ -58,7 +47,7 @@ private static Stream exportFormats() { void exportingEmptyDatabaseYieldsEmptyFile(Exporter exportFormat, String name, @TempDir Path testFolder) throws Exception { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); - exportFormat.export(databaseContext, tmpFile, entries); + exportFormat.export(new BibDatabaseContext(), tmpFile, List.of()); assertEquals(Collections.emptyList(), Files.readAllLines(tmpFile)); } @@ -68,7 +57,7 @@ void exportingNullDatabaseThrowsNPE(Exporter exportFormat, String name, @TempDir assertThrows(NullPointerException.class, () -> { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); - exportFormat.export(null, tmpFile, entries); + exportFormat.export(null, tmpFile, List.of()); }); } } From d26002c274ee9bcc64716abb9756d25dab30bbf2 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 17:16:47 +0200 Subject: [PATCH 05/16] Remove Injector from JabRefCLI --- src/main/java/org/jabref/cli/JabRefCLI.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/cli/JabRefCLI.java b/src/main/java/org/jabref/cli/JabRefCLI.java index 795288f8638..d27511e9e24 100644 --- a/src/main/java/org/jabref/cli/JabRefCLI.java +++ b/src/main/java/org/jabref/cli/JabRefCLI.java @@ -14,7 +14,6 @@ import org.jabref.model.strings.StringUtil; import org.jabref.model.util.DummyFileUpdateMonitor; -import com.airhacks.afterburner.injection.Injector; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; @@ -339,8 +338,7 @@ public static void printUsage(CliPreferences preferences) { } private String getVersionInfo() { - BuildInfo buildInfo = Injector.instantiateModelOrService(BuildInfo.class); - return "JabRef %s".formatted(buildInfo.version); + return "JabRef %s".formatted(new BuildInfo().version); } public List getLeftOver() { From d7aa63cae8ba7a4dc0332781527c4152e3918605 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 20:38:35 +0200 Subject: [PATCH 06/16] Remove --automaticallySetFileLinks because of UI dependency --- CHANGELOG.md | 2 +- .../org/jabref/cli/ArgumentProcessor.java | 23 ------------------- src/main/java/org/jabref/cli/JabRefCLI.java | 5 ---- 3 files changed, 1 insertion(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffecf1b4298..0c956ad8176 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,7 +93,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We removed support for case-sensitive and exact search. [#11542](https://github.com/JabRef/jabref/pull/11542) - We removed the description of search strings. [#11542](https://github.com/JabRef/jabref/pull/11542) - We removed support for importing using the SilverPlatterImporter (`Record INSPEC`). [#11576](https://github.com/JabRef/jabref/pull/11576) - +- We removed support for automatically generating file links using the CLI (`--automaticallySetFileLinks`). diff --git a/src/main/java/org/jabref/cli/ArgumentProcessor.java b/src/main/java/org/jabref/cli/ArgumentProcessor.java index ebac484faa1..227f329fa5d 100644 --- a/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -13,7 +13,6 @@ import java.util.Set; import java.util.prefs.BackingStoreException; -import org.jabref.gui.externalfiles.AutoSetFileLinksUtil; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.logic.FilePreferences; import org.jabref.logic.JabRefException; @@ -243,10 +242,6 @@ public void processArguments() { regenerateCitationKeys(loaded); } - if (cli.isAutomaticallySetFileLinks()) { - automaticallySetFileLinks(loaded); - } - if ((cli.isWriteXmpToPdf() && cli.isEmbedBibFileInPdf()) || (cli.isWriteMetadataToPdf() && (cli.isWriteXmpToPdf() || cli.isEmbedBibFileInPdf()))) { System.err.println("Give only one of [writeXmpToPdf, embedBibFileInPdf, writeMetadataToPdf]"); } @@ -729,24 +724,6 @@ private void resetPreferences(String value) { } } - private void automaticallySetFileLinks(List loaded) { - for (ParserResult parserResult : loaded) { - BibDatabase database = parserResult.getDatabase(); - LOGGER.info("Automatically setting file links for {}", - parserResult.getDatabaseContext().getDatabasePath() - .map(Path::getFileName) - .map(Path::toString).orElse("UNKNOWN")); - - AutoSetFileLinksUtil util = new AutoSetFileLinksUtil( - parserResult.getDatabaseContext(), - guiPreferences.getExternalApplicationsPreferences(), - cliPreferences.getFilePreferences(), - cliPreferences.getAutoLinkPreferences()); - - util.linkAssociatedFiles(database.getEntries(), (linkedFile, bibEntry) -> bibEntry.addFile(linkedFile)); - } - } - private void regenerateCitationKeys(List loaded) { for (ParserResult parserResult : loaded) { BibDatabase database = parserResult.getDatabase(); diff --git a/src/main/java/org/jabref/cli/JabRefCLI.java b/src/main/java/org/jabref/cli/JabRefCLI.java index d27511e9e24..cc31251abbc 100644 --- a/src/main/java/org/jabref/cli/JabRefCLI.java +++ b/src/main/java/org/jabref/cli/JabRefCLI.java @@ -146,10 +146,6 @@ public boolean isGenerateCitationKeys() { return cl.hasOption("generateCitationKeys"); } - public boolean isAutomaticallySetFileLinks() { - return cl.hasOption("automaticallySetFileLinks"); - } - public boolean isWriteXmpToPdf() { return cl.hasOption("writeXmpToPdf"); } @@ -182,7 +178,6 @@ private static Options getOptions() { // boolean options options.addOption("h", "help", false, Localization.lang("Display help on command line options")); options.addOption("n", "nogui", false, Localization.lang("No GUI. Only process command line options")); - options.addOption("asfl", "automaticallySetFileLinks", false, Localization.lang("Automatically set file links")); options.addOption("g", "generateCitationKeys", false, Localization.lang("Regenerate all keys for the entries in a BibTeX file")); options.addOption("b", "blank", false, Localization.lang("Do not open any files at startup")); options.addOption("v", "version", false, Localization.lang("Display version")); From 46063e904bc8c6dd0c8e770f1a2efed7386c8feb Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 20:42:52 +0200 Subject: [PATCH 07/16] Remove GuiPreferences from ArgumentProcessor --- src/main/java/org/jabref/Launcher.java | 1 - src/main/java/org/jabref/cli/ArgumentProcessor.java | 4 ---- src/main/java/org/jabref/gui/remote/CLIMessageHandler.java | 1 - src/test/java/org/jabref/cli/ArgumentProcessorTest.java | 3 --- 4 files changed, 9 deletions(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index 947c2f3dd34..c1119b2245d 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -97,7 +97,6 @@ public static void main(String[] args) { args, ArgumentProcessor.Mode.INITIAL_START, preferences, - preferences, fileUpdateMonitor, entryTypesManager); argumentProcessor.processArguments(); diff --git a/src/main/java/org/jabref/cli/ArgumentProcessor.java b/src/main/java/org/jabref/cli/ArgumentProcessor.java index 227f329fa5d..6e6acf60c12 100644 --- a/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -13,7 +13,6 @@ import java.util.Set; import java.util.prefs.BackingStoreException; -import org.jabref.gui.preferences.GuiPreferences; import org.jabref.logic.FilePreferences; import org.jabref.logic.JabRefException; import org.jabref.logic.UiCommand; @@ -74,7 +73,6 @@ public enum Mode { INITIAL_START, REMOTE_START } private final Mode startupMode; private final CliPreferences cliPreferences; - private final GuiPreferences guiPreferences; private final FileUpdateMonitor fileUpdateMonitor; private final BibEntryTypesManager entryTypesManager; @@ -90,14 +88,12 @@ public enum Mode { INITIAL_START, REMOTE_START } public ArgumentProcessor(String[] args, Mode startupMode, CliPreferences cliPreferences, - GuiPreferences guiPreferences, FileUpdateMonitor fileUpdateMonitor, BibEntryTypesManager entryTypesManager) throws org.apache.commons.cli.ParseException { this.cli = new JabRefCLI(args); this.startupMode = startupMode; this.cliPreferences = cliPreferences; - this.guiPreferences = guiPreferences; this.fileUpdateMonitor = fileUpdateMonitor; this.entryTypesManager = entryTypesManager; } diff --git a/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java b/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java index e42bcc2e358..4da679c147c 100644 --- a/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java +++ b/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java @@ -41,7 +41,6 @@ public void handleCommandLineArguments(String[] message) { message, ArgumentProcessor.Mode.REMOTE_START, preferences, - preferences, fileUpdateMonitor, entryTypesManager); argumentProcessor.processArguments(); diff --git a/src/test/java/org/jabref/cli/ArgumentProcessorTest.java b/src/test/java/org/jabref/cli/ArgumentProcessorTest.java index 9f662dfe8da..c106bea23ed 100644 --- a/src/test/java/org/jabref/cli/ArgumentProcessorTest.java +++ b/src/test/java/org/jabref/cli/ArgumentProcessorTest.java @@ -73,7 +73,6 @@ void auxImport(@TempDir Path tempDir) throws Exception { args.toArray(String[]::new), Mode.INITIAL_START, preferences, - preferences, mock(FileUpdateMonitor.class), entryTypesManager); processor.processArguments(); @@ -103,7 +102,6 @@ void exportMatches(@TempDir Path tempDir) throws Exception { args.toArray(String[]::new), Mode.INITIAL_START, preferences, - preferences, mock(FileUpdateMonitor.class), entryTypesManager); processor.processArguments(); @@ -136,7 +134,6 @@ void convertBibtexToTablerefsabsbib(@TempDir Path tempDir) throws Exception { args.toArray(String[]::new), Mode.INITIAL_START, preferences, - preferences, mock(FileUpdateMonitor.class), entryTypesManager); processor.processArguments(); From b57d2fc24cfb46b5b9a9eac3f86194e92450a1b7 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 20:43:32 +0200 Subject: [PATCH 08/16] CLI must not depepend on GUI --- src/test/java/org/jabref/architecture/MainArchitectureTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/jabref/architecture/MainArchitectureTest.java b/src/test/java/org/jabref/architecture/MainArchitectureTest.java index 88370b12beb..1c5fd478d18 100644 --- a/src/test/java/org/jabref/architecture/MainArchitectureTest.java +++ b/src/test/java/org/jabref/architecture/MainArchitectureTest.java @@ -100,7 +100,7 @@ public void respectLayeredArchitecture(JavaClasses classes) { .layer(CLI).definedBy(PACKAGE_ORG_JABREF_CLI) .layer(Migrations).definedBy("org.jabref.migrations..") // TODO: Move to logic - .whereLayer(GUI).mayOnlyBeAccessedByLayers(CLI, Migrations) + .whereLayer(GUI).mayOnlyBeAccessedByLayers(Migrations) .whereLayer(Logic).mayOnlyBeAccessedByLayers(GUI, CLI, Model, Migrations) .whereLayer(Model).mayOnlyBeAccessedByLayers(GUI, Logic, Migrations, CLI) From e857322af6cbaf9e4117ba20e91a9c6bcd4890c3 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 20:49:09 +0200 Subject: [PATCH 09/16] Rename JabRefCLI to CliOptions --- src/main/java/org/jabref/Launcher.java | 8 +- .../org/jabref/cli/ArgumentProcessor.java | 8 +- .../cli/{JabRefCLI.java => CliOptions.java} | 81 ++++++++++--------- ...JabRefCLITest.java => CliOptionsTest.java} | 38 ++++----- 4 files changed, 69 insertions(+), 66 deletions(-) rename src/main/java/org/jabref/cli/{JabRefCLI.java => CliOptions.java} (82%) rename src/test/java/org/jabref/cli/{JabRefCLITest.java => CliOptionsTest.java} (65%) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index c1119b2245d..41705097b01 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -12,7 +12,7 @@ import java.util.Map; import org.jabref.cli.ArgumentProcessor; -import org.jabref.cli.JabRefCLI; +import org.jabref.cli.CliOptions; import org.jabref.gui.JabRefGUI; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.preferences.JabRefGuiPreferences; @@ -112,7 +112,7 @@ public static void main(String[] args) { JabRefGUI.launch(JabRefGUI.class, args); } catch (ParseException e) { LOGGER.error("Problem parsing arguments", e); - JabRefCLI.printUsage(preferences); + CliOptions.printUsage(preferences); } } catch (Exception ex) { LOGGER.error("Unexpected exception", ex); @@ -132,8 +132,8 @@ private static void initLogging(String[] args) { // argument parsing workflow to parse logging options .e.g. --debug boolean isDebugEnabled; try { - JabRefCLI jabRefCLI = new JabRefCLI(args); - isDebugEnabled = jabRefCLI.isDebugLogging(); + CliOptions cliOptions = new CliOptions(args); + isDebugEnabled = cliOptions.isDebugLogging(); } catch (ParseException e) { isDebugEnabled = false; } diff --git a/src/main/java/org/jabref/cli/ArgumentProcessor.java b/src/main/java/org/jabref/cli/ArgumentProcessor.java index 6e6acf60c12..1021049647a 100644 --- a/src/main/java/org/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/org/jabref/cli/ArgumentProcessor.java @@ -68,7 +68,7 @@ public class ArgumentProcessor { public enum Mode { INITIAL_START, REMOTE_START } - private final JabRefCLI cli; + private final CliOptions cli; private final Mode startupMode; @@ -91,7 +91,7 @@ public ArgumentProcessor(String[] args, FileUpdateMonitor fileUpdateMonitor, BibEntryTypesManager entryTypesManager) throws org.apache.commons.cli.ParseException { - this.cli = new JabRefCLI(args); + this.cli = new CliOptions(args); this.startupMode = startupMode; this.cliPreferences = cliPreferences; this.fileUpdateMonitor = fileUpdateMonitor; @@ -201,7 +201,7 @@ public void processArguments() { } if ((startupMode == Mode.INITIAL_START) && cli.isHelp()) { - JabRefCLI.printUsage(cliPreferences); + CliOptions.printUsage(cliPreferences); guiNeeded = false; return; } @@ -477,7 +477,7 @@ private boolean exportMatches(List loaded) { formatName = "bib"; default -> { System.err.println(Localization.lang("Output file missing").concat(". \n \t ") - .concat(Localization.lang("Usage")).concat(": ") + JabRefCLI.getExportMatchesSyntax()); + .concat(Localization.lang("Usage")).concat(": ") + CliOptions.getExportMatchesSyntax()); guiNeeded = false; return false; } diff --git a/src/main/java/org/jabref/cli/JabRefCLI.java b/src/main/java/org/jabref/cli/CliOptions.java similarity index 82% rename from src/main/java/org/jabref/cli/JabRefCLI.java rename to src/main/java/org/jabref/cli/CliOptions.java index cc31251abbc..dc88a87269e 100644 --- a/src/main/java/org/jabref/cli/JabRefCLI.java +++ b/src/main/java/org/jabref/cli/CliOptions.java @@ -21,18 +21,21 @@ import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; -public class JabRefCLI { +/** + * Holds the command line options. It parses it using Apache Commons CLI. + */ +public class CliOptions { private static final int WIDTH = 100; // Number of characters per line before a line break must be added. private static final String WRAPPED_LINE_PREFIX = ""; // If a line break is added, this prefix will be inserted at the beginning of the next line private static final String STRING_TABLE_DELIMITER = " : "; - private final CommandLine cl; + private final CommandLine commandLine; private final List leftOver; - public JabRefCLI(String[] args) throws ParseException { + public CliOptions(String[] args) throws ParseException { Options options = getOptions(); - this.cl = new DefaultParser().parse(options, args, true); - this.leftOver = cl.getArgList(); + this.commandLine = new DefaultParser().parse(options, args, true); + this.leftOver = commandLine.getArgList(); } public static String getExportMatchesSyntax() { @@ -43,133 +46,133 @@ public static String getExportMatchesSyntax() { } public boolean isHelp() { - return cl.hasOption("help"); + return commandLine.hasOption("help"); } public boolean isShowVersion() { - return cl.hasOption("version"); + return commandLine.hasOption("version"); } public boolean isBlank() { - return cl.hasOption("blank"); + return commandLine.hasOption("blank"); } public boolean isDisableGui() { - return cl.hasOption("nogui"); + return commandLine.hasOption("nogui"); } public boolean isPreferencesExport() { - return cl.hasOption("prexp"); + return commandLine.hasOption("prexp"); } public String getPreferencesExport() { - return cl.getOptionValue("prexp", "jabref_prefs.xml"); + return commandLine.getOptionValue("prexp", "jabref_prefs.xml"); } public boolean isPreferencesImport() { - return cl.hasOption("primp"); + return commandLine.hasOption("primp"); } public String getPreferencesImport() { - return cl.getOptionValue("primp", "jabref_prefs.xml"); + return commandLine.getOptionValue("primp", "jabref_prefs.xml"); } public boolean isPreferencesReset() { - return cl.hasOption("prdef"); + return commandLine.hasOption("prdef"); } public String getPreferencesReset() { - return cl.getOptionValue("prdef"); + return commandLine.getOptionValue("prdef"); } public boolean isFileExport() { - return cl.hasOption("output"); + return commandLine.hasOption("output"); } public String getFileExport() { - return cl.getOptionValue("output"); + return commandLine.getOptionValue("output"); } public boolean isBibtexImport() { - return cl.hasOption("importBibtex"); + return commandLine.hasOption("importBibtex"); } public String getBibtexImport() { - return cl.getOptionValue("importBibtex"); + return commandLine.getOptionValue("importBibtex"); } public boolean isFileImport() { - return cl.hasOption("import"); + return commandLine.hasOption("import"); } public String getFileImport() { - return cl.getOptionValue("import"); + return commandLine.getOptionValue("import"); } public boolean isAuxImport() { - return cl.hasOption("aux"); + return commandLine.hasOption("aux"); } public String getAuxImport() { - return cl.getOptionValue("aux"); + return commandLine.getOptionValue("aux"); } public boolean isImportToOpenBase() { - return cl.hasOption("importToOpen"); + return commandLine.hasOption("importToOpen"); } public String getImportToOpenBase() { - return cl.getOptionValue("importToOpen"); + return commandLine.getOptionValue("importToOpen"); } public boolean isDebugLogging() { - return cl.hasOption("debug"); + return commandLine.hasOption("debug"); } public boolean isFetcherEngine() { - return cl.hasOption("fetch"); + return commandLine.hasOption("fetch"); } public String getFetcherEngine() { - return cl.getOptionValue("fetch"); + return commandLine.getOptionValue("fetch"); } public boolean isExportMatches() { - return cl.hasOption("exportMatches"); + return commandLine.hasOption("exportMatches"); } public String getExportMatches() { - return cl.getOptionValue("exportMatches"); + return commandLine.getOptionValue("exportMatches"); } public boolean isGenerateCitationKeys() { - return cl.hasOption("generateCitationKeys"); + return commandLine.hasOption("generateCitationKeys"); } public boolean isWriteXmpToPdf() { - return cl.hasOption("writeXmpToPdf"); + return commandLine.hasOption("writeXmpToPdf"); } public boolean isEmbedBibFileInPdf() { - return cl.hasOption("embedBibFileInPdf"); + return commandLine.hasOption("embedBibFileInPdf"); } public boolean isWriteMetadataToPdf() { - return cl.hasOption("writeMetadataToPdf"); + return commandLine.hasOption("writeMetadataToPdf"); } public String getWriteMetadataToPdf() { - return cl.hasOption("writeMetadatatoPdf") ? cl.getOptionValue("writeMetadataToPdf") : - cl.hasOption("writeXMPtoPdf") ? cl.getOptionValue("writeXmpToPdf") : - cl.hasOption("embeddBibfileInPdf") ? cl.getOptionValue("embeddBibfileInPdf") : null; + return commandLine.hasOption("writeMetadatatoPdf") ? commandLine.getOptionValue("writeMetadataToPdf") : + commandLine.hasOption("writeXMPtoPdf") ? commandLine.getOptionValue("writeXmpToPdf") : + commandLine.hasOption("embeddBibfileInPdf") ? commandLine.getOptionValue("embeddBibfileInPdf") : null; } public String getJumpToKey() { - return cl.getOptionValue("jumpToKey"); + return commandLine.getOptionValue("jumpToKey"); } public boolean isJumpToKey() { - return cl.hasOption("jumpToKey"); + return commandLine.hasOption("jumpToKey"); } private static Options getOptions() { diff --git a/src/test/java/org/jabref/cli/JabRefCLITest.java b/src/test/java/org/jabref/cli/CliOptionsTest.java similarity index 65% rename from src/test/java/org/jabref/cli/JabRefCLITest.java rename to src/test/java/org/jabref/cli/CliOptionsTest.java index ee868aaaa85..49512fab364 100644 --- a/src/test/java/org/jabref/cli/JabRefCLITest.java +++ b/src/test/java/org/jabref/cli/CliOptionsTest.java @@ -12,125 +12,125 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -class JabRefCLITest { +class CliOptionsTest { private final String bibtex = "@article{test, title=\"test title\"}"; @Test void emptyCLILeftOversLongOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); } @Test void guiIsDisabledLongOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); assertTrue(cli.isDisableGui()); } @Test void successfulParsingOfFileImportCLILongOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); assertEquals("some/file", cli.getFileImport()); } @Test void successfulParsingOfFileExportCLILongOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); assertEquals("some/export/file", cli.getFileExport()); } @Test void emptyCLILeftOversShortOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); } @Test void guiIsDisabledShortOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); assertTrue(cli.isDisableGui()); } @Test void successfulParsingOfFileImportShortOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); assertEquals("some/file", cli.getFileImport()); } @Test void successfulParsingOfFileExportShortOptions() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); assertEquals("some/export/file", cli.getFileExport()); } @Test void emptyPreferencesLeftOver() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-x=some/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); } @Test void successfulExportOfPreferences() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-x=some/file"}); assertEquals("some/file", cli.getPreferencesExport()); } @Test void guiDisabledForPreferencesExport() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"}); + CliOptions cli = new CliOptions(new String[] {"-n", "-x=some/file"}); assertTrue(cli.isDisableGui()); } @Test void emptyLeftOversCLIShortImportingBibtex() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-ib", bibtex}); assertEquals(Collections.emptyList(), cli.getLeftOver()); } @Test void recognizesImportBibtexShort() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-ib", bibtex}); assertTrue(cli.isBibtexImport()); } @Test void successfulParsingOfBibtexImportShort() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-ib", bibtex}); assertEquals(bibtex, cli.getBibtexImport()); } @Test void emptyLeftOversCLILongImportingBibtex() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-importBibtex", bibtex}); assertEquals(Collections.emptyList(), cli.getLeftOver()); } @Test void recognizesImportBibtexLong() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-importBibtex", bibtex}); assertTrue(cli.isBibtexImport()); } @Test void successfulParsingOfBibtexImportLong() throws Exception { - JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex}); + CliOptions cli = new CliOptions(new String[] {"-importBibtex", bibtex}); assertEquals(bibtex, cli.getBibtexImport()); } @@ -150,6 +150,6 @@ void alignStringTable() { Country : County """.replace("\n", OS.NEWLINE); - assertEquals(expected, JabRefCLI.alignStringTable(given)); + assertEquals(expected, CliOptions.alignStringTable(given)); } } From e944e571f911a408c02944f42dfbbef03fa9722e Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 21:09:01 +0200 Subject: [PATCH 10/16] Introduce JabKit (by moving much Gui launching code to there) --- src/main/java/org/jabref/Launcher.java | 239 ++-------------------- src/main/java/org/jabref/cli/JabKit.java | 247 +++++++++++++++++++++++ 2 files changed, 259 insertions(+), 227 deletions(-) create mode 100644 src/main/java/org/jabref/cli/JabKit.java diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index 41705097b01..424028dca97 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -1,236 +1,21 @@ package org.jabref; -import java.io.File; -import java.io.IOException; -import java.net.Authenticator; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import org.jabref.cli.ArgumentProcessor; -import org.jabref.cli.CliOptions; +import org.jabref.cli.JabKit; import org.jabref.gui.JabRefGUI; -import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.preferences.JabRefGuiPreferences; -import org.jabref.gui.util.DefaultDirectoryMonitor; -import org.jabref.gui.util.DefaultFileUpdateMonitor; -import org.jabref.logic.UiCommand; -import org.jabref.logic.journals.JournalAbbreviationLoader; -import org.jabref.logic.journals.JournalAbbreviationRepository; -import org.jabref.logic.net.ProxyAuthenticator; -import org.jabref.logic.net.ProxyPreferences; -import org.jabref.logic.net.ProxyRegisterer; -import org.jabref.logic.net.ssl.SSLPreferences; -import org.jabref.logic.net.ssl.TrustStoreManager; -import org.jabref.logic.preferences.CliPreferences; -import org.jabref.logic.protectedterms.ProtectedTermsLoader; -import org.jabref.logic.remote.RemotePreferences; -import org.jabref.logic.remote.client.RemoteClient; -import org.jabref.logic.util.BuildInfo; -import org.jabref.logic.util.Directories; -import org.jabref.logic.util.HeadlessExecutorService; -import org.jabref.migrations.PreferencesMigrations; -import org.jabref.model.entry.BibEntryTypesManager; -import org.jabref.model.util.DirectoryMonitor; -import org.jabref.model.util.FileUpdateMonitor; - -import com.airhacks.afterburner.injection.Injector; -import org.apache.commons.cli.ParseException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.bridge.SLF4JBridgeHandler; -import org.tinylog.configuration.Configuration; -/** - * The main entry point for the JabRef application. - *

- * It has two main functions: - * - Handle the command line arguments - * - Start the JavaFX application (if not in cli mode) - */ -public class Launcher { - private static Logger LOGGER; +/// The main entry point for the JabRef application. +/// +/// It has two main functions: +/// +/// - Handle the command line arguments +/// - Start the JavaFX application (if not in CLI mode) +public class Launcher extends JabKit { public static void main(String[] args) { - initLogging(args); - - try { - Injector.setModelOrService(BuildInfo.class, new BuildInfo()); - - // Initialize preferences - final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); - Injector.setModelOrService(CliPreferences.class, preferences); - Injector.setModelOrService(GuiPreferences.class, preferences); - - // Early exit in case another instance is already running - if (!handleMultipleAppInstances(args, preferences.getRemotePreferences())) { - return; - } - - BibEntryTypesManager entryTypesManager = preferences.getCustomEntryTypesRepository(); - Injector.setModelOrService(BibEntryTypesManager.class, entryTypesManager); - - PreferencesMigrations.runMigrations(preferences, entryTypesManager); - - Injector.setModelOrService(JournalAbbreviationRepository.class, JournalAbbreviationLoader.loadRepository(preferences.getJournalAbbreviationPreferences())); - Injector.setModelOrService(ProtectedTermsLoader.class, new ProtectedTermsLoader(preferences.getProtectedTermsPreferences())); - - configureProxy(preferences.getProxyPreferences()); - configureSSL(preferences.getSSLPreferences()); - - clearOldSearchIndices(); - - try { - DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); - Injector.setModelOrService(FileUpdateMonitor.class, fileUpdateMonitor); - HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); - - DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); - Injector.setModelOrService(DirectoryMonitor.class, directoryMonitor); - - // Process arguments - ArgumentProcessor argumentProcessor = new ArgumentProcessor( - args, - ArgumentProcessor.Mode.INITIAL_START, - preferences, - fileUpdateMonitor, - entryTypesManager); - argumentProcessor.processArguments(); - if (argumentProcessor.shouldShutDown()) { - LOGGER.debug("JabRef shut down after processing command line arguments"); - // A clean shutdown takes 60s time - // We don't need the clean shutdown here - System.exit(0); - } - - List uiCommands = new ArrayList<>(argumentProcessor.getUiCommands()); - JabRefGUI.setup(uiCommands, preferences, fileUpdateMonitor); - JabRefGUI.launch(JabRefGUI.class, args); - } catch (ParseException e) { - LOGGER.error("Problem parsing arguments", e); - CliOptions.printUsage(preferences); - } - } catch (Exception ex) { - LOGGER.error("Unexpected exception", ex); - } - } - - /** - * This needs to be called as early as possible. After the first log write, it - * is not possible to alter the log configuration programmatically anymore. - */ - private static void initLogging(String[] args) { - // routeLoggingToSlf4J - SLF4JBridgeHandler.removeHandlersForRootLogger(); - SLF4JBridgeHandler.install(); - - // We must configure logging as soon as possible, which is why we cannot wait for the usual - // argument parsing workflow to parse logging options .e.g. --debug - boolean isDebugEnabled; - try { - CliOptions cliOptions = new CliOptions(args); - isDebugEnabled = cliOptions.isDebugLogging(); - } catch (ParseException e) { - isDebugEnabled = false; - } - - // addLogToDisk - Path directory = Directories.getLogDirectory(); - try { - Files.createDirectories(directory); - } catch (IOException e) { - LOGGER = LoggerFactory.getLogger(Launcher.class); - LOGGER.error("Could not create log directory {}", directory, e); - return; - } - - // The "Shared File Writer" is explained at - // https://tinylog.org/v2/configuration/#shared-file-writer - Map configuration = Map.of( - "level", isDebugEnabled ? "debug" : "info", - "writerFile", "rolling file", - "writerFile.level", isDebugEnabled ? "debug" : "info", - // We need to manually join the path, because ".resolve" does not work on Windows, because ":" is not allowed in file names on Windows - "writerFile.file", directory + File.separator + "log_{date:yyyy-MM-dd_HH-mm-ss}.txt", - "writerFile.charset", "UTF-8", - "writerFile.policies", "startup", - "writerFile.backups", "30"); - configuration.forEach(Configuration::set); - - LOGGER = LoggerFactory.getLogger(Launcher.class); - } - - /** - * @return true if JabRef should continue starting up, false if it should quit. - */ - private static boolean handleMultipleAppInstances(String[] args, RemotePreferences remotePreferences) throws InterruptedException { - LOGGER.trace("Checking for remote handling..."); - if (remotePreferences.useRemoteServer()) { - // Try to contact already running JabRef - RemoteClient remoteClient = new RemoteClient(remotePreferences.getPort()); - if (remoteClient.ping()) { - LOGGER.debug("Pinging other instance succeeded."); - if (args.length == 0) { - // There is already a server out there, avoid showing log "Passing arguments" while no arguments are provided. - LOGGER.warn("This JabRef instance is already running. Please switch to that instance."); - } else { - // We are not alone, there is already a server out there, send command line arguments to other instance - LOGGER.debug("Passing arguments passed on to running JabRef..."); - if (remoteClient.sendCommandLineArguments(args)) { - // So we assume it's all taken care of, and quit. - // Output to both to the log and the screen. Therefore, we do not have an additional System.out.println. - LOGGER.info("Arguments passed on to running JabRef instance. Shutting down."); - } else { - LOGGER.warn("Could not communicate with other running JabRef instance."); - } - } - // We do not launch a new instance in presence if there is another instance running - return false; - } else { - LOGGER.debug("Could not ping JabRef instance."); - } - } - return true; - } - - private static void configureProxy(ProxyPreferences proxyPreferences) { - ProxyRegisterer.register(proxyPreferences); - if (proxyPreferences.shouldUseProxy() && proxyPreferences.shouldUseAuthentication()) { - Authenticator.setDefault(new ProxyAuthenticator()); - } - } - - private static void configureSSL(SSLPreferences sslPreferences) { - TrustStoreManager.createTruststoreFileIfNotExist(Path.of(sslPreferences.getTruststorePath())); - } - - private static void clearOldSearchIndices() { - Path currentIndexPath = Directories.getFulltextIndexBaseDirectory(); - Path appData = currentIndexPath.getParent(); - - try { - Files.createDirectories(currentIndexPath); - } catch (IOException e) { - LOGGER.error("Could not create index directory {}", appData, e); - } + Result result = JabKit.processArguments(args); + // The method `processArguments` quites the whole JVM if no GUI is needed. - try (DirectoryStream stream = Files.newDirectoryStream(appData)) { - for (Path path : stream) { - if (Files.isDirectory(path) && !path.toString().endsWith("ssl") && path.toString().contains("lucene") - && !path.equals(currentIndexPath)) { - LOGGER.info("Deleting out-of-date fulltext search index at {}.", path); - Files.walk(path) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - } catch (IOException e) { - LOGGER.error("Could not access app-directory at {}", appData, e); - } + JabRefGUI.setup(result.uiCommands(), result.preferences(), result.fileUpdateMonitor()); + JabRefGUI.launch(JabRefGUI.class, args); } } diff --git a/src/main/java/org/jabref/cli/JabKit.java b/src/main/java/org/jabref/cli/JabKit.java new file mode 100644 index 00000000000..40a2151aca9 --- /dev/null +++ b/src/main/java/org/jabref/cli/JabKit.java @@ -0,0 +1,247 @@ +package org.jabref.cli; + +import java.io.File; +import java.io.IOException; +import java.net.Authenticator; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import org.jabref.Launcher; +import org.jabref.gui.preferences.GuiPreferences; +import org.jabref.gui.preferences.JabRefGuiPreferences; +import org.jabref.gui.util.DefaultDirectoryMonitor; +import org.jabref.gui.util.DefaultFileUpdateMonitor; +import org.jabref.logic.UiCommand; +import org.jabref.logic.journals.JournalAbbreviationLoader; +import org.jabref.logic.journals.JournalAbbreviationRepository; +import org.jabref.logic.net.ProxyAuthenticator; +import org.jabref.logic.net.ProxyPreferences; +import org.jabref.logic.net.ProxyRegisterer; +import org.jabref.logic.net.ssl.SSLPreferences; +import org.jabref.logic.net.ssl.TrustStoreManager; +import org.jabref.logic.preferences.CliPreferences; +import org.jabref.logic.protectedterms.ProtectedTermsLoader; +import org.jabref.logic.remote.RemotePreferences; +import org.jabref.logic.remote.client.RemoteClient; +import org.jabref.logic.util.BuildInfo; +import org.jabref.logic.util.Directories; +import org.jabref.logic.util.HeadlessExecutorService; +import org.jabref.migrations.PreferencesMigrations; +import org.jabref.model.entry.BibEntryTypesManager; +import org.jabref.model.util.DirectoryMonitor; +import org.jabref.model.util.FileUpdateMonitor; + +import com.airhacks.afterburner.injection.Injector; +import org.apache.commons.cli.ParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.bridge.SLF4JBridgeHandler; +import org.tinylog.configuration.Configuration; + +/** + * Entrypoint for a command-line only version of JabRef. + */ +public class JabKit { + private static Logger LOGGER; + + public static void main(String[] args) { + processArguments(args); + } + + public record Result(List uiCommands, GuiPreferences preferences, FileUpdateMonitor fileUpdateMonitor) { + } + + private static void systemExit() { + LOGGER.debug("JabRef shut down after processing command line arguments"); + // A clean shutdown takes 60s time + // We don't need the clean shutdown here + System.exit(0); + } + + public static Result processArguments(String[] args) { + initLogging(args); + + try { + Injector.setModelOrService(BuildInfo.class, new BuildInfo()); + + // Initialize preferences + final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); + Injector.setModelOrService(CliPreferences.class, preferences); + Injector.setModelOrService(GuiPreferences.class, preferences); + + // Early exit in case another instance is already running + if (!handleMultipleAppInstances(args, preferences.getRemotePreferences())) { + systemExit(); + } + + BibEntryTypesManager entryTypesManager = preferences.getCustomEntryTypesRepository(); + Injector.setModelOrService(BibEntryTypesManager.class, entryTypesManager); + + PreferencesMigrations.runMigrations(preferences, entryTypesManager); + + Injector.setModelOrService(JournalAbbreviationRepository.class, JournalAbbreviationLoader.loadRepository(preferences.getJournalAbbreviationPreferences())); + Injector.setModelOrService(ProtectedTermsLoader.class, new ProtectedTermsLoader(preferences.getProtectedTermsPreferences())); + + configureProxy(preferences.getProxyPreferences()); + configureSSL(preferences.getSSLPreferences()); + + clearOldSearchIndices(); + + try { + DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); + Injector.setModelOrService(FileUpdateMonitor.class, fileUpdateMonitor); + HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); + + DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); + Injector.setModelOrService(DirectoryMonitor.class, directoryMonitor); + + // Process arguments + ArgumentProcessor argumentProcessor = new ArgumentProcessor( + args, + ArgumentProcessor.Mode.INITIAL_START, + preferences, + fileUpdateMonitor, + entryTypesManager); + argumentProcessor.processArguments(); + if (argumentProcessor.shouldShutDown()) { + LOGGER.debug("JabRef shut down after processing command line arguments"); + // A clean shutdown takes 60s time + // We don't need the clean shutdown here + System.exit(0); + return null; + } + + return new Result(new ArrayList<>(argumentProcessor.getUiCommands()), preferences, fileUpdateMonitor); + } catch (ParseException e) { + LOGGER.error("Problem parsing arguments", e); + CliOptions.printUsage(preferences); + systemExit(); + return null; + } + } catch (Exception ex) { + LOGGER.error("Unexpected exception", ex); + systemExit(); + return null; + } + } + + /** + * This needs to be called as early as possible. After the first log write, it + * is not possible to alter the log configuration programmatically anymore. + */ + private static void initLogging(String[] args) { + // routeLoggingToSlf4J + SLF4JBridgeHandler.removeHandlersForRootLogger(); + SLF4JBridgeHandler.install(); + + // We must configure logging as soon as possible, which is why we cannot wait for the usual + // argument parsing workflow to parse logging options .e.g. --debug + boolean isDebugEnabled; + try { + CliOptions cliOptions = new CliOptions(args); + isDebugEnabled = cliOptions.isDebugLogging(); + } catch (ParseException e) { + isDebugEnabled = false; + } + + // addLogToDisk + Path directory = Directories.getLogDirectory(); + try { + Files.createDirectories(directory); + } catch (IOException e) { + LOGGER = LoggerFactory.getLogger(Launcher.class); + LOGGER.error("Could not create log directory {}", directory, e); + return; + } + + // The "Shared File Writer" is explained at + // https://tinylog.org/v2/configuration/#shared-file-writer + Map configuration = Map.of( + "level", isDebugEnabled ? "debug" : "info", + "writerFile", "rolling file", + "writerFile.level", isDebugEnabled ? "debug" : "info", + // We need to manually join the path, because ".resolve" does not work on Windows, because ":" is not allowed in file names on Windows + "writerFile.file", directory + File.separator + "log_{date:yyyy-MM-dd_HH-mm-ss}.txt", + "writerFile.charset", "UTF-8", + "writerFile.policies", "startup", + "writerFile.backups", "30"); + configuration.forEach(Configuration::set); + + LOGGER = LoggerFactory.getLogger(JabKit.class); + } + + /** + * @return true if JabRef should continue starting up, false if it should quit. + */ + private static boolean handleMultipleAppInstances(String[] args, RemotePreferences remotePreferences) throws InterruptedException { + LOGGER.trace("Checking for remote handling..."); + if (remotePreferences.useRemoteServer()) { + // Try to contact already running JabRef + RemoteClient remoteClient = new RemoteClient(remotePreferences.getPort()); + if (remoteClient.ping()) { + LOGGER.debug("Pinging other instance succeeded."); + if (args.length == 0) { + // There is already a server out there, avoid showing log "Passing arguments" while no arguments are provided. + LOGGER.warn("This JabRef instance is already running. Please switch to that instance."); + } else { + // We are not alone, there is already a server out there, send command line arguments to other instance + LOGGER.debug("Passing arguments passed on to running JabRef..."); + if (remoteClient.sendCommandLineArguments(args)) { + // So we assume it's all taken care of, and quit. + // Output to both to the log and the screen. Therefore, we do not have an additional System.out.println. + LOGGER.info("Arguments passed on to running JabRef instance. Shutting down."); + } else { + LOGGER.warn("Could not communicate with other running JabRef instance."); + } + } + // We do not launch a new instance in presence if there is another instance running + return false; + } else { + LOGGER.debug("Could not ping JabRef instance."); + } + } + return true; + } + + private static void configureProxy(ProxyPreferences proxyPreferences) { + ProxyRegisterer.register(proxyPreferences); + if (proxyPreferences.shouldUseProxy() && proxyPreferences.shouldUseAuthentication()) { + Authenticator.setDefault(new ProxyAuthenticator()); + } + } + + private static void configureSSL(SSLPreferences sslPreferences) { + TrustStoreManager.createTruststoreFileIfNotExist(Path.of(sslPreferences.getTruststorePath())); + } + + private static void clearOldSearchIndices() { + Path currentIndexPath = Directories.getFulltextIndexBaseDirectory(); + Path appData = currentIndexPath.getParent(); + + try { + Files.createDirectories(currentIndexPath); + } catch (IOException e) { + LOGGER.error("Could not create index directory {}", appData, e); + } + + try (DirectoryStream stream = Files.newDirectoryStream(appData)) { + for (Path path : stream) { + if (Files.isDirectory(path) && !path.toString().endsWith("ssl") && path.toString().contains("lucene") + && !path.equals(currentIndexPath)) { + LOGGER.info("Deleting out-of-date fulltext search index at {}.", path); + Files.walk(path) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + } catch (IOException e) { + LOGGER.error("Could not access app-directory at {}", appData, e); + } + } +} From d6820870813ede64726bf96f97b9daaad9ae2610 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Fri, 11 Oct 2024 21:37:13 +0200 Subject: [PATCH 11/16] Remove hiearchy --- src/main/java/org/jabref/Launcher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index 424028dca97..c0d503422ca 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -9,7 +9,7 @@ /// /// - Handle the command line arguments /// - Start the JavaFX application (if not in CLI mode) -public class Launcher extends JabKit { +public class Launcher { public static void main(String[] args) { Result result = JabKit.processArguments(args); From 6c7856d7a99c16c1d0fe4117215ea6e3c480107b Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Sat, 12 Oct 2024 13:32:05 +0200 Subject: [PATCH 12/16] Fix compilation error --- src/main/java/org/jabref/Launcher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index c0d503422ca..ec26a8bf35c 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -12,7 +12,7 @@ public class Launcher { public static void main(String[] args) { - Result result = JabKit.processArguments(args); + JabKit.Result result = JabKit.processArguments(args); // The method `processArguments` quites the whole JVM if no GUI is needed. JabRefGUI.setup(result.uiCommands(), result.preferences(), result.fileUpdateMonitor()); From 74251ef3aa42d3b90ec2fb3c6f95056439f74b3d Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Sun, 13 Oct 2024 06:34:37 +0200 Subject: [PATCH 13/16] Fix usage of GuiPreferences in JabKit --- src/main/java/org/jabref/Launcher.java | 15 ++++++++++++++- src/main/java/org/jabref/cli/JabKit.java | 16 +++++----------- .../jabref/migrations/PreferencesMigrations.java | 4 ++-- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index ec26a8bf35c..d1f835116b7 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -2,6 +2,12 @@ import org.jabref.cli.JabKit; import org.jabref.gui.JabRefGUI; +import org.jabref.gui.preferences.GuiPreferences; +import org.jabref.gui.preferences.JabRefGuiPreferences; +import org.jabref.logic.preferences.CliPreferences; +import org.jabref.migrations.PreferencesMigrations; + +import com.airhacks.afterburner.injection.Injector; /// The main entry point for the JabRef application. /// @@ -15,7 +21,14 @@ public static void main(String[] args) { JabKit.Result result = JabKit.processArguments(args); // The method `processArguments` quites the whole JVM if no GUI is needed. - JabRefGUI.setup(result.uiCommands(), result.preferences(), result.fileUpdateMonitor()); + // Initialize preferences + final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); + Injector.setModelOrService(CliPreferences.class, preferences); + Injector.setModelOrService(GuiPreferences.class, preferences); + + PreferencesMigrations.runMigrations(preferences); + + JabRefGUI.setup(result.uiCommands(), preferences, result.fileUpdateMonitor()); JabRefGUI.launch(JabRefGUI.class, args); } } diff --git a/src/main/java/org/jabref/cli/JabKit.java b/src/main/java/org/jabref/cli/JabKit.java index 40a2151aca9..dd8d6ca0efd 100644 --- a/src/main/java/org/jabref/cli/JabKit.java +++ b/src/main/java/org/jabref/cli/JabKit.java @@ -11,9 +11,6 @@ import java.util.List; import java.util.Map; -import org.jabref.Launcher; -import org.jabref.gui.preferences.GuiPreferences; -import org.jabref.gui.preferences.JabRefGuiPreferences; import org.jabref.gui.util.DefaultDirectoryMonitor; import org.jabref.gui.util.DefaultFileUpdateMonitor; import org.jabref.logic.UiCommand; @@ -25,13 +22,13 @@ import org.jabref.logic.net.ssl.SSLPreferences; import org.jabref.logic.net.ssl.TrustStoreManager; import org.jabref.logic.preferences.CliPreferences; +import org.jabref.logic.preferences.JabRefCliPreferences; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.remote.client.RemoteClient; import org.jabref.logic.util.BuildInfo; import org.jabref.logic.util.Directories; import org.jabref.logic.util.HeadlessExecutorService; -import org.jabref.migrations.PreferencesMigrations; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.util.DirectoryMonitor; import org.jabref.model.util.FileUpdateMonitor; @@ -53,7 +50,7 @@ public static void main(String[] args) { processArguments(args); } - public record Result(List uiCommands, GuiPreferences preferences, FileUpdateMonitor fileUpdateMonitor) { + public record Result(List uiCommands, FileUpdateMonitor fileUpdateMonitor) { } private static void systemExit() { @@ -70,9 +67,8 @@ public static Result processArguments(String[] args) { Injector.setModelOrService(BuildInfo.class, new BuildInfo()); // Initialize preferences - final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); + final JabRefCliPreferences preferences = JabRefCliPreferences.getInstance(); Injector.setModelOrService(CliPreferences.class, preferences); - Injector.setModelOrService(GuiPreferences.class, preferences); // Early exit in case another instance is already running if (!handleMultipleAppInstances(args, preferences.getRemotePreferences())) { @@ -82,8 +78,6 @@ public static Result processArguments(String[] args) { BibEntryTypesManager entryTypesManager = preferences.getCustomEntryTypesRepository(); Injector.setModelOrService(BibEntryTypesManager.class, entryTypesManager); - PreferencesMigrations.runMigrations(preferences, entryTypesManager); - Injector.setModelOrService(JournalAbbreviationRepository.class, JournalAbbreviationLoader.loadRepository(preferences.getJournalAbbreviationPreferences())); Injector.setModelOrService(ProtectedTermsLoader.class, new ProtectedTermsLoader(preferences.getProtectedTermsPreferences())); @@ -116,7 +110,7 @@ public static Result processArguments(String[] args) { return null; } - return new Result(new ArrayList<>(argumentProcessor.getUiCommands()), preferences, fileUpdateMonitor); + return new Result(new ArrayList<>(argumentProcessor.getUiCommands()), fileUpdateMonitor); } catch (ParseException e) { LOGGER.error("Problem parsing arguments", e); CliOptions.printUsage(preferences); @@ -154,7 +148,7 @@ private static void initLogging(String[] args) { try { Files.createDirectories(directory); } catch (IOException e) { - LOGGER = LoggerFactory.getLogger(Launcher.class); + LOGGER = LoggerFactory.getLogger(JabKit.class); LOGGER.error("Could not create log directory {}", directory, e); return; } diff --git a/src/main/java/org/jabref/migrations/PreferencesMigrations.java b/src/main/java/org/jabref/migrations/PreferencesMigrations.java index b0299ea3f72..b5a2ba9bbad 100644 --- a/src/main/java/org/jabref/migrations/PreferencesMigrations.java +++ b/src/main/java/org/jabref/migrations/PreferencesMigrations.java @@ -47,7 +47,7 @@ private PreferencesMigrations() { /** * Perform checks and changes for users with a preference set from an older JabRef version. */ - public static void runMigrations(JabRefGuiPreferences preferences, BibEntryTypesManager entryTypesManager) { + public static void runMigrations(JabRefGuiPreferences preferences) { Preferences mainPrefsNode = Preferences.userRoot().node("/org/jabref"); upgradePrefsToOrgJabRef(mainPrefsNode); @@ -55,7 +55,7 @@ public static void runMigrations(JabRefGuiPreferences preferences, BibEntryTypes upgradeFaultyEncodingStrings(preferences); upgradeLabelPatternToCitationKeyPattern(preferences, mainPrefsNode); upgradeImportFileAndDirePatterns(preferences, mainPrefsNode); - upgradeStoredBibEntryTypes(preferences, mainPrefsNode, entryTypesManager); + upgradeStoredBibEntryTypes(preferences, mainPrefsNode, preferences.getCustomEntryTypesRepository()); upgradeKeyBindingsToJavaFX(preferences); addCrossRefRelatedFieldsForAutoComplete(preferences); upgradePreviewStyle(preferences); From 56b7c1cbaa8a344ec199906ba9a557d44a19ced2 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Sun, 13 Oct 2024 06:34:48 +0200 Subject: [PATCH 14/16] Fix use of GUI monitors at JabKit --- src/main/java/org/jabref/Launcher.java | 20 ++++++++++-- src/main/java/org/jabref/cli/JabKit.java | 34 ++++++++------------- src/main/java/org/jabref/gui/JabRefGUI.java | 4 +++ 3 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index d1f835116b7..5acef7e378d 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -1,11 +1,18 @@ package org.jabref; +import java.util.List; + import org.jabref.cli.JabKit; import org.jabref.gui.JabRefGUI; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.preferences.JabRefGuiPreferences; +import org.jabref.gui.util.DefaultDirectoryMonitor; +import org.jabref.gui.util.DefaultFileUpdateMonitor; +import org.jabref.logic.UiCommand; import org.jabref.logic.preferences.CliPreferences; +import org.jabref.logic.util.HeadlessExecutorService; import org.jabref.migrations.PreferencesMigrations; +import org.jabref.model.util.DirectoryMonitor; import com.airhacks.afterburner.injection.Injector; @@ -18,17 +25,24 @@ public class Launcher { public static void main(String[] args) { - JabKit.Result result = JabKit.processArguments(args); - // The method `processArguments` quites the whole JVM if no GUI is needed. + JabKit.initLogging(args); // Initialize preferences final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); Injector.setModelOrService(CliPreferences.class, preferences); Injector.setModelOrService(GuiPreferences.class, preferences); + DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); + HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); + + DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); + + List uiCommands = JabKit.processArguments(args, preferences, fileUpdateMonitor); + // The method `processArguments` quites the whole JVM if no GUI is needed. + PreferencesMigrations.runMigrations(preferences); - JabRefGUI.setup(result.uiCommands(), preferences, result.fileUpdateMonitor()); + JabRefGUI.setup(uiCommands, preferences, fileUpdateMonitor); JabRefGUI.launch(JabRefGUI.class, args); } } diff --git a/src/main/java/org/jabref/cli/JabKit.java b/src/main/java/org/jabref/cli/JabKit.java index dd8d6ca0efd..669300b5e8f 100644 --- a/src/main/java/org/jabref/cli/JabKit.java +++ b/src/main/java/org/jabref/cli/JabKit.java @@ -11,8 +11,6 @@ import java.util.List; import java.util.Map; -import org.jabref.gui.util.DefaultDirectoryMonitor; -import org.jabref.gui.util.DefaultFileUpdateMonitor; import org.jabref.logic.UiCommand; import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.journals.JournalAbbreviationRepository; @@ -28,9 +26,8 @@ import org.jabref.logic.remote.client.RemoteClient; import org.jabref.logic.util.BuildInfo; import org.jabref.logic.util.Directories; -import org.jabref.logic.util.HeadlessExecutorService; import org.jabref.model.entry.BibEntryTypesManager; -import org.jabref.model.util.DirectoryMonitor; +import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import com.airhacks.afterburner.injection.Injector; @@ -42,15 +39,21 @@ /** * Entrypoint for a command-line only version of JabRef. + * + * Does not do any preference migrations */ public class JabKit { private static Logger LOGGER; public static void main(String[] args) { - processArguments(args); - } + initLogging(args); + + final JabRefCliPreferences preferences = JabRefCliPreferences.getInstance(); + Injector.setModelOrService(CliPreferences.class, preferences); + + FileUpdateMonitor fileUpdateMonitor = new DummyFileUpdateMonitor(); - public record Result(List uiCommands, FileUpdateMonitor fileUpdateMonitor) { + processArguments(args, preferences, fileUpdateMonitor); } private static void systemExit() { @@ -60,16 +63,10 @@ private static void systemExit() { System.exit(0); } - public static Result processArguments(String[] args) { - initLogging(args); - + public static List processArguments(String[] args, JabRefCliPreferences preferences, FileUpdateMonitor fileUpdateMonitor) { try { Injector.setModelOrService(BuildInfo.class, new BuildInfo()); - // Initialize preferences - final JabRefCliPreferences preferences = JabRefCliPreferences.getInstance(); - Injector.setModelOrService(CliPreferences.class, preferences); - // Early exit in case another instance is already running if (!handleMultipleAppInstances(args, preferences.getRemotePreferences())) { systemExit(); @@ -87,12 +84,7 @@ public static Result processArguments(String[] args) { clearOldSearchIndices(); try { - DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); Injector.setModelOrService(FileUpdateMonitor.class, fileUpdateMonitor); - HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); - - DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); - Injector.setModelOrService(DirectoryMonitor.class, directoryMonitor); // Process arguments ArgumentProcessor argumentProcessor = new ArgumentProcessor( @@ -110,7 +102,7 @@ public static Result processArguments(String[] args) { return null; } - return new Result(new ArrayList<>(argumentProcessor.getUiCommands()), fileUpdateMonitor); + return new ArrayList<>(argumentProcessor.getUiCommands()); } catch (ParseException e) { LOGGER.error("Problem parsing arguments", e); CliOptions.printUsage(preferences); @@ -128,7 +120,7 @@ public static Result processArguments(String[] args) { * This needs to be called as early as possible. After the first log write, it * is not possible to alter the log configuration programmatically anymore. */ - private static void initLogging(String[] args) { + public static void initLogging(String[] args) { // routeLoggingToSlf4J SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); diff --git a/src/main/java/org/jabref/gui/JabRefGUI.java b/src/main/java/org/jabref/gui/JabRefGUI.java index 820e4468c34..94c223eb6c0 100644 --- a/src/main/java/org/jabref/gui/JabRefGUI.java +++ b/src/main/java/org/jabref/gui/JabRefGUI.java @@ -24,6 +24,7 @@ import org.jabref.gui.remote.CLIMessageHandler; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.undo.CountingUndoManager; +import org.jabref.gui.util.DefaultDirectoryMonitor; import org.jabref.gui.util.UiTaskExecutor; import org.jabref.logic.UiCommand; import org.jabref.logic.ai.AiService; @@ -134,6 +135,9 @@ public void start(Stage stage) { public void initialize() { WebViewStore.init(); + DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); + Injector.setModelOrService(DirectoryMonitor.class, directoryMonitor); + JabRefGUI.remoteListenerServerManager = new RemoteListenerServerManager(); Injector.setModelOrService(RemoteListenerServerManager.class, remoteListenerServerManager); From 55f30e42f63c062709d0f53020f40ffadc2b681c Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Mon, 14 Oct 2024 22:46:28 +0200 Subject: [PATCH 15/16] Remove unused variable --- src/main/java/org/jabref/Launcher.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index 5acef7e378d..8806c7892bf 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -6,13 +6,11 @@ import org.jabref.gui.JabRefGUI; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.preferences.JabRefGuiPreferences; -import org.jabref.gui.util.DefaultDirectoryMonitor; import org.jabref.gui.util.DefaultFileUpdateMonitor; import org.jabref.logic.UiCommand; import org.jabref.logic.preferences.CliPreferences; import org.jabref.logic.util.HeadlessExecutorService; import org.jabref.migrations.PreferencesMigrations; -import org.jabref.model.util.DirectoryMonitor; import com.airhacks.afterburner.injection.Injector; @@ -35,8 +33,6 @@ public static void main(String[] args) { DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); - DirectoryMonitor directoryMonitor = new DefaultDirectoryMonitor(); - List uiCommands = JabKit.processArguments(args, preferences, fileUpdateMonitor); // The method `processArguments` quites the whole JVM if no GUI is needed. From 8c18c1e2703041e7ccaee7e7e8810a3255a876da Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Mon, 14 Oct 2024 22:53:13 +0200 Subject: [PATCH 16/16] Rename JabKit to JabRefCli (and add logging if UICommands are left in Cli) --- src/main/java/org/jabref/Launcher.java | 6 +++--- .../org/jabref/cli/{JabKit.java => JabRefCli.java} | 11 +++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) rename src/main/java/org/jabref/cli/{JabKit.java => JabRefCli.java} (96%) diff --git a/src/main/java/org/jabref/Launcher.java b/src/main/java/org/jabref/Launcher.java index 8806c7892bf..caee40d6dae 100644 --- a/src/main/java/org/jabref/Launcher.java +++ b/src/main/java/org/jabref/Launcher.java @@ -2,7 +2,7 @@ import java.util.List; -import org.jabref.cli.JabKit; +import org.jabref.cli.JabRefCli; import org.jabref.gui.JabRefGUI; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.preferences.JabRefGuiPreferences; @@ -23,7 +23,7 @@ public class Launcher { public static void main(String[] args) { - JabKit.initLogging(args); + JabRefCli.initLogging(args); // Initialize preferences final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance(); @@ -33,7 +33,7 @@ public static void main(String[] args) { DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor(); HeadlessExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); - List uiCommands = JabKit.processArguments(args, preferences, fileUpdateMonitor); + List uiCommands = JabRefCli.processArguments(args, preferences, fileUpdateMonitor); // The method `processArguments` quites the whole JVM if no GUI is needed. PreferencesMigrations.runMigrations(preferences); diff --git a/src/main/java/org/jabref/cli/JabKit.java b/src/main/java/org/jabref/cli/JabRefCli.java similarity index 96% rename from src/main/java/org/jabref/cli/JabKit.java rename to src/main/java/org/jabref/cli/JabRefCli.java index 669300b5e8f..f276f6df258 100644 --- a/src/main/java/org/jabref/cli/JabKit.java +++ b/src/main/java/org/jabref/cli/JabRefCli.java @@ -42,7 +42,7 @@ * * Does not do any preference migrations */ -public class JabKit { +public class JabRefCli { private static Logger LOGGER; public static void main(String[] args) { @@ -53,7 +53,10 @@ public static void main(String[] args) { FileUpdateMonitor fileUpdateMonitor = new DummyFileUpdateMonitor(); - processArguments(args, preferences, fileUpdateMonitor); + List uiCommands = processArguments(args, preferences, fileUpdateMonitor); + if (!uiCommands.isEmpty()) { + LOGGER.error("No GUI needed, but UI commands were returned. Exiting."); + } } private static void systemExit() { @@ -140,7 +143,7 @@ public static void initLogging(String[] args) { try { Files.createDirectories(directory); } catch (IOException e) { - LOGGER = LoggerFactory.getLogger(JabKit.class); + LOGGER = LoggerFactory.getLogger(JabRefCli.class); LOGGER.error("Could not create log directory {}", directory, e); return; } @@ -158,7 +161,7 @@ public static void initLogging(String[] args) { "writerFile.backups", "30"); configuration.forEach(Configuration::set); - LOGGER = LoggerFactory.getLogger(JabKit.class); + LOGGER = LoggerFactory.getLogger(JabRefCli.class); } /**