From 73ec321895fb07e131bfd3cc560d0d8f4214cf3c Mon Sep 17 00:00:00 2001 From: Nivedha Date: Mon, 15 Oct 2018 03:11:26 +0530 Subject: [PATCH 01/30] Fixed testExportAsModsAndThenImportAsMods (#4369) * Fixed testExportAsModsAndThenImportAsMods * Fixed indentation * Fixed indentation --- .../exporter/ModsExportFormatTestFiles.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java index dfce7d716e1..1c0bbbca22f 100644 --- a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java @@ -1,5 +1,8 @@ package org.jabref.logic.exporter; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.mock; + import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -16,7 +19,6 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,15 +26,13 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junitpioneer.jupiter.TempDirectory; import org.mockito.Answers; +import org.mockito.Mockito; import org.xmlunit.builder.Input; import org.xmlunit.builder.Input.Builder; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - @ExtendWith(TempDirectory.class) public class ModsExportFormatTestFiles { @@ -65,8 +65,10 @@ public void setUp(@TempDirectory.TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ARandomlyNamedFile.tmp"); Files.createFile(path); tempFile = path.toAbsolutePath(); - bibtexImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); - modsImporter = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + ImportFormatPreferences mock = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + bibtexImporter = new BibtexImporter(mock, new DummyFileUpdateMonitor()); + Mockito.when(mock.getKeywordSeparator()).thenReturn(','); + modsImporter = new ModsImporter(mock); } @Disabled @@ -78,17 +80,16 @@ public final void testPerformExport(String filename) throws Exception { Path tempFilename = tempFile.toAbsolutePath(); List entries = bibtexImporter.importDatabase(importFile, charset).getDatabase().getEntries(); Path xmlFile = Paths.get(ModsExportFormatTestFiles.class.getResource(xmlFileName).toURI()); - + modsExportFormat.export(databaseContext, tempFile, charset, entries); Builder control = Input.from(Files.newInputStream(xmlFile)); Builder test = Input.from(Files.newInputStream(tempFilename)); - assertThat(test, CompareMatcher.isSimilarTo(control) .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } - @Disabled + @ParameterizedTest @MethodSource("fileNames") public final void testExportAsModsAndThenImportAsMods(String filename) throws Exception { From 3c7ef87d59be59cbe49502133c79c35c480a133f Mon Sep 17 00:00:00 2001 From: Linus Dietz Date: Mon, 15 Oct 2018 22:15:35 +0200 Subject: [PATCH 02/30] Update junit-pioneer from 0.2.1 -> 0.2.2 (#4374) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index ae67cf00cb6..79387f7c926 100644 --- a/build.gradle +++ b/build.gradle @@ -168,7 +168,7 @@ dependencies { testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1' testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1' testCompile 'org.junit.platform:junit-platform-launcher:1.3.1' - testCompile 'org.junit-pioneer:junit-pioneer:0.2.1' + testCompile 'org.junit-pioneer:junit-pioneer:0.2.2' testRuntime 'org.apache.logging.log4j:log4j-core:2.11.1' testRuntime 'org.apache.logging.log4j:log4j-jul:2.11.1' testCompile 'org.mockito:mockito-core:2.23.0' From 78926c7d18bd5aa1a6b1ad873075c1ec3a0e99ed Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Tue, 16 Oct 2018 10:07:12 +0200 Subject: [PATCH 03/30] Extend list of journal abbreviations by a few math journals (#4376) --- src/main/resources/journals/journalList.txt | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/resources/journals/journalList.txt b/src/main/resources/journals/journalList.txt index a1d9b69831d..3d019b4bfa6 100644 --- a/src/main/resources/journals/journalList.txt +++ b/src/main/resources/journals/journalList.txt @@ -1136,6 +1136,7 @@ Annales des Ponts et Chausses = Ann. Ponts Chaussees Annales des Sciences Naturelles - Zoologie et Biologie Animale = Ann. Sci. Nat. Zool. Biol. Anim. Annales Francaises d'Anesthesie et de Reanimation = Ann. Fr. Anesth. Reanim. Annales Geophysicae = Ann. Geophys. +Annales Henri Poincaré = Ann. Henri Poincaré Annales Hydrographiques = Ann. Hydrogr. Annales Immunologiae Hungaricae = Ann. Immunol. Hung. Annales Medicales de Nancy = Ann. Med. Nancy @@ -1195,6 +1196,7 @@ Annals of Hepatology = Ann. Hepatol. Annals of Human Biology = Ann. Hum. Biol. Annals of Human Genetics = Ann. Hum. Genet. Annals of Internal Medicine = Ann. Intern. Med. +Annals of Mathematics = Ann. of Math. Annals of Medicine = Ann. Med. Annals of Neurology = Ann. Neurol. Annals of Noninvasive Electrocardiology = Ann. Noninvasive Electrocardiol. @@ -4258,6 +4260,7 @@ Dianhuaxue = Dianhuaxue Diastema = Diastema Dicle University Tip Fakultesi Dergisitesi = Dicle Univ. Tip Fakul. Derg. DICP = DICP +Differential Geometry and its Applications = Differential Geom. Appl. Differentiation (Malden, MA, United States) = Differentiation (Malden, MA, U. S.) Differentiation = Differentiation Diffusion and Defect Data--Solid State Data, Pt. A: Defect and Diffusion Forum = Diffus. Defect Data, Pt. A @@ -4291,6 +4294,7 @@ Diseases of the Colon and Rectum = Dis. Colon Rectum Diseases of the Esophagus = Dis. Esophagus Diseases of the Nervous System = Dis. Nerv. Syst. Diskussionsforum Medizinische Ethik = Diskussionsforum Med. Ethik +Dissertationes Mathematicae = Dissertationes Math. Distributed Systems Engineering = Distrib. Sys. Eng. District Nursing = Dist. Nurs. Diversity and Distributions = Divers. Distrib. @@ -7146,6 +7150,7 @@ Japanese Journal of Forensic Toxicology = Jpn. J. Forensic Toxicol. Japanese Journal of Genetics = Jpn. J. Genet. Japanese Journal of Human Genetics = Jpn. J. Hum. Genet. Japanese Journal of Infectious Diseases = Jpn. J. Infect. Dis. +Japanese Journal of Mathematics = Japan. J. Math. Japanese Journal of Medical Science and Biology = Jpn. J. Med. Sci. Biol. Japanese Journal of Medicine = Jpn. J. Med. Japanese Journal of Microbiology = Jpn. J. Microbiol. @@ -8875,6 +8880,7 @@ Journal of Surveying Engineering = J. Surv. Eng. Journal of Sustainable Forestry = J. Sustainable For. Journal of Sustainable Product Design = J. Sustainable Prod. Des. Journal of Sustainable Science and Management = J. Sustainable Sci. Manage. +Journal of Symplectic Geometry = J. Symplectic Geom. Journal of Synchrotron Radiat. = J. Synchrotron Radiat. Journal of Synthetic Lubrication = J. Synth. Lubr. Journal of Synthetic Organic Chemistry, Japan = J. Synth. Org. Chem Jpn. @@ -9907,7 +9913,7 @@ Mathematical Modeling and Computation = Math. Model. Comput. Mathematical Modelling: Theory and Applications = Math. Modell. Theory Appl. Mathematical Models and Computer Simulations = Math. Models Comput. Simul. Mathematical Models and Methods in Applied Sciences = Math. Models Methods Appl. Sci. -Mathematical Physics Analysis and Geometry = Math. Phys. Anal. Geom. +Mathematical Physics, Analysis and Geometry = Math. Phys. Anal. Geom. Mathematical Population Studies = Math. Popul. Stud. Mathematical Proceedings of the Cambridge Philosophical Society = Math. Proc. Cambridge Philos. Soc. Mathematical Programming = Math. Program. @@ -9915,6 +9921,7 @@ Mathematics and Computers in Simulation = Math. Comput. Simul Mathematics of Computation = Math. Comput. Mathematics of Operations Research = Math. Oper. Res. Mathematicsl Methods in the Applied Sciences = Math. Methods Appl. Sci. +Mathematische Annalen = Math. Ann. Mathematische und Naturwissenschaftliche Unterricht = Math. Naturwiss. Unterr. Mathematische Zeitschrift = Math. Z. Matrix = Matrix @@ -11813,6 +11820,7 @@ Physical Review B = Phys. Rev. B Physical Review B: Condensed Matter = Phys. Rev. B: Condens. Matter Physical Review B: Condensed Matter and Materials Physics = Phys. Rev. B: Condens. Matter Mater. Phys. Physical Review C: Nuclear Physics = Phys. Rev. C: Nucl. Phys. +Physical Review D = Phys. Rev. D Physical Review D: Particles and Fields = Phys. Rev. D: Part. Fields Physical Review E: Statistical Physics, Plasmas, Fluids, and Related Interdisciplinary Topics = Phys. Rev. E: Stat. Phys. Plasmas Fluids Relat. Interdisciplin. Top. Physical Review E: Statistical, Nonlinear, and Soft Matter Physics = Phys. Rev. E: Stat., Nonlinear, Soft Matter Phys. @@ -12151,6 +12159,7 @@ Proceedings - United States Naval Institute = Proc. U.S. Nav. Inst. Proceedings and Papers of the Annual Conference of the California Mosquito Control Association = Proc. Pap. Annu. Conf. Calif. Mosq. Control Assoc. Proceedings in Applied Mathematics and Mechanics = Proc. Appl. Math. Mech. Proceedings of SPIE The International Society for Optical Engineering = Proc. SPIE Int. Soc. Opt. Eng. +Proceedings of the American Mathematical Society = Proc. Amer. Math. Soc. Proceedings of the American Society of Brewing Chemists = Proc. Am. Soc. Brew. Chem. Proceedings of the American Thoracic Society = Proc. Am. Thorac. Soc. Proceedings of the Analytical Division of the Chemical Society = Proc. Anal. Div. Chem. Soc. From 6e5b7b2b4b4ef5628c8a1785bb924c12697888ec Mon Sep 17 00:00:00 2001 From: Linus Dietz Date: Tue, 16 Oct 2018 10:18:21 +0200 Subject: [PATCH 04/30] Downgrade shadow plugin from 4.0.0 -> 2.0.4 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 79387f7c926..5f06b384566 100644 --- a/build.gradle +++ b/build.gradle @@ -17,7 +17,7 @@ buildscript { plugins { id 'com.gradle.build-scan' version '1.16' id 'com.install4j.gradle' version '7.0.7' - id 'com.github.johnrengelman.shadow' version '4.0.0' + id 'com.github.johnrengelman.shadow' version '2.0.4' id "de.sebastianboegl.shadow.transformer.log4j" version "2.1.1" id "com.simonharrer.modernizer" version '1.6.0-1' id 'me.champeau.gradle.jmh' version '0.4.7' From c2d9832e33bc30af1a4d3e2ad5d8f280e42555ac Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Tue, 16 Oct 2018 13:45:56 +0200 Subject: [PATCH 05/30] Color special column icons in lighter gray on mouse hover (#4377) --- src/main/java/org/jabref/gui/maintable/MainTable.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.css b/src/main/java/org/jabref/gui/maintable/MainTable.css index 6096c5379f6..5855a86c120 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTable.css +++ b/src/main/java/org/jabref/gui/maintable/MainTable.css @@ -14,7 +14,7 @@ .table-row-cell:hover .empty-special-field { visibility: visible; - /*-fx-fill: -jr-grayed-text;*/ + -fx-fill: -jr-gray-2; } .rating > .container { From 453e7b50adda6fc27bd7c5d83f31be086409e8b5 Mon Sep 17 00:00:00 2001 From: Ali Date: Wed, 17 Oct 2018 13:35:05 +0600 Subject: [PATCH 06/30] Provide access to dark theme in preferences (#4372) Fixes #4130. --- CHANGELOG.md | 2 +- src/main/java/org/jabref/Globals.java | 4 +-- .../gui/preferences/AppearancePrefsTab.java | 36 ++++++++++++++++--- .../java/org/jabref/gui/util/ThemeLoader.java | 36 ++++++++++++------- .../jabref/preferences/JabRefPreferences.java | 1 + .../jabref/styletester/StyleTesterMain.java | 5 +-- 6 files changed, 63 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61130cb9435..adc97d7c507 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,7 +34,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We add auto url formatting when user paste link to URL field in entry editor. [#254](https://github.com/koppor/jabref/issues/254) - We added a minimal height for the entry editor so that it can no longer be hidden by accident. [#4279](https://github.com/JabRef/jabref/issues/4279) - We added a new keyboard shortcut so that the entry editor could be closed by Ctrl + E. [#4222] (https://github.com/JabRef/jabref/issues/4222) - +- We added an option in the preference dialog box, that allows user to pick the dark or light theme option. [#4130] (https://github.com/JabRef/jabref/issues/4130) diff --git a/src/main/java/org/jabref/Globals.java b/src/main/java/org/jabref/Globals.java index 60a1d626acf..b86cc83cbd2 100644 --- a/src/main/java/org/jabref/Globals.java +++ b/src/main/java/org/jabref/Globals.java @@ -75,11 +75,11 @@ public static synchronized KeyBindingRepository getKeyPrefs() { } // Background tasks - public static void startBackgroundTasks() { + public static void startBackgroundTasks() throws JabRefException { Globals.fileUpdateMonitor = new DefaultFileUpdateMonitor(); JabRefExecutorService.INSTANCE.executeInterruptableTask(Globals.fileUpdateMonitor, "FileUpdateMonitor"); - themeLoader = new ThemeLoader(fileUpdateMonitor); + themeLoader = new ThemeLoader(fileUpdateMonitor, prefs); if (Globals.prefs.shouldCollectTelemetry() && !GraphicsEnvironment.isHeadless()) { startTelemetryClient(); diff --git a/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java b/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java index c13de2563c3..92c62d12864 100644 --- a/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java +++ b/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java @@ -4,7 +4,9 @@ import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; +import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; +import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; @@ -16,12 +18,16 @@ class AppearancePrefsTab extends Pane implements PrefsTab { + public static final String BASE_CSS = "Base.css"; + public static final String DARK_CSS = "Dark.css"; private final JabRefPreferences prefs; private final CheckBox fontTweaksLAF; private final TextField fontSize; private final CheckBox overrideFonts; private final VBox container = new VBox(); private final DialogService dialogService; + private final RadioButton lightTheme; + private final RadioButton darkTheme; /** * Customization of appearance parameters. @@ -41,7 +47,18 @@ public AppearancePrefsTab(DialogService dialogService, JabRefPreferences prefs) fontSizeContainer.disableProperty().bind(overrideFonts.selectedProperty().not()); fontTweaksLAF = new CheckBox(Localization.lang("Tweak font rendering for entry editor on Linux")); - container.getChildren().addAll(overrideFonts, fontSizeContainer, fontTweaksLAF); + ToggleGroup themeGroup = new ToggleGroup(); + lightTheme = new RadioButton("Light theme"); + lightTheme.setToggleGroup(themeGroup); + darkTheme = new RadioButton("Dark theme"); + darkTheme.setToggleGroup(themeGroup); + + if (prefs.get(JabRefPreferences.FX_THEME).equals(BASE_CSS)) + lightTheme.setSelected(true); + else if (prefs.get(JabRefPreferences.FX_THEME).equals(DARK_CSS)) + darkTheme.setSelected(true); + + container.getChildren().addAll(overrideFonts, fontSizeContainer, fontTweaksLAF, lightTheme, darkTheme); } @@ -68,10 +85,21 @@ public void storeSettings() { int newFontSize = Integer.parseInt(fontSize.getText()); prefs.putInt(JabRefPreferences.MAIN_FONT_SIZE, newFontSize); + boolean isThemeChanged = false; + + if (lightTheme.isSelected() && !prefs.get(JabRefPreferences.FX_THEME).equals(BASE_CSS)) { + prefs.put(JabRefPreferences.FX_THEME, BASE_CSS); + isThemeChanged = true; + } else if (darkTheme.isSelected() && !prefs.get(JabRefPreferences.FX_THEME).equals(DARK_CSS)) { + prefs.put(JabRefPreferences.FX_THEME, DARK_CSS); + isThemeChanged = true; + } + boolean isRestartRequired = - oldFxTweakValue != fontTweaksLAF.isSelected() - || oldOverrideDefaultFontSize != overrideFonts.isSelected() - || oldFontSize != newFontSize; + (oldFxTweakValue != fontTweaksLAF.isSelected()) + || (oldOverrideDefaultFontSize != overrideFonts.isSelected()) + || (oldFontSize != newFontSize) + || isThemeChanged; if (isRestartRequired) { dialogService.showWarningDialogAndWait(Localization.lang("Settings"), Localization.lang("Some appearance settings you changed require to restart JabRef to come into effect.")); diff --git a/src/main/java/org/jabref/gui/util/ThemeLoader.java b/src/main/java/org/jabref/gui/util/ThemeLoader.java index 87eeb0a83e9..7a7004d3445 100644 --- a/src/main/java/org/jabref/gui/util/ThemeLoader.java +++ b/src/main/java/org/jabref/gui/util/ThemeLoader.java @@ -11,6 +11,7 @@ import javafx.scene.Parent; import javafx.scene.Scene; +import org.jabref.JabRefException; import org.jabref.gui.JabRefFrame; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; @@ -21,28 +22,39 @@ /** * Installs the style file and provides live reloading. - * + *

* The live reloading has to be turned on by setting the -Djabref.theme.css property. * There two possible modes: - * (1) When only -Djabref.theme.css is specified, then the standard Base.css that is found will be watched - * and on changes in that file, the style-sheet will be reloaded and changes are immediately visible. - * (2) When a path to a css file is passed to -Djabref.theme.css, then the given style is loaded in addition to the base css file. - * Changes in the specified css file lead to an immediate redraw of the interface. - * + * (1) When only -Djabref.theme.css is specified, then the standard Base.css that is found will be watched + * and on changes in that file, the style-sheet will be reloaded and changes are immediately visible. + * (2) When a path to a css file is passed to -Djabref.theme.css, then the given style is loaded in addition to the base css file. + * Changes in the specified css file lead to an immediate redraw of the interface. + *

* When working from an IDE, this usually means that the Base.css is located in the build folder. * To use the css-file that is located in the sources directly, the full path can be given as value for the "VM option": * -Djabref.theme.css="/path/to/src/Base.css" - * */ public class ThemeLoader { private static final String DEFAULT_PATH_MAIN_CSS = JabRefFrame.class.getResource("Base.css").toExternalForm(); - private static final String CSS_SYSTEM_PROPERTY = System.getProperty("jabref.theme.css"); private static final Logger LOGGER = LoggerFactory.getLogger(ThemeLoader.class); + private String cssProperty = System.getProperty("jabref.theme.css"); private final FileUpdateMonitor fileUpdateMonitor; - public ThemeLoader(FileUpdateMonitor fileUpdateMonitor) { + public ThemeLoader(FileUpdateMonitor fileUpdateMonitor, JabRefPreferences jabRefPreferences) throws JabRefException { this.fileUpdateMonitor = Objects.requireNonNull(fileUpdateMonitor); + + if (StringUtil.isNullOrEmpty(cssProperty)) { + String cssFileName = jabRefPreferences.get(JabRefPreferences.FX_THEME); + if (cssFileName != null) { + try { + cssProperty = Paths.get(JabRefFrame.class.getResource(cssFileName).toURI()).toString(); + } catch (URISyntaxException e) { + LOGGER.warn("can't get css file URI"); + throw new JabRefException("can't set custom theme"); + } + } + } } /** @@ -52,8 +64,8 @@ public ThemeLoader(FileUpdateMonitor fileUpdateMonitor) { public void installBaseCss(Scene scene, JabRefPreferences preferences) { addAndWatchForChanges(scene, DEFAULT_PATH_MAIN_CSS, 0); - if (StringUtil.isNotBlank(CSS_SYSTEM_PROPERTY)) { - final Path path = Paths.get(CSS_SYSTEM_PROPERTY); + if (StringUtil.isNotBlank(cssProperty)) { + final Path path = Paths.get(cssProperty); if (Files.isReadable(path)) { String cssUrl = path.toUri().toString(); addAndWatchForChanges(scene, cssUrl, 1); @@ -69,7 +81,7 @@ private void addAndWatchForChanges(Scene scene, String cssUrl, int index) { try { // If -Djabref.theme.css is defined and the resources are not part of a .jar bundle, // we watch the file for changes and turn on live reloading - if (!cssUrl.startsWith("jar:") && CSS_SYSTEM_PROPERTY != null) { + if (!cssUrl.startsWith("jar:") && cssProperty != null) { Path cssFile = Paths.get(new URL(cssUrl).toURI()); LOGGER.info("Enabling live reloading of " + cssFile); fileUpdateMonitor.addListenerForFile(cssFile, () -> { diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 0c898045a68..ea96020a5fb 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -119,6 +119,7 @@ public class JabRefPreferences implements PreferencesService { public static final String EXTERNAL_FILE_TYPES = "externalFileTypes"; public static final String FONT_FAMILY = "fontFamily"; public static final String FX_FONT_RENDERING_TWEAK = "fxFontRenderingTweak"; + public static final String FX_THEME = "fxTheme"; public static final String LANGUAGE = "language"; public static final String NAMES_LAST_ONLY = "namesLastOnly"; public static final String ABBR_AUTHOR_NAMES = "abbrAuthorNames"; diff --git a/src/main/java/org/jabref/styletester/StyleTesterMain.java b/src/main/java/org/jabref/styletester/StyleTesterMain.java index 1bd2cc75d9c..68a7331b989 100644 --- a/src/main/java/org/jabref/styletester/StyleTesterMain.java +++ b/src/main/java/org/jabref/styletester/StyleTesterMain.java @@ -4,6 +4,7 @@ import javafx.scene.Scene; import javafx.stage.Stage; +import org.jabref.JabRefException; import org.jabref.JabRefExecutorService; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.DefaultFileUpdateMonitor; @@ -20,7 +21,7 @@ public static void main(String[] args) { } @Override - public void start(Stage stage) { + public void start(Stage stage) throws JabRefException { StyleTesterView view = new StyleTesterView(); IconTheme.loadFonts(); @@ -29,7 +30,7 @@ public void start(Stage stage) { JabRefExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); Scene scene = new Scene(view.getContent()); - new ThemeLoader(fileUpdateMonitor).installBaseCss(scene, JabRefPreferences.getInstance()); + new ThemeLoader(fileUpdateMonitor, JabRefPreferences.getInstance()).installBaseCss(scene, JabRefPreferences.getInstance()); stage.setScene(scene); stage.show(); } From e7780ed8038fd2a9193573eca03750777f9f7bec Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Wed, 17 Oct 2018 11:05:51 +0200 Subject: [PATCH 07/30] Enable checkstyle for tests and fix style issues (#4378) * Enable checkstyle for tests * Correct imports * Reformat code * Reformat code --- build.gradle | 8 +- config/checkstyle/suppressions.xml | 1 - .../org/jabref/CatchExceptionsFromThread.java | 4 +- .../org/jabref/JabRefPreferencesTest.java | 1 - .../architecture/MainArchitectureTests.java | 4 +- .../MainArchitectureTestsWithArchUnit.java | 14 +- .../architecture/TestArchitectureTests.java | 39 ++-- .../cleanup/CleanupActionsListModelTest.java | 3 - .../org/jabref/cli/AuxCommandLineTest.java | 1 - .../java/org/jabref/cli/JabRefCLITest.java | 6 +- .../org/jabref/gui/AWTExceptionHandler.java | 1 - .../java/org/jabref/gui/AbstractUITest.java | 7 +- src/test/java/org/jabref/gui/DialogTest.java | 2 +- .../java/org/jabref/gui/EntryTableTest.java | 16 +- .../org/jabref/gui/IdFetcherDialogTest.java | 2 - .../gui/ParameterizedDialogNewEntryTest.java | 1 - .../jabref/gui/ParameterizedDialogTest.java | 13 +- .../gui/ParameterizedMenuNewEntryTest.java | 1 - .../PersonNameSuggestionProviderTest.java | 2 +- .../FileAnnotationViewModelTest.java | 10 +- .../AutoSetFileLinksUtilTest.java | 1 - .../gui/groups/GroupNodeViewModelTest.java | 2 +- .../gui/groups/GroupTreeViewModelTest.java | 2 +- .../EntryFromFileCreatorManagerTest.java | 3 +- .../gui/importer/EntryFromPDFCreatorTest.java | 1 - ...nageJournalAbbreviationsViewModelTest.java | 8 +- .../KeyBindingsDialogViewModelTest.java | 1 - .../jabref/gui/search/SearchResultsTest.java | 2 - .../gui/util/FileDialogConfigurationTest.java | 3 - .../gui/util/RecursiveTreeItemTest.java | 1 - .../autosaveandbackup/BackupManagerTest.java | 1 - .../jabref/logic/bibtex/BibEntryAssert.java | 38 ++-- .../logic/bibtex/BibEntryWriterTest.java | 1 - .../logic/bibtex/FieldContentParserTest.java | 1 - .../bibtex/LatexFieldFormatterTests.java | 5 +- .../comparator/BibDatabaseDiffTest.java | 1 - .../BibtexStringComparatorTest.java | 3 - .../bibtex/comparator/MetaDataDiffTest.java | 1 - .../BibtexKeyGeneratorTest.java | 8 +- .../MakeLabelWithDatabaseTest.java | 1 - .../MakeLabelWithoutDatabaseTest.java | 2 - .../logic/bst/BibtexCaseChangersTest.java | 2 - .../logic/bst/BibtexNameFormatterTest.java | 2 - .../org/jabref/logic/bst/BibtexWidthTest.java | 2 - .../java/org/jabref/logic/bst/TestVM.java | 5 +- .../logic/bst/TextPrefixFunctionTest.java | 1 - .../CitationStyleGeneratorTest.java | 2 - .../citationstyle/CitationStyleTest.java | 1 - .../logic/cleanup/CleanupWorkerTest.java | 1 - .../cleanup/FieldFormatterCleanupTest.java | 4 +- .../jabref/logic/cleanup/ISSNCleanupTest.java | 1 - .../exporter/BibTeXMLExporterTestFiles.java | 10 +- .../exporter/BibtexDatabaseWriterTest.java | 37 ++-- .../logic/exporter/CsvExportFormatTest.java | 21 +-- .../jabref/logic/exporter/ExporterTest.java | 4 +- .../exporter/FieldFormatterCleanupsTest.java | 1 - .../logic/exporter/GroupSerializerTest.java | 1 - .../logic/exporter/HtmlExportFormatTest.java | 4 +- .../exporter/MSBibExportFormatTestFiles.java | 3 +- .../exporter/ModsExportFormatTestFiles.java | 20 +- .../logic/exporter/XmpExporterTest.java | 176 +++++++++--------- .../jabref/logic/formatter/FormatterTest.java | 19 +- .../bibtexfields/AddBracesFormatterTest.java | 3 +- .../bibtexfields/CleanupUrlFormatterTest.java | 4 +- .../bibtexfields/ClearFormatterTest.java | 1 - .../HtmlToUnicodeFormatterTest.java | 1 - .../LatexCleanupFormatterTest.java | 1 - .../NormalizeMonthFormatterTest.java | 1 - .../NormalizePagesFormatterTest.java | 1 - .../RemoveBracesFormatterTest.java | 1 - .../TrimWhitespaceFormatterTest.java | 2 - .../bibtexfields/UnicodeConverterTest.java | 3 +- .../UnitsToLatexFormatterTest.java | 1 - .../casechanger/CapitalizeFormatterTest.java | 1 - .../casechanger/LowerCaseFormatterTest.java | 1 - .../ProtectTermsFormatterTest.java | 4 +- .../SentenceCaseFormatterTest.java | 1 - .../casechanger/TitleCaseFormatterTest.java | 1 - .../casechanger/UpperCaseFormatterTest.java | 1 - .../minifier/MinifyNameListFormatterTest.java | 1 - .../importer/BibDatabaseTestsWithFiles.java | 3 +- .../importer/DatabaseFileLookupTest.java | 4 +- .../jabref/logic/importer/ImportDataTest.java | 2 - .../ImportFormatReaderIntegrationTest.java | 17 +- .../ImportFormatReaderTestParameterless.java | 3 - .../jabref/logic/importer/ImporterTest.java | 24 ++- .../logic/importer/OpenDatabaseTest.java | 2 +- .../logic/importer/fetcher/ACSTest.java | 2 +- .../fetcher/AbstractIsbnFetcherTest.java | 1 - .../logic/importer/fetcher/ArXivTest.java | 7 +- .../importer/fetcher/DBLPFetcherTest.java | 8 +- .../logic/importer/fetcher/DiVATest.java | 2 +- .../importer/fetcher/DoiFetcherTest.java | 2 - .../fetcher/IacrEprintFetcherTest.java | 2 +- .../importer/fetcher/IsbnFetcherTest.java | 7 +- .../fetcher/IsbnViaChimboriFetcherTest.java | 5 +- .../fetcher/IsbnViaEbookDeFetcherTest.java | 5 +- .../importer/fetcher/MathSciNetTest.java | 2 +- .../importer/fetcher/MrDLibFetcherTest.java | 1 - .../importer/fetcher/TitleFetcherTest.java | 1 - .../fileformat/BibTeXMLImporterTest.java | 1 - .../fileformat/BibTeXMLImporterTestFiles.java | 1 - .../fileformat/BibTeXMLImporterTestTypes.java | 3 +- .../fileformat/BiblioscapeImporterTest.java | 1 - .../BiblioscapeImporterTestTypes.java | 4 +- .../fileformat/BibtexImporterTest.java | 24 +-- .../importer/fileformat/BibtexParserTest.java | 6 +- .../fileformat/CopacImporterTest.java | 2 - .../fileformat/CopacImporterTestFiles.java | 1 - .../fileformat/EndnoteImporterTest.java | 2 +- .../fileformat/ImporterTestEngine.java | 2 +- .../fileformat/InspecImporterTest.java | 14 +- .../importer/fileformat/IsiImporterTest.java | 6 +- .../fileformat/MedlineImporterTest.java | 12 +- .../fileformat/MedlineImporterTestFiles.java | 2 - .../fileformat/MedlinePlainImporterTest.java | 10 +- .../fileformat/MsBibImporterTest.java | 1 - .../fileformat/MsBibImporterTestFiles.java | 1 - .../importer/fileformat/OvidImporterTest.java | 5 +- .../fileformat/PdfContentImporterTest.java | 1 - .../PdfContentImporterTestFiles.java | 1 - .../importer/fileformat/RISImporterTest.java | 1 - .../fileformat/SilverPlatterImporterTest.java | 2 - .../logic/importer/util/GroupsParserTest.java | 1 - .../logic/integrity/BracesCorrectorTest.java | 1 - .../logic/integrity/IntegrityCheckTest.java | 9 +- .../integrity/NoBibTexFieldCheckerTest.java | 2 - .../journals/AbbreviationParserTest.java | 2 +- .../logic/journals/AbbreviationTest.java | 1 - .../logic/journals/AbbreviationsTest.java | 10 +- .../JournalAbbreviationRepositoryTest.java | 3 - ...ippedJournalAbbreviationDuplicateTest.java | 1 - .../l10n/LocalizationConsistencyTest.java | 34 ++-- .../jabref/logic/l10n/LocalizationEntry.java | 3 +- .../logic/l10n/LocalizationKeyParamsTest.java | 1 - .../logic/l10n/LocalizationKeyTest.java | 1 - .../jabref/logic/l10n/LocalizationParser.java | 22 +-- .../logic/l10n/LocalizationParserTest.java | 1 - .../jabref/logic/l10n/LocalizationTest.java | 1 - .../jabref/logic/layout/LayoutEntryTest.java | 24 +-- .../org/jabref/logic/layout/LayoutTest.java | 2 +- .../layout/format/AuthorAbbreviatorTest.java | 5 +- .../AuthorAndToSemicolonReplacerTest.java | 4 +- .../format/AuthorAndsCommaReplacerTest.java | 6 +- .../layout/format/AuthorAndsReplacerTest.java | 7 +- .../format/AuthorFirstAbbrLastCommasTest.java | 4 +- .../AuthorFirstAbbrLastOxfordCommasTest.java | 4 +- .../format/AuthorFirstFirstCommasTest.java | 7 +- .../layout/format/AuthorFirstFirstTest.java | 7 +- .../format/AuthorFirstLastCommasTest.java | 4 +- .../AuthorFirstLastOxfordCommasTest.java | 4 +- .../layout/format/AuthorLF_FFAbbrTest.java | 7 +- .../logic/layout/format/AuthorLF_FFTest.java | 7 +- .../format/AuthorLastFirstAbbrCommasTest.java | 5 +- .../AuthorLastFirstAbbrOxfordCommasTest.java | 4 +- .../AuthorLastFirstAbbreviatorTester.java | 4 +- .../format/AuthorLastFirstCommasTest.java | 7 +- .../AuthorLastFirstOxfordCommasTest.java | 4 +- .../layout/format/AuthorLastFirstTest.java | 4 +- .../logic/layout/format/AuthorNatBibTest.java | 10 +- .../logic/layout/format/AuthorOrgSciTest.java | 4 +- .../logic/layout/format/AuthorsTest.java | 4 +- .../layout/format/CompositeFormatTest.java | 6 +- .../logic/layout/format/DOICheckTest.java | 4 +- .../logic/layout/format/DOIStripTest.java | 5 +- .../layout/format/DateFormatterTest.java | 4 +- .../logic/layout/format/DefaultTest.java | 4 +- .../layout/format/EntryTypeFormatterTest.java | 2 - .../logic/layout/format/FileLinkTest.java | 3 +- .../logic/layout/format/FirstPageTest.java | 3 +- .../logic/layout/format/HTMLCharsTest.java | 1 - .../layout/format/HTMLParagraphsTest.java | 5 +- .../logic/layout/format/IfPluralTest.java | 3 +- .../logic/layout/format/LastPageTest.java | 3 +- .../format/LatexToUnicodeFormatterTest.java | 4 - .../layout/format/NameFormatterTest.java | 5 +- .../NoSpaceBetweenAbbreviationsTest.java | 4 +- .../logic/layout/format/RTFCharsTest.java | 105 ++++++----- .../logic/layout/format/RemoveTildeTest.java | 3 +- .../logic/layout/format/ReplaceTest.java | 3 +- .../logic/layout/format/RisKeywordsTest.java | 1 - .../logic/layout/format/RisMonthTest.java | 1 - .../logic/layout/format/ToLowerCaseTest.java | 1 - .../logic/layout/format/ToUpperCaseTest.java | 1 - .../logic/layout/format/WrapContentTest.java | 3 +- .../layout/format/WrapFileLinksTest.java | 3 - .../jabref/logic/msbib/MsBibAuthorTest.java | 1 - .../org/jabref/logic/net/URLDownloadTest.java | 1 - .../logic/openoffice/OOBibStyleTest.java | 16 +- .../logic/openoffice/OOPreFormatterTest.java | 2 - .../logic/openoffice/StyleLoaderTest.java | 15 +- .../logic/pdf/PdfAnnotationImporterTest.java | 1 - .../ProtectedTermsListTest.java | 3 +- .../ProtectedTermsLoaderTest.java | 19 +- .../logic/remote/RemoteCommunicationTest.java | 4 +- .../logic/remote/RemotePreferencesTest.java | 2 - .../logic/search/DatabaseSearcherTest.java | 1 - .../SearchQueryHighlightObservableTest.java | 4 +- .../jabref/logic/search/SearchQueryTest.java | 3 - .../logic/shared/DBMSConnectionTest.java | 2 +- .../logic/shared/DBMSProcessorTest.java | 8 +- .../logic/shared/DBMSSynchronizerTest.java | 17 +- .../org/jabref/logic/shared/DBMSTypeTest.java | 1 - .../SynchronizationTestEventListener.java | 1 - .../shared/SynchronizationTestSimulator.java | 15 +- .../org/jabref/logic/shared/TestManager.java | 14 +- .../logic/util/DevelopmentStageTest.java | 3 - .../jabref/logic/util/JavaVersionTest.java | 16 +- .../jabref/logic/util/UpdateFieldTest.java | 3 - .../org/jabref/logic/util/VersionTest.java | 2 - .../util/io/CiteKeyBasedFileFinderTest.java | 5 +- .../jabref/logic/util/io/FileUtilTest.java | 47 +++-- .../util/io/RegExpBasedFileFinderTests.java | 13 +- .../strings/StringLengthComparatorTest.java | 2 - .../jabref/logic/xmp/XmpUtilReaderTest.java | 8 +- .../jabref/logic/xmp/XmpUtilWriterTest.java | 7 +- .../migrations/PreferencesMigrationsTest.java | 85 ++++----- .../java/org/jabref/model/EntryTypesTest.java | 5 +- .../java/org/jabref/model/TreeNodeTest.java | 1 - .../org/jabref/model/TreeNodeTestData.java | 30 +-- .../BibDatabaseModeDetectionTest.java | 1 - .../model/database/BibDatabaseTest.java | 4 - .../database/DuplicationCheckerTest.java | 9 +- .../model/database/KeyChangeListenerTest.java | 3 - .../model/entry/AuthorListParameterTest.java | 1 - .../jabref/model/entry/AuthorListTest.java | 43 ++--- .../org/jabref/model/entry/AuthorTest.java | 1 - .../org/jabref/model/entry/BibEntryTest.java | 2 - .../org/jabref/model/entry/BibEntryTests.java | 4 - .../jabref/model/entry/BibtexStringTest.java | 1 - .../model/entry/CanonicalBibEntryTest.java | 1 - .../jabref/model/entry/EntryLinkListTest.java | 8 +- .../org/jabref/model/entry/FieldNameTest.java | 1 - .../model/entry/FileFieldWriterTest.java | 10 +- .../model/entry/IEEETranEntryTypesTest.java | 1 - .../jabref/model/entry/IdGeneratorTest.java | 2 - .../jabref/model/entry/KeywordListTest.java | 1 - .../org/jabref/model/entry/MonthTest.java | 2 +- .../model/entry/identifier/DOITest.java | 2 - .../model/entry/identifier/ISBNTest.java | 1 - .../entry/specialfields/SpecialFieldTest.java | 1 - .../jabref/model/event/TestEventListener.java | 2 - .../jabref/model/groups/SearchGroupTest.java | 1 - .../jabref/model/pdf/FileAnnotationTest.java | 1 - .../search/matchers/MatcherSetsTest.java | 2 - .../rules/ContainBasedSearchRuleTest.java | 1 - .../search/rules/SentenceAnalyzerTest.java | 5 +- .../jabref/model/strings/StringUtilTest.java | 4 +- .../performance/BibtexEntryGenerator.java | 1 - .../org/jabref/support/CIServerCondition.java | 4 +- .../java/org/jabref/testutils/TestUtils.java | 4 +- 251 files changed, 675 insertions(+), 985 deletions(-) diff --git a/build.gradle b/build.gradle index 5f06b384566..8796658b173 100644 --- a/build.gradle +++ b/build.gradle @@ -177,7 +177,8 @@ dependencies { testCompile 'org.reflections:reflections:0.9.11' testCompile 'org.xmlunit:xmlunit-core:2.6.2' testCompile 'org.xmlunit:xmlunit-matchers:2.6.2' - testCompile 'com.tngtech.archunit:archunit-junit:0.8.3' + testCompile 'com.tngtech.archunit:archunit-junit5-api:0.9.1' + testRuntime 'com.tngtech.archunit:archunit-junit5-engine:0.9.1' testCompile "org.testfx:testfx-core:4.0.+" testCompile "org.testfx:testfx-junit5:4.0.+" @@ -402,12 +403,7 @@ jacocoTestReport { // Code quality tasks checkstyle { - // do not use other packages for checkstyle, excluding gen(erated) sources - checkstyleMain.source = "src/main/java" - toolVersion = '8.5' - // do not perform checkstyle checks by default - sourceSets = [] } modernizer { diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml index 7e853704d9d..71943814250 100644 --- a/config/checkstyle/suppressions.xml +++ b/config/checkstyle/suppressions.xml @@ -6,5 +6,4 @@ - diff --git a/src/test/java/org/jabref/CatchExceptionsFromThread.java b/src/test/java/org/jabref/CatchExceptionsFromThread.java index 16cb2c6845c..dc3b523e280 100644 --- a/src/test/java/org/jabref/CatchExceptionsFromThread.java +++ b/src/test/java/org/jabref/CatchExceptionsFromThread.java @@ -3,8 +3,8 @@ import org.junit.rules.ExternalResource; /** - * JUnit by default ignores exceptions, which are reported via {@link Thread.UncaughtExceptionHandler}. - * With this rule also these kind of exceptions result in a failure of the test. + * JUnit by default ignores exceptions, which are reported via {@link Thread.UncaughtExceptionHandler}. With this rule + * also these kind of exceptions result in a failure of the test. */ public class CatchExceptionsFromThread extends ExternalResource { @Override diff --git a/src/test/java/org/jabref/JabRefPreferencesTest.java b/src/test/java/org/jabref/JabRefPreferencesTest.java index 91f441936bf..187bab026a6 100644 --- a/src/test/java/org/jabref/JabRefPreferencesTest.java +++ b/src/test/java/org/jabref/JabRefPreferencesTest.java @@ -26,5 +26,4 @@ void getDefaultEncodingReturnsPreviouslyStoredEncoding() { prefs.setDefaultEncoding(StandardCharsets.UTF_8); assertEquals(StandardCharsets.UTF_8, prefs.getDefaultEncoding()); } - } diff --git a/src/test/java/org/jabref/architecture/MainArchitectureTests.java b/src/test/java/org/jabref/architecture/MainArchitectureTests.java index 85983851bb3..042b72a6610 100644 --- a/src/test/java/org/jabref/architecture/MainArchitectureTests.java +++ b/src/test/java/org/jabref/architecture/MainArchitectureTests.java @@ -84,8 +84,8 @@ void firstPackageIsIndependentOfSecondPackage(String firstPackage, String second Predicate isExceptionPackage = (s) -> (s.startsWith("import " + secondPackage) || s.startsWith("import static " + secondPackage)) && exceptions.getOrDefault(firstPackage, Collections.emptyList()) - .stream() - .noneMatch(exception -> s.startsWith("import " + exception)); + .stream() + .noneMatch(exception -> s.startsWith("import " + exception)); Predicate isPackage = (s) -> s.startsWith("package " + firstPackage); diff --git a/src/test/java/org/jabref/architecture/MainArchitectureTestsWithArchUnit.java b/src/test/java/org/jabref/architecture/MainArchitectureTestsWithArchUnit.java index 6120da6b808..ab22b7dd5aa 100644 --- a/src/test/java/org/jabref/architecture/MainArchitectureTestsWithArchUnit.java +++ b/src/test/java/org/jabref/architecture/MainArchitectureTestsWithArchUnit.java @@ -1,20 +1,18 @@ package org.jabref.architecture; +import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; -import com.tngtech.archunit.junit.ArchUnitRunner; -import com.tngtech.archunit.lang.ArchRule; -import org.junit.runner.RunWith; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; -@RunWith(ArchUnitRunner.class) @AnalyzeClasses(packages = "org.jabref") public class MainArchitectureTestsWithArchUnit { @ArchTest - public static final ArchRule doNotUseApacheCommonsLang3 = - noClasses().that().areNotAnnotatedWith(ApacheCommonsLang3Allowed.class) - .should().accessClassesThat().resideInAPackage("org.apache.commons.lang3"); - + public static void doNotUseApacheCommonsLang3(JavaClasses classes) { + noClasses().that().areNotAnnotatedWith(ApacheCommonsLang3Allowed.class) + .should().accessClassesThat().resideInAPackage("org.apache.commons.lang3") + .check(classes); + } } diff --git a/src/test/java/org/jabref/architecture/TestArchitectureTests.java b/src/test/java/org/jabref/architecture/TestArchitectureTests.java index 1e98148ca4c..c37c450d8a0 100644 --- a/src/test/java/org/jabref/architecture/TestArchitectureTests.java +++ b/src/test/java/org/jabref/architecture/TestArchitectureTests.java @@ -39,15 +39,14 @@ public TestArchitectureTests() { exceptions.add(CLASS_ORG_JABREF_UPDATE_TIMESTAMP_LISTENER_TEST); exceptions.add(CLASS_ORG_JABREF_ENTRY_EDITOR_TEST); exceptions.add(CLASS_ORG_JABREF_LINKED_FILE_VIEW_MODEL_TEST); - } public static Stream data() { return Stream.of( - new String[][] { - {CLASS_ORG_JABREF_PREFERENCES}, - {CLASS_ORG_JABREF_GLOBALS} - }); + new String[][]{ + {CLASS_ORG_JABREF_PREFERENCES}, + {CLASS_ORG_JABREF_GLOBALS} + }); } @ParameterizedTest @@ -58,21 +57,21 @@ public void testsAreIndependent(String forbiddenPackage) throws IOException { try (Stream pathStream = Files.walk(Paths.get("src/test/"))) { List files = pathStream - .filter(p -> p.toString().endsWith(".java")) - .filter(p -> { - try { - return Files.readAllLines(p, StandardCharsets.UTF_8).stream().noneMatch(isExceptionClass); - } catch (IOException e) { - return false; - } - }) - .filter(p -> { - try { - return Files.readAllLines(p, StandardCharsets.UTF_8).stream().anyMatch(isForbiddenPackage); - } catch (IOException e) { - return false; - } - }).collect(Collectors.toList()); + .filter(p -> p.toString().endsWith(".java")) + .filter(p -> { + try { + return Files.readAllLines(p, StandardCharsets.UTF_8).stream().noneMatch(isExceptionClass); + } catch (IOException e) { + return false; + } + }) + .filter(p -> { + try { + return Files.readAllLines(p, StandardCharsets.UTF_8).stream().anyMatch(isForbiddenPackage); + } catch (IOException e) { + return false; + } + }).collect(Collectors.toList()); assertEquals(Collections.emptyList(), files, "The following classes are not allowed to depend on " + forbiddenPackage); } diff --git a/src/test/java/org/jabref/cleanup/CleanupActionsListModelTest.java b/src/test/java/org/jabref/cleanup/CleanupActionsListModelTest.java index 885a6d1e109..b44b0c572aa 100644 --- a/src/test/java/org/jabref/cleanup/CleanupActionsListModelTest.java +++ b/src/test/java/org/jabref/cleanup/CleanupActionsListModelTest.java @@ -68,7 +68,6 @@ public void removedAtIndexOkay() { ArgumentCaptor argument = ArgumentCaptor.forClass(ListDataEvent.class); verify(listener).intervalRemoved(argument.capture()); assertEquals(ListDataEvent.INTERVAL_REMOVED, argument.getValue().getType()); - } @Test @@ -91,7 +90,5 @@ public void removedAtIndexgreaterListSizeDoesNothing() { model.removeAtIndex((getDefaultFieldFormatterCleanups().size() + 1)); verifyZeroInteractions(listener); - } - } diff --git a/src/test/java/org/jabref/cli/AuxCommandLineTest.java b/src/test/java/org/jabref/cli/AuxCommandLineTest.java index 81e81952062..c366e54ffba 100644 --- a/src/test/java/org/jabref/cli/AuxCommandLineTest.java +++ b/src/test/java/org/jabref/cli/AuxCommandLineTest.java @@ -45,5 +45,4 @@ public void test() throws URISyntaxException, IOException { assertEquals(2, newDB.getEntries().size()); } } - } diff --git a/src/test/java/org/jabref/cli/JabRefCLITest.java b/src/test/java/org/jabref/cli/JabRefCLITest.java index f3c43c05fed..cd79ca7cecf 100644 --- a/src/test/java/org/jabref/cli/JabRefCLITest.java +++ b/src/test/java/org/jabref/cli/JabRefCLITest.java @@ -11,7 +11,7 @@ class JabRefCLITest { @Test void parsingLongOptions() { - JabRefCLI cli = new JabRefCLI(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); + JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); assertEquals("some/file", cli.getFileImport()); @@ -21,7 +21,7 @@ void parsingLongOptions() { @Test void parsingShortOptions() { - JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); + JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); assertEquals("some/file", cli.getFileImport()); @@ -31,7 +31,7 @@ void parsingShortOptions() { @Test void preferencesExport() { - JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-x=some/file"}); + JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"}); assertEquals(Collections.emptyList(), cli.getLeftOver()); assertEquals("some/file", cli.getPreferencesExport()); diff --git a/src/test/java/org/jabref/gui/AWTExceptionHandler.java b/src/test/java/org/jabref/gui/AWTExceptionHandler.java index a6e25848e4b..74586f4d709 100644 --- a/src/test/java/org/jabref/gui/AWTExceptionHandler.java +++ b/src/test/java/org/jabref/gui/AWTExceptionHandler.java @@ -21,5 +21,4 @@ public void assertNoExceptions() { throw new AssertionError("Uncaught exception in EDT", list.get(0)); } } - } diff --git a/src/test/java/org/jabref/gui/AbstractUITest.java b/src/test/java/org/jabref/gui/AbstractUITest.java index 579729783d2..dfc33236d98 100644 --- a/src/test/java/org/jabref/gui/AbstractUITest.java +++ b/src/test/java/org/jabref/gui/AbstractUITest.java @@ -45,8 +45,9 @@ protected void onSetUp() { } /** - * Returns the absolute Path of the given relative Path - * The backlashes are replaced with forwardslashes b/c assertJ can't type the former one on windows + * Returns the absolute Path of the given relative Path The backlashes are replaced with forwardslashes b/c assertJ + * can't type the former one on windows + * * @param relativePath the relative path to the resource database */ protected String getAbsolutePath(String relativePath) throws URISyntaxException { @@ -94,7 +95,7 @@ protected void takeScreenshot(AbstractWindowFixture dialog, String file screenshotTaker.saveComponentAsPng(dialog.target(), file.toString()); } - protected void assertColumnValue(JTableFixture table, int rowIndex, int columnIndex, String selectionValue){ + protected void assertColumnValue(JTableFixture table, int rowIndex, int columnIndex, String selectionValue) { String[][] tableContent; tableContent = table.contents(); diff --git a/src/test/java/org/jabref/gui/DialogTest.java b/src/test/java/org/jabref/gui/DialogTest.java index fb038b8588b..e97eb1a56dc 100644 --- a/src/test/java/org/jabref/gui/DialogTest.java +++ b/src/test/java/org/jabref/gui/DialogTest.java @@ -3,13 +3,13 @@ import javax.swing.JButton; import javax.swing.JDialog; - import org.assertj.swing.core.GenericTypeMatcher; import org.assertj.swing.dependency.jsr305.Nonnull; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.assertj.swing.finder.WindowFinder.findDialog; + /** * This test has been split to work, the other part can be found at DialogTest2 */ diff --git a/src/test/java/org/jabref/gui/EntryTableTest.java b/src/test/java/org/jabref/gui/EntryTableTest.java index 42dd811c1b3..d5f4fbfa861 100644 --- a/src/test/java/org/jabref/gui/EntryTableTest.java +++ b/src/test/java/org/jabref/gui/EntryTableTest.java @@ -11,13 +11,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; /** - * Specific Use-Case: - * I import a database. Then I doubleclick on the first entry in the table to open the entry editor. - * Then I click on the first entry again, and scroll through all of the lists entries, without having to click - * on the table again. + * Specific Use-Case: I import a database. Then I doubleclick on the first entry in the table to open the entry editor. + * Then I click on the first entry again, and scroll through all of the lists entries, without having to click on the + * table again. */ @Tag("GUITest") -public class EntryTableTest extends AbstractUITest{ +public class EntryTableTest extends AbstractUITest { private final static int SCROLL_ACTION_EXECUTION = 5; private final static String TEST_FILE_NAME = "testbib/testjabref.bib"; @@ -48,20 +47,19 @@ public void scrollThroughEntryList() throws Exception { assertColumnValue(entryTable, 0, TITLE_COLUMN_INDEX, entryTable.selectionValue()); //go throught the table and check if the entry with the correct index is selected - for (int i=0; i < SCROLL_ACTION_EXECUTION; i++) { + for (int i = 0; i < SCROLL_ACTION_EXECUTION; i++) { robot().pressAndReleaseKey(DOWN); assertNotNull(entryTable.selectionValue()); - assertColumnValue(entryTable, i+1, TITLE_COLUMN_INDEX, entryTable.selectionValue()); + assertColumnValue(entryTable, i + 1, TITLE_COLUMN_INDEX, entryTable.selectionValue()); } //do the same going up again for (int i = SCROLL_ACTION_EXECUTION; i > 0; i--) { robot().pressAndReleaseKey(UP); assertNotNull(entryTable.selectionValue()); - assertColumnValue(entryTable, i-1, TITLE_COLUMN_INDEX, entryTable.selectionValue()); + assertColumnValue(entryTable, i - 1, TITLE_COLUMN_INDEX, entryTable.selectionValue()); } closeDatabase(); exitJabRef(); } - } diff --git a/src/test/java/org/jabref/gui/IdFetcherDialogTest.java b/src/test/java/org/jabref/gui/IdFetcherDialogTest.java index 023d2c5f0fa..65a1330b25a 100644 --- a/src/test/java/org/jabref/gui/IdFetcherDialogTest.java +++ b/src/test/java/org/jabref/gui/IdFetcherDialogTest.java @@ -110,7 +110,6 @@ public boolean test() { entryTable.requireRowCount(1); } - public static Stream instancesToTest() { return Stream.of( new Object[]{"BibTeX", "DOI", "10.1002/9781118257517"}, @@ -119,5 +118,4 @@ public static Stream instancesToTest() { new Object[]{"biblatex", "ISBN", "9780321356680"} ); } - } diff --git a/src/test/java/org/jabref/gui/ParameterizedDialogNewEntryTest.java b/src/test/java/org/jabref/gui/ParameterizedDialogNewEntryTest.java index 6ce2bb71083..2cfd70baa8a 100644 --- a/src/test/java/org/jabref/gui/ParameterizedDialogNewEntryTest.java +++ b/src/test/java/org/jabref/gui/ParameterizedDialogNewEntryTest.java @@ -188,5 +188,4 @@ public static Stream instancesToTest() { ); // @formatter:on } - } diff --git a/src/test/java/org/jabref/gui/ParameterizedDialogTest.java b/src/test/java/org/jabref/gui/ParameterizedDialogTest.java index 07d1f0a63e8..de3d6dcfc43 100644 --- a/src/test/java/org/jabref/gui/ParameterizedDialogTest.java +++ b/src/test/java/org/jabref/gui/ParameterizedDialogTest.java @@ -36,13 +36,13 @@ protected boolean isMatching(JDialog dialog) { findDialog(matcher).withTimeout(10_000).using(robot()).close(); } else { findDialog(matcher).withTimeout(10_000).using(robot()) - .button(new GenericTypeMatcher(JButton.class) { + .button(new GenericTypeMatcher(JButton.class) { - @Override - protected boolean isMatching(@Nonnull JButton jButton) { - return buttonName.equals(jButton.getText()); - } - }).click(); + @Override + protected boolean isMatching(@Nonnull JButton jButton) { + return buttonName.equals(jButton.getText()); + } + }).click(); } if (createDatabase) { closeDatabase(); @@ -130,5 +130,4 @@ public static Stream instancesToTest() { ); // @formatter:on } - } diff --git a/src/test/java/org/jabref/gui/ParameterizedMenuNewEntryTest.java b/src/test/java/org/jabref/gui/ParameterizedMenuNewEntryTest.java index 31a66bb3b6c..67efff9e04b 100644 --- a/src/test/java/org/jabref/gui/ParameterizedMenuNewEntryTest.java +++ b/src/test/java/org/jabref/gui/ParameterizedMenuNewEntryTest.java @@ -61,5 +61,4 @@ public static Stream instancesToTest() { ); // @formatter:on } - } diff --git a/src/test/java/org/jabref/gui/autocompleter/PersonNameSuggestionProviderTest.java b/src/test/java/org/jabref/gui/autocompleter/PersonNameSuggestionProviderTest.java index dcb9d07e32c..2ae76c383b6 100644 --- a/src/test/java/org/jabref/gui/autocompleter/PersonNameSuggestionProviderTest.java +++ b/src/test/java/org/jabref/gui/autocompleter/PersonNameSuggestionProviderTest.java @@ -16,7 +16,7 @@ public class PersonNameSuggestionProviderTest { - private static final Author vassilisKostakos = new Author("Vassilis", "V.", "", "Kostakos", ""); + private final Author vassilisKostakos = new Author("Vassilis", "V.", "", "Kostakos", ""); private PersonNameSuggestionProvider autoCompleter; private BibEntry entry; diff --git a/src/test/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModelTest.java b/src/test/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModelTest.java index 57279df9b55..32450d93cc4 100644 --- a/src/test/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModelTest.java +++ b/src/test/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModelTest.java @@ -16,8 +16,8 @@ public class FileAnnotationViewModelTest { public void removeOnlyLineBreaksNotPrecededByPeriodOrColon() { String content = "This is content"; String marking = String.format("This is paragraph 1.%n" + - "This is paragr-%naph 2, and it crosses%nseveral lines,%nnow you can see next paragraph:%n" - + "This is paragraph%n3."); + "This is paragr-%naph 2, and it crosses%nseveral lines,%nnow you can see next paragraph:%n" + + "This is paragraph%n3."); FileAnnotation linkedFileAnnotation = new FileAnnotation("John", LocalDateTime.now(), 3, content, FileAnnotationType.FREETEXT, Optional.empty()); FileAnnotation annotation = new FileAnnotation("Jaroslav Kucha ˇr", LocalDateTime.parse("2017-07-20T10:11:30"), 1, marking, FileAnnotationType.HIGHLIGHT, Optional.of(linkedFileAnnotation)); @@ -30,8 +30,8 @@ public void removeOnlyLineBreaksNotPrecededByPeriodOrColon() { assertEquals("This is content", annotationViewModel.getContent()); assertEquals(String.format("This is paragraph 1.%n" + - "This is paragraph 2, and it crosses several lines, now you can see next paragraph:%n" - + "This is paragraph 3."), - annotationViewModel.getMarking()); + "This is paragraph 2, and it crosses several lines, now you can see next paragraph:%n" + + "This is paragraph 3."), + annotationViewModel.getMarking()); } } diff --git a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java index c2e2773a31f..e25495e99f2 100644 --- a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java +++ b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java @@ -51,5 +51,4 @@ public void test() throws Exception { List actual = util.findAssociatedNotLinkedFiles(entry); assertEquals(expected, actual); } - } diff --git a/src/test/java/org/jabref/gui/groups/GroupNodeViewModelTest.java b/src/test/java/org/jabref/gui/groups/GroupNodeViewModelTest.java index 05941f3a4ab..aa369649d73 100644 --- a/src/test/java/org/jabref/gui/groups/GroupNodeViewModelTest.java +++ b/src/test/java/org/jabref/gui/groups/GroupNodeViewModelTest.java @@ -154,7 +154,7 @@ public void draggedOnTopOfGroupAddsBeforeItWhenSourceGroupWasBefore() throws Exc @Test public void entriesAreAddedCorrectly() { String groupName = "group"; - ExplicitGroup group = new ExplicitGroup(groupName, GroupHierarchyType.INDEPENDENT,','); + ExplicitGroup group = new ExplicitGroup(groupName, GroupHierarchyType.INDEPENDENT, ','); BibEntry entry = new BibEntry(); databaseContext.getDatabase().insertEntry(entry); diff --git a/src/test/java/org/jabref/gui/groups/GroupTreeViewModelTest.java b/src/test/java/org/jabref/gui/groups/GroupTreeViewModelTest.java index afa4ad53eba..4b0c57c6448 100644 --- a/src/test/java/org/jabref/gui/groups/GroupTreeViewModelTest.java +++ b/src/test/java/org/jabref/gui/groups/GroupTreeViewModelTest.java @@ -44,7 +44,7 @@ public void rootGroupIsAllEntriesByDefault() throws Exception { @Test public void explicitGroupsAreRemovedFromEntriesOnDelete() { - ExplicitGroup group = new ExplicitGroup("group", GroupHierarchyType.INDEPENDENT,','); + ExplicitGroup group = new ExplicitGroup("group", GroupHierarchyType.INDEPENDENT, ','); BibEntry entry = new BibEntry(); databaseContext.getDatabase().insertEntry(entry); diff --git a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java index 38301e769ef..ec04c0d99e7 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java @@ -41,7 +41,6 @@ public class EntryFromFileCreatorManagerTest { public void setUp() { externalFileTypes = mock(ExternalFileTypes.class, Answers.RETURNS_DEEP_STUBS); when(externalFileTypes.getExternalFileTypeByExt("pdf")).thenReturn(Optional.empty()); - } @Test @@ -58,7 +57,7 @@ public void testGetCreator() { @Test public void testAddEntrysFromFiles() throws IOException { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); - InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { + InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { ParserResult result = new BibtexParser(prefs, new DummyFileUpdateMonitor()).parse(reader); BibDatabase database = result.getDatabase(); diff --git a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java index 17817eeb6b4..575d82852b0 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java @@ -55,6 +55,5 @@ public void testCreationOfEntryNotInDatabase() { assertTrue(entry.get().getField("file").get().endsWith(":PDF")); assertEquals(Optional.of(ImportDataTest.FILE_NOT_IN_DATABASE.getName()), entry.get().getField("title")); - } } diff --git a/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java b/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java index 5c47dec695e..77e7d20cc36 100644 --- a/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java +++ b/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java @@ -209,7 +209,7 @@ void testBuiltInListsIncludeAllBuiltInAbbreviations() { .observableArrayList(JournalAbbreviationLoader.getBuiltInAbbreviations()); ObservableList actualAbbreviations = FXCollections .observableArrayList(viewModel.abbreviationsProperty().stream() - .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); + .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); } @@ -224,7 +224,7 @@ void testBuiltInListsStandardIEEEIncludesAllBuiltIEEEAbbreviations() throws Exce .observableArrayList(JournalAbbreviationLoader.getOfficialIEEEAbbreviations()); ObservableList actualAbbreviations = FXCollections .observableArrayList(viewModel.abbreviationsProperty().stream() - .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); + .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); } @@ -443,7 +443,7 @@ void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throw void testSaveExternalFilesListToPreferences() throws Exception { addFourTestFileToViewModelAndPreferences(); List expected = Stream.of(testFile1Entries, testFile3Entries, testFile4Entries, testFile5EntriesWithDuplicate) - .map(Path::toString).collect(Collectors.toList()); + .map(Path::toString).collect(Collectors.toList()); verify(abbreviationPreferences).setExternalJournalLists(expected); } @@ -478,6 +478,6 @@ private void addFourTestFileToViewModelAndPreferences() throws Exception { */ private void selectLastAbbreviation() { viewModel.currentAbbreviationProperty() - .set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1)); + .set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1)); } } diff --git a/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java b/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java index 7878cb9c678..c9c34e25e0e 100644 --- a/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java +++ b/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java @@ -50,7 +50,6 @@ public void testInvalidKeyBindingIsNotSaved() { assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent)); } - @Test public void testSpecialKeysValidKeyBindingIsSaved() { setKeyBindingViewModel(KeyBinding.IMPORT_INTO_NEW_DATABASE); diff --git a/src/test/java/org/jabref/gui/search/SearchResultsTest.java b/src/test/java/org/jabref/gui/search/SearchResultsTest.java index 6daafde1f70..1e2badcc2ad 100644 --- a/src/test/java/org/jabref/gui/search/SearchResultsTest.java +++ b/src/test/java/org/jabref/gui/search/SearchResultsTest.java @@ -21,7 +21,6 @@ public class SearchResultsTest extends AssertJSwingJUnitTestCase { private FrameFixture frameFixture; - @BeforeAll public static void before() { FailOnThreadViolationRepaintManager.uninstall(); @@ -94,5 +93,4 @@ public void testSearchInvalidQuery() { Assert.assertTrue(entries.stream().noneMatch(entry -> entry.isSearchHit())); */ } - } diff --git a/src/test/java/org/jabref/gui/util/FileDialogConfigurationTest.java b/src/test/java/org/jabref/gui/util/FileDialogConfigurationTest.java index 74c90fd5f9b..2a19e5593a6 100644 --- a/src/test/java/org/jabref/gui/util/FileDialogConfigurationTest.java +++ b/src/test/java/org/jabref/gui/util/FileDialogConfigurationTest.java @@ -30,7 +30,6 @@ void testWithValidDirectoryString(@TempDirectory.TempDir Path folder) { assertEquals(Optional.of(Paths.get(tempFolder)), fileDialogConfiguration.getInitialDirectory()); } - @Test void testWithValidDirectoryPath(@TempDirectory.TempDir Path tempFolder) { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() @@ -74,10 +73,8 @@ void testSingleExtension() { assertEquals(filter.getExtensions(), fileDialogConfiguration.getDefaultExtension().getExtensions()); } - private FileChooser.ExtensionFilter toFilter(String description, FileType extension) { return new FileChooser.ExtensionFilter(description, extension.getExtensions().stream().map(ending -> "*." + ending).collect(Collectors.toList())); } - } diff --git a/src/test/java/org/jabref/gui/util/RecursiveTreeItemTest.java b/src/test/java/org/jabref/gui/util/RecursiveTreeItemTest.java index 912ad78feb7..343ed8d63b1 100644 --- a/src/test/java/org/jabref/gui/util/RecursiveTreeItemTest.java +++ b/src/test/java/org/jabref/gui/util/RecursiveTreeItemTest.java @@ -16,7 +16,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - class RecursiveTreeItemTest { private RecursiveTreeItem rootTreeItem; diff --git a/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerTest.java b/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerTest.java index 744682b6f9c..fea23323f6c 100644 --- a/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerTest.java +++ b/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerTest.java @@ -15,5 +15,4 @@ public void backupFileNameIsCorrectlyGeneratedWithinTmpDirectory() { Path savPath = BackupManager.getBackupPath(bibPath); assertEquals(Paths.get("tmp", "test.bib.sav"), savPath); } - } diff --git a/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java b/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java index e5cd84faa34..c745a684457 100644 --- a/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java +++ b/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java @@ -19,11 +19,11 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; -import static org.junit.jupiter.api.Assertions.*; - import org.junit.jupiter.api.Assertions; import org.mockito.Answers; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; public class BibEntryAssert { @@ -32,9 +32,9 @@ public class BibEntryAssert { * Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to * contain a single entry * - * @param clazz the class where to call `getResourceAsStream` + * @param clazz the class where to call `getResourceAsStream` * @param resourceName the resource to read - * @param entry the entry to compare with + * @param entry the entry to compare with */ public static void assertEquals(Class clazz, String resourceName, BibEntry entry) throws IOException { @@ -50,9 +50,9 @@ public static void assertEquals(Class clazz, String resourceName, BibEntry en * Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to * contain a single entry * - * @param clazz the class where to call `getResourceAsStream` + * @param clazz the class where to call `getResourceAsStream` * @param resourceName the resource to read - * @param asIsEntries a list containing a single entry to compare with + * @param asIsEntries a list containing a single entry to compare with */ public static void assertEquals(Class clazz, String resourceName, List asIsEntries) throws IOException { @@ -79,7 +79,7 @@ private static List getListFromInputStream(InputStream is) throws IOEx * Reads a bibtex database from the given InputStream. The list is compared with the given list. * * @param expectedInputStream the inputStream reading the entry from - * @param actualEntries a list containing a single entry to compare with + * @param actualEntries a list containing a single entry to compare with */ public static void assertEquals(InputStream expectedInputStream, List actualEntries) throws IOException { @@ -102,7 +102,7 @@ public static void assertEquals(List expectedEntries, InputStream actu * compared to the given entry * * @param expected the inputStream reading the entry from - * @param actual the entry to compare with + * @param actual the entry to compare with */ public static void assertEquals(InputStream expected, BibEntry actual) throws IOException { @@ -110,11 +110,13 @@ public static void assertEquals(InputStream expected, BibEntry actual) } /** - * Compares two InputStreams. For each InputStream a list will be created. expectedIs is read directly, actualIs is filtered through importer to convert to a list of BibEntries. - * @param expectedIs A BibtexImporter InputStream. + * Compares two InputStreams. For each InputStream a list will be created. expectedIs is read directly, actualIs is + * filtered through importer to convert to a list of BibEntries. + * + * @param expectedIs A BibtexImporter InputStream. * @param fileToImport The path to the file to be imported. - * @param importer The fileformat you want to use to read the passed file to get the list of expected BibEntries - * @throws IOException + * @param importer The fileformat you want to use to read the passed file to get the list of expected + * BibEntries */ public static void assertEquals(InputStream expectedIs, Path fileToImport, Importer importer) throws IOException { @@ -127,16 +129,18 @@ public static void assertEquals(InputStream expectedIs, URL fileToImport, Import } /** - * Compares a list of BibEntries to an InputStream. actualIs is filtered through importerForActualIs to convert to a list of BibEntries. - * @param expected A BibtexImporter InputStream. + * Compares a list of BibEntries to an InputStream. actualIs is filtered through importerForActualIs to convert to a + * list of BibEntries. + * + * @param expected A BibtexImporter InputStream. * @param fileToImport The path to the file to be imported. - * @param importer The fileformat you want to use to read the passed file to get the list of expected BibEntries - * @throws IOException + * @param importer The fileformat you want to use to read the passed file to get the list of expected + * BibEntries */ public static void assertEquals(List expected, Path fileToImport, Importer importer) throws IOException { List actualEntries = importer.importDatabase(fileToImport, StandardCharsets.UTF_8) - .getDatabase().getEntries(); + .getDatabase().getEntries(); // explicit reference of Assertions is needed here to disambiguate from the methods defined by this class Assertions.assertEquals(expected, actualEntries); } diff --git a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java index 68a31d6eb54..a340fdc7b59 100644 --- a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java +++ b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java @@ -509,5 +509,4 @@ public void roundTripWithPrecedingCommentAndModificationTest() throws IOExceptio assertEquals(expected, actual); } - } diff --git a/src/test/java/org/jabref/logic/bibtex/FieldContentParserTest.java b/src/test/java/org/jabref/logic/bibtex/FieldContentParserTest.java index b63242b6f30..a2d40588f96 100644 --- a/src/test/java/org/jabref/logic/bibtex/FieldContentParserTest.java +++ b/src/test/java/org/jabref/logic/bibtex/FieldContentParserTest.java @@ -13,7 +13,6 @@ public class FieldContentParserTest { private FieldContentParser parser; - @BeforeEach public void setUp() throws Exception { FieldContentParserPreferences prefs = new FieldContentParserPreferences(Collections.emptyList()); diff --git a/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java b/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java index 7b822bb1b98..aafd1e80c8e 100644 --- a/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java +++ b/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java @@ -28,7 +28,7 @@ public void normalizeNewlineInAbstractField() throws Exception { // The newlines are normalized according to the globally configured newline setting in the formatter String expected = "{" + "lorem" + OS.NEWLINE + " ipsum lorem ipsum" + OS.NEWLINE - + "lorem ipsum " + + "lorem ipsum " + OS.NEWLINE + "lorem ipsum" + OS.NEWLINE + "test" + "}"; @@ -69,7 +69,7 @@ public void preserveNewlineInReviewField() throws Exception { String text = "lorem ipsum lorem ipsum" + OS.NEWLINE + "lorem ipsum lorem ipsum" + OS.NEWLINE; String result = formatter.format(text, fieldName); - String expected = "{"+text+"}"; + String expected = "{" + text + "}"; assertEquals(expected, result); } @@ -126,5 +126,4 @@ public void hashEnclosedWordsGetRealStringsInMonthFieldBecauseMonthIsStandardFie String text = "#jan# - #feb#"; assertEquals("jan #{ - } # feb", formatter.format(text, "month")); } - } diff --git a/src/test/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiffTest.java b/src/test/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiffTest.java index cdf7115824c..3061f648959 100644 --- a/src/test/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiffTest.java +++ b/src/test/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiffTest.java @@ -19,5 +19,4 @@ public void compareOfEmptyDatabasesReportsNoDifferences() throws Exception { assertEquals(Collections.emptyList(), diff.getBibStringDifferences()); assertEquals(Collections.emptyList(), diff.getEntryDifferences()); } - } diff --git a/src/test/java/org/jabref/logic/bibtex/comparator/BibtexStringComparatorTest.java b/src/test/java/org/jabref/logic/bibtex/comparator/BibtexStringComparatorTest.java index 9a6d3bbbb26..d256f4472b4 100644 --- a/src/test/java/org/jabref/logic/bibtex/comparator/BibtexStringComparatorTest.java +++ b/src/test/java/org/jabref/logic/bibtex/comparator/BibtexStringComparatorTest.java @@ -12,7 +12,6 @@ public class BibtexStringComparatorTest { private final BibtexStringComparator bsc1 = new BibtexStringComparator(false); private final BibtexStringComparator bsc2 = new BibtexStringComparator(true); - @Test public void test() { BibtexString bs1 = new BibtexString("VLSI", "Very Large Scale Integration"); @@ -42,7 +41,5 @@ public void test() { // bs4 after bs1 if considering that bs4 contains bs1 assertTrue(bsc2.compare(bs1, bs4) < 0); assertTrue(bsc2.compare(bs4, bs1) > 0); - } - } diff --git a/src/test/java/org/jabref/logic/bibtex/comparator/MetaDataDiffTest.java b/src/test/java/org/jabref/logic/bibtex/comparator/MetaDataDiffTest.java index 38c9b152f61..89c212c3839 100644 --- a/src/test/java/org/jabref/logic/bibtex/comparator/MetaDataDiffTest.java +++ b/src/test/java/org/jabref/logic/bibtex/comparator/MetaDataDiffTest.java @@ -19,5 +19,4 @@ public void compareWithSameContentSelectorsDoesNotReportAnyDiffs() throws Except assertEquals(Optional.empty(), MetaDataDiff.compare(one, two)); } - } diff --git a/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyGeneratorTest.java b/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyGeneratorTest.java index 17134b98dc8..4ed5b5bb728 100644 --- a/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyGeneratorTest.java +++ b/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyGeneratorTest.java @@ -227,8 +227,8 @@ public void testMakeLabelAndCheckLegalKeysAccentGrave() throws ParseException { } /** - * Tests if checkLegalKey replaces Non-ASCII chars. - * There are quite a few chars that should be replaced. Perhaps there is a better method than the current. + * Tests if checkLegalKey replaces Non-ASCII chars. There are quite a few chars that should be replaced. Perhaps + * there is a better method than the current. * * @see BibtexKeyGenerator#checkLegalKey(String) */ @@ -799,8 +799,8 @@ public void shortTitle() { } /** - * Tests [camel] - */ + * Tests [camel] + */ @Test public void camel() { // camel capitalises and concatenates all the words of the title diff --git a/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithDatabaseTest.java b/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithDatabaseTest.java index 20f7c634dcf..a28d412bc35 100644 --- a/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithDatabaseTest.java +++ b/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithDatabaseTest.java @@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - class MakeLabelWithDatabaseTest { private BibDatabase database; diff --git a/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithoutDatabaseTest.java b/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithoutDatabaseTest.java index 3ca979b9be3..10c02b89016 100644 --- a/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithoutDatabaseTest.java +++ b/src/test/java/org/jabref/logic/bibtexkeypattern/MakeLabelWithoutDatabaseTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - class MakeLabelWithoutDatabaseTest { private BibEntry entry; @@ -36,5 +35,4 @@ void makeEditorLabelForFileSearch() { String label = BibtexKeyGenerator.generateKey(localEntry, "auth"); assertEquals("Doe", label); } - } diff --git a/src/test/java/org/jabref/logic/bst/BibtexCaseChangersTest.java b/src/test/java/org/jabref/logic/bst/BibtexCaseChangersTest.java index a6214a7f0c8..bcdcac3b4ce 100644 --- a/src/test/java/org/jabref/logic/bst/BibtexCaseChangersTest.java +++ b/src/test/java/org/jabref/logic/bst/BibtexCaseChangersTest.java @@ -77,7 +77,6 @@ public void testChangeCase() { assertCaseChangerTitleLowers("On notions of information transfer in {VLSI} circuits", "On Notions of Information Transfer in {VLSI} Circuits"); - } @Test @@ -123,7 +122,6 @@ public void testTitleCase() { private void assertCaseChangerTitleLowers(final String string, final String string2) { assertEquals(string, BibtexCaseChanger.changeCase(string2, FORMAT_MODE.TITLE_LOWERS)); - } private void assertCaseChangerAllLowers(final String string, final String string2) { diff --git a/src/test/java/org/jabref/logic/bst/BibtexNameFormatterTest.java b/src/test/java/org/jabref/logic/bst/BibtexNameFormatterTest.java index 8fd58e42ff1..5a457bc0f7d 100644 --- a/src/test/java/org/jabref/logic/bst/BibtexNameFormatterTest.java +++ b/src/test/java/org/jabref/logic/bst/BibtexNameFormatterTest.java @@ -54,7 +54,6 @@ public void testFormatName() { assertNameFormatB("P.~{\\'E}. Victor", "Paul {\\'E}mile Victor and and de la Cierva y Codorn{\\’\\i}u, Juan"); assertNameFormatC("Paul~{\\'E}mile Victor", "Paul {\\'E}mile Victor and and de la Cierva y Codorn{\\’\\i}u, Juan"); - } private void assertNameFormat(String string, String string2, int which, String format) { @@ -114,5 +113,4 @@ public void testNumberOfChars() { assertEquals(8, BibtexNameFormatter.numberOfChars("Vall{e}e", -1)); assertEquals(6, BibtexNameFormatter.numberOfChars("Vall{\\'e this will be skipped}e", -1)); } - } diff --git a/src/test/java/org/jabref/logic/bst/BibtexWidthTest.java b/src/test/java/org/jabref/logic/bst/BibtexWidthTest.java index 924165bf5e0..015eb900300 100644 --- a/src/test/java/org/jabref/logic/bst/BibtexWidthTest.java +++ b/src/test/java/org/jabref/logic/bst/BibtexWidthTest.java @@ -1,7 +1,5 @@ package org.jabref.logic.bst; - - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/src/test/java/org/jabref/logic/bst/TestVM.java b/src/test/java/org/jabref/logic/bst/TestVM.java index a1e853b8c83..54bf2f0b7c1 100644 --- a/src/test/java/org/jabref/logic/bst/TestVM.java +++ b/src/test/java/org/jabref/logic/bst/TestVM.java @@ -58,7 +58,6 @@ public void testVMSimple() throws RecognitionException, IOException { assertEquals(1, vm.getEntries().size()); assertEquals(5, vm.getEntries().get(0).getFields().size()); assertEquals(38, vm.getFunctions().size()); - } @Test @@ -76,7 +75,6 @@ public void testLabel() throws RecognitionException, IOException { assertEquals("Effective work practices for floss development: A model and propositions", vm .getStack() .pop()); - } @Test @@ -171,8 +169,8 @@ public void testVMArithmetic() throws RecognitionException { assertEquals(3, vm.getStack().pop()); assertEquals(2, vm.getStack().pop()); assertEquals(0, vm.getStack().size()); - } + @Test public void testVMArithmetic2() throws RecognitionException { VM vm = new VM("FUNCTION {test} { " + "#1 \"HELLO\" + #5 #2 - }" + "EXECUTE {test}"); @@ -666,5 +664,4 @@ public void testHypthenatedName() throws RecognitionException, IOException { private BibEntry t1BibtexEntry() throws IOException { return TestVM.bibtexString2BibtexEntry(t1BibtexString()); } - } diff --git a/src/test/java/org/jabref/logic/bst/TextPrefixFunctionTest.java b/src/test/java/org/jabref/logic/bst/TextPrefixFunctionTest.java index 353a7643314..d91eadd8920 100644 --- a/src/test/java/org/jabref/logic/bst/TextPrefixFunctionTest.java +++ b/src/test/java/org/jabref/logic/bst/TextPrefixFunctionTest.java @@ -23,5 +23,4 @@ public void testPrefix() { private static void assertPrefix(final String string, final String string2) { assertEquals(string, BibtexTextPrefix.textPrefix(5, string2, s -> fail("Should not Warn! text.prefix$ should be " + string + " for (5) " + string2))); } - } diff --git a/src/test/java/org/jabref/logic/citationstyle/CitationStyleGeneratorTest.java b/src/test/java/org/jabref/logic/citationstyle/CitationStyleGeneratorTest.java index 890eed33bea..3b9189afed5 100644 --- a/src/test/java/org/jabref/logic/citationstyle/CitationStyleGeneratorTest.java +++ b/src/test/java/org/jabref/logic/citationstyle/CitationStyleGeneratorTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class CitationStyleGeneratorTest { @Test @@ -116,5 +115,4 @@ public void testXslFoFormat() { String actualCitation = CitationStyleGenerator.generateCitation(entry, style, format); assertEquals(expectedCitation, actualCitation); } - } diff --git a/src/test/java/org/jabref/logic/citationstyle/CitationStyleTest.java b/src/test/java/org/jabref/logic/citationstyle/CitationStyleTest.java index b63d9d94f0e..040f7a7155d 100644 --- a/src/test/java/org/jabref/logic/citationstyle/CitationStyleTest.java +++ b/src/test/java/org/jabref/logic/citationstyle/CitationStyleTest.java @@ -27,5 +27,4 @@ public void testDefaultCitation() { assertEquals(expected, citation); } - } diff --git a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java index 124e08b2304..567dffd1f6a 100644 --- a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java @@ -350,5 +350,4 @@ void cleanupWithDisabledFieldFormatterChangesNothing() { worker.cleanup(preset, entry); assertEquals(Optional.of("01"), entry.getField("month")); } - } diff --git a/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupTest.java index 57a87a1493d..196263f76ea 100644 --- a/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupTest.java @@ -3,8 +3,8 @@ import java.util.HashMap; import java.util.Map; -import org.jabref.logic.formatter.casechanger.UpperCaseFormatter; import org.jabref.logic.formatter.bibtexfields.UnicodeToLatexFormatter; +import org.jabref.logic.formatter.casechanger.UpperCaseFormatter; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexEntryTypes; @@ -34,7 +34,6 @@ public void setUp() { fieldMap.put("doi", "jabrefdoi"); fieldMap.put("issn", "jabrefissn"); entry.setField(fieldMap); - } @Test @@ -91,5 +90,4 @@ public void testCleanupKeyFieldCleansUpKeyField() throws Exception { assertEquals("Fran{\\c{c}}ois-Marie Arouet", entry.getField(BibEntry.KEY_FIELD).get()); } - } diff --git a/src/test/java/org/jabref/logic/cleanup/ISSNCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/ISSNCleanupTest.java index fbe92bc4a65..aa6dc774647 100644 --- a/src/test/java/org/jabref/logic/cleanup/ISSNCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/ISSNCleanupTest.java @@ -52,5 +52,4 @@ public void cleanupISSNJunkStaysJunk() { worker.cleanup(preset, entry); assertEquals(Optional.of("Banana"), entry.getField("issn")); } - } diff --git a/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java b/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java index a683dd2bff5..85051a17351 100644 --- a/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java @@ -35,21 +35,19 @@ @ExtendWith(TempDirectory.class) public class BibTeXMLExporterTestFiles { + private static Path resourceDir; public BibDatabaseContext databaseContext; public Charset charset; public Path tempFile; public BibTeXMLExporter bibtexmlExportFormat; public BibtexImporter testImporter; - private static Path resourceDir; - public static Stream fileNames() throws IOException, URISyntaxException { resourceDir = Paths.get(MSBibExportFormatTestFiles.class.getResource("BibTeXMLExporterTestArticle.bib").toURI()).getParent(); -// System.out.println(resourceDir); try (Stream stream = Files.list(resourceDir)) { return stream.map(n -> n.getFileName().toString()).filter(n -> n.endsWith(".bib")) - .filter(n -> n.startsWith("BibTeXML")).collect(Collectors.toList()).stream(); + .filter(n -> n.startsWith("BibTeXML")).collect(Collectors.toList()).stream(); } } @@ -71,7 +69,7 @@ public final void testPerformExport(String filename) throws IOException, SaveExc String tempFilePath = tempFile.toAbsolutePath().toString(); List entries = testImporter.importDatabase(importFile, StandardCharsets.UTF_8).getDatabase() - .getEntries(); + .getEntries(); bibtexmlExportFormat.export(databaseContext, tempFile, charset, entries); @@ -79,6 +77,6 @@ public final void testPerformExport(String filename) throws IOException, SaveExc Builder test = Input.from(Files.newInputStream(Paths.get(tempFilePath))); assertThat(test, CompareMatcher.isSimilarTo(control) - .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } } diff --git a/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java b/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java index 1d988120573..e30ecf77ca8 100644 --- a/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java +++ b/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java @@ -218,9 +218,9 @@ void writeGroupsAndEncoding() throws Exception { // @formatter:off assertEquals( "% Encoding: US-ASCII" + OS.NEWLINE + - OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: grouping:" + OS.NEWLINE - + "0 AllEntriesGroup:;" + OS.NEWLINE + + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 StaticGroup:test\\;2\\;1\\;\\;\\;\\;;" + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); // @formatter:on @@ -297,7 +297,7 @@ void roundtripWithUserComment() throws Exception { new Defaults(BibDatabaseMode.BIBTEX)); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); - try (Scanner scanner = new Scanner(testBibtexFile,encoding.name())) { + try (Scanner scanner = new Scanner(testBibtexFile, encoding.name())) { assertEquals(scanner.useDelimiter("\\A").next(), stringWriter.toString()); } } @@ -341,7 +341,7 @@ void roundtripWithUserCommentBeforeStringAndChange() throws Exception { databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); - try (Scanner scanner = new Scanner(testBibtexFile,encoding.name())) { + try (Scanner scanner = new Scanner(testBibtexFile, encoding.name())) { assertEquals(scanner.useDelimiter("\\A").next(), stringWriter.toString()); } } @@ -358,7 +358,7 @@ void roundtripWithUnknownMetaData() throws Exception { new Defaults(BibDatabaseMode.BIBTEX)); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); - try (Scanner scanner = new Scanner(testBibtexFile,encoding.name())) { + try (Scanner scanner = new Scanner(testBibtexFile, encoding.name())) { assertEquals(scanner.useDelimiter("\\A").next(), stringWriter.toString()); } } @@ -419,7 +419,6 @@ void reformatStringIfAskedToDoSo() throws Exception { databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals(OS.NEWLINE + "@String{name = {content}}" + OS.NEWLINE, stringWriter.toString()); - } @Test @@ -525,21 +524,21 @@ void writeEntriesSorted() throws Exception { assertEquals( OS.NEWLINE + - "@Article{," + OS.NEWLINE + - " author = {A}," + OS.NEWLINE + + "@Article{," + OS.NEWLINE + + " author = {A}," + OS.NEWLINE + " year = {2010}," + OS.NEWLINE + - "}" + OS.NEWLINE + OS.NEWLINE + - "@Article{," + OS.NEWLINE + - " author = {A}," + OS.NEWLINE + + "}" + OS.NEWLINE + OS.NEWLINE + + "@Article{," + OS.NEWLINE + + " author = {A}," + OS.NEWLINE + + " year = {2000}," + OS.NEWLINE + + "}" + OS.NEWLINE + OS.NEWLINE + + "@Article{," + OS.NEWLINE + + " author = {B}," + OS.NEWLINE + " year = {2000}," + OS.NEWLINE + - "}" + OS.NEWLINE + OS.NEWLINE + - "@Article{," + OS.NEWLINE + - " author = {B}," + OS.NEWLINE + - " year = {2000}," + OS.NEWLINE + - "}" + OS.NEWLINE + OS.NEWLINE + - "@Comment{jabref-meta: databaseType:bibtex;}" - + OS.NEWLINE + OS.NEWLINE + - "@Comment{jabref-meta: saveOrderConfig:specified;author;false;year;true;abstract;false;}" + + "}" + OS.NEWLINE + OS.NEWLINE + + "@Comment{jabref-meta: databaseType:bibtex;}" + + OS.NEWLINE + OS.NEWLINE + + "@Comment{jabref-meta: saveOrderConfig:specified;author;false;year;true;abstract;false;}" + OS.NEWLINE, stringWriter.toString()); } diff --git a/src/test/java/org/jabref/logic/exporter/CsvExportFormatTest.java b/src/test/java/org/jabref/logic/exporter/CsvExportFormatTest.java index 776b1d84235..a2e7cd9ccfa 100644 --- a/src/test/java/org/jabref/logic/exporter/CsvExportFormatTest.java +++ b/src/test/java/org/jabref/logic/exporter/CsvExportFormatTest.java @@ -15,9 +15,9 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junitpioneer.jupiter.TempDirectory; import org.mockito.Answers; @@ -28,9 +28,9 @@ @ExtendWith(TempDirectory.class) public class CsvExportFormatTest { - private Exporter exportFormat; public BibDatabaseContext databaseContext; public Charset charset; + private Exporter exportFormat; @BeforeEach public void setUp() { @@ -64,8 +64,8 @@ public void testPerformExportForSingleAuthor(@TempDirectory.TempDir Path testFol List lines = Files.readAllLines(path); assertEquals(2, lines.size()); assertEquals( - "10,\"\",\"\",\"Someone, Van Something\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", - lines.get(1)); + "10,\"\",\"\",\"Someone, Van Something\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", + lines.get(1)); } @Test @@ -81,8 +81,8 @@ public void testPerformExportForMultipleAuthors(@TempDirectory.TempDir Path test List lines = Files.readAllLines(path); assertEquals(2, lines.size()); assertEquals( - "10,\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", - lines.get(1)); + "10,\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", + lines.get(1)); } @Test @@ -98,8 +98,8 @@ public void testPerformExportForSingleEditor(@TempDirectory.TempDir Path testFol List lines = Files.readAllLines(tmpFile.toPath()); assertEquals(2, lines.size()); assertEquals( - "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Someone, Van Something\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", - lines.get(1)); + "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Someone, Van Something\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", + lines.get(1)); } @Test @@ -115,8 +115,7 @@ public void testPerformExportForMultipleEditors(@TempDirectory.TempDir Path test List lines = Files.readAllLines(tmpFile.toPath()); assertEquals(2, lines.size()); assertEquals( - "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", - lines.get(1)); + "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", + lines.get(1)); } - } diff --git a/src/test/java/org/jabref/logic/exporter/ExporterTest.java b/src/test/java/org/jabref/logic/exporter/ExporterTest.java index e5978b76343..842319f2bb3 100644 --- a/src/test/java/org/jabref/logic/exporter/ExporterTest.java +++ b/src/test/java/org/jabref/logic/exporter/ExporterTest.java @@ -68,7 +68,7 @@ public void testExportingEmptyDatabaseYieldsEmptyFile(Exporter exportFormat, Str @ParameterizedTest @MethodSource("exportFormats") public void testExportingNullDatabaseThrowsNPE(Exporter exportFormat, String name, @TempDirectory.TempDir Path testFolder) { - assertThrows(NullPointerException.class, ()->{ + assertThrows(NullPointerException.class, () -> { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); exportFormat.export(null, tmpFile, charset, entries); @@ -78,7 +78,7 @@ public void testExportingNullDatabaseThrowsNPE(Exporter exportFormat, String nam @ParameterizedTest @MethodSource("exportFormats") public void testExportingNullEntriesThrowsNPE(Exporter exportFormat, String name, @TempDirectory.TempDir Path testFolder) { - assertThrows(NullPointerException.class, ()->{ + assertThrows(NullPointerException.class, () -> { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); exportFormat.export(databaseContext, tmpFile, charset, null); diff --git a/src/test/java/org/jabref/logic/exporter/FieldFormatterCleanupsTest.java b/src/test/java/org/jabref/logic/exporter/FieldFormatterCleanupsTest.java index ae6a864d198..9cea5c9c203 100644 --- a/src/test/java/org/jabref/logic/exporter/FieldFormatterCleanupsTest.java +++ b/src/test/java/org/jabref/logic/exporter/FieldFormatterCleanupsTest.java @@ -24,7 +24,6 @@ public class FieldFormatterCleanupsTest { private BibEntry entry; - @BeforeEach public void setUp() { entry = new BibEntry(); diff --git a/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java b/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java index 92549163859..b1560a3aa65 100644 --- a/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java +++ b/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java @@ -157,5 +157,4 @@ public void getTreeAsStringInComplexTree() throws Exception { ); assertEquals(expected, groupSerializer.serializeTree(root)); } - } diff --git a/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java b/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java index 87433f65fb6..7fe930f9fd5 100644 --- a/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java +++ b/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java @@ -14,9 +14,9 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junitpioneer.jupiter.TempDirectory; import org.mockito.Answers; @@ -26,10 +26,10 @@ @ExtendWith(TempDirectory.class) public class HtmlExportFormatTest { - private Exporter exportFormat; public BibDatabaseContext databaseContext; public Charset charset; public List entries; + private Exporter exportFormat; @BeforeEach public void setUp() { diff --git a/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java index ad8b02d9bd2..e1de292326a 100644 --- a/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java @@ -35,14 +35,13 @@ @ExtendWith(TempDirectory.class) public class MSBibExportFormatTestFiles { + private static Path resourceDir; public BibDatabaseContext databaseContext; public Charset charset; public Path tempFile; public MSBibExporter msBibExportFormat; public BibtexImporter testImporter; - private static Path resourceDir; - static Stream fileNames() throws IOException, URISyntaxException { //we have to point it to one existing file, otherwise it will return the default class path resourceDir = Paths.get(MSBibExportFormatTestFiles.class.getResource("MsBibExportFormatTest1.bib").toURI()).getParent(); diff --git a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java index 1c0bbbca22f..7a0d8ac6b6f 100644 --- a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java @@ -1,8 +1,5 @@ package org.jabref.logic.exporter; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -19,6 +16,7 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.extension.ExtendWith; @@ -33,9 +31,13 @@ import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.mock; + @ExtendWith(TempDirectory.class) public class ModsExportFormatTestFiles { + private static Path resourceDir; public Charset charset; private BibDatabaseContext databaseContext; private Path tempFile; @@ -44,8 +46,6 @@ public class ModsExportFormatTestFiles { private ModsImporter modsImporter; private Path importFile; - private static Path resourceDir; - public static Stream fileNames() throws Exception { resourceDir = Paths.get(MSBibExportFormatTestFiles.class.getResource("ModsExportFormatTestAllFields.bib").toURI()).getParent(); System.out.println(resourceDir); @@ -53,7 +53,7 @@ public static Stream fileNames() throws Exception { try (Stream stream = Files.list(resourceDir)) { // stream.forEach(n -> System.out.println(n)); return stream.map(n -> n.getFileName().toString()).filter(n -> n.endsWith(".bib")) - .filter(n -> n.startsWith("Mods")).collect(Collectors.toList()).stream(); + .filter(n -> n.startsWith("Mods")).collect(Collectors.toList()).stream(); } } @@ -80,16 +80,15 @@ public final void testPerformExport(String filename) throws Exception { Path tempFilename = tempFile.toAbsolutePath(); List entries = bibtexImporter.importDatabase(importFile, charset).getDatabase().getEntries(); Path xmlFile = Paths.get(ModsExportFormatTestFiles.class.getResource(xmlFileName).toURI()); - + modsExportFormat.export(databaseContext, tempFile, charset, entries); Builder control = Input.from(Files.newInputStream(xmlFile)); Builder test = Input.from(Files.newInputStream(tempFilename)); assertThat(test, CompareMatcher.isSimilarTo(control) - .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } - @ParameterizedTest @MethodSource("fileNames") public final void testExportAsModsAndThenImportAsMods(String filename) throws Exception { @@ -117,7 +116,6 @@ public final void testImportAsModsAndExportAsMods(String filename) throws Except Builder test = Input.from(Files.newInputStream(tempFilename)); assertThat(test, CompareMatcher.isSimilarTo(control) - .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } - } diff --git a/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java b/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java index 4174683a69e..7038e8f436e 100644 --- a/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java +++ b/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java @@ -59,20 +59,20 @@ public void exportSingleEntry(@TempDirectory.TempDir Path testFolder) throws Exc exporter.export(databaseContext, file, encoding, Collections.singletonList(entry)); String actual = Files.readAllLines(file).stream().collect(Collectors.joining("\n")); //we are using \n to join, so we need it in the expected string as well, \r\n would fail String expected = " \n" + - " \n" + - " \n" + - " \n" + - " Alan Turing\n" + - " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " "; + " \n" + + " \n" + + " \n" + + " Alan Turing\n" + + " \n" + + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " "; assertEquals(expected, actual); } @@ -93,38 +93,38 @@ public void writeMultipleEntriesInASingleFile(@TempDirectory.TempDir Path testFo String actual = Files.readAllLines(file).stream().collect(Collectors.joining("\n")); //we are using \n to join, so we need it in the expected string as well, \r\n would fail String expected = " \n" + - " \n" + - " \n" + - " \n" + - " Alan Turing\n" + - " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " Michael Armbrust\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " bibtex/bibtexkey/Armbrust2010\n" + - " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " "; + " \n" + + " \n" + + " \n" + + " Alan Turing\n" + + " \n" + + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " Michael Armbrust\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " bibtex/bibtexkey/Armbrust2010\n" + + " \n" + + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " "; assertEquals(expected, actual); } @@ -150,20 +150,20 @@ public void writeMultipleEntriesInDifferentFiles(@TempDirectory.TempDir Path tes String actualTuring = Files.readAllLines(fileTuring).stream().collect(Collectors.joining("\n")); //we are using \n to join, so we need it in the expected string as well, \r\n would fail String expectedTuring = " \n" + - " \n" + - " \n" + - " \n" + - " Alan Turing\n" + - " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " "; + " \n" + + " \n" + + " \n" + + " Alan Turing\n" + + " \n" + + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " "; assertEquals(expectedTuring, actualTuring); @@ -171,25 +171,25 @@ public void writeMultipleEntriesInDifferentFiles(@TempDirectory.TempDir Path tes String actualArmbrust = Files.readAllLines(fileArmbrust).stream().collect(Collectors.joining("\n")); //we are using \n to join, so we need it in the expected string as well, \r\n would fail String expectedArmbrust = " \n" + - " \n" + - " \n" + - " \n" + - " Michael Armbrust\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " bibtex/bibtexkey/Armbrust2010\n" + - " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " "; + " \n" + + " \n" + + " \n" + + " Michael Armbrust\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " bibtex/bibtexkey/Armbrust2010\n" + + " \n" + + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " "; assertEquals(expectedArmbrust, actualArmbrust); } @@ -208,15 +208,15 @@ public void exportSingleEntryWithPrivacyFilter(@TempDirectory.TempDir Path testF exporter.export(databaseContext, file, encoding, Collections.singletonList(entry)); String actual = Files.readAllLines(file).stream().collect(Collectors.joining("\n")); String expected = " \n" + - " \n" + - " application/pdf\n" + - " \n" + - " \n" + - " Misc\n" + - " \n" + - " \n" + - " \n" + - " "; + " \n" + + " application/pdf\n" + + " \n" + + " \n" + + " Misc\n" + + " \n" + + " \n" + + " \n" + + " "; assertEquals(expected, actual); } } diff --git a/src/test/java/org/jabref/logic/formatter/FormatterTest.java b/src/test/java/org/jabref/logic/formatter/FormatterTest.java index 90ffd962d72..316fc9142c7 100644 --- a/src/test/java/org/jabref/logic/formatter/FormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/FormatterTest.java @@ -33,19 +33,20 @@ static void setUp() { } /** - * When a new formatter is added by copy and pasting another formatter, it may happen that the getKey() method is not adapted. This results in duplicate keys, which this test tests for. + * When a new formatter is added by copy and pasting another formatter, it may happen that the getKey() + * method is not adapted. This results in duplicate keys, which this test tests for. */ @Test public void allFormatterKeysAreUnique() { // idea for uniqueness checking by https://stackoverflow.com/a/44032568/873282 - assertEquals(Collections.emptyList(), - getFormatters().collect(Collectors.groupingBy( - formatter -> formatter.getKey(), - Collectors.counting())) - .entrySet().stream() - .filter(e -> e.getValue() > 1) - .map(Map.Entry::getKey) - .collect(Collectors.toList())); + assertEquals(Collections.emptyList(), + getFormatters().collect(Collectors.groupingBy( + formatter -> formatter.getKey(), + Collectors.counting())) + .entrySet().stream() + .filter(e -> e.getValue() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toList())); } @ParameterizedTest diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/AddBracesFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/AddBracesFormatterTest.java index 7bb7788e462..85b6ef5003e 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/AddBracesFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/AddBracesFormatterTest.java @@ -3,7 +3,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} @@ -72,5 +72,4 @@ public void formatDoesNotRemoveBracesInBrokenString() { public void formatExample() { assertEquals("{In CDMA}", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatterTest.java index f6bd4e789fa..46e4bea3508 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatterTest.java @@ -6,7 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} + * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ class CleanupUrlFormatterTest { @@ -32,7 +32,7 @@ void extractURLFormLink() { @Test void formatExample() { assertEquals("http://www.focus.de/" + - "gesundheit/ratgeber/herz/test/lebenserwartung-werden-sie-100-jahre-alt_aid_363828.html", + "gesundheit/ratgeber/herz/test/lebenserwartung-werden-sie-100-jahre-alt_aid_363828.html", formatter.format(formatter.getExampleInput())); } } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/ClearFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/ClearFormatterTest.java index 3c2fe1b9f67..ea4f8407eb5 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/ClearFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/ClearFormatterTest.java @@ -9,7 +9,6 @@ * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ - public class ClearFormatterTest { private ClearFormatter formatter; diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java index 13ce11e3d05..81997715f25 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java @@ -39,7 +39,6 @@ public void testUmlauts() { assertEquals("ä", formatter.format("ä")); assertEquals("ä", formatter.format("ä")); assertEquals("ä", formatter.format("ä")); - } @Test diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/LatexCleanupFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/LatexCleanupFormatterTest.java index 4e24f6ccaa2..202aaa8ddb3 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/LatexCleanupFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/LatexCleanupFormatterTest.java @@ -45,5 +45,4 @@ public void escapePercentSignOnlnyOnceWithNumber() { public void formatExample() { assertEquals("{VLSI DSP}", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeMonthFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeMonthFormatterTest.java index c6253e15112..31c3f935989 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeMonthFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeMonthFormatterTest.java @@ -21,5 +21,4 @@ public void setUp() { public void formatExample() { assertEquals("#dec#", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizePagesFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizePagesFormatterTest.java index 77468ca156f..b0b019ddbe0 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizePagesFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizePagesFormatterTest.java @@ -108,5 +108,4 @@ public void keepFormattedACMPages() { public void formatExample() { assertEquals("1--2", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveBracesFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveBracesFormatterTest.java index 7ffb7179bd5..b2f417cd587 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveBracesFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveBracesFormatterTest.java @@ -72,5 +72,4 @@ public void formatDoesNotRemoveBracesInBrokenString() { public void formatExample() { assertEquals("In CDMA", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/TrimWhitespaceFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/TrimWhitespaceFormatterTest.java index d0554334a0e..3154a1a91fb 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/TrimWhitespaceFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/TrimWhitespaceFormatterTest.java @@ -56,6 +56,4 @@ public void removeMixedWhitespaceChars() { assertEquals("whitespace", formatter.format("whitespace \n \r")); assertEquals("whitespace", formatter.format(" \f\t whitespace \r \n")); } - - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeConverterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeConverterTest.java index fe4d723ad06..a4d7f3fa7cb 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeConverterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeConverterTest.java @@ -10,7 +10,7 @@ */ public class UnicodeConverterTest { - private UnicodeToLatexFormatter formatter; + private UnicodeToLatexFormatter formatter; @BeforeEach public void setUp() { @@ -38,5 +38,4 @@ public void testUnicode() { public void testUnicodeSingle() { assertEquals("a", formatter.format("a")); } - } diff --git a/src/test/java/org/jabref/logic/formatter/bibtexfields/UnitsToLatexFormatterTest.java b/src/test/java/org/jabref/logic/formatter/bibtexfields/UnitsToLatexFormatterTest.java index 43d1338831a..292a79b7869 100644 --- a/src/test/java/org/jabref/logic/formatter/bibtexfields/UnitsToLatexFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/bibtexfields/UnitsToLatexFormatterTest.java @@ -27,5 +27,4 @@ public void test() { public void formatExample() { assertEquals("1~{Hz}", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/CapitalizeFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/CapitalizeFormatterTest.java index 437f42b096a..61d7fdd9837 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/CapitalizeFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/CapitalizeFormatterTest.java @@ -28,5 +28,4 @@ public void test() { public void formatExample() { assertEquals("I Have {a} Dream", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/LowerCaseFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/LowerCaseFormatterTest.java index abc194048c6..0629e48a3fe 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/LowerCaseFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/LowerCaseFormatterTest.java @@ -28,5 +28,4 @@ public void test() { public void formatExample() { assertEquals("kde {Amarok}", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/ProtectTermsFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/ProtectTermsFormatterTest.java index a21eb71c99c..5840c12a4c6 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/ProtectTermsFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/ProtectTermsFormatterTest.java @@ -20,8 +20,8 @@ public class ProtectTermsFormatterTest { @BeforeEach public void setUp() { formatter = new ProtectTermsFormatter( - new ProtectedTermsLoader(new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), - Collections.emptyList(), Collections.emptyList(), Collections.emptyList()))); + new ProtectedTermsLoader(new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), + Collections.emptyList(), Collections.emptyList(), Collections.emptyList()))); } @Test diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatterTest.java index 9e03374df67..9116062136f 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatterTest.java @@ -29,5 +29,4 @@ public void test() { public void formatExample() { assertEquals("I have {Aa} dream", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatterTest.java index faccd196267..11e22b1123d 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatterTest.java @@ -84,5 +84,4 @@ public void testTwoExperiencesTitle() { public void formatExample() { assertEquals("{BPMN} Conformance in Open Source Engines", formatter.format(formatter.getExampleInput())); } - } diff --git a/src/test/java/org/jabref/logic/formatter/casechanger/UpperCaseFormatterTest.java b/src/test/java/org/jabref/logic/formatter/casechanger/UpperCaseFormatterTest.java index fd1a2aa2b7a..2c669a6a5d2 100644 --- a/src/test/java/org/jabref/logic/formatter/casechanger/UpperCaseFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/casechanger/UpperCaseFormatterTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ diff --git a/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java b/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java index 99a3146e3ed..28d6140e248 100644 --- a/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java +++ b/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java @@ -1,6 +1,5 @@ package org.jabref.logic.formatter.minifier; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java b/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java index f8317b118c6..0bfe55d3a03 100644 --- a/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java +++ b/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java @@ -28,7 +28,7 @@ public void setUp() { @Test public void resolveStrings() throws IOException { try (FileInputStream stream = new FileInputStream("src/test/resources/org/jabref/util/twente.bib"); - InputStreamReader fr = new InputStreamReader(stream, StandardCharsets.UTF_8)) { + InputStreamReader fr = new InputStreamReader(stream, StandardCharsets.UTF_8)) { ParserResult result = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()).parse(fr); BibDatabase db = result.getDatabase(); @@ -41,5 +41,4 @@ public void resolveStrings() throws IOException { assertEquals("#unknown#", db.resolveForStrings("#unknown#")); } } - } diff --git a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java index 29313bb46e0..fdb97e6ed88 100644 --- a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java +++ b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java @@ -26,11 +26,10 @@ public class DatabaseFileLookupTest { private BibEntry entry1; private BibEntry entry2; - @BeforeEach public void setUp() throws Exception { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); - InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { + InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { ParserResult result = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()).parse(reader); database = result.getDatabase(); entries = database.getEntries(); @@ -50,5 +49,4 @@ public void testTestDatabase() { assertNotNull(entry1); assertNotNull(entry2); } - } diff --git a/src/test/java/org/jabref/logic/importer/ImportDataTest.java b/src/test/java/org/jabref/logic/importer/ImportDataTest.java index a2fa5889d09..dc457791f75 100644 --- a/src/test/java/org/jabref/logic/importer/ImportDataTest.java +++ b/src/test/java/org/jabref/logic/importer/ImportDataTest.java @@ -23,7 +23,6 @@ public class ImportDataTest { public static final File UNLINKED_FILES_TEST_BIB = Paths .get("src/test/resources/org/jabref/util/unlinkedFilesTestBib.bib").toFile(); - /** * Tests the testing environment. */ @@ -45,5 +44,4 @@ public void testOpenNotExistingDirectory() { assertFalse(ImportDataTest.NOT_EXISTING_FOLDER.exists()); assertFalse(ImportDataTest.NOT_EXISTING_PDF.exists()); } - } diff --git a/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java b/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java index e861f07b999..0550e3b8ec3 100644 --- a/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java +++ b/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java @@ -57,15 +57,14 @@ void testImportUnknownFormatFromString(String resource, String format, int count 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/SilverPlatterImporterTest1.txt", "silverplatter", 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/RisImporterTest1.ris", "ris", 1}); + result.add(new Object[]{"fileformat/IsiImporterTest1.isi", "isi", 1}); + result.add(new Object[]{"fileformat/SilverPlatterImporterTest1.txt", "silverplatter", 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}); return result.stream(); } - } diff --git a/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java b/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java index fc057c3f331..9ddc2962ef0 100644 --- a/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java +++ b/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java @@ -38,18 +38,15 @@ void importUnknownFormatThrowsExceptionIfNoMatchingImporterWasFound() throws Exc @Test void importUnknownFormatThrowsExceptionIfPathIsNull() throws Exception { assertThrows(NullPointerException.class, () -> reader.importUnknownFormat(null, fileMonitor)); - } @Test void importUnknownFormatThrowsExceptionIfDataIsNull() throws Exception { assertThrows(NullPointerException.class, () -> reader.importUnknownFormat(null)); - } @Test void importFromFileWithUnknownFormatThrowsException() throws Exception { assertThrows(ImportException.class, () -> reader.importFromFile("someunknownformat", Paths.get("somepath"))); } - } diff --git a/src/test/java/org/jabref/logic/importer/ImporterTest.java b/src/test/java/org/jabref/logic/importer/ImporterTest.java index c16eb4a2fb2..348cce8217d 100644 --- a/src/test/java/org/jabref/logic/importer/ImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/ImporterTest.java @@ -29,9 +29,9 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,50 +41,50 @@ public class ImporterTest { @ParameterizedTest @MethodSource("instancesToTest") public void isRecognizedFormatWithNullForBufferedReaderThrowsException(Importer format) { - assertThrows(NullPointerException.class, ()-> format.isRecognizedFormat((BufferedReader) null)); + assertThrows(NullPointerException.class, () -> format.isRecognizedFormat((BufferedReader) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void isRecognizedFormatWithNullForStringThrowsException(Importer format) { - assertThrows(NullPointerException.class, ()-> format.isRecognizedFormat((String) null)); + assertThrows(NullPointerException.class, () -> format.isRecognizedFormat((String) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void importDatabaseWithNullForBufferedReaderThrowsException(Importer format) { - assertThrows(NullPointerException.class, ()-> format.importDatabase((BufferedReader) null)); + assertThrows(NullPointerException.class, () -> format.importDatabase((BufferedReader) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void importDatabaseWithNullForStringThrowsException(Importer format) { - assertThrows(NullPointerException.class, ()-> format.importDatabase((String) null)); + assertThrows(NullPointerException.class, () -> format.importDatabase((String) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void getFormatterNameDoesNotReturnNull(Importer format) { - assertNotNull(format.getName()); + assertNotNull(format.getName()); } @ParameterizedTest @MethodSource("instancesToTest") public void getFileTypeDoesNotReturnNull(Importer format) { - assertNotNull(format.getFileType()); + assertNotNull(format.getFileType()); } @ParameterizedTest @MethodSource("instancesToTest") public void getIdDoesNotReturnNull(Importer format) { - assertNotNull(format.getId()); + assertNotNull(format.getId()); } @ParameterizedTest @MethodSource("instancesToTest") public void getIdDoesNotContainWhitespace(Importer format) { Pattern whitespacePattern = Pattern.compile("\\s"); - assertFalse(whitespacePattern.matcher(format.getId()).find()); + assertFalse(whitespacePattern.matcher(format.getId()).find()); } @ParameterizedTest @@ -92,16 +92,15 @@ public void getIdDoesNotContainWhitespace(Importer format) { public void getIdStripsSpecialCharactersAndConvertsToLowercase(Importer format) { Importer importer = mock(Importer.class, Mockito.CALLS_REAL_METHODS); when(importer.getName()).thenReturn("*Test-Importer"); - assertEquals("testimporter", importer.getId()); + assertEquals("testimporter", importer.getId()); } @ParameterizedTest @MethodSource("instancesToTest") public void getDescriptionDoesNotReturnNull(Importer format) { - assertNotNull(format.getDescription()); + assertNotNull(format.getDescription()); } - public static Stream instancesToTest() { // all classes implementing {@link Importer} // sorted alphabetically @@ -131,5 +130,4 @@ public static Stream instancesToTest() { ); // @formatter:on } - } diff --git a/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java b/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java index 47ca7b116dc..d722690e7a3 100644 --- a/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java +++ b/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java @@ -38,7 +38,7 @@ public OpenDatabaseTest() throws URISyntaxException { bibWrongHeader = Paths.get(OpenDatabaseTest.class.getResource("wrong-header.bib").toURI()).toFile(); bibHeader = Paths.get(OpenDatabaseTest.class.getResource("encoding-header.bib").toURI()).toFile(); bibHeaderAndSignature = Paths.get(OpenDatabaseTest.class.getResource("jabref-header.bib").toURI()) - .toFile(); + .toFile(); bibEncodingWithoutNewline = Paths .get(OpenDatabaseTest.class.getResource("encodingWithoutNewline.bib").toURI()).toFile(); } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/ACSTest.java b/src/test/java/org/jabref/logic/importer/fetcher/ACSTest.java index c11b94cb2bb..6bf36592f56 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/ACSTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/ACSTest.java @@ -31,7 +31,7 @@ void findByDOI() throws IOException { entry.setField("doi", "10.1021/bk-2006-STYG.ch014"); assertEquals( - Optional.of(new URL("https://pubs.acs.org/doi/pdf/10.1021/bk-2006-STYG.ch014")), + Optional.of(new URL("https://pubs.acs.org/doi/pdf/10.1021/bk-2006-STYG.ch014")), finder.findFullText(entry) ); } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/AbstractIsbnFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/AbstractIsbnFetcherTest.java index 096f11e840a..ffad948cba1 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/AbstractIsbnFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/AbstractIsbnFetcherTest.java @@ -51,5 +51,4 @@ public void searchByIdThrowsExceptionForLongInvalidISB() { public void searchByIdThrowsExceptionForInvalidISBN() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("jabref-4-ever")); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/ArXivTest.java b/src/test/java/org/jabref/logic/importer/fetcher/ArXivTest.java index e988822af5a..ae71b8849c7 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/ArXivTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/ArXivTest.java @@ -64,7 +64,6 @@ public void findFullTextByDOI() throws IOException { entry.setField(FieldName.TITLE, "Pause Point Spectra in DNA Constant-Force Unzipping"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/cond-mat/0406246v1")), finder.findFullText(entry)); - } @Test @@ -198,17 +197,17 @@ public void searchEmptyId() throws Exception { } @Test - public void searchWithHttpUrl() throws Exception{ + public void searchWithHttpUrl() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), finder.performSearchById("http://arxiv.org/abs/1405.2249")); } @Test - public void searchWithHttpsUrl() throws Exception{ + public void searchWithHttpsUrl() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), finder.performSearchById("https://arxiv.org/abs/1405.2249")); } @Test - public void searchWithHttpsUrlNotTrimmed() throws Exception{ + public void searchWithHttpsUrlNotTrimmed() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), finder.performSearchById("https : // arxiv . org / abs / 1405 . 2249 ")); } } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/DBLPFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/DBLPFetcherTest.java index 51e1ba7ad97..dcf548eca80 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/DBLPFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/DBLPFetcherTest.java @@ -28,24 +28,23 @@ public class DBLPFetcherTest { public void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); when(importFormatPreferences.getFieldContentParserPreferences()) - .thenReturn(mock(FieldContentParserPreferences.class)); + .thenReturn(mock(FieldContentParserPreferences.class)); dblpFetcher = new DBLPFetcher(importFormatPreferences); entry = new BibEntry(); entry.setType(BibtexEntryTypes.ARTICLE.getName()); entry.setCiteKey("DBLP:journals/stt/GeigerHL16"); entry.setField(FieldName.TITLE, - "Process Engine Benchmarking with Betsy in the Context of {ISO/IEC} Quality Standards"); + "Process Engine Benchmarking with Betsy in the Context of {ISO/IEC} Quality Standards"); entry.setField(FieldName.AUTHOR, "Matthias Geiger and Simon Harrer and J{\\\"{o}}rg Lenhard"); entry.setField(FieldName.JOURNAL, "Softwaretechnik-Trends"); entry.setField(FieldName.VOLUME, "36"); entry.setField(FieldName.NUMBER, "2"); entry.setField(FieldName.YEAR, "2016"); entry.setField(FieldName.URL, - "http://pi.informatik.uni-siegen.de/stt/36_2/./03_Technische_Beitraege/ZEUS2016/beitrag_2.pdf"); + "http://pi.informatik.uni-siegen.de/stt/36_2/./03_Technische_Beitraege/ZEUS2016/beitrag_2.pdf"); entry.setField("biburl", "https://dblp.org/rec/bib/journals/stt/GeigerHL16"); entry.setField("bibsource", "dblp computer science bibliography, https://dblp.org"); - } @Test @@ -68,5 +67,4 @@ public void findSingleEntryUsingComplexOperators() throws FetcherException { public void findNothing() throws Exception { assertEquals(Collections.emptyList(), dblpFetcher.performSearch("")); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java b/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java index fa76e65b9b4..8fbfd9277ea 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java @@ -44,7 +44,7 @@ public void testPerformSearchById() throws Exception { entry.setField("institution", "Linköping University, The Institute of Technology"); entry.setCiteKey("Gustafsson260746"); entry.setField("journal", - "IEEE transactions on circuits and systems. 2, Analog and digital signal processing (Print)"); + "IEEE transactions on circuits and systems. 2, Analog and digital signal processing (Print)"); entry.setField("number", "11"); entry.setField("pages", "974--978"); entry.setField("title", "Lower bounds for constant multiplication problems"); diff --git a/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java index d6411540e39..3c8c4d130f0 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java @@ -48,7 +48,6 @@ public void setUp() { bibEntryDecker2007.setField("doi", "10.1109/icws.2007.59"); } - @Test public void testGetName() { assertEquals("DOI", fetcher.getName()); @@ -79,7 +78,6 @@ public void testPerformSearchEmptyDOI() { @Test public void testPerformSearchInvalidDOI() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("10.1002/9781118257517F")); - } @Test diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java index e03a54eb7ec..7b887663a76 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java @@ -161,7 +161,7 @@ public void searchByIdWithOldHtmlFormatWithoutDateCheck(String id) throws Fetche /** * Helper method for allNonWithdrawnIdsWithOldHtmlFormat. * - * @param year The year of the generated IDs (e.g. 1996) + * @param year The year of the generated IDs (e.g. 1996) * @param maxId The maximum ID to generate in the given year (e.g. 112) * @return A list of IDs in the from yyyy/iii (e.g. [1996/001, 1996/002, ..., 1996/112] */ diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java index a8a6f0fd40a..ed140ff3dc8 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java @@ -38,7 +38,6 @@ public void setUp() { bibEntry.setField("ean", "9780134685991"); bibEntry.setField("isbn", "0134685997"); bibEntry.setField("url", "https://www.ebook.de/de/product/28983211/joshua_bloch_effective_java.html"); - } @Test @@ -85,14 +84,12 @@ public void searchByIdThrowsExceptionForInvalidISBN() { } /** - * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 - * However, this ISBN is not available on ebook.de. The fetcher should something as it falls back to Chimbori - * @throws FetcherException + * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 However, this ISBN is + * not available on ebook.de. The fetcher should something as it falls back to Chimbori */ @Test public void searchForIsbnAvailableAtChimboriButNonOnEbookDe() throws FetcherException { Optional fetchedEntry = fetcher.performSearchById("3728128155"); assertNotEquals(Optional.empty(), fetchedEntry); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java index 7371043febc..5eb46520f88 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java @@ -30,7 +30,7 @@ public void setUp() { bibEntry.setField("author", "Joshua Bloch"); bibEntry.setField("isbn", "978-0321356680"); bibEntry.setField("url", - "https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683?SubscriptionId=AKIAIOBINVZYXZQZ2U3A&tag=chimbori05-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=0321356683"); + "https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683?SubscriptionId=AKIAIOBINVZYXZQZ2U3A&tag=chimbori05-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=0321356683"); fetcher = new IsbnViaChimboriFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @@ -77,7 +77,7 @@ public void authorsAreCorrectlyFormatted() throws Exception { bibEntry.setField("author", "Marlon Dumas and Marcello La Rosa and Jan Mendling and Hajo A. Reijers"); bibEntry.setField("isbn", "3642434738"); bibEntry.setField("url", - "https://www.amazon.com/Fundamentals-Business-Process-Management-Marlon/dp/3642434738?SubscriptionId=AKIAIOBINVZYXZQZ2U3A&tag=chimbori05-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=3642434738"); + "https://www.amazon.com/Fundamentals-Business-Process-Management-Marlon/dp/3642434738?SubscriptionId=AKIAIOBINVZYXZQZ2U3A&tag=chimbori05-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=3642434738"); Optional fetchedEntry = fetcher.performSearchById("3642434738"); assertEquals(Optional.of(bibEntry), fetchedEntry); @@ -88,5 +88,4 @@ public void searchForIsbnAvailableAtChimboriButNonOnEbookDe() throws Exception { Optional fetchedEntry = fetcher.performSearchById("3728128155"); assertNotEquals(Optional.empty(), fetchedEntry); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java index a20318709b1..f84fe58799d 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java @@ -80,13 +80,12 @@ public void authorsAreCorrectlyFormatted() throws Exception { } /** - * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 - * However, this ISBN is not available on ebook.de. The fetcher should return nothing rather than throwing an exeption. + * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 However, this ISBN is + * not available on ebook.de. The fetcher should return nothing rather than throwing an exeption. */ @Test public void searchForValidButNotFoundISBN() throws Exception { Optional fetchedEntry = fetcher.performSearchById("3728128155"); assertEquals(Optional.empty(), fetchedEntry); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/MathSciNetTest.java b/src/test/java/org/jabref/logic/importer/fetcher/MathSciNetTest.java index 5c2f2787854..e66d81f0948 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/MathSciNetTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/MathSciNetTest.java @@ -28,7 +28,7 @@ class MathSciNetTest { void setUp() throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); when(importFormatPreferences.getFieldContentParserPreferences()).thenReturn( - mock(FieldContentParserPreferences.class)); + mock(FieldContentParserPreferences.class)); fetcher = new MathSciNet(importFormatPreferences); ratiuEntry = new BibEntry(); diff --git a/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java index 82a7116f7a2..c35684edf48 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java @@ -56,5 +56,4 @@ public void testPerformSearchForHornecker2006() throws FetcherException { public void testGetName() { assertEquals("MDL_FETCHER", fetcher.getName()); } - } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java index 728ef5de1b9..715c1fb6220 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java @@ -63,5 +63,4 @@ public void testPerformSearchInvalidTitle() throws FetcherException { Optional fetchedEntry = fetcher.performSearchById("An unknown title where noi DOI can be determined"); assertEquals(Optional.empty(), fetchedEntry); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTest.java index 6b904f75ffd..0b2b490c0e7 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class BibTeXMLImporterTest { private BibTeXMLImporter importer; diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestFiles.java index 6ab7a54ce7d..e25c020989f 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestFiles.java @@ -41,5 +41,4 @@ public void testIsNotRecognizedFormat(String fileName) throws IOException { public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new BibTeXMLImporter(), fileName, FILE_ENDING); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestTypes.java b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestTypes.java index 84f9035a8e8..bf66acaf56a 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestTypes.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTestTypes.java @@ -38,7 +38,6 @@ public static Collection types() { }); } - @ParameterizedTest @MethodSource("types") public void importConvertsToCorrectBibType(String type) throws IOException { @@ -49,7 +48,7 @@ public void importConvertsToCorrectBibType(String type) throws IOException { + type + ">\n" + "\n" + ""; List bibEntries = new BibTeXMLImporter().importDatabase(new BufferedReader(new StringReader(bibteXMLInput))) - .getDatabase().getEntries(); + .getDatabase().getEntries(); BibEntry entry = new BibEntry(); entry.setField("author", "Max Mustermann"); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTest.java index 2a979f5030d..2ee415b14ab 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTest.java @@ -16,7 +16,6 @@ public class BiblioscapeImporterTest { private BiblioscapeImporter importer; - @BeforeEach public void setUp() throws Exception { importer = new BiblioscapeImporter(); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTestTypes.java b/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTestTypes.java index 12c3d195189..7e37160a023 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTestTypes.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTestTypes.java @@ -17,7 +17,7 @@ public class BiblioscapeImporterTestTypes { private static Stream types() { - return Arrays.stream(new String[][] { + return Arrays.stream(new String[][]{ {"journal", "article"}, {"book section", "inbook"}, {"book", "book"}, @@ -36,7 +36,7 @@ public void importConvertsToCorrectBibType(String biblioscapeType, String bibtex + "--RT-- " + biblioscapeType + "\n" + "------"; List bibEntries = new BiblioscapeImporter().importDatabase(new BufferedReader(new StringReader(bsInput))) - .getDatabase().getEntries(); + .getDatabase().getEntries(); BibEntry entry = new BibEntry(); entry.setField("author", "Baklouti, F."); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java index 6e631a788c2..77330b76028 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java @@ -22,18 +22,14 @@ import static org.mockito.Mockito.mock; /** - * This class tests the BibtexImporter. - * That importer is only used for --importToOpen, which is currently untested + * This class tests the BibtexImporter. That importer is only used for --importToOpen, which is currently untested *

- * TODO: - * 1. Add test for --importToOpen - * 2. Move these tests to the code opening a bibtex file + * TODO: 1. Add test for --importToOpen 2. Move these tests to the code opening a bibtex file */ public class BibtexImporterTest { private BibtexImporter importer; - @BeforeEach public void setUp() { importer = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); @@ -68,23 +64,23 @@ public void testImportEntries() throws IOException, URISyntaxException { assertEquals(Optional.of("13"), entry.getField("number")); assertEquals(Optional.of("3027-3036"), entry.getField("pages")); assertEquals(Optional - .of("Effect of immobilization on catalytic characteristics of saturated {Pd-N}-heterocyclic " - + "carbenes in {Mizoroki-Heck} reactions"), + .of("Effect of immobilization on catalytic characteristics of saturated {Pd-N}-heterocyclic " + + "carbenes in {Mizoroki-Heck} reactions"), entry.getField("title")); assertEquals(Optional.of("691"), entry.getField("volume")); } else if (entry.getCiteKeyOptional().get().equals("stdmodel")) { assertEquals(Optional - .of("A \\texttt{set} with three members discussing the standard model of particle physics. " - + "The \\texttt{crossref} field in the \\texttt{@set} entry and the \\texttt{entryset} field in " - + "each set member entry is needed only when using BibTeX as the backend"), + .of("A \\texttt{set} with three members discussing the standard model of particle physics. " + + "The \\texttt{crossref} field in the \\texttt{@set} entry and the \\texttt{entryset} field in " + + "each set member entry is needed only when using BibTeX as the backend"), entry.getField("annotation")); assertEquals(Optional.of("stdmodel"), entry.getField("bibtexkey")); assertEquals(Optional.of("glashow,weinberg,salam"), entry.getField("entryset")); } else if (entry.getCiteKeyOptional().get().equals("set")) { assertEquals(Optional - .of("A \\texttt{set} with three members. The \\texttt{crossref} field in the \\texttt{@set} " - + "entry and the \\texttt{entryset} field in each set member entry is needed only when using " - + "BibTeX as the backend"), + .of("A \\texttt{set} with three members. The \\texttt{crossref} field in the \\texttt{@set} " + + "entry and the \\texttt{entryset} field in each set member entry is needed only when using " + + "BibTeX as the backend"), entry.getField("annotation")); assertEquals(Optional.of("set"), entry.getField("bibtexkey")); assertEquals(Optional.of("herrmann,aksin,yoon"), entry.getField("entryset")); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java index 0da7422a378..866a5a39e57 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java @@ -326,7 +326,7 @@ void parseRecognizesEntryWithAtInField() throws IOException { List parsed = result.getDatabase().getEntries(); BibEntry expected = new BibEntry("article").withField(BibEntry.KEY_FIELD, "test") - .withField("author", "Ed von T@st"); + .withField("author", "Ed von T@st"); assertEquals(Collections.singletonList(expected), parsed); } @@ -938,7 +938,6 @@ void parseRecognizesStringAndEntry() throws IOException { + " Isbn = 2707318256," + " Publisher = {Minuit}," + " Title = {Questions de sociologie}," + " Year = 2002" + "}")); - BibtexString parsedString = result.getDatabase().getStringValues().iterator().next(); Collection parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); @@ -1339,7 +1338,7 @@ void integrationTestSaveOrderConfig() throws IOException { Optional saveOrderConfig = result.getMetaData().getSaveOrderConfig(); assertEquals(new SaveOrderConfig(false, new SaveOrderConfig.SortCriterion("author", false), - new SaveOrderConfig.SortCriterion("year", true), new SaveOrderConfig.SortCriterion("abstract", false)), + new SaveOrderConfig.SortCriterion("year", true), new SaveOrderConfig.SortCriterion("abstract", false)), saveOrderConfig.get()); } @@ -1442,7 +1441,6 @@ void parseOtherTypeTest() throws Exception { assertEquals(Collections.singletonList(expectedEntry), entries); } - @Test void parseRecognizesDatabaseID() throws Exception { String expectedDatabaseID = "q1w2e3r4t5z6"; diff --git a/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTest.java index 3baafe04f27..262291911d8 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTest.java @@ -26,7 +26,6 @@ public void setUp() throws Exception { @Test public void testsGetExtensions() { assertEquals(StandardFileType.TXT, importer.getFileType()); - } @Test @@ -34,7 +33,6 @@ public void testGetDescription() { assertEquals("Importer for COPAC format.", importer.getDescription()); } - @Test public void testImportEmptyEntries() throws Exception { Path path = Paths.get(CopacImporterTest.class.getResource("Empty.txt").toURI()); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTestFiles.java index dd67ddcb7b7..7b66dc89513 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTestFiles.java @@ -39,5 +39,4 @@ public void testIsNotRecognizedFormat(String fileName) throws IOException { public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new CopacImporter(), fileName, FILE_ENDING); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java index 835708db5d5..bec95cbb8a4 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java @@ -126,7 +126,7 @@ public void testImportEntries0() throws IOException, URISyntaxException { public void testImportEntries1() throws IOException { String medlineString = "%O Artn\\\\s testO\n%A testA,\n%E testE0, testE1"; List bibEntries = importer.importDatabase(new BufferedReader(new StringReader(medlineString))).getDatabase() - .getEntries(); + .getEntries(); BibEntry entry = bibEntries.get(0); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/ImporterTestEngine.java b/src/test/java/org/jabref/logic/importer/fileformat/ImporterTestEngine.java index c2eaa089a38..00e6b6aef81 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/ImporterTestEngine.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/ImporterTestEngine.java @@ -69,7 +69,7 @@ private static Path getPath(String fileName) throws IOException { public static void testImportMalformedFiles(Importer importer, String fileName) throws IOException { List entries = importer.importDatabase(getPath(fileName), StandardCharsets.UTF_8).getDatabase() - .getEntries(); + .getEntries(); assertEquals(entries, new ArrayList()); } } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/InspecImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/InspecImporterTest.java index 99528b89042..a2ebd1bf1b7 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/InspecImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/InspecImporterTest.java @@ -22,14 +22,8 @@ public class InspecImporterTest { - private InspecImporter importer; - private static final String FILE_ENDING = ".txt"; - - @BeforeEach - public void setUp() throws Exception { - this.importer = new InspecImporter(); - } + private InspecImporter importer; private static Stream fileNames() throws IOException { Predicate fileName = name -> name.startsWith("InspecImportTest") @@ -43,6 +37,11 @@ private static Stream nonInspecfileNames() throws IOException { return ImporterTestEngine.getTestFiles(fileName).stream(); } + @BeforeEach + public void setUp() throws Exception { + this.importer = new InspecImporter(); + } + @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormatAccept(String fileName) throws IOException { @@ -126,5 +125,4 @@ public void testsGetExtensions() { public void testGetDescription() { assertEquals("INSPEC format importer.", importer.getDescription()); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/IsiImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/IsiImporterTest.java index f511f7c7803..ddcd6398676 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/IsiImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/IsiImporterTest.java @@ -25,9 +25,8 @@ */ public class IsiImporterTest { - private final IsiImporter importer = new IsiImporter(); - private static final String FILE_ENDING = ".isi"; + private final IsiImporter importer = new IsiImporter(); private static Stream fileNames() throws IOException { Predicate fileName = name -> name.startsWith("IsiImporterTest") @@ -228,7 +227,6 @@ public void testIsiAuthorsConvert() { "Joffe, Hadine and Hall, Janet E. and Gruber, Staci and Sarmiento, Ingrid A. and Cohen, Lee S. and Yurgelun-Todd, Deborah and Martin, Kathryn A.", IsiImporter.isiAuthorsConvert( "Joffe, Hadine; Hall, Janet E; Gruber, Staci; Sarmiento, Ingrid A; Cohen, Lee S; Yurgelun-Todd, Deborah; Martin, Kathryn A")); - } @Test @@ -266,7 +264,7 @@ public void testImportIEEEExport() throws IOException, URISyntaxException { assertEquals("article", entry.getType()); assertEquals(Optional.of("Geoscience and Remote Sensing Letters, IEEE"), entry.getField("journal")); assertEquals(Optional.of("Improving Urban Road Extraction in High-Resolution " - + "Images Exploiting Directional Filtering, Perceptual " + "Grouping, and Simple Topological Concepts"), + + "Images Exploiting Directional Filtering, Perceptual " + "Grouping, and Simple Topological Concepts"), entry.getField("title")); assertEquals(Optional.of("4"), entry.getField("volume")); assertEquals(Optional.of("3"), entry.getField("number")); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTest.java index 2444508639c..b20effa34aa 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTest.java @@ -8,13 +8,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Articles in the medline format can be downloaded from http://www.ncbi.nlm.nih.gov/pubmed/. - * 1. Search for a term and make sure you have selected the PubMed database - * 2. Select the results you want to export by checking their checkboxes - * 3. Press on the 'Send to' drop down menu on top of the search results - * 4. Select 'File' as Destination and 'XML' as Format - * 5. Press 'Create File' to download your search results in a medline xml file - * + * Articles in the medline format can be downloaded from http://www.ncbi.nlm.nih.gov/pubmed/. 1. Search for a term and + * make sure you have selected the PubMed database 2. Select the results you want to export by checking their checkboxes + * 3. Press on the 'Send to' drop down menu on top of the search results 4. Select 'File' as Destination and 'XML' as + * Format 5. Press 'Create File' to download your search results in a medline xml file */ public class MedlineImporterTest { @@ -44,5 +41,4 @@ public void testsGetExtensions() { public void testGetDescription() { assertEquals("Importer for the Medline format.", importer.getDescription()); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTestFiles.java index 91c49fd3d9b..fae9374c580 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTestFiles.java @@ -53,6 +53,4 @@ private static Stream malformedFileNames() throws IOException { public void testImportMalfomedFiles(String fileName) throws IOException { ImporterTestEngine.testImportMalformedFiles(new MedlineImporter(), fileName); } - - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java index 2d66b44a0c5..a3c64cf378e 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java @@ -27,13 +27,15 @@ import org.junit.jupiter.params.provider.MethodSource; import static junit.framework.TestCase.assertTrue; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; class MedlinePlainImporterTest { - private MedlinePlainImporter importer; - private static final String FILE_ENDING = ".txt"; + private MedlinePlainImporter importer; private static Stream fileNames() throws IOException { Predicate fileName = name -> name.startsWith("MedlinePlainImporterTest") @@ -77,7 +79,7 @@ void testImportMultipleEntriesInSingleFile() throws IOException, URISyntaxExcept .get(MedlinePlainImporter.class.getResource("MedlinePlainImporterTestMultipleEntries.txt").toURI()); List entries = importer.importDatabase(inputFile, StandardCharsets.UTF_8).getDatabase() - .getEntries(); + .getEntries(); BibEntry testEntry = entries.get(0); assertEquals(7, entries.size()); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTest.java index be10df36e14..56cfec29750 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTest.java @@ -69,5 +69,4 @@ public final void testGetCommandLineId() { MsBibImporter testImporter = new MsBibImporter(); assertEquals("msbib", testImporter.getId()); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTestFiles.java index cae3447b6c8..e9928fa1190 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTestFiles.java @@ -39,5 +39,4 @@ public void testIsNotRecognizedFormat(String fileName) throws IOException { public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new MsBibImporter(), fileName, FILE_ENDING); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/OvidImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/OvidImporterTest.java index e9812c4738a..d734cb20727 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/OvidImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/OvidImporterTest.java @@ -26,9 +26,8 @@ public class OvidImporterTest { - private OvidImporter importer; - private static final String FILE_ENDING = ".txt"; + private OvidImporter importer; private static Stream fileNames() throws IOException { Predicate fileName = name -> name.startsWith("OvidImporterTest") @@ -153,7 +152,7 @@ public void testImportSingleEntries() throws IOException, URISyntaxException { Path file = Paths.get(OvidImporter.class.getResource("OvidImporterTest" + n + ".txt").toURI()); try (InputStream nis = OvidImporter.class.getResourceAsStream("OvidImporterTestBib" + n + ".bib")) { List entries = importer.importDatabase(file, StandardCharsets.UTF_8).getDatabase() - .getEntries(); + .getEntries(); assertNotNull(entries); assertEquals(1, entries.size()); BibEntryAssert.assertEquals(nis, entries.get(0)); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java index 396ba734d2f..db7396d047c 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java @@ -44,5 +44,4 @@ public void doesNotHandleEncryptedPdfs() throws URISyntaxException { List result = importer.importDatabase(file, StandardCharsets.UTF_8).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java index 74b84bc6a3d..7dc4cef6f26 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java @@ -32,5 +32,4 @@ public void testIsRecognizedFormat(String fileName) throws IOException { public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new PdfContentImporter(mock(ImportFormatPreferences.class)), fileName, FILE_ENDING); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/RISImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/RISImporterTest.java index f9aedbb7094..7e46c83d27f 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/RISImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/RISImporterTest.java @@ -48,5 +48,4 @@ public void testIfNotRecognizedFormat() throws IOException, URISyntaxException { Path file = Paths.get(RISImporterTest.class.getResource("RisImporterCorrupted.ris").toURI()); assertFalse(importer.isRecognizedFormat(file, StandardCharsets.UTF_8)); } - } diff --git a/src/test/java/org/jabref/logic/importer/fileformat/SilverPlatterImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/SilverPlatterImporterTest.java index 3ecffde377f..5fdee2d9235 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/SilverPlatterImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/SilverPlatterImporterTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - class SilverPlatterImporterTest { private static final String FILE_ENDING = ".txt"; @@ -63,5 +62,4 @@ void testsGetExtensions() { void testGetDescription() { assertEquals("Imports a SilverPlatter exported file.", testImporter.getDescription()); } - } diff --git a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java index f618009b947..765f93ddcfe 100644 --- a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java +++ b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java @@ -87,7 +87,6 @@ public void testImportSubGroups() throws Exception { GroupTreeNode parsedNode = GroupsParser.importGroups(orderedData, ',', fileMonitor); assertEquals(rootNode.getChildren(), parsedNode.getChildren()); - } @Test diff --git a/src/test/java/org/jabref/logic/integrity/BracesCorrectorTest.java b/src/test/java/org/jabref/logic/integrity/BracesCorrectorTest.java index dbe3c745b92..b14d6e5c49f 100644 --- a/src/test/java/org/jabref/logic/integrity/BracesCorrectorTest.java +++ b/src/test/java/org/jabref/logic/integrity/BracesCorrectorTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; - public class BracesCorrectorTest { @Test diff --git a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java index 879abb26d7e..10b75ae8a37 100644 --- a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java +++ b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java @@ -135,13 +135,13 @@ public void testJournaltitleChecks() { @Test public void testBibtexkeyChecks() { final BibDatabaseContext correctContext = createContext("bibtexkey", "Knuth2014"); - correctContext.getDatabase().getEntries().get(0).setField("author","Knuth"); - correctContext.getDatabase().getEntries().get(0).setField("year","2014"); + correctContext.getDatabase().getEntries().get(0).setField("author", "Knuth"); + correctContext.getDatabase().getEntries().get(0).setField("year", "2014"); assertCorrect(correctContext); final BibDatabaseContext wrongContext = createContext("bibtexkey", "Knuth2014a"); - wrongContext.getDatabase().getEntries().get(0).setField("author","Knuth"); - wrongContext.getDatabase().getEntries().get(0).setField("year","2014"); + wrongContext.getDatabase().getEntries().get(0).setField("author", "Knuth"); + wrongContext.getDatabase().getEntries().get(0).setField("year", "2014"); assertWrong(wrongContext); } @@ -410,5 +410,4 @@ private BibDatabaseContext withMode(BibDatabaseContext context, BibDatabaseMode context.setMode(mode); return context; } - } diff --git a/src/test/java/org/jabref/logic/integrity/NoBibTexFieldCheckerTest.java b/src/test/java/org/jabref/logic/integrity/NoBibTexFieldCheckerTest.java index 7539dc826a6..1ce9aae56a7 100644 --- a/src/test/java/org/jabref/logic/integrity/NoBibTexFieldCheckerTest.java +++ b/src/test/java/org/jabref/logic/integrity/NoBibTexFieldCheckerTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class NoBibTexFieldCheckerTest { private final NoBibtexFieldChecker checker = new NoBibtexFieldChecker(); @@ -96,5 +95,4 @@ public void reviewIsNotRecognizedAsBiblatexOnlyField() { entry.setField("review", "test"); assertEquals(Collections.emptyList(), checker.check(entry)); } - } diff --git a/src/test/java/org/jabref/logic/journals/AbbreviationParserTest.java b/src/test/java/org/jabref/logic/journals/AbbreviationParserTest.java index 15c761dd2b5..4381458a39c 100644 --- a/src/test/java/org/jabref/logic/journals/AbbreviationParserTest.java +++ b/src/test/java/org/jabref/logic/journals/AbbreviationParserTest.java @@ -10,6 +10,6 @@ public class AbbreviationParserTest { public void testReadJournalListFromResource() { AbbreviationParser ap = new AbbreviationParser(); ap.readJournalListFromResource("/journals/journalList.txt"); - assertFalse(ap.getAbbreviations().isEmpty()); + assertFalse(ap.getAbbreviations().isEmpty()); } } diff --git a/src/test/java/org/jabref/logic/journals/AbbreviationTest.java b/src/test/java/org/jabref/logic/journals/AbbreviationTest.java index cf1a769df72..bfd45940a51 100644 --- a/src/test/java/org/jabref/logic/journals/AbbreviationTest.java +++ b/src/test/java/org/jabref/logic/journals/AbbreviationTest.java @@ -47,5 +47,4 @@ public void testIsoAndMedlineAbbreviationsAreSame() { Abbreviation abbreviation = new Abbreviation(" Long Name ", " L N "); assertEquals(abbreviation.getIsoAbbreviation(), abbreviation.getMedlineAbbreviation()); } - } diff --git a/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java b/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java index ec4ed515926..47b6240c8a5 100644 --- a/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java +++ b/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java @@ -24,7 +24,7 @@ public void getNextAbbreviationAbbreviatesIEEEJournalTitle() { assertEquals("#IEEE_J_PROC#", abbreviations.getRepository(prefs) - .getNextAbbreviation("Proceedings of the IEEE").get()); + .getNextAbbreviation("Proceedings of the IEEE").get()); } @Test @@ -33,27 +33,27 @@ public void getNextAbbreviationExpandsIEEEAbbreviation() { assertEquals("Proceedings of the IEEE", abbreviations.getRepository(prefs) - .getNextAbbreviation("#IEEE_J_PROC#").get()); + .getNextAbbreviation("#IEEE_J_PROC#").get()); } @Test public void getNextAbbreviationAbbreviatesJournalTitle() { assertEquals("Proc. IEEE", abbreviations.getRepository(prefs) - .getNextAbbreviation("Proceedings of the IEEE").get()); + .getNextAbbreviation("Proceedings of the IEEE").get()); } @Test public void getNextAbbreviationRemovesPoint() { assertEquals("Proc IEEE", abbreviations.getRepository(prefs) - .getNextAbbreviation("Proc. IEEE").get()); + .getNextAbbreviation("Proc. IEEE").get()); } @Test public void getNextAbbreviationExpandsAbbreviation() { assertEquals("Proceedings of the IEEE", abbreviations.getRepository(prefs) - .getNextAbbreviation("Proc IEEE").get()); + .getNextAbbreviation("Proc IEEE").get()); } } diff --git a/src/test/java/org/jabref/logic/journals/JournalAbbreviationRepositoryTest.java b/src/test/java/org/jabref/logic/journals/JournalAbbreviationRepositoryTest.java index f8c99cff5d4..5582e0f7aa9 100644 --- a/src/test/java/org/jabref/logic/journals/JournalAbbreviationRepositoryTest.java +++ b/src/test/java/org/jabref/logic/journals/JournalAbbreviationRepositoryTest.java @@ -36,7 +36,6 @@ public void oneElement() { assertTrue(repository.isKnownName("L. N.")); assertTrue(repository.isKnownName("L N")); assertFalse(repository.isKnownName("?")); - } @Test @@ -65,7 +64,5 @@ public void testDuplicateKeys() { repository.addEntry(new Abbreviation("Long Name", "LA. N.")); assertEquals(1, repository.size()); assertEquals("LA. N.", repository.getIsoAbbreviation("Long Name").orElse("WRONG")); - } - } diff --git a/src/test/java/org/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java b/src/test/java/org/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java index dbff021a2df..bda85d58207 100644 --- a/src/test/java/org/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java +++ b/src/test/java/org/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java @@ -29,5 +29,4 @@ public void noDuplicatesInShippedIEEEStandardJournalAbbreviations() { assertFalse(repoBuiltIn.getAbbreviation(abbreviation.getMedlineAbbreviation()).isPresent(), "duplicate medline " + abbreviation.toString()); }); } - } diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationConsistencyTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationConsistencyTest.java index 63848639692..6f8aa2c15de 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationConsistencyTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationConsistencyTest.java @@ -93,27 +93,27 @@ void languageKeysShouldNotBeQuotedInFiles() throws IOException { assertEquals(Collections.EMPTY_LIST, quotedEntries, "Language keys must not be used quoted in code! Use \"This is a message\" instead of \"This_is_a_message\".\n" + - "Please correct the following entries:\n" + - quotedEntries - .stream() - .map(key -> String.format("\n%s (%s)\n", key.getKey(), key.getPath())) - .collect(Collectors.toList())); + "Please correct the following entries:\n" + + quotedEntries + .stream() + .map(key -> String.format("\n%s (%s)\n", key.getKey(), key.getPath())) + .collect(Collectors.toList())); } @Test void findMissingLocalizationKeys() throws IOException { List missingKeys = LocalizationParser.find(LocalizationBundleForTest.LANG) - .stream() - .sorted() - .distinct() - .collect(Collectors.toList()); + .stream() + .sorted() + .distinct() + .collect(Collectors.toList()); assertEquals(Collections.emptyList(), missingKeys, "DETECTED LANGUAGE KEYS WHICH ARE NOT IN THE ENGLISH LANGUAGE FILE\n" + - "PASTE THESE INTO THE ENGLISH LANGUAGE FILE\n" + - missingKeys.parallelStream() - .map(key -> String.format("\n%s=%s\n", key.getKey(), key.getKey().replaceAll("\\\\ ", " "))) - .collect(Collectors.joining("\n"))); + "PASTE THESE INTO THE ENGLISH LANGUAGE FILE\n" + + missingKeys.parallelStream() + .map(key -> String.format("\n%s=%s\n", key.getKey(), key.getKey().replaceAll("\\\\ ", " "))) + .collect(Collectors.joining("\n"))); } @Test @@ -122,10 +122,10 @@ void findObsoleteLocalizationKeys() throws IOException { assertEquals(Collections.emptySet(), obsoleteKeys, "Obsolete keys found in language properties file: \n" + - obsoleteKeys.stream().collect(Collectors.joining("\n")) + - "\n" + - "1. CHECK IF THE KEY IS REALLY NOT USED ANYMORE\n" + - "2. REMOVE THESE FROM THE ENGLISH LANGUAGE FILE\n"); + obsoleteKeys.stream().collect(Collectors.joining("\n")) + + "\n" + + "1. CHECK IF THE KEY IS REALLY NOT USED ANYMORE\n" + + "2. REMOVE THESE FROM THE ENGLISH LANGUAGE FILE\n"); } @Test diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationEntry.java b/src/test/java/org/jabref/logic/l10n/LocalizationEntry.java index 9c814d64849..ed4fd477853 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationEntry.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationEntry.java @@ -3,7 +3,7 @@ import java.nio.file.Path; import java.util.Objects; -class LocalizationEntry implements Comparable{ +class LocalizationEntry implements Comparable { private final Path path; private final String key; @@ -42,7 +42,6 @@ public boolean equals(Object o) { return false; } return bundle == that.bundle; - } @Override diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationKeyParamsTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationKeyParamsTest.java index 0edc4975f8b..657d0e76649 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationKeyParamsTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationKeyParamsTest.java @@ -20,5 +20,4 @@ public void testReplacePlaceholders() { public void testTooManyParams() { assertThrows(IllegalStateException.class, () -> new LocalizationKeyParams("", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0")); } - } diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationKeyTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationKeyTest.java index 42a492d44fa..407800bfb6f 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationKeyTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationKeyTest.java @@ -19,5 +19,4 @@ void underscoreIsPreserved() { LocalizationKey localizationKey = new LocalizationKey("test_with_underscore"); assertEquals("test_with_underscore", localizationKey.getPropertiesKey()); } - } diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationParser.java b/src/test/java/org/jabref/logic/l10n/LocalizationParser.java index 8ffdd5a7a96..ee9d254305b 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationParser.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationParser.java @@ -32,10 +32,10 @@ public static SortedSet find(LocalizationBundleForTest type) Set entries = findLocalizationEntriesInFiles(type); Set keysInJavaFiles = entries.stream() - .map(LocalizationEntry::getKey) - .distinct() - .sorted() - .collect(Collectors.toSet()); + .map(LocalizationEntry::getKey) + .distinct() + .sorted() + .collect(Collectors.toSet()); Set englishKeys; if (type == LocalizationBundleForTest.LANG) { @@ -117,11 +117,11 @@ public static SortedSet getKeysInPropertiesFile(String path) { Properties properties = getProperties(path); return properties.keySet().stream() - .sorted() - .map(Object::toString) - .map(String::trim) - .map(e -> new LocalizationKey(e).getPropertiesKey()) - .collect(Collectors.toCollection(TreeSet::new)); + .sorted() + .map(Object::toString) + .map(String::trim) + .map(e -> new LocalizationKey(e).getPropertiesKey()) + .collect(Collectors.toCollection(TreeSet::new)); } public static Properties getProperties(String path) { @@ -222,8 +222,8 @@ public boolean containsKey(String key) { } return result.stream() - .map(key -> new LocalizationEntry(path, new LocalizationKey(key).getPropertiesKey(), type)) - .collect(Collectors.toList()); + .map(key -> new LocalizationEntry(path, new LocalizationKey(key).getPropertiesKey(), type)) + .collect(Collectors.toList()); } static class JavaLocalizationEntryParser { diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationParserTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationParserTest.java index 2463a15cdc6..b6b0f5a69de 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationParserTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationParserTest.java @@ -50,5 +50,4 @@ private void assertLocalizationParameterParsing(String code, List expect private void assertLocalizationParameterParsing(String code, String expectedParameter) { assertLocalizationParameterParsing(code, Collections.singletonList(expectedParameter)); } - } diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationTest.java index 021c5c53bd1..37d22dacead 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationTest.java @@ -65,5 +65,4 @@ void testUnknownTranslation() { void testUnsetLanguageTranslation() { assertEquals("Groups", Localization.lang("Groups")); } - } diff --git a/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java b/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java index b3f669d4ca7..340fd35f7ad 100644 --- a/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java +++ b/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java @@ -12,27 +12,24 @@ import static org.mockito.Mockito.mock; /** - * The test class LayoutEntryTest test the net.sf.jabref.export.layout.LayoutEntry. - * Indirectly the net.sf.jabref.export.layout.Layout is tested too. + * The test class LayoutEntryTest test the net.sf.jabref.export.layout.LayoutEntry. Indirectly the + * net.sf.jabref.export.layout.Layout is tested too. *

- * The LayoutEntry creates a human readable String assigned with HTML formatters. - * To test the Highlighting Feature, an instance of LayoutEntry will be instantiated via Layout and LayoutHelper. - * With these instance the doLayout() Method is called several times for each test case. - * To simulate a search, a BibEntry will be created, which will be used by LayoutEntry. + * The LayoutEntry creates a human readable String assigned with HTML formatters. To test the Highlighting Feature, an + * instance of LayoutEntry will be instantiated via Layout and LayoutHelper. With these instance the doLayout() Method + * is called several times for each test case. To simulate a search, a BibEntry will be created, which will be used by + * LayoutEntry. * - * There are five test cases: - * - The shown result text has no words which should be highlighted. - * - There is one word which will be highlighted ignoring case sensitivity. - * - There are two words which will be highlighted ignoring case sensitivity. - * - There is one word which will be highlighted case sensitivity. - * - There are more words which will be highlighted case sensitivity. + * There are five test cases: - The shown result text has no words which should be highlighted. - There is one word + * which will be highlighted ignoring case sensitivity. - There are two words which will be highlighted ignoring case + * sensitivity. - There is one word which will be highlighted case sensitivity. - There are more words which will be + * highlighted case sensitivity. */ public class LayoutEntryTest { private BibEntry mBTE; - @BeforeEach public void setUp() { mBTE = new BibEntry(); @@ -95,5 +92,4 @@ public void testParseMethodCalls() { assertEquals("test", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(0)).get(1)); assertEquals("fark", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(1)).get(1)); } - } diff --git a/src/test/java/org/jabref/logic/layout/LayoutTest.java b/src/test/java/org/jabref/logic/layout/LayoutTest.java index 899c62d1446..34c8ae2418f 100644 --- a/src/test/java/org/jabref/logic/layout/LayoutTest.java +++ b/src/test/java/org/jabref/logic/layout/LayoutTest.java @@ -98,7 +98,7 @@ void HTMLCharsWithDotlessIAndTiled() throws IOException { } @Test - // Test for http://discourse.jabref.org/t/the-wrapfilelinks-formatter/172 (the example in the help files) + // Test for http://discourse.jabref.org/t/the-wrapfilelinks-formatter/172 (the example in the help files) void wrapFileLinksExpandFile() throws IOException { when(layoutFormatterPreferences.getFileLinkPreferences()).thenReturn( new FileLinkPreferences(Collections.emptyList(), Collections.singletonList("src/test/resources/pdfs/"))); diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorAbbreviatorTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorAbbreviatorTest.java index 9ae1cbc797c..9ed893e166d 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorAbbreviatorTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorAbbreviatorTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Is the save as the AuthorLastFirstAbbreviator. */ @@ -21,7 +22,5 @@ public void testFormat() { assertEquals(b.format("Smith, John"), a.format("Smith, John")); assertEquals(b.format("von Neumann, John and Smith, John and Black Brown, Peter"), a .format("von Neumann, John and Smith, John and Black Brown, Peter")); - } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacerTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacerTest.java index 94b37737595..317400fbad3 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacerTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacerTest.java @@ -14,11 +14,11 @@ class AuthorAndToSemicolonReplacerTest { private static Stream data() { return Stream.of( - Arguments.of("",""), + Arguments.of("", ""), Arguments.of("Someone, Van Something", "Someone, Van Something"), Arguments.of("John Smith and Black Brown, Peter", "John Smith; Black Brown, Peter"), Arguments.of("von Neumann, John and Smith, John and Black Brown, Peter", "von Neumann, John; Smith, John; Black Brown, Peter"), - Arguments.of("John von Neumann and John Smith and Peter Black Brown","John von Neumann; John Smith; Peter Black Brown")); + Arguments.of("John von Neumann and John Smith and Peter Black Brown", "John von Neumann; John Smith; Peter Black Brown")); } @ParameterizedTest diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacerTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacerTest.java index 19a643988d0..f19b4681d6e 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacerTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacerTest.java @@ -2,14 +2,14 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorAndsCommaReplacerTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorAndsCommaReplacer#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorAndsCommaReplacer#format(java.lang.String)}. */ @Test public void testFormat() { diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorAndsReplacerTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorAndsReplacerTest.java index 44a85ca7ce6..9c2bcb40c2c 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorAndsReplacerTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorAndsReplacerTest.java @@ -2,14 +2,14 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorAndsReplacerTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorAndsReplacer#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorAndsReplacer#format(java.lang.String)}. */ @Test public void testFormat() { @@ -32,5 +32,4 @@ public void testFormat() { assertEquals("John von Neumann; John Smith & Peter Black Brown", a .format("John von Neumann and John Smith and Peter Black Brown")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommasTest.java index 9a91ff56c9b..b4f6f544589 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstAbbrLastCommasTest { @Test @@ -28,5 +29,4 @@ public void testFormat() { assertEquals("J. von Neumann, J. Smith and P. Black Brown", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommasTest.java index 9871a0a9da5..f35de4b55ac 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstAbbrLastOxfordCommasTest { /** @@ -31,5 +32,4 @@ public void testFormat() { assertEquals("J. von Neumann, J. Smith, and P. Black Brown", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstCommasTest.java index 97a9c29b82c..1972b6b781e 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstCommasTest.java @@ -1,13 +1,13 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstFirstCommasTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorFirstFirstCommas#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorFirstFirstCommas#format(java.lang.String)}. */ @Test public void testFormat() { @@ -15,5 +15,4 @@ public void testFormat() { new AuthorFirstFirstCommas() .format("von Neumann,,John and John Smith and Black Brown, Jr, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstTest.java index d61d5840520..d71647dd45e 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstTest.java @@ -1,13 +1,13 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstFirstTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorFirstFirst#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorFirstFirst#format(java.lang.String)}. */ @Test public void testFormat() { @@ -15,5 +15,4 @@ public void testFormat() { new AuthorFirstFirst() .format("von Neumann,,John and John Smith and Black Brown, Jr, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastCommasTest.java index 8607bfffeb1..6ba9a15966d 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstLastCommasTest { /** @@ -31,5 +32,4 @@ public void testFormat() { assertEquals("John von Neumann, John Smith and Peter Black Brown", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommasTest.java index 9f8a91fd569..14c31580339 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorFirstLastOxfordCommasTest { /** @@ -31,5 +32,4 @@ public void testFormat() { assertEquals("John von Neumann, John Smith, and Peter Black Brown", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFAbbrTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFAbbrTest.java index 795c7129f0c..937f7e0a71a 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFAbbrTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFAbbrTest.java @@ -1,13 +1,13 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLF_FFAbbrTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorLF_FFAbbr#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorLF_FFAbbr#format(java.lang.String)}. */ @Test public void testFormat() { @@ -15,5 +15,4 @@ public void testFormat() { new AuthorLF_FFAbbr() .format("von Neumann,,John and John Smith and Black Brown, Jr, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java index 1531cbfd0aa..c3bd13219bc 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java @@ -1,13 +1,13 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLF_FFTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}. */ @Test public void testFormat() { @@ -15,5 +15,4 @@ public void testFormat() { new AuthorLF_FF() .format("von Neumann,,John and John Smith and Black Brown, Jr, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommasTest.java index 63faf76cd37..e49653a18c2 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLastFirstAbbrCommasTest { /** @@ -30,7 +31,5 @@ public void testFormat() { assertEquals("von Neumann, J., Smith, J. and Black Brown, P.", a .format("John von Neumann and John Smith and Black Brown, Peter")); - } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommasTest.java index e3ada4bd62a..21a8e6a195d 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLastFirstAbbrOxfordCommasTest { /** @@ -31,5 +32,4 @@ public void testFormat() { assertEquals("von Neumann, J., Smith, J., and Black Brown, P.", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java index 91bf403bd74..f28a1055396 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java @@ -5,8 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Test case that verifies the functionalities of the - * formater AuthorLastFirstAbbreviator. + * Test case that verifies the functionalities of the formater AuthorLastFirstAbbreviator. */ class AuthorLastFirstAbbreviatorTester { @@ -60,5 +59,4 @@ void testFormat() { private String abbreviate(String name) { return new AuthorLastFirstAbbreviator().format(name); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstCommasTest.java index 9e141ca1925..8a544a5a7d0 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstCommasTest.java @@ -2,14 +2,14 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLastFirstCommasTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorLastFirstCommas#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorLastFirstCommas#format(java.lang.String)}. */ @Test public void testFormat() { @@ -33,5 +33,4 @@ public void testFormat() { assertEquals("von Neumann, John, Smith, John and Black Brown, Peter", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommasTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommasTest.java index 930a0ae6a6d..e3beacbd4b4 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommasTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommasTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLastFirstOxfordCommasTest { /** @@ -31,5 +32,4 @@ public void testFormat() { assertEquals("von Neumann, John, Smith, John, and Black Brown, Peter", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstTest.java index 8d1822ec1b7..8d26609ee87 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorLastFirstTest { @Test @@ -28,5 +29,4 @@ public void testFormat() { assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", a .format("John von Neumann and John Smith and Black Brown, Peter")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorNatBibTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorNatBibTest.java index b6308e0daa9..35b8d4b0cae 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorNatBibTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorNatBibTest.java @@ -1,13 +1,13 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorNatBibTest { /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorNatBib#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorNatBib#format(java.lang.String)}. */ @Test public void testFormatThreeAuthors() { @@ -16,12 +16,10 @@ public void testFormatThreeAuthors() { } /** - * Test method for - * {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}. + * Test method for {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}. */ @Test public void testFormatTwoAuthors() { assertEquals("von Neumann and Smith", new AuthorNatBib().format("von Neumann,,John and John Smith")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorOrgSciTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorOrgSciTest.java index 568cae4a8d3..522c4caae58 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorOrgSciTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorOrgSciTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorOrgSciTest { @Test @@ -14,7 +15,6 @@ public void testOrgSci() { assertEquals("Flynn, J., S. Gartska", f.format("John Flynn and Sabine Gartska")); assertEquals("Garvin, D. A.", f.format("David A. Garvin")); assertEquals("Makridakis, S., S. C. Wheelwright, V. E. McGee", f.format("Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")); - } @Test diff --git a/src/test/java/org/jabref/logic/layout/format/AuthorsTest.java b/src/test/java/org/jabref/logic/layout/format/AuthorsTest.java index 581d32c236f..fe0cb06ca4d 100644 --- a/src/test/java/org/jabref/logic/layout/format/AuthorsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/AuthorsTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class AuthorsTest { @Test @@ -153,5 +154,4 @@ public void testEmptyEtAl() { assertEquals("Bruce, Bob Croydon", a.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java b/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java index b7869a703ff..da23a764241 100644 --- a/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java +++ b/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class CompositeFormatTest { @Test @@ -15,7 +16,7 @@ public void testEmptyComposite() { @Test public void testArrayComposite() { - 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")); @@ -33,5 +34,4 @@ public void testDoubleComposite() { assertEquals(second.format(first.format("Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")), f.format("Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/DOICheckTest.java b/src/test/java/org/jabref/logic/layout/format/DOICheckTest.java index fae8c751630..e14af93ecbd 100644 --- a/src/test/java/org/jabref/logic/layout/format/DOICheckTest.java +++ b/src/test/java/org/jabref/logic/layout/format/DOICheckTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class DOICheckTest { @Test @@ -34,5 +35,4 @@ public void testFormat() { // Obviously a wrong doi, will not change anything. assertEquals("1", lf.format("1")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java b/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java index c4f40d3b835..8bb16e57265 100644 --- a/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java +++ b/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class DOIStripTest { @Test @@ -20,7 +21,5 @@ public void testFormat() { assertEquals("10.1000/ISBN1-900512-44-0", lf.format("http://doi.acm.org/10.1000/ISBN1-900512-44-0")); - } - } diff --git a/src/test/java/org/jabref/logic/layout/format/DateFormatterTest.java b/src/test/java/org/jabref/logic/layout/format/DateFormatterTest.java index 7ada16578a6..b9f878d25ae 100644 --- a/src/test/java/org/jabref/logic/layout/format/DateFormatterTest.java +++ b/src/test/java/org/jabref/logic/layout/format/DateFormatterTest.java @@ -2,10 +2,11 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class DateFormatterTest { private ParamLayoutFormatter formatter; @@ -25,5 +26,4 @@ public void testRequestedFormat() { formatter.setArgument("MM/yyyy"); assertEquals("07/2016", formatter.format("2016-07-15")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/DefaultTest.java b/src/test/java/org/jabref/logic/layout/format/DefaultTest.java index c4c386d2975..c746de8c858 100644 --- a/src/test/java/org/jabref/logic/layout/format/DefaultTest.java +++ b/src/test/java/org/jabref/logic/layout/format/DefaultTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class DefaultTest { @Test @@ -45,5 +46,4 @@ public void testNoArgumentSetEmptyInput() { ParamLayoutFormatter a = new Default(); assertEquals("", a.format("")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/EntryTypeFormatterTest.java b/src/test/java/org/jabref/logic/layout/format/EntryTypeFormatterTest.java index 89d6850f593..0dd5c4f7c11 100644 --- a/src/test/java/org/jabref/logic/layout/format/EntryTypeFormatterTest.java +++ b/src/test/java/org/jabref/logic/layout/format/EntryTypeFormatterTest.java @@ -9,7 +9,6 @@ public class EntryTypeFormatterTest { private EntryTypeFormatter formatter; - @BeforeEach public void setUp() { formatter = new EntryTypeFormatter(); @@ -29,5 +28,4 @@ public void testCorrectFormatInBook() { public void testIncorrectTypeAarticle() { assertEquals("Aarticle", formatter.format("aarticle")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java b/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java index 23c5c205232..f15ae958dc2 100644 --- a/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java +++ b/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java @@ -8,10 +8,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; - public class FileLinkTest { private FileLinkPreferences prefs; + @BeforeEach public void setUp() throws Exception { prefs = mock(FileLinkPreferences.class); @@ -60,5 +60,4 @@ public void testMultipleFilesPickNonExistant() { a.setArgument("doc"); assertEquals("", a.format("paper:test.pdf:PDF;presentation:pres.ppt:PPT")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/FirstPageTest.java b/src/test/java/org/jabref/logic/layout/format/FirstPageTest.java index 5c20c5d7898..f0aa9836743 100644 --- a/src/test/java/org/jabref/logic/layout/format/FirstPageTest.java +++ b/src/test/java/org/jabref/logic/layout/format/FirstPageTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class FirstPageTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java b/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java index 42d6a488683..1bd1c441935 100644 --- a/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java @@ -64,7 +64,6 @@ public void testLaTeXHighlighting() { assertEquals("hallo", layout.format("\\underline{hallo}")); assertEquals("hallo", layout.format("\\sout{hallo}")); assertEquals("hallo", layout.format("\\texttt{hallo}")); - } @Test diff --git a/src/test/java/org/jabref/logic/layout/format/HTMLParagraphsTest.java b/src/test/java/org/jabref/logic/layout/format/HTMLParagraphsTest.java index 6cd36359c4e..6b2094c3ce4 100644 --- a/src/test/java/org/jabref/logic/layout/format/HTMLParagraphsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/HTMLParagraphsTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class HTMLParagraphsTest { @Test @@ -17,7 +18,5 @@ public void testFormat() { assertEquals("

\nHello\nWorld\n

", f.format("Hello\nWorld")); assertEquals("

\nHello World\n

\n

\nWhat a lovely day\n

", f.format("Hello World\n \nWhat a lovely day\n")); assertEquals("

\nHello World\n

\n

\nCould not be any better\n

\n

\nWhat a lovely day\n

", f.format("Hello World\n \n\nCould not be any better\n\nWhat a lovely day\n")); - } - } diff --git a/src/test/java/org/jabref/logic/layout/format/IfPluralTest.java b/src/test/java/org/jabref/logic/layout/format/IfPluralTest.java index 5ebd278be81..bb5dbbaceff 100644 --- a/src/test/java/org/jabref/logic/layout/format/IfPluralTest.java +++ b/src/test/java/org/jabref/logic/layout/format/IfPluralTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class IfPluralTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/LastPageTest.java b/src/test/java/org/jabref/logic/layout/format/LastPageTest.java index 64dece591f0..6647038a126 100644 --- a/src/test/java/org/jabref/logic/layout/format/LastPageTest.java +++ b/src/test/java/org/jabref/logic/layout/format/LastPageTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class LastPageTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/LatexToUnicodeFormatterTest.java b/src/test/java/org/jabref/logic/layout/format/LatexToUnicodeFormatterTest.java index cf4dbb86723..0c6203356dc 100644 --- a/src/test/java/org/jabref/logic/layout/format/LatexToUnicodeFormatterTest.java +++ b/src/test/java/org/jabref/logic/layout/format/LatexToUnicodeFormatterTest.java @@ -31,7 +31,6 @@ public void testFormatTextit() { assertEquals("\uD835\uDC61\uD835\uDC52\uD835\uDC65\uD835\uDC61", formatter.format("\\textit{text}")); } - @Test public void testEscapedDollarSign() { assertEquals("$", formatter.format("\\$")); @@ -75,7 +74,6 @@ public void testIWithDiaresisAndEscapedI() { assertEquals("ı̈", formatter.format("\\\"{\\i}")); } - @Test public void testIWithDiaresisAndUnnecessaryBraces() { assertEquals("ï", formatter.format("{\\\"{i}}")); @@ -91,7 +89,6 @@ public void testPolishName() { assertEquals("Łęski", formatter.format("\\L\\k{e}ski")); } - @Test public void testDoubleCombiningAccents() { assertEquals("ώ", formatter.format("$\\acute{\\omega}$")); @@ -190,5 +187,4 @@ public void testConversionOfOrdinal4th() { public void testConversionOfOrdinal9th() { assertEquals("9ᵗʰ", formatter.format("9\\textsuperscript{th}")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/NameFormatterTest.java b/src/test/java/org/jabref/logic/layout/format/NameFormatterTest.java index 0b5adc77462..41ff6b2ff5d 100644 --- a/src/test/java/org/jabref/logic/layout/format/NameFormatterTest.java +++ b/src/test/java/org/jabref/logic/layout/format/NameFormatterTest.java @@ -1,8 +1,9 @@ package org.jabref.logic.layout.format; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class NameFormatterTest { @Test @@ -27,7 +28,6 @@ public void testFormatStringStringBibtexEntry() { assertEquals("Doe Joe and Jane, M. and Kamp, J.~A.", l.format("Joe Doe and Mary Jane and John Arthur van Kamp", "1@*@{ll}, {ff}@@*@1@{ll} {ff}@2..-1@ and {ll}, {f}.")); - } @Test @@ -58,5 +58,4 @@ public void testFormat() { assertEquals("von Neumann John, Smith, John, Vandekamp, Mary~Ann and Black~Brown, Peter", a.format( "von Neumann, John and Smith, John and Vandekamp, Mary Ann and Black Brown, Peter", formatString)); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviationsTest.java b/src/test/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviationsTest.java index e49493fe097..bd787b1ce39 100644 --- a/src/test/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviationsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviationsTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class NoSpaceBetweenAbbreviationsTest { @Test @@ -16,5 +17,4 @@ public void testFormat() { assertEquals("J.R.R. Tolkien", f.format("J. R. R. Tolkien")); assertEquals("J.R.R. Tolkien and J.F. Kennedy", f.format("J. R. R. Tolkien and J. F. Kennedy")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/RTFCharsTest.java b/src/test/java/org/jabref/logic/layout/format/RTFCharsTest.java index 3e1f6e972b1..68c50e17384 100644 --- a/src/test/java/org/jabref/logic/layout/format/RTFCharsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/RTFCharsTest.java @@ -2,12 +2,12 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + class RTFCharsTest { private LayoutFormatter formatter; @@ -88,7 +88,7 @@ void testComplicated5() { @Test void testComplicated6() { assertEquals("Pchn\\u261a\\u263c w t\\u281e \\u322l\\u243od\\u378z je\\u380za lub o\\u347sm skrzy\\u324n fig" - ,formatter.format("Pchnąć w tę łódź jeża lub ośm skrzyń fig")); + , formatter.format("Pchnąć w tę łódź jeża lub ośm skrzyń fig")); } @Test @@ -131,59 +131,58 @@ void testSpecialCharacters() { } @Test - void testRTFCharacters(){ - assertEquals("\\'e0",formatter.format("\\`{a}")); - assertEquals("\\'e8",formatter.format("\\`{e}")); - assertEquals("\\'ec",formatter.format("\\`{i}")); - assertEquals("\\'f2",formatter.format("\\`{o}")); - assertEquals("\\'f9",formatter.format("\\`{u}")); - - assertEquals("\\'e1",formatter.format("\\'a")); - assertEquals("\\'e9",formatter.format("\\'e")); - assertEquals("\\'ed",formatter.format("\\'i")); - assertEquals("\\'f3",formatter.format("\\'o")); - assertEquals("\\'fa",formatter.format("\\'u")); - - assertEquals("\\'e2",formatter.format("\\^a")); - assertEquals("\\'ea",formatter.format("\\^e")); - assertEquals("\\'ee",formatter.format("\\^i")); - assertEquals("\\'f4",formatter.format("\\^o")); - assertEquals("\\'fa",formatter.format("\\^u")); - - assertEquals("\\'e4",formatter.format("\\\"a")); - assertEquals("\\'eb",formatter.format("\\\"e")); - assertEquals("\\'ef",formatter.format("\\\"i")); - assertEquals("\\'f6",formatter.format("\\\"o")); - assertEquals("\\u252u",formatter.format("\\\"u")); - - assertEquals("\\'f1",formatter.format("\\~n")); + void testRTFCharacters() { + assertEquals("\\'e0", formatter.format("\\`{a}")); + assertEquals("\\'e8", formatter.format("\\`{e}")); + assertEquals("\\'ec", formatter.format("\\`{i}")); + assertEquals("\\'f2", formatter.format("\\`{o}")); + assertEquals("\\'f9", formatter.format("\\`{u}")); + + assertEquals("\\'e1", formatter.format("\\'a")); + assertEquals("\\'e9", formatter.format("\\'e")); + assertEquals("\\'ed", formatter.format("\\'i")); + assertEquals("\\'f3", formatter.format("\\'o")); + assertEquals("\\'fa", formatter.format("\\'u")); + + assertEquals("\\'e2", formatter.format("\\^a")); + assertEquals("\\'ea", formatter.format("\\^e")); + assertEquals("\\'ee", formatter.format("\\^i")); + assertEquals("\\'f4", formatter.format("\\^o")); + assertEquals("\\'fa", formatter.format("\\^u")); + + assertEquals("\\'e4", formatter.format("\\\"a")); + assertEquals("\\'eb", formatter.format("\\\"e")); + assertEquals("\\'ef", formatter.format("\\\"i")); + assertEquals("\\'f6", formatter.format("\\\"o")); + assertEquals("\\u252u", formatter.format("\\\"u")); + + assertEquals("\\'f1", formatter.format("\\~n")); } @Test void testRTFCharactersCapital() { - assertEquals("\\'c0",formatter.format("\\`A")); - assertEquals("\\'c8",formatter.format("\\`E")); - assertEquals("\\'cc",formatter.format("\\`I")); - assertEquals("\\'d2",formatter.format("\\`O")); - assertEquals("\\'d9",formatter.format("\\`U")); - - assertEquals("\\'c1",formatter.format("\\'A")); - assertEquals("\\'c9",formatter.format("\\'E")); - assertEquals("\\'cd",formatter.format("\\'I")); - assertEquals("\\'d3",formatter.format("\\'O")); - assertEquals("\\'da",formatter.format("\\'U")); - - assertEquals("\\'c2",formatter.format("\\^A")); - assertEquals("\\'ca",formatter.format("\\^E")); - assertEquals("\\'ce",formatter.format("\\^I")); - assertEquals("\\'d4",formatter.format("\\^O")); - assertEquals("\\'db",formatter.format("\\^U")); - - assertEquals("\\'c4",formatter.format("\\\"A")); - assertEquals("\\'cb",formatter.format("\\\"E")); - assertEquals("\\'cf",formatter.format("\\\"I")); - assertEquals("\\'d6",formatter.format("\\\"O")); - assertEquals("\\'dc",formatter.format("\\\"U")); + assertEquals("\\'c0", formatter.format("\\`A")); + assertEquals("\\'c8", formatter.format("\\`E")); + assertEquals("\\'cc", formatter.format("\\`I")); + assertEquals("\\'d2", formatter.format("\\`O")); + assertEquals("\\'d9", formatter.format("\\`U")); + + assertEquals("\\'c1", formatter.format("\\'A")); + assertEquals("\\'c9", formatter.format("\\'E")); + assertEquals("\\'cd", formatter.format("\\'I")); + assertEquals("\\'d3", formatter.format("\\'O")); + assertEquals("\\'da", formatter.format("\\'U")); + + assertEquals("\\'c2", formatter.format("\\^A")); + assertEquals("\\'ca", formatter.format("\\^E")); + assertEquals("\\'ce", formatter.format("\\^I")); + assertEquals("\\'d4", formatter.format("\\^O")); + assertEquals("\\'db", formatter.format("\\^U")); + + assertEquals("\\'c4", formatter.format("\\\"A")); + assertEquals("\\'cb", formatter.format("\\\"E")); + assertEquals("\\'cf", formatter.format("\\\"I")); + assertEquals("\\'d6", formatter.format("\\\"O")); + assertEquals("\\'dc", formatter.format("\\\"U")); } - } diff --git a/src/test/java/org/jabref/logic/layout/format/RemoveTildeTest.java b/src/test/java/org/jabref/logic/layout/format/RemoveTildeTest.java index 31406596bfe..1961b3dfac5 100644 --- a/src/test/java/org/jabref/logic/layout/format/RemoveTildeTest.java +++ b/src/test/java/org/jabref/logic/layout/format/RemoveTildeTest.java @@ -2,10 +2,11 @@ import org.jabref.logic.layout.LayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class RemoveTildeTest { private LayoutFormatter formatter; diff --git a/src/test/java/org/jabref/logic/layout/format/ReplaceTest.java b/src/test/java/org/jabref/logic/layout/format/ReplaceTest.java index e5653beb9f7..3d1eb4ebb9b 100644 --- a/src/test/java/org/jabref/logic/layout/format/ReplaceTest.java +++ b/src/test/java/org/jabref/logic/layout/format/ReplaceTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class ReplaceTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/RisKeywordsTest.java b/src/test/java/org/jabref/logic/layout/format/RisKeywordsTest.java index 3cf2333bab6..863683620fa 100644 --- a/src/test/java/org/jabref/logic/layout/format/RisKeywordsTest.java +++ b/src/test/java/org/jabref/logic/layout/format/RisKeywordsTest.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class RisKeywordsTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/RisMonthTest.java b/src/test/java/org/jabref/logic/layout/format/RisMonthTest.java index b3880bec7cb..cd8bfbec58a 100644 --- a/src/test/java/org/jabref/logic/layout/format/RisMonthTest.java +++ b/src/test/java/org/jabref/logic/layout/format/RisMonthTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class RisMonthTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/ToLowerCaseTest.java b/src/test/java/org/jabref/logic/layout/format/ToLowerCaseTest.java index 59ce12216b5..be565fcdc6f 100644 --- a/src/test/java/org/jabref/logic/layout/format/ToLowerCaseTest.java +++ b/src/test/java/org/jabref/logic/layout/format/ToLowerCaseTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; - public class ToLowerCaseTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/ToUpperCaseTest.java b/src/test/java/org/jabref/logic/layout/format/ToUpperCaseTest.java index b0ca246bdd9..adb559e5bf9 100644 --- a/src/test/java/org/jabref/logic/layout/format/ToUpperCaseTest.java +++ b/src/test/java/org/jabref/logic/layout/format/ToUpperCaseTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; - public class ToUpperCaseTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/WrapContentTest.java b/src/test/java/org/jabref/logic/layout/format/WrapContentTest.java index 58e9e54c94e..6184b8ccfff 100644 --- a/src/test/java/org/jabref/logic/layout/format/WrapContentTest.java +++ b/src/test/java/org/jabref/logic/layout/format/WrapContentTest.java @@ -2,9 +2,10 @@ import org.jabref.logic.layout.ParamLayoutFormatter; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class WrapContentTest { @Test diff --git a/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java b/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java index 05dfc422f2b..09799d584b4 100644 --- a/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java +++ b/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java @@ -10,12 +10,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - public class WrapFileLinksTest { private WrapFileLinks formatter; - @BeforeEach public void setUp() { FileLinkPreferences preferences = new FileLinkPreferences(Collections.emptyList(), Collections.emptyList()); @@ -34,7 +32,6 @@ public void testNull() { public void testNoFormatSetNonEmptyString() { assertThrows(NullPointerException.class, () -> formatter.format("test.pdf")); - } @Test diff --git a/src/test/java/org/jabref/logic/msbib/MsBibAuthorTest.java b/src/test/java/org/jabref/logic/msbib/MsBibAuthorTest.java index 328f90566ad..cbb37c47408 100644 --- a/src/test/java/org/jabref/logic/msbib/MsBibAuthorTest.java +++ b/src/test/java/org/jabref/logic/msbib/MsBibAuthorTest.java @@ -44,5 +44,4 @@ public void testGetLastName() { MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals("Bach", msBibAuthor.getLastName()); } - } diff --git a/src/test/java/org/jabref/logic/net/URLDownloadTest.java b/src/test/java/org/jabref/logic/net/URLDownloadTest.java index 4c4de67475b..89ea7b33183 100644 --- a/src/test/java/org/jabref/logic/net/URLDownloadTest.java +++ b/src/test/java/org/jabref/logic/net/URLDownloadTest.java @@ -91,5 +91,4 @@ public void downloadOfHttpsSucceeds() throws IOException { Path path = ftp.toTemporaryFile(); assertNotNull(path); } - } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index dff07571e76..84d4ff9e12a 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -59,7 +59,7 @@ public void testAuthorYear() throws IOException { @Test public void testAuthorYearAsFile() throws URISyntaxException, IOException { File defFile = Paths.get(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile(); + .toFile(); OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isFromResource()); @@ -115,7 +115,7 @@ public void testGetNumCitationMarkerUndefined() throws IOException { style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); } @@ -151,9 +151,9 @@ public void testGetCitationMarker() throws IOException { assertEquals("[Boström et al., 2006]", style.getCitationMarker(Arrays.asList(entry), entryDBMap, true, null, null)); assertEquals("Boström et al. [2006]", - style.getCitationMarker(Arrays.asList(entry), entryDBMap, false, null, new int[] {3})); + style.getCitationMarker(Arrays.asList(entry), entryDBMap, false, null, new int[]{3})); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Arrays.asList(entry), entryDBMap, true, null, new int[] {5})); + style.getCitationMarker(Arrays.asList(entry), entryDBMap, true, null, new int[]{5})); } /** @@ -345,7 +345,7 @@ public void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, new String[] {"a", "b", ""}, new int[] {1, 1, 1})); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -381,7 +381,7 @@ public void testGetCitationMarkerInTextUniquefiers() throws IOException { assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", style.getCitationMarker(entries, entryDBMap, false, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, new String[] {"a", "b", ""}, new int[] {1, 1, 1})); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -416,7 +416,7 @@ public void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throw } assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, true, new String[] {"a", "b", "c"}, new int[] {1, 1, 1})); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test @@ -451,7 +451,7 @@ public void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOExc } assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, false, new String[] {"a", "b", "c"}, new int[] {1, 1, 1})); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test diff --git a/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java b/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java index 2c51434577e..8b76fbeacd0 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class OOPreFormatterTest { @Test @@ -39,7 +38,6 @@ public void testUnsupportedSpecialCommands() { assertEquals("ftmchaaa", new OOPreFormatter().format("{\\ftmch\\aaa}")); } - @Test public void testEquations() { assertEquals("Σ", new OOPreFormatter().format("$\\Sigma$")); diff --git a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java b/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java index 945b70fa356..3765fd37f39 100644 --- a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java +++ b/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java @@ -30,19 +30,16 @@ public class StyleLoaderTest { private LayoutFormatterPreferences layoutPreferences; private Charset encoding; - @BeforeEach public void setUp() { preferences = mock(OpenOfficePreferences.class, Answers.RETURNS_DEEP_STUBS); layoutPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); encoding = StandardCharsets.UTF_8; - } @Test public void throwNPEWithNullPreferences() { assertThrows(NullPointerException.class, () -> loader = new StyleLoader(null, layoutPreferences, mock(Charset.class))); - } @Test @@ -69,7 +66,7 @@ public void testAddStyleLeadsToOneMoreStyle() throws URISyntaxException { loader = new StyleLoader(preferences, layoutPreferences, encoding); String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile().getPath(); + .toFile().getPath(); loader.addStyleIfValid(filename); assertEquals(numberOfInternalStyles + 1, loader.getStyles().size()); } @@ -86,7 +83,7 @@ public void testAddInvalidStyleLeadsToNoMoreStyle() { @Test public void testInitalizeWithOneExternalFile() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile().getPath(); + .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); assertEquals(numberOfInternalStyles + 1, loader.getStyles().size()); @@ -103,7 +100,7 @@ public void testInitalizeWithIncorrectExternalFile() { @Test public void testInitalizeWithOneExternalFileRemoveStyle() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile().getPath(); + .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); @@ -124,7 +121,7 @@ public void testInitalizeWithOneExternalFileRemoveStyle() throws URISyntaxExcept @Test public void testInitalizeWithOneExternalFileRemoveStyleUpdatesPreferences() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile().getPath(); + .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); @@ -148,7 +145,7 @@ public void testAddSameStyleTwiceLeadsToOneMoreStyle() throws URISyntaxException loader = new StyleLoader(preferences, layoutPreferences, encoding); int beforeAdding = loader.getStyles().size(); String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile().getPath(); + .toFile().getPath(); loader.addStyleIfValid(filename); loader.addStyleIfValid(filename); assertEquals(beforeAdding + 1, loader.getStyles().size()); @@ -158,7 +155,6 @@ public void testAddSameStyleTwiceLeadsToOneMoreStyle() throws URISyntaxException public void testAddNullStyleThrowsNPE() { loader = new StyleLoader(preferences, layoutPreferences, encoding); assertThrows(NullPointerException.class, () -> loader.addStyleIfValid(null)); - } @Test @@ -206,5 +202,4 @@ public void testRemoveInternalStyleReturnsFalseAndDoNotRemove() { assertFalse(loader.removeStyle(toremove.get(0))); assertEquals(numberOfInternalStyles, loader.getStyles().size()); } - } diff --git a/src/test/java/org/jabref/logic/pdf/PdfAnnotationImporterTest.java b/src/test/java/org/jabref/logic/pdf/PdfAnnotationImporterTest.java index 01bb95f00ea..fc0bb832b35 100644 --- a/src/test/java/org/jabref/logic/pdf/PdfAnnotationImporterTest.java +++ b/src/test/java/org/jabref/logic/pdf/PdfAnnotationImporterTest.java @@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class PdfAnnotationImporterTest { private final AnnotationImporter importer = new PdfAnnotationImporter(); diff --git a/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsListTest.java b/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsListTest.java index da3b4ddf5f1..c8fbdf7f7e6 100644 --- a/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsListTest.java +++ b/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsListTest.java @@ -6,8 +6,8 @@ import java.util.ArrayList; import java.util.Arrays; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junitpioneer.jupiter.TempDirectory; @@ -99,5 +99,4 @@ public void testTermAddedToExternalList() { externalList.addProtectedTerm("CCC"); assertTrue(externalList.getTermList().contains("CCC")); } - } diff --git a/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java b/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java index f73da3e5b45..0cc24dc3b8a 100644 --- a/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java +++ b/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java @@ -12,8 +12,8 @@ import org.jabref.logic.l10n.Localization; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junitpioneer.jupiter.TempDirectory; @@ -30,7 +30,6 @@ class ProtectedTermsLoaderTest { void setUp() { loader = new ProtectedTermsLoader(new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - } @Test @@ -43,7 +42,7 @@ void testGetProtectedTerms() throws URISyntaxException { assertTrue(loader.getProtectedTermsLists().isEmpty()); String filename = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms").toURI()) - .toFile().getPath(); + .toFile().getPath(); loader.addProtectedTermsListFromFile(filename, true); assertEquals(Arrays.asList("Einstein"), loader.getProtectedTerms()); } @@ -52,7 +51,7 @@ void testGetProtectedTerms() throws URISyntaxException { void testAddProtectedTermsListFromFile() throws URISyntaxException { String filename = Paths .get(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") - .toURI()) + .toURI()) .toFile().getPath(); assertEquals(ProtectedTermsLoader.getInternalLists().size(), loader.getProtectedTermsLists().size()); loader.addProtectedTermsListFromFile(filename, false); @@ -63,7 +62,7 @@ void testAddProtectedTermsListFromFile() throws URISyntaxException { void testReadProtectedTermsListFromFileReadsDescription() throws URISyntaxException, FileNotFoundException { File file = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms").toURI()) - .toFile(); + .toFile(); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertEquals("Term list", list.getDescription()); } @@ -72,7 +71,7 @@ void testReadProtectedTermsListFromFileReadsDescription() throws URISyntaxExcept void testReadProtectedTermsListFromFileDisabledWorks() throws URISyntaxException, FileNotFoundException { File file = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms").toURI()) - .toFile(); + .toFile(); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, false); assertFalse(list.isEnabled()); } @@ -81,7 +80,7 @@ void testReadProtectedTermsListFromFileDisabledWorks() throws URISyntaxException void testReadProtectedTermsListFromFileEnabledWorks() throws URISyntaxException, FileNotFoundException { File file = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms").toURI()) - .toFile(); + .toFile(); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertTrue(list.isEnabled()); } @@ -90,7 +89,7 @@ void testReadProtectedTermsListFromFileEnabledWorks() throws URISyntaxException, void testReadProtectedTermsListFromFileIsNotInternalList() throws URISyntaxException, FileNotFoundException { File file = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms").toURI()) - .toFile(); + .toFile(); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertFalse(list.isInternalList()); } @@ -100,8 +99,8 @@ void testReadProtectedTermsListFromFileNoDescriptionGivesDefaultDescription() throws URISyntaxException, FileNotFoundException { File file = Paths.get( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/unnamedterms.terms") - .toURI()) - .toFile(); + .toURI()) + .toFile(); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertEquals(Localization.lang("The text after the last line starting with # will be used"), list.getDescription()); diff --git a/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java b/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java index a5bfe728722..9f5a34ed95f 100644 --- a/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java +++ b/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java @@ -16,8 +16,8 @@ import static org.mockito.Mockito.verify; /** - * Tests for the case where the client and server are set-up correctly. - * Testing the exceptional cases happens in {@link RemoteSetupTest}. + * Tests for the case where the client and server are set-up correctly. Testing the exceptional cases happens in {@link + * RemoteSetupTest}. */ @DisabledOnCIServer("Tests fails sporadically on CI server") class RemoteCommunicationTest { diff --git a/src/test/java/org/jabref/logic/remote/RemotePreferencesTest.java b/src/test/java/org/jabref/logic/remote/RemotePreferencesTest.java index 3b7b5c85470..a1a5aab1a72 100644 --- a/src/test/java/org/jabref/logic/remote/RemotePreferencesTest.java +++ b/src/test/java/org/jabref/logic/remote/RemotePreferencesTest.java @@ -11,7 +11,6 @@ public class RemotePreferencesTest { private RemotePreferences preferences; - @BeforeEach public void setUp() { preferences = new RemotePreferences(1000, true); @@ -48,5 +47,4 @@ public void testIsDifferentPortTrue() { public void testIsDifferentPortFalse() { assertFalse(preferences.isDifferentPort(1000)); } - } diff --git a/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java b/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java index b5c18e1234d..e1ac0540649 100644 --- a/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java +++ b/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java @@ -18,7 +18,6 @@ public class DatabaseSearcherTest { private BibDatabase database; - @BeforeEach public void setUp() { database = new BibDatabase(); diff --git a/src/test/java/org/jabref/logic/search/SearchQueryHighlightObservableTest.java b/src/test/java/org/jabref/logic/search/SearchQueryHighlightObservableTest.java index 33011ec476a..fbe998e8a85 100644 --- a/src/test/java/org/jabref/logic/search/SearchQueryHighlightObservableTest.java +++ b/src/test/java/org/jabref/logic/search/SearchQueryHighlightObservableTest.java @@ -3,9 +3,8 @@ import java.util.Optional; import java.util.regex.Pattern; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; - +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -15,7 +14,6 @@ import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; - class SearchQueryHighlightObservableTest { @Captor ArgumentCaptor> captor; diff --git a/src/test/java/org/jabref/logic/search/SearchQueryTest.java b/src/test/java/org/jabref/logic/search/SearchQueryTest.java index 029b03ce147..2718943d6a6 100644 --- a/src/test/java/org/jabref/logic/search/SearchQueryTest.java +++ b/src/test/java/org/jabref/logic/search/SearchQueryTest.java @@ -10,7 +10,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - public class SearchQueryTest { @Test @@ -183,7 +182,6 @@ public void isMatchedForNormalAndFieldBasedSearchMixed() { entry.setField("abstract", "text"); assertTrue(new SearchQuery("text AND author=asdf", true, true).isMatch(entry)); - } @Test @@ -194,5 +192,4 @@ public void testSimpleTerm() { assertFalse(result.isGrammarBasedSearch()); } - } diff --git a/src/test/java/org/jabref/logic/shared/DBMSConnectionTest.java b/src/test/java/org/jabref/logic/shared/DBMSConnectionTest.java index 64a1eeb381e..1594d8a93da 100644 --- a/src/test/java/org/jabref/logic/shared/DBMSConnectionTest.java +++ b/src/test/java/org/jabref/logic/shared/DBMSConnectionTest.java @@ -26,6 +26,6 @@ public void testGetConnection(DBMSType dbmsType) throws SQLException, InvalidDBM @Test public void testGetConnectionFail(DBMSType dbmsType) throws SQLException, InvalidDBMSConnectionPropertiesException { assertThrows(SQLException.class, - () -> new DBMSConnection(new DBMSConnectionProperties(dbmsType, "XXXX", 0, "XXXX", "XXXX", "XXXX", false)).getConnection()); + () -> new DBMSConnection(new DBMSConnectionProperties(dbmsType, "XXXX", 0, "XXXX", "XXXX", "XXXX", false)).getConnection()); } } diff --git a/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java b/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java index 72df4f9301e..1d84949752b 100644 --- a/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java +++ b/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java @@ -33,10 +33,10 @@ class DBMSProcessorTest { private static Stream getTestingDatabaseSystems() throws InvalidDBMSConnectionPropertiesException, SQLException { Collection result = new ArrayList<>(); for (DBMSType dbmsType : TestManager.getDBMSTypeTestParameter()) { - result.add(new Object[] { - dbmsType, - TestConnector.getTestDBMSConnection(dbmsType), - DBMSProcessor.getProcessorInstance(TestConnector.getTestDBMSConnection(dbmsType))}); + result.add(new Object[]{ + dbmsType, + TestConnector.getTestDBMSConnection(dbmsType), + DBMSProcessor.getProcessorInstance(TestConnector.getTestDBMSConnection(dbmsType))}); } return result.stream(); } diff --git a/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java b/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java index 036309362e1..c9f6ff3ecd5 100644 --- a/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java +++ b/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java @@ -38,14 +38,18 @@ @DatabaseTest public class DBMSSynchronizerTest { + @Parameter + public DBMSType dbmsType; private DBMSSynchronizer dbmsSynchronizer; private DBMSConnection dbmsConnection; private DBMSProcessor dbmsProcessor; private BibDatabase bibDatabase; private GlobalBibtexKeyPattern pattern; - @Parameter - public DBMSType dbmsType; + @Parameters(name = "Test with {0} database system") + public static Collection getTestingDatabaseSystems() { + return TestManager.getDBMSTypeTestParameter(); + } @BeforeEach public void setUp() throws SQLException, DatabaseNotSupportedException, InvalidDBMSConnectionPropertiesException { @@ -63,12 +67,6 @@ public void setUp() throws SQLException, DatabaseNotSupportedException, InvalidD bibDatabase.registerListener(dbmsSynchronizer); dbmsSynchronizer.openSharedDatabase(dbmsConnection); - - } - - @Parameters(name = "Test with {0} database system") - public static Collection getTestingDatabaseSystems() { - return TestManager.getDBMSTypeTestParameter(); } @Test @@ -99,7 +97,6 @@ public void testFieldChangedEventListener() { assertEquals(1, actualEntries.size()); assertEquals(expectedEntry.getField("author"), actualEntries.get(0).getField("author")); assertEquals("The nano processor1", actualEntries.get(0).getField("title").get()); - } @Test @@ -200,7 +197,6 @@ public void testApplyMetaData() { dbmsSynchronizer.applyMetaData(); assertEquals("wirthlin, michael j1", bibEntry.getField("author").get()); - } private BibEntry getBibEntryExample(int index) { @@ -216,5 +212,4 @@ private BibEntry getBibEntryExample(int index) { public void clear() throws SQLException { TestManager.clearTables(dbmsConnection); } - } diff --git a/src/test/java/org/jabref/logic/shared/DBMSTypeTest.java b/src/test/java/org/jabref/logic/shared/DBMSTypeTest.java index 3c350aeb6d3..855f522a239 100644 --- a/src/test/java/org/jabref/logic/shared/DBMSTypeTest.java +++ b/src/test/java/org/jabref/logic/shared/DBMSTypeTest.java @@ -46,5 +46,4 @@ public void testGetDefaultPort() { assertEquals(5432, DBMSType.POSTGRESQL.getDefaultPort()); assertEquals(1521, DBMSType.ORACLE.getDefaultPort()); } - } diff --git a/src/test/java/org/jabref/logic/shared/SynchronizationTestEventListener.java b/src/test/java/org/jabref/logic/shared/SynchronizationTestEventListener.java index 99a554422a9..efef81b7cbc 100644 --- a/src/test/java/org/jabref/logic/shared/SynchronizationTestEventListener.java +++ b/src/test/java/org/jabref/logic/shared/SynchronizationTestEventListener.java @@ -12,7 +12,6 @@ public class SynchronizationTestEventListener { private SharedEntryNotPresentEvent sharedEntryNotPresentEvent; private UpdateRefusedEvent updateRefusedEvent; - @Subscribe public void listen(SharedEntryNotPresentEvent event) { this.sharedEntryNotPresentEvent = event; diff --git a/src/test/java/org/jabref/logic/shared/SynchronizationTestSimulator.java b/src/test/java/org/jabref/logic/shared/SynchronizationTestSimulator.java index 276167728f1..058216af789 100644 --- a/src/test/java/org/jabref/logic/shared/SynchronizationTestSimulator.java +++ b/src/test/java/org/jabref/logic/shared/SynchronizationTestSimulator.java @@ -29,15 +29,17 @@ @DatabaseTest public class SynchronizationTestSimulator { + @Parameter + public DBMSType dbmsType; private BibDatabaseContext clientContextA; private BibDatabaseContext clientContextB; - private SynchronizationTestEventListener eventListenerB; // used to monitor occurring events - private DBMSConnection dbmsConnection; - @Parameter - public DBMSType dbmsType; + @Parameters(name = "Test with {0} database system") + public static Collection getTestingDatabaseSystems() { + return TestManager.getDBMSTypeTestParameter(); + } @BeforeEach public void setUp() throws SQLException, DatabaseNotSupportedException, InvalidDBMSConnectionPropertiesException { @@ -57,11 +59,6 @@ public void setUp() throws SQLException, DatabaseNotSupportedException, InvalidD clientContextB.getDBMSSynchronizer().registerListener(eventListenerB); } - @Parameters(name = "Test with {0} database system") - public static Collection getTestingDatabaseSystems() { - return TestManager.getDBMSTypeTestParameter(); - } - @Test public void simulateEntryInsertionAndManualPull() { //client A inserts an entry diff --git a/src/test/java/org/jabref/logic/shared/TestManager.java b/src/test/java/org/jabref/logic/shared/TestManager.java index 1413275de95..6c9ec6fd5b6 100644 --- a/src/test/java/org/jabref/logic/shared/TestManager.java +++ b/src/test/java/org/jabref/logic/shared/TestManager.java @@ -9,8 +9,8 @@ import org.jabref.model.database.shared.DBMSType; /** - * This class provides helping methods for database tests. - * Furthermore it determines database systems which are ready to be used for tests. + * This class provides helping methods for database tests. Furthermore it determines database systems which are ready to + * be used for tests. */ public class TestManager { @@ -41,11 +41,11 @@ public static void clearTables(DBMSConnection dbmsConnection) throws SQLExceptio dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS \"METADATA\""); } else if (dbmsType == DBMSType.ORACLE) { dbmsConnection.getConnection().createStatement() - .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP TABLE \"FIELD\"';\n" - + "EXECUTE IMMEDIATE 'DROP TABLE \"ENTRY\"';\n" - + "EXECUTE IMMEDIATE 'DROP TABLE \"METADATA\"';\n" - + "EXECUTE IMMEDIATE 'DROP SEQUENCE \"ENTRY_SEQ\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" - + "IF SQLCODE != -942 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;"); + .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP TABLE \"FIELD\"';\n" + + "EXECUTE IMMEDIATE 'DROP TABLE \"ENTRY\"';\n" + + "EXECUTE IMMEDIATE 'DROP TABLE \"METADATA\"';\n" + + "EXECUTE IMMEDIATE 'DROP SEQUENCE \"ENTRY_SEQ\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" + + "IF SQLCODE != -942 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;"); } } } diff --git a/src/test/java/org/jabref/logic/util/DevelopmentStageTest.java b/src/test/java/org/jabref/logic/util/DevelopmentStageTest.java index 5e520890608..b2d33d2eed7 100644 --- a/src/test/java/org/jabref/logic/util/DevelopmentStageTest.java +++ b/src/test/java/org/jabref/logic/util/DevelopmentStageTest.java @@ -1,7 +1,5 @@ package org.jabref.logic.util; - - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,5 +32,4 @@ public void parseNull() { public void parseUnknownString() { assertEquals(Version.DevelopmentStage.UNKNOWN, Version.DevelopmentStage.parse("asdf")); } - } diff --git a/src/test/java/org/jabref/logic/util/JavaVersionTest.java b/src/test/java/org/jabref/logic/util/JavaVersionTest.java index 5f67d084363..443b404f803 100644 --- a/src/test/java/org/jabref/logic/util/JavaVersionTest.java +++ b/src/test/java/org/jabref/logic/util/JavaVersionTest.java @@ -8,18 +8,13 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Tests for ensuring we can compare most appearing version strings */ public class JavaVersionTest { private static List java = new ArrayList<>(); - private static List java9 = new ArrayList<>(); - - private final static JavaVersion nullCheck = new JavaVersion(null); - private final static JavaVersion noSenseCheck = new JavaVersion("U.N.K.N.O.W.N"); - + private static List java9 = new ArrayList<>(); static { java.add("1.6.0_10"); // Oracle @@ -54,8 +49,8 @@ public void isJava9() throws Exception { } // For impossible comparisons we assume it's not java 9 - assertFalse(nullCheck.isJava9()); - assertFalse(noSenseCheck.isJava9()); + assertFalse(new JavaVersion(null).isJava9()); + assertFalse(new JavaVersion("U.N.K.N.O.W.N").isJava9()); } @Test @@ -68,11 +63,10 @@ public void isAtLeast() throws Exception { // Check if we optimistically return true if we cannot determine the result assertTrue(java8Example.isAtLeast(null)); - assertTrue(nullCheck.isAtLeast(version8)); - assertTrue(noSenseCheck.isAtLeast(version8)); + assertTrue(new JavaVersion(null).isAtLeast(version8)); + assertTrue(new JavaVersion("U.N.K.N.O.W.N").isAtLeast(version8)); assertTrue(java8Example.isAtLeast("useless")); - // Check against all java 9 entries in both directions for (String version9 : java9) { assertFalse(java8Example.isAtLeast(version9)); diff --git a/src/test/java/org/jabref/logic/util/UpdateFieldTest.java b/src/test/java/org/jabref/logic/util/UpdateFieldTest.java index d79d4014bff..57a15b34621 100644 --- a/src/test/java/org/jabref/logic/util/UpdateFieldTest.java +++ b/src/test/java/org/jabref/logic/util/UpdateFieldTest.java @@ -13,12 +13,10 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - public class UpdateFieldTest { private BibEntry entry; - @BeforeEach public void setUp() throws Exception { entry = new BibEntry(); @@ -168,5 +166,4 @@ public void testUpdateNonDisplayableFieldHasNotChanged() { UpdateField.updateNonDisplayableField(entry, "year", "2016"); assertFalse(entry.hasChanged()); } - } diff --git a/src/test/java/org/jabref/logic/util/VersionTest.java b/src/test/java/org/jabref/logic/util/VersionTest.java index b2f90644b65..7601f29910e 100644 --- a/src/test/java/org/jabref/logic/util/VersionTest.java +++ b/src/test/java/org/jabref/logic/util/VersionTest.java @@ -1,6 +1,5 @@ package org.jabref.logic.util; - import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -283,5 +282,4 @@ public void alphaShouldBeUpdatedToStables() { List availableVersions = Arrays.asList(Version.parse("2.8-beta"), stable); assertEquals(Optional.of(stable), alpha.shouldBeUpdatedTo(availableVersions)); } - } diff --git a/src/test/java/org/jabref/logic/util/io/CiteKeyBasedFileFinderTest.java b/src/test/java/org/jabref/logic/util/io/CiteKeyBasedFileFinderTest.java index 9d3a8374416..0629afe3a97 100644 --- a/src/test/java/org/jabref/logic/util/io/CiteKeyBasedFileFinderTest.java +++ b/src/test/java/org/jabref/logic/util/io/CiteKeyBasedFileFinderTest.java @@ -1,8 +1,8 @@ package org.jabref.logic.util.io; import java.io.IOException; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -10,7 +10,6 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexEntryTypes; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/org/jabref/logic/util/io/FileUtilTest.java b/src/test/java/org/jabref/logic/util/io/FileUtilTest.java index 7073e65415e..4103e8b7d23 100644 --- a/src/test/java/org/jabref/logic/util/io/FileUtilTest.java +++ b/src/test/java/org/jabref/logic/util/io/FileUtilTest.java @@ -2,7 +2,10 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -19,7 +22,11 @@ import org.junitpioneer.jupiter.TempDirectory; import org.mockito.Answers; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @ExtendWith(TempDirectory.class) @@ -137,9 +144,9 @@ void testGetLinkedFileNameByYearAuthorFirstpage() { // bibkey - title String fileNamePattern = "[year]_[auth]_[firstpage]"; BibEntry entry = new BibEntry(); - entry.setField( "author", "O. Kitsune" ); - entry.setField( "year", "1868" ); - entry.setField( "pages", "567-579" ); + entry.setField("author", "O. Kitsune"); + entry.setField("year", "1868"); + entry.setField("pages", "567-579"); assertEquals("1868_Kitsune_567", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @@ -215,42 +222,42 @@ void uniquePathSubstrings() { } @Test - void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithOverrideExistFile(){ + void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, nonExistingTestPath, true)); } @Test - void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithoutOverrideExistFile(){ + void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, nonExistingTestPath, false)); } @Test - void testCopyFileFromEmptySourcePathToExistDestinationPathWithOverrideExistFile(){ + void testCopyFileFromEmptySourcePathToExistDestinationPathWithOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, existingTestFile, true)); } @Test - void testCopyFileFromEmptySourcePathToExistDestinationPathWithoutOverrideExistFile(){ + void testCopyFileFromEmptySourcePathToExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, existingTestFile, false)); } @Test - void testCopyFileFromExistSourcePathToExistDestinationPathWithOverrideExistFile(){ + void testCopyFileFromExistSourcePathToExistDestinationPathWithOverrideExistFile() { assertTrue(FileUtil.copyFile(existingTestFile, existingTestFile, true)); } @Test - void testCopyFileFromExistSourcePathToExistDestinationPathWithoutOverrideExistFile(){ + void testCopyFileFromExistSourcePathToExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(existingTestFile, existingTestFile, false)); } @Test - void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithOverrideExistFile(){ + void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithOverrideExistFile() { assertTrue(FileUtil.copyFile(existingTestFile, otherExistingTestFile, true)); } @Test - void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithoutOverrideExistFile(){ + void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(existingTestFile, otherExistingTestFile, false)); } @@ -290,27 +297,27 @@ void testRenameFileWithFromFileIsNullAndToFileExist() { } @Test - void testRenameFileWithFromFileNotExistAndToFileNotExist(){ + void testRenameFileWithFromFileNotExistAndToFileNotExist() { assertFalse(FileUtil.renameFile(nonExistingTestPath, nonExistingTestPath)); } @Test - void testRenameFileWithFromFileNotExistAndToFileExist(){ + void testRenameFileWithFromFileNotExistAndToFileExist() { assertFalse(FileUtil.renameFile(nonExistingTestPath, existingTestFile)); } @Test - void testRenameFileWithFromFileExistAndToFileNotExist(){ + void testRenameFileWithFromFileExistAndToFileNotExist() { assertTrue(FileUtil.renameFile(existingTestFile, nonExistingTestPath)); } @Test - void testRenameFileWithFromFileExistAndToFileExist(){ + void testRenameFileWithFromFileExistAndToFileExist() { assertTrue(FileUtil.renameFile(existingTestFile, existingTestFile)); } @Test - void testRenameFileWithFromFileExistAndOtherToFileExist(){ + void testRenameFileWithFromFileExistAndOtherToFileExist() { assertFalse(FileUtil.renameFile(existingTestFile, otherExistingTestFile)); } @@ -362,9 +369,9 @@ void testGetLinkedDirNameDefaultFullTitle() { assertEquals("PDF/1998/Åuthör/1234 - mytitle", FileUtil.createDirNameFromPattern(null, entry, fileNamePattern)); } + @Test - public void testIsBibFile() throws IOException - { + public void testIsBibFile() throws IOException { Path bibFile = Files.createFile(rootDir.resolve("test.bib")); assertTrue(FileUtil.isBibFile(bibFile)); diff --git a/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTests.java b/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTests.java index b550ca52a2d..d024017ff34 100644 --- a/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTests.java +++ b/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTests.java @@ -17,7 +17,7 @@ public class RegExpBasedFileFinderTests { - private static final String filesDirectory = "src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder"; + private static final String FILES_DIRECTORY = "src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder"; private BibDatabase database; private BibEntry entry; @@ -52,7 +52,7 @@ public void testFindFiles() throws Exception { List extensions = Collections.singletonList("pdf"); - List dirs = Collections.singletonList(Paths.get(filesDirectory)); + List dirs = Collections.singletonList(Paths.get(FILES_DIRECTORY)); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[bibtexkey].*\\\\.[extension]", ','); //when @@ -68,7 +68,7 @@ public void testYearAuthFirspageFindFiles() throws Exception { //given List extensions = Collections.singletonList("pdf"); - List dirs = Collections.singletonList(Paths.get(filesDirectory)); + List dirs = Collections.singletonList(Paths.get(FILES_DIRECTORY)); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[year]_[auth]_[firstpage].*\\\\.[extension]", ','); //when @@ -90,7 +90,7 @@ public void testAuthorWithDiacritics() throws Exception { List extensions = Collections.singletonList("pdf"); - List dirs = Collections.singletonList(Paths.get(filesDirectory)); + List dirs = Collections.singletonList(Paths.get(FILES_DIRECTORY)); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[year]_[auth]_[firstpage]\\\\.[extension]", ','); //when @@ -110,7 +110,7 @@ public void testFindFileInSubdirectory() throws Exception { List extensions = Collections.singletonList("pdf"); - List dirs = Collections.singletonList(Paths.get(filesDirectory)); + List dirs = Collections.singletonList(Paths.get(FILES_DIRECTORY)); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[bibtexkey].*\\\\.[extension]", ','); //when @@ -130,7 +130,7 @@ public void testFindFileNonRecursive() throws Exception { List extensions = Collections.singletonList("pdf"); - List dirs = Collections.singletonList(Paths.get(filesDirectory)); + List dirs = Collections.singletonList(Paths.get(FILES_DIRECTORY)); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("*/[bibtexkey].*\\\\.[extension]", ','); //when @@ -169,5 +169,4 @@ public void testExpandBrackets() { RegExpBasedFileFinder.expandBrackets("[author] have published [title] in [journal].", entry, database, ',')); } - } diff --git a/src/test/java/org/jabref/logic/util/strings/StringLengthComparatorTest.java b/src/test/java/org/jabref/logic/util/strings/StringLengthComparatorTest.java index 29b691b4e13..bf53b938ef4 100644 --- a/src/test/java/org/jabref/logic/util/strings/StringLengthComparatorTest.java +++ b/src/test/java/org/jabref/logic/util/strings/StringLengthComparatorTest.java @@ -9,7 +9,6 @@ public class StringLengthComparatorTest { private StringLengthComparator slc; - @BeforeEach public void setUp() { slc = new StringLengthComparator(); @@ -21,5 +20,4 @@ public void test() { assertEquals(0, slc.compare("AA", "AA")); assertEquals(1, slc.compare("AA", "AAA")); } - } diff --git a/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java b/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java index ea5dfe702c1..92160685052 100644 --- a/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java +++ b/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java @@ -14,12 +14,10 @@ import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; -import org.jabref.model.util.FileUpdateMonitor; import com.google.common.io.Resources; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.DublinCoreSchema; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; @@ -30,10 +28,7 @@ class XmpUtilReaderTest { - private static final FileUpdateMonitor fileMonitor = new DummyFileUpdateMonitor(); - private XmpPreferences xmpPreferences; - private BibtexParser parser; /** @@ -49,7 +44,7 @@ void setUp() { when(xmpPreferences.getKeywordSeparator()).thenReturn(','); - parser = new BibtexParser(importFormatPreferences, fileMonitor); + parser = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()); } /** @@ -104,5 +99,4 @@ void testReadPDMetadata() throws IOException, URISyntaxException, ParseException assertEquals(entryFromBibFile.get(), entries.get(0)); } - } diff --git a/src/test/java/org/jabref/logic/xmp/XmpUtilWriterTest.java b/src/test/java/org/jabref/logic/xmp/XmpUtilWriterTest.java index bad198f9d0f..f3d57c6bfae 100644 --- a/src/test/java/org/jabref/logic/xmp/XmpUtilWriterTest.java +++ b/src/test/java/org/jabref/logic/xmp/XmpUtilWriterTest.java @@ -13,8 +13,8 @@ import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junitpioneer.jupiter.TempDirectory; @@ -25,11 +25,10 @@ @ExtendWith(TempDirectory.class) class XmpUtilWriterTest { - private XmpPreferences xmpPreferences; - private static BibEntry olly2018; private static BibEntry toral2006; private static BibEntry vapnik2000; + private XmpPreferences xmpPreferences; private void initBibEntries() { @@ -113,7 +112,6 @@ void testWriteXmp(@TempDirectory.TempDir Path tempDir) throws IOException, Trans // compare the two entries assertEquals(entry, entryWritten); - } /** @@ -130,7 +128,6 @@ void testWriteMultipleBibEntries(@TempDirectory.TempDir Path tempDir) throws IOE List entryList = XmpUtilReader.readXmp(Paths.get(pdfFile.toAbsolutePath().toString()), xmpPreferences); assertEquals(3, entryList.size()); - } private Path createDefaultFile(String fileName, Path tempDir) throws IOException { diff --git a/src/test/java/org/jabref/migrations/PreferencesMigrationsTest.java b/src/test/java/org/jabref/migrations/PreferencesMigrationsTest.java index 0b7128da0da..c646bab55bb 100644 --- a/src/test/java/org/jabref/migrations/PreferencesMigrationsTest.java +++ b/src/test/java/org/jabref/migrations/PreferencesMigrationsTest.java @@ -17,16 +17,15 @@ class PreferencesMigrationsTest { private JabRefPreferences prefs; private Preferences mainPrefsNode; - private final String[] oldStylePatterns = new String[] {"\\bibtexkey", - "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; - private final String[] newStylePatterns = new String[] {"[bibtexkey]", - "[bibtexkey] - [fulltitle]"}; + private final String[] oldStylePatterns = new String[]{"\\bibtexkey", + "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; + private final String[] newStylePatterns = new String[]{"[bibtexkey]", + "[bibtexkey] - [fulltitle]"}; @BeforeEach void setUp() { prefs = mock(JabRefPreferences.class); mainPrefsNode = mock(Preferences.class); - } @Test @@ -39,7 +38,6 @@ void testOldStyleBibtexkeyPattern0() { verify(prefs).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[0]); verify(mainPrefsNode).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[0]); - } @Test @@ -53,7 +51,6 @@ void testOldStyleBibtexkeyPattern1() { verify(prefs).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[1]); verify(mainPrefsNode).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[1]); - } @Test @@ -67,50 +64,49 @@ void testArbitraryBibtexkeyPattern() { verify(prefs, never()).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, arbitraryPattern); verify(mainPrefsNode, never()).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, arbitraryPattern); - } @Test void testPreviewStyle() { String oldPreviewStyle = "" - + "\\bibtextype\\begin{bibtexkey} (\\bibtexkey)" - + "\\end{bibtexkey}
__NEWLINE__" - + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}
\\end{author}__NEWLINE__" - + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " - + "(\\format[IfPlural(Eds.,Ed.)]{\\editor})
\\end{editor}__NEWLINE__" - + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}
__NEWLINE__" - + "\\begin{chapter} \\format[HTMLChars]{\\chapter}
\\end{chapter}__NEWLINE__" - + "\\begin{journal} \\format[HTMLChars]{\\journal}, \\end{journal}__NEWLINE__" - // Include the booktitle field for @inproceedings, @proceedings, etc. - + "\\begin{booktitle} \\format[HTMLChars]{\\booktitle}, \\end{booktitle}__NEWLINE__" - + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" - + "\\begin{institution} \\format[HTMLChars]{\\institution}, \\end{institution}__NEWLINE__" - + "\\begin{publisher} \\format[HTMLChars]{\\publisher}, \\end{publisher}__NEWLINE__" - + "\\begin{year}\\year\\end{year}\\begin{volume}, \\volume\\end{volume}" - + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" - + "\\begin{abstract}

Abstract: \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" - + "\\begin{review}

Review: \\format[HTMLChars]{\\review} \\end{review}" - + "__NEWLINE__

"; + + "\\bibtextype\\begin{bibtexkey} (\\bibtexkey)" + + "\\end{bibtexkey}
__NEWLINE__" + + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}
\\end{author}__NEWLINE__" + + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + + "(\\format[IfPlural(Eds.,Ed.)]{\\editor})
\\end{editor}__NEWLINE__" + + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}
__NEWLINE__" + + "\\begin{chapter} \\format[HTMLChars]{\\chapter}
\\end{chapter}__NEWLINE__" + + "\\begin{journal} \\format[HTMLChars]{\\journal}, \\end{journal}__NEWLINE__" + // Include the booktitle field for @inproceedings, @proceedings, etc. + + "\\begin{booktitle} \\format[HTMLChars]{\\booktitle}, \\end{booktitle}__NEWLINE__" + + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" + + "\\begin{institution} \\format[HTMLChars]{\\institution}, \\end{institution}__NEWLINE__" + + "\\begin{publisher} \\format[HTMLChars]{\\publisher}, \\end{publisher}__NEWLINE__" + + "\\begin{year}\\year\\end{year}\\begin{volume}, \\volume\\end{volume}" + + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" + + "\\begin{abstract}

Abstract: \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + + "\\begin{review}

Review: \\format[HTMLChars]{\\review} \\end{review}" + + "__NEWLINE__

"; String newPreviewStyle = "" - + "\\bibtextype\\begin{bibtexkey} (\\bibtexkey)" - + "\\end{bibtexkey}
__NEWLINE__" - + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}
\\end{author}__NEWLINE__" - + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " - + "(\\format[IfPlural(Eds.,Ed.)]{\\editor})
\\end{editor}__NEWLINE__" - + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}
__NEWLINE__" - + "\\begin{chapter} \\format[HTMLChars]{\\chapter}
\\end{chapter}__NEWLINE__" - + "\\begin{journal} \\format[HTMLChars]{\\journal}, \\end{journal}__NEWLINE__" - // Include the booktitle field for @inproceedings, @proceedings, etc. - + "\\begin{booktitle} \\format[HTMLChars]{\\booktitle}, \\end{booktitle}__NEWLINE__" - + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" - + "\\begin{institution} \\format[HTMLChars]{\\institution}, \\end{institution}__NEWLINE__" - + "\\begin{publisher} \\format[HTMLChars]{\\publisher}, \\end{publisher}__NEWLINE__" - + "\\begin{year}\\year\\end{year}\\begin{volume}, \\volume\\end{volume}" - + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" - + "\\begin{abstract}

Abstract: \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" - + "\\begin{comment}

Comment: \\format[HTMLChars]{\\comment} \\end{comment}" - + "__NEWLINE__

"; + + "\\bibtextype\\begin{bibtexkey} (\\bibtexkey)" + + "\\end{bibtexkey}
__NEWLINE__" + + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}
\\end{author}__NEWLINE__" + + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + + "(\\format[IfPlural(Eds.,Ed.)]{\\editor})
\\end{editor}__NEWLINE__" + + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}
__NEWLINE__" + + "\\begin{chapter} \\format[HTMLChars]{\\chapter}
\\end{chapter}__NEWLINE__" + + "\\begin{journal} \\format[HTMLChars]{\\journal}, \\end{journal}__NEWLINE__" + // Include the booktitle field for @inproceedings, @proceedings, etc. + + "\\begin{booktitle} \\format[HTMLChars]{\\booktitle}, \\end{booktitle}__NEWLINE__" + + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" + + "\\begin{institution} \\format[HTMLChars]{\\institution}, \\end{institution}__NEWLINE__" + + "\\begin{publisher} \\format[HTMLChars]{\\publisher}, \\end{publisher}__NEWLINE__" + + "\\begin{year}\\year\\end{year}\\begin{volume}, \\volume\\end{volume}" + + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" + + "\\begin{abstract}

Abstract: \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + + "\\begin{comment}

Comment: \\format[HTMLChars]{\\comment} \\end{comment}" + + "__NEWLINE__

"; prefs.setPreviewStyle(oldPreviewStyle); when(prefs.getPreviewStyle()).thenReturn(oldPreviewStyle); @@ -118,6 +114,5 @@ void testPreviewStyle() { PreferencesMigrations.upgradePreviewStyleFromReviewToComment(prefs); verify(prefs).setPreviewStyle(newPreviewStyle); - } } diff --git a/src/test/java/org/jabref/model/EntryTypesTest.java b/src/test/java/org/jabref/model/EntryTypesTest.java index d58cc7ff904..8a77703ee1a 100644 --- a/src/test/java/org/jabref/model/EntryTypesTest.java +++ b/src/test/java/org/jabref/model/EntryTypesTest.java @@ -15,10 +15,9 @@ import org.jabref.model.entry.FieldName; import org.jabref.model.entry.IEEETranEntryTypes; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; - +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -147,7 +146,6 @@ void registeredCustomizedStandardEntryTypeIsContainedInListOfCustomizedEntryType assertEquals(Arrays.asList(overwrittenStandardType), EntryTypes.getAllModifiedStandardTypes(mode)); } - @ParameterizedTest @MethodSource("standardArticleTypeAndMode") void standardTypeIsStillAcessibleIfOverwritten(EntryType standardArticleType, BibDatabaseMode mode) { @@ -176,5 +174,4 @@ void overwriteStandardTypeRequiredFieldsDoesNotAffectOtherMode(BibDatabaseMode m EntryTypes.addOrModifyCustomEntryType(overwrittenStandardType, mode); assertFalse(EntryTypes.getAllValues(otherMode).contains(overwrittenStandardType)); } - } diff --git a/src/test/java/org/jabref/model/TreeNodeTest.java b/src/test/java/org/jabref/model/TreeNodeTest.java index 577c2420d8d..4ae97c6c2ea 100644 --- a/src/test/java/org/jabref/model/TreeNodeTest.java +++ b/src/test/java/org/jabref/model/TreeNodeTest.java @@ -29,7 +29,6 @@ public void setUp() { @Test public void constructorChecksThatClassImplementsCorrectInterface() { assertThrows(UnsupportedOperationException.class, () -> new WrongTreeNodeImplementation()); - } @Test diff --git a/src/test/java/org/jabref/model/TreeNodeTestData.java b/src/test/java/org/jabref/model/TreeNodeTestData.java index 939e9629292..c4f669ec9a6 100644 --- a/src/test/java/org/jabref/model/TreeNodeTestData.java +++ b/src/test/java/org/jabref/model/TreeNodeTestData.java @@ -2,11 +2,7 @@ public class TreeNodeTestData { /** - * Gets the marked node in the following tree: - * Root - * A - * A (= parent) - * B (<-- this) + * Gets the marked node in the following tree: Root A A (= parent) B (<-- this) */ public static TreeNodeMock getNodeInSimpleTree(TreeNodeMock root) { root.addChild(new TreeNodeMock()); @@ -22,21 +18,8 @@ public static TreeNodeMock getNodeInSimpleTree() { } /** - * Gets the marked node in the following tree: - * Root - * A - * A - * A (= grand parent) - * B - * B (= parent) - * C (<-- this) - * D (= child) - * C - * C - * C - * B - * B - * A + * Gets the marked node in the following tree: Root A A A (= grand parent) B B (= parent) C (<-- this) D (= child) C + * C C B B A */ public static TreeNodeMock getNodeInComplexTree(TreeNodeMock root) { root.addChild(new TreeNodeMock()); @@ -66,12 +49,7 @@ public static TreeNodeMock getNodeInComplexTree() { } /** - * Gets the marked in the following tree: - * Root - * A - * A - * A (<- this) - * A + * Gets the marked in the following tree: Root A A A (<- this) A */ public static TreeNodeMock getNodeAsChild(TreeNodeMock root) { root.addChild(new TreeNodeMock()); diff --git a/src/test/java/org/jabref/model/database/BibDatabaseModeDetectionTest.java b/src/test/java/org/jabref/model/database/BibDatabaseModeDetectionTest.java index a157a4e3de9..3902da07a58 100644 --- a/src/test/java/org/jabref/model/database/BibDatabaseModeDetectionTest.java +++ b/src/test/java/org/jabref/model/database/BibDatabaseModeDetectionTest.java @@ -68,5 +68,4 @@ public void ignoreUnknownTypesForBiblatexDecision() { assertEquals(BibDatabaseMode.BIBLATEX, BibDatabaseModeDetection.inferMode(BibDatabases.createDatabase(entries))); } - } diff --git a/src/test/java/org/jabref/model/database/BibDatabaseTest.java b/src/test/java/org/jabref/model/database/BibDatabaseTest.java index 4a11fdc737d..84fcbb426e7 100644 --- a/src/test/java/org/jabref/model/database/BibDatabaseTest.java +++ b/src/test/java/org/jabref/model/database/BibDatabaseTest.java @@ -58,7 +58,6 @@ public void insertEntryWithSameIdThrowsException() { BibEntry entry1 = new BibEntry(); entry1.setId(entry0.getId()); assertThrows(KeyCollisionException.class, () -> database.insertEntry(entry1)); - } @Test @@ -127,7 +126,6 @@ public void addSameStringLabelTwiceThrowsKeyCollisionException() { final BibtexString finalString = new BibtexString("DSP", "Digital Signal Processor"); assertThrows(KeyCollisionException.class, () -> database.addString(finalString)); - } @Test @@ -139,7 +137,6 @@ public void addSameStringIdTwiceThrowsKeyCollisionException() { finalString.setId("duplicateid"); assertThrows(KeyCollisionException.class, () -> database.addString(finalString)); - } @Test @@ -319,5 +316,4 @@ public void setPreambleWorks() { database.setPreamble("Oh yeah!"); assertEquals(Optional.of("Oh yeah!"), database.getPreamble()); } - } diff --git a/src/test/java/org/jabref/model/database/DuplicationCheckerTest.java b/src/test/java/org/jabref/model/database/DuplicationCheckerTest.java index e280a41d5c7..28782f83642 100644 --- a/src/test/java/org/jabref/model/database/DuplicationCheckerTest.java +++ b/src/test/java/org/jabref/model/database/DuplicationCheckerTest.java @@ -11,7 +11,6 @@ public class DuplicationCheckerTest { private BibDatabase database; - @BeforeEach public void setUp() { database = new BibDatabase(); @@ -46,7 +45,6 @@ public void changeCiteKey() { assertEquals(1, database.getDuplicationChecker().getNumberOfKeyOccurrences("BBB")); } - @Test public void setCiteKeySameKeyDifferentEntries() { BibEntry entry0 = new BibEntry(); @@ -64,7 +62,7 @@ public void setCiteKeySameKeyDifferentEntries() { } @Test - public void removeMultipleCiteKeys(){ + public void removeMultipleCiteKeys() { BibEntry entry0 = new BibEntry(); entry0.setCiteKey("AAA"); database.insertEntry(entry0); @@ -87,7 +85,7 @@ public void removeMultipleCiteKeys(){ } @Test - public void addEmptyCiteKey(){ + public void addEmptyCiteKey() { BibEntry entry = new BibEntry(); entry.setCiteKey(""); database.insertEntry(entry); @@ -96,7 +94,7 @@ public void addEmptyCiteKey(){ } @Test - public void removeEmptyCiteKey(){ + public void removeEmptyCiteKey() { BibEntry entry = new BibEntry(); entry.setCiteKey("AAA"); database.insertEntry(entry); @@ -106,5 +104,4 @@ public void removeEmptyCiteKey(){ database.removeEntry(entry); assertEquals(0, database.getDuplicationChecker().getNumberOfKeyOccurrences("AAA")); } - } diff --git a/src/test/java/org/jabref/model/database/KeyChangeListenerTest.java b/src/test/java/org/jabref/model/database/KeyChangeListenerTest.java index 2540b5ed75e..52ed7cbd403 100644 --- a/src/test/java/org/jabref/model/database/KeyChangeListenerTest.java +++ b/src/test/java/org/jabref/model/database/KeyChangeListenerTest.java @@ -18,7 +18,6 @@ public class KeyChangeListenerTest { private BibEntry entry3; private BibEntry entry4; - @BeforeEach public void setUp() { db = new BibDatabase(); @@ -41,7 +40,6 @@ public void setUp() { entry4 = new BibEntry(); entry4.setCiteKey("Entry4"); db.insertEntry(entry4); - } @Test @@ -89,5 +87,4 @@ public void testRelatedAllEntriesRemoved() { db.removeEntry(entry3); assertEquals(Optional.empty(), entry2.getField("related")); } - } diff --git a/src/test/java/org/jabref/model/entry/AuthorListParameterTest.java b/src/test/java/org/jabref/model/entry/AuthorListParameterTest.java index ee1d3d5defc..5739ed944ca 100644 --- a/src/test/java/org/jabref/model/entry/AuthorListParameterTest.java +++ b/src/test/java/org/jabref/model/entry/AuthorListParameterTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - public class AuthorListParameterTest { private static Stream data() { diff --git a/src/test/java/org/jabref/model/entry/AuthorListTest.java b/src/test/java/org/jabref/model/entry/AuthorListTest.java index d5856c04165..0916af571f0 100644 --- a/src/test/java/org/jabref/model/entry/AuthorListTest.java +++ b/src/test/java/org/jabref/model/entry/AuthorListTest.java @@ -29,7 +29,6 @@ public void testFixAuthorNatbib() { assertTrue(AuthorList .fixAuthorNatbib("John von Neumann and John Smith and Black Brown, Peter").equals(AuthorList .fixAuthorNatbib("John von Neumann and John Smith and Black Brown, Peter"))); - } @Test @@ -55,8 +54,8 @@ public void testFixAuthorFirstNameFirstCommas() { // Check caching assertTrue(AuthorList.fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, false).equals( - AuthorList - .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, false))); + AuthorList + .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, false))); assertEquals("John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas("John Smith and Black Brown, Peter", false, false)); @@ -86,8 +85,8 @@ public void testFixAuthorFirstNameFirstCommas() { // Check caching assertTrue(AuthorList.fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, true).equals( - AuthorList - .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, true))); + AuthorList + .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, true))); assertEquals("John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas("John Smith and Black Brown, Peter", false, true)); @@ -105,7 +104,6 @@ public void testFixAuthorFirstNameFirstCommas() { assertEquals("J. P. von Neumann", AuthorList.fixAuthorFirstNameFirstCommas( "John Peter von Neumann", true, true)); - } @Test @@ -125,7 +123,6 @@ public void testFixAuthorFirstNameFirst() { assertTrue(AuthorList .fixAuthorFirstNameFirst("John von Neumann and John Smith and Black Brown, Peter").equals(AuthorList .fixAuthorFirstNameFirst("John von Neumann and John Smith and Black Brown, Peter"))); - } @Test @@ -230,8 +227,8 @@ public void testFixAuthorLastNameFirst() { assertTrue(AuthorList.fixAuthorLastNameFirst( "John von Neumann and John Smith and Black Brown, Peter", false).equals( - AuthorList - .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", false))); + AuthorList + .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", false))); // Test Abbreviate == true assertEquals("Smith, J.", AuthorList.fixAuthorLastNameFirst("John Smith", true)); @@ -248,9 +245,8 @@ public void testFixAuthorLastNameFirst() { assertTrue(AuthorList.fixAuthorLastNameFirst( "John von Neumann and John Smith and Black Brown, Peter", true).equals( - AuthorList - .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", true))); - + AuthorList + .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", true))); } @Test @@ -263,8 +259,8 @@ public void testFixAuthorLastNameOnlyCommas() { assertTrue(AuthorList.fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", false).equals( - AuthorList - .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", false))); + AuthorList + .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", false))); assertEquals("von Neumann, Smith and Black Brown", AuthorList .fixAuthorLastNameOnlyCommas( @@ -276,8 +272,8 @@ public void testFixAuthorLastNameOnlyCommas() { assertTrue(AuthorList.fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", true).equals( - AuthorList - .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", true))); + AuthorList + .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", true))); assertEquals("von Neumann, Smith, and Black Brown", AuthorList .fixAuthorLastNameOnlyCommas( @@ -365,7 +361,6 @@ public void testGetAuthor() { assertEquals("von Neumann", author.getLastOnly()); assertEquals("Neumann, Jr, J.", author.getNameForAlphabetization()); assertEquals(Optional.of("von"), author.getVon()); - } @Test @@ -506,7 +501,7 @@ public void testGetAuthorsLastFirstAnds() { .parse("John von Neumann and John Smith and Black Brown, Peter") .getAsLastFirstNamesWithAnd(false)); assertEquals("von Last, Jr, First", AuthorList.parse("von Last, Jr ,First") - .getAsLastFirstNamesWithAnd(false)); + .getAsLastFirstNamesWithAnd(false)); assertEquals("Smith, J.", AuthorList.parse("John Smith").getAsLastFirstNamesWithAnd( true)); @@ -515,8 +510,7 @@ public void testGetAuthorsLastFirstAnds() { assertEquals("von Neumann, J. and Smith, J. and Black Brown, P.", AuthorList.parse( "John von Neumann and John Smith and Black Brown, Peter").getAsLastFirstNamesWithAnd(true)); assertEquals("von Last, Jr, F.", AuthorList.parse("von Last, Jr ,First") - .getAsLastFirstNamesWithAnd(true)); - + .getAsLastFirstNamesWithAnd(true)); } @Test @@ -571,7 +565,7 @@ public void testGetAuthorsFirstFirst() { @Test public void testGetAuthorsFirstFirstAnds() { assertEquals("John Smith", AuthorList.parse("John Smith") - .getAsFirstLastNamesWithAnd()); + .getAsFirstLastNamesWithAnd()); assertEquals("John Smith and Peter Black Brown", AuthorList.parse( "John Smith and Black Brown, Peter").getAsFirstLastNamesWithAnd()); assertEquals("John von Neumann and John Smith and Peter Black Brown", AuthorList @@ -584,11 +578,11 @@ public void testGetAuthorsFirstFirstAnds() { @Test public void testGetAuthorsForAlphabetization() { assertEquals("Smith, J.", AuthorList.parse("John Smith") - .getForAlphabetization()); + .getForAlphabetization()); assertEquals("Neumann, J.", AuthorList.parse("John von Neumann") - .getForAlphabetization()); + .getForAlphabetization()); assertEquals("Neumann, J.", AuthorList.parse("J. von Neumann") - .getForAlphabetization()); + .getForAlphabetization()); assertEquals("Neumann, J. and Smith, J. and Black Brown, Jr., P.", AuthorList .parse("John von Neumann and John Smith and de Black Brown, Jr., Peter") .getForAlphabetization()); @@ -677,5 +671,4 @@ public void correctNamesWithOneComma() throws Exception { expected = new Author("José María", "J. M.", null, "Rodriguez Fernandez", null); assertEquals(new AuthorList(expected), AuthorList.parse("Rodriguez Fernandez, José María")); } - } diff --git a/src/test/java/org/jabref/model/entry/AuthorTest.java b/src/test/java/org/jabref/model/entry/AuthorTest.java index c5c40902927..431d6798e61 100644 --- a/src/test/java/org/jabref/model/entry/AuthorTest.java +++ b/src/test/java/org/jabref/model/entry/AuthorTest.java @@ -35,5 +35,4 @@ public void addDotIfAbbreviationDoNotAddDot() { assertEquals("Moore, O. and O. Moore and Moore, O. O.", Author.addDotIfAbbreviation("Moore, O. and O. Moore and Moore, O. O.")); } - } diff --git a/src/test/java/org/jabref/model/entry/BibEntryTest.java b/src/test/java/org/jabref/model/entry/BibEntryTest.java index 886439451a0..5f7e95f52ac 100644 --- a/src/test/java/org/jabref/model/entry/BibEntryTest.java +++ b/src/test/java/org/jabref/model/entry/BibEntryTest.java @@ -131,6 +131,4 @@ public void testGetResolvedKeywords() { assertEquals(new KeywordList(new Keyword("kw"), new Keyword("kw2"), new Keyword("kw3")), actual); } - - } diff --git a/src/test/java/org/jabref/model/entry/BibEntryTests.java b/src/test/java/org/jabref/model/entry/BibEntryTests.java index eb6b414225f..2f39ddb131c 100644 --- a/src/test/java/org/jabref/model/entry/BibEntryTests.java +++ b/src/test/java/org/jabref/model/entry/BibEntryTests.java @@ -36,7 +36,6 @@ public void setUp() { emptyEntry = new BibEntry(); emptyEntry.setType("article"); emptyEntry.setChanged(false); - } @Test @@ -211,7 +210,6 @@ public void getFieldOrAliasLatexFreeComplexConversionInAlias() { @Test public void setNullField() { assertThrows(NullPointerException.class, () -> emptyEntry.setField(null)); - } @Test @@ -222,7 +220,6 @@ public void addNullKeywordThrowsNPE() { @Test public void putNullKeywordListThrowsNPE() { assertThrows(NullPointerException.class, () -> keywordEntry.putKeywords((KeywordList) null, ',')); - } @Test @@ -410,7 +407,6 @@ public void testGroupAndSearchHits() { assertTrue(be.isSearchHit()); be.setSearchHit(false); assertFalse(be.isSearchHit()); - } @Test diff --git a/src/test/java/org/jabref/model/entry/BibtexStringTest.java b/src/test/java/org/jabref/model/entry/BibtexStringTest.java index 440c950394d..1341ac43b33 100644 --- a/src/test/java/org/jabref/model/entry/BibtexStringTest.java +++ b/src/test/java/org/jabref/model/entry/BibtexStringTest.java @@ -33,7 +33,6 @@ public void test() { bs2.setContent("Oscar Gustafsson"); assertEquals("aOG", bs2.getName()); assertEquals("Oscar Gustafsson", bs2.getContent()); - } @Test diff --git a/src/test/java/org/jabref/model/entry/CanonicalBibEntryTest.java b/src/test/java/org/jabref/model/entry/CanonicalBibEntryTest.java index cb1a79ad172..8a3eb16d7c9 100644 --- a/src/test/java/org/jabref/model/entry/CanonicalBibEntryTest.java +++ b/src/test/java/org/jabref/model/entry/CanonicalBibEntryTest.java @@ -26,5 +26,4 @@ public void canonicalRepresentationWithNewlines() { String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); assertEquals("@article{key,\n abstract = {line 1\nline 2}\n}", canonicalRepresentation); } - } diff --git a/src/test/java/org/jabref/model/entry/EntryLinkListTest.java b/src/test/java/org/jabref/model/entry/EntryLinkListTest.java index 77a5c71d059..e187bccd57e 100644 --- a/src/test/java/org/jabref/model/entry/EntryLinkListTest.java +++ b/src/test/java/org/jabref/model/entry/EntryLinkListTest.java @@ -13,7 +13,7 @@ public class EntryLinkListTest { - private static final String key = "test"; + private static final String KEY = "test"; private BibDatabase database; private List links; @@ -24,7 +24,7 @@ public class EntryLinkListTest { @BeforeEach public void before() { database = new BibDatabase(); - links = EntryLinkList.parse(key, database); + links = EntryLinkList.parse(KEY, database); link = links.get(0); source = create("source"); target = create("target"); @@ -39,7 +39,7 @@ private BibEntry create(String citeKey) { @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectKey() { - assertEquals(key, link.getKey()); + assertEquals(KEY, link.getKey()); } @Test @@ -54,7 +54,7 @@ public void givenFieldValueAndDatabaseWhenParsingThenExpectEmptyLinkedEntry() { @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectLink() { - ParsedEntryLink expected = new ParsedEntryLink(key, database); + ParsedEntryLink expected = new ParsedEntryLink(KEY, database); assertEquals(expected, link); } diff --git a/src/test/java/org/jabref/model/entry/FieldNameTest.java b/src/test/java/org/jabref/model/entry/FieldNameTest.java index ae0eb69c2d2..9220fcb86d6 100644 --- a/src/test/java/org/jabref/model/entry/FieldNameTest.java +++ b/src/test/java/org/jabref/model/entry/FieldNameTest.java @@ -15,5 +15,4 @@ public void testOrFieldsTwoTerms() { public void testOrFieldsThreeTerms() { assertEquals("aaa/bbb/ccc", FieldName.orFields("aaa", "bbb", "ccc")); } - } diff --git a/src/test/java/org/jabref/model/entry/FileFieldWriterTest.java b/src/test/java/org/jabref/model/entry/FileFieldWriterTest.java index d9b6fb0f1e7..84aba43fcbf 100644 --- a/src/test/java/org/jabref/model/entry/FileFieldWriterTest.java +++ b/src/test/java/org/jabref/model/entry/FileFieldWriterTest.java @@ -103,10 +103,10 @@ public void testQuoteNull() { @Test public void testEncodeStringArray() { - assertEquals("a:b;c:d", FileFieldWriter.encodeStringArray(new String[][] {{"a", "b"}, {"c", "d"}})); - assertEquals("a:;c:d", FileFieldWriter.encodeStringArray(new String[][] {{"a", ""}, {"c", "d"}})); - assertEquals("a:" + null + ";c:d", FileFieldWriter.encodeStringArray(new String[][] {{"a", null}, {"c", "d"}})); - assertEquals("a:\\:b;c\\;:d", FileFieldWriter.encodeStringArray(new String[][] {{"a", ":b"}, {"c;", "d"}})); + assertEquals("a:b;c:d", FileFieldWriter.encodeStringArray(new String[][]{{"a", "b"}, {"c", "d"}})); + assertEquals("a:;c:d", FileFieldWriter.encodeStringArray(new String[][]{{"a", ""}, {"c", "d"}})); + assertEquals("a:" + null + ";c:d", FileFieldWriter.encodeStringArray(new String[][]{{"a", null}, {"c", "d"}})); + assertEquals("a:\\:b;c\\;:d", FileFieldWriter.encodeStringArray(new String[][]{{"a", ":b"}, {"c;", "d"}})); } @Test @@ -114,6 +114,4 @@ public void testFileFieldWriterGetStringRepresentation() { LinkedFile file = new LinkedFile("test", "X:\\Users\\abc.pdf", "PDF"); assertEquals("test:X\\:/Users/abc.pdf:PDF", FileFieldWriter.getStringRepresentation(file)); } - - } diff --git a/src/test/java/org/jabref/model/entry/IEEETranEntryTypesTest.java b/src/test/java/org/jabref/model/entry/IEEETranEntryTypesTest.java index 6d87b4bfcfb..dfeb26bf53f 100644 --- a/src/test/java/org/jabref/model/entry/IEEETranEntryTypesTest.java +++ b/src/test/java/org/jabref/model/entry/IEEETranEntryTypesTest.java @@ -16,5 +16,4 @@ public void ctlTypeContainsYesNoFields() { assertTrue(ctlFields.containsAll(ynFields)); } - } diff --git a/src/test/java/org/jabref/model/entry/IdGeneratorTest.java b/src/test/java/org/jabref/model/entry/IdGeneratorTest.java index f49e00b11c1..2775dd19590 100644 --- a/src/test/java/org/jabref/model/entry/IdGeneratorTest.java +++ b/src/test/java/org/jabref/model/entry/IdGeneratorTest.java @@ -17,7 +17,5 @@ public void testCreateNeutralId() { assertFalse(set.contains(string)); set.add(string); } - } - } diff --git a/src/test/java/org/jabref/model/entry/KeywordListTest.java b/src/test/java/org/jabref/model/entry/KeywordListTest.java index bb24fb66c68..6dbb9b08db5 100644 --- a/src/test/java/org/jabref/model/entry/KeywordListTest.java +++ b/src/test/java/org/jabref/model/entry/KeywordListTest.java @@ -88,5 +88,4 @@ public void parseTwoHierarchicalChains() throws Exception { assertEquals(new KeywordList(expectedOne, expectedTwo), KeywordList.parse("Parent1 > Node1 > Child1, Parent2 > Node2 > Child2", ',', '>')); } - } diff --git a/src/test/java/org/jabref/model/entry/MonthTest.java b/src/test/java/org/jabref/model/entry/MonthTest.java index d99b7c3c472..20914aabc44 100644 --- a/src/test/java/org/jabref/model/entry/MonthTest.java +++ b/src/test/java/org/jabref/model/entry/MonthTest.java @@ -137,7 +137,7 @@ public void parseCorrectlyByFullNameGerman() { @Test public void parseCorrectlyByShortNameGermanLowercase() { - assertEquals(Optional.of(Month.JANUARY), Month.parse("jan")); + assertEquals(Optional.of(Month.JANUARY), Month.parse("jan")); assertEquals(Optional.of(Month.FEBRUARY), Month.parse("feb")); assertEquals(Optional.of(Month.MARCH), Month.parse("mär")); assertEquals(Optional.of(Month.MARCH), Month.parse("mae")); diff --git a/src/test/java/org/jabref/model/entry/identifier/DOITest.java b/src/test/java/org/jabref/model/entry/identifier/DOITest.java index e1e8636c1f1..4d45bb239cf 100644 --- a/src/test/java/org/jabref/model/entry/identifier/DOITest.java +++ b/src/test/java/org/jabref/model/entry/identifier/DOITest.java @@ -148,7 +148,5 @@ public void noDOIFoundInsideArbitraryText() { public void parseDOIWithWhiteSpace() { String doiWithSpace = "https : / / doi.org / 10 .1109 /V LHCC.20 04.20"; assertEquals("https://doi.org/10.1109/VLHCC.2004.20", DOI.parse(doiWithSpace).get().getURIAsASCIIString()); - } - } diff --git a/src/test/java/org/jabref/model/entry/identifier/ISBNTest.java b/src/test/java/org/jabref/model/entry/identifier/ISBNTest.java index acd4d4149fe..55dcfe847ca 100644 --- a/src/test/java/org/jabref/model/entry/identifier/ISBNTest.java +++ b/src/test/java/org/jabref/model/entry/identifier/ISBNTest.java @@ -70,5 +70,4 @@ public void testIsIsbn13Correct() { public void testIsIsbn13Incorrect() { assertFalse(new ISBN("0-123456-47-9").isIsbn13()); } - } diff --git a/src/test/java/org/jabref/model/entry/specialfields/SpecialFieldTest.java b/src/test/java/org/jabref/model/entry/specialfields/SpecialFieldTest.java index 23cff29c279..9036c7bffe2 100644 --- a/src/test/java/org/jabref/model/entry/specialfields/SpecialFieldTest.java +++ b/src/test/java/org/jabref/model/entry/specialfields/SpecialFieldTest.java @@ -10,7 +10,6 @@ public class SpecialFieldTest { - @Test public void getSpecialFieldInstanceFromFieldNameValid() { assertEquals(Optional.of(SpecialField.RANKING), diff --git a/src/test/java/org/jabref/model/event/TestEventListener.java b/src/test/java/org/jabref/model/event/TestEventListener.java index 7619adb51a8..c8e3b2cd1d5 100644 --- a/src/test/java/org/jabref/model/event/TestEventListener.java +++ b/src/test/java/org/jabref/model/event/TestEventListener.java @@ -11,7 +11,6 @@ public class TestEventListener { private BibEntry bibEntry; - @Subscribe public void listen(EntryAddedEvent event) { this.bibEntry = event.getBibEntry(); @@ -30,5 +29,4 @@ public void listen(EntryChangedEvent event) { public BibEntry getBibEntry() { return this.bibEntry; } - } diff --git a/src/test/java/org/jabref/model/groups/SearchGroupTest.java b/src/test/java/org/jabref/model/groups/SearchGroupTest.java index 24849ff6e8a..bdc24d22b56 100644 --- a/src/test/java/org/jabref/model/groups/SearchGroupTest.java +++ b/src/test/java/org/jabref/model/groups/SearchGroupTest.java @@ -8,7 +8,6 @@ public class SearchGroupTest { - @Test public void containsFindsWordWithRegularExpression() { SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=rev*", true, true); diff --git a/src/test/java/org/jabref/model/pdf/FileAnnotationTest.java b/src/test/java/org/jabref/model/pdf/FileAnnotationTest.java index a96aa095835..4d907144d4c 100644 --- a/src/test/java/org/jabref/model/pdf/FileAnnotationTest.java +++ b/src/test/java/org/jabref/model/pdf/FileAnnotationTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - public class FileAnnotationTest { @Test diff --git a/src/test/java/org/jabref/model/search/matchers/MatcherSetsTest.java b/src/test/java/org/jabref/model/search/matchers/MatcherSetsTest.java index acd7e385b6b..be77c6773e3 100644 --- a/src/test/java/org/jabref/model/search/matchers/MatcherSetsTest.java +++ b/src/test/java/org/jabref/model/search/matchers/MatcherSetsTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - public class MatcherSetsTest { @Test @@ -46,5 +45,4 @@ public void testBuildNotWithFalse() { NotMatcher matcher = new NotMatcher(new MockSearchMatcher(false)); assertTrue(matcher.isMatch(new BibEntry())); } - } diff --git a/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java b/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java index a31483330f4..b60ec5ebc83 100644 --- a/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java +++ b/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java @@ -40,7 +40,6 @@ public void testBasicSearchParsing() { assertEquals(false, bsCaseInsensitive.applyRule(query, be)); assertEquals(false, bsCaseSensitiveRegexp.applyRule(query, be)); assertEquals(true, bsCaseInsensitiveRegexp.applyRule(query, be)); - } public BibEntry makeBibtexEntry() { diff --git a/src/test/java/org/jabref/model/search/rules/SentenceAnalyzerTest.java b/src/test/java/org/jabref/model/search/rules/SentenceAnalyzerTest.java index c75ee11dc4b..732f4114f5f 100644 --- a/src/test/java/org/jabref/model/search/rules/SentenceAnalyzerTest.java +++ b/src/test/java/org/jabref/model/search/rules/SentenceAnalyzerTest.java @@ -11,10 +11,9 @@ public class SentenceAnalyzerTest { @Test public void testGetWords() { - assertEquals(Arrays.asList("a","b"), new SentenceAnalyzer("a b").getWords()); - assertEquals(Arrays.asList("a","b"), new SentenceAnalyzer(" a b ").getWords()); + assertEquals(Arrays.asList("a", "b"), new SentenceAnalyzer("a b").getWords()); + assertEquals(Arrays.asList("a", "b"), new SentenceAnalyzer(" a b ").getWords()); assertEquals(Collections.singletonList("b "), new SentenceAnalyzer("\"b \" ").getWords()); assertEquals(Collections.singletonList(" a"), new SentenceAnalyzer(" \\ a").getWords()); } - } diff --git a/src/test/java/org/jabref/model/strings/StringUtilTest.java b/src/test/java/org/jabref/model/strings/StringUtilTest.java index 19872c9d294..383b97c1cc0 100644 --- a/src/test/java/org/jabref/model/strings/StringUtilTest.java +++ b/src/test/java/org/jabref/model/strings/StringUtilTest.java @@ -57,7 +57,6 @@ void testQuoteMoreComplicated() { assertEquals("a::b:%c:;", StringUtil.quote("a:b%c;", "%;", ':')); } - @Test void testUnifyLineBreaks() { // Mac < v9 @@ -129,7 +128,7 @@ void testJoin() { assertEquals("", StringUtil.join(s, "\\", 3, s.length)); - assertEquals("", StringUtil.join(new String[] {}, "\\", 0, 0)); + assertEquals("", StringUtil.join(new String[]{}, "\\", 0, 0)); } @Test @@ -192,7 +191,6 @@ void testIsInCurlyBrackets() { assertFalse(StringUtil.isInCurlyBrackets("}")); assertFalse(StringUtil.isInCurlyBrackets("a{}a")); assertFalse(StringUtil.isInCurlyBrackets("{\\AA}sa {\\AA}Stor{\\aa}")); - } @Test diff --git a/src/test/java/org/jabref/performance/BibtexEntryGenerator.java b/src/test/java/org/jabref/performance/BibtexEntryGenerator.java index 676e008ccd6..f69932fe26a 100644 --- a/src/test/java/org/jabref/performance/BibtexEntryGenerator.java +++ b/src/test/java/org/jabref/performance/BibtexEntryGenerator.java @@ -23,5 +23,4 @@ private String generateBibtexEntry(int i) { " publisher={Wiley Online Library}\n" + "}\n"; } - } diff --git a/src/test/java/org/jabref/support/CIServerCondition.java b/src/test/java/org/jabref/support/CIServerCondition.java index cc7ad59251c..3aa8812a3fe 100644 --- a/src/test/java/org/jabref/support/CIServerCondition.java +++ b/src/test/java/org/jabref/support/CIServerCondition.java @@ -34,8 +34,8 @@ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext con Optional disabled = AnnotationUtils.findAnnotation(element, DisabledOnCIServer.class); if (disabled.isPresent()) { String reason = disabled.map(DisabledOnCIServer::value) - .filter(StringUtil::isNotBlank) - .orElseGet(() -> element.get() + " is disabled on CI server"); + .filter(StringUtil::isNotBlank) + .orElseGet(() -> element.get() + " is disabled on CI server"); return ConditionEvaluationResult.disabled(reason); } diff --git a/src/test/java/org/jabref/testutils/TestUtils.java b/src/test/java/org/jabref/testutils/TestUtils.java index 83120f4c62c..3c03bfa2714 100644 --- a/src/test/java/org/jabref/testutils/TestUtils.java +++ b/src/test/java/org/jabref/testutils/TestUtils.java @@ -8,8 +8,7 @@ public class TestUtils { private static final String PATH_TO_TEST_BIBTEX = "src/test/resources/org/jabref/bibtexFiles/test.bib"; /** - * Initialize JabRef. Can be cleaned up with - * {@link TestUtils#closeJabRef()} + * Initialize JabRef. Can be cleaned up with {@link TestUtils#closeJabRef()} * * @see TestUtils#closeJabRef() */ @@ -25,5 +24,4 @@ public static void closeJabRef() { if (JabRefGUI.getMainFrame() != null) { } } - } From 4893461482d8d04a8d71310d73c3a870dc042f76 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Wed, 17 Oct 2018 12:31:34 +0200 Subject: [PATCH 08/30] Convert find unlinked files dialog to JavaFX (#4375) * Convert find unlinked files dialog to JavaFX Fixes #4357. * Fix tests * Fix checkstyle * Fix checkstyle * Remove obsolete language keys --- .../jabref/gui/FindUnlinkedFilesDialog.java | 1226 ----------------- src/main/java/org/jabref/gui/JabRefFrame.java | 2 +- .../FindUnlinkedFilesAction.java | 6 +- .../FindUnlinkedFilesDialog.java | 440 ++++++ .../importer/EntryFromFileCreatorManager.java | 78 +- .../gui/importer/UnlinkedFilesCrawler.java | 68 +- .../org/jabref/gui/util/BackgroundTask.java | 56 +- .../jabref/gui/util/DefaultTaskExecutor.java | 6 + .../gui/util/ViewModelListCellFactory.java | 9 +- .../gui/util/ViewModelTreeCellFactory.java | 84 ++ .../jabref/preferences/JabRefPreferences.java | 1 - src/main/resources/l10n/JabRef_en.properties | 5 - .../EntryFromFileCreatorManagerTest.java | 98 +- .../gui/importer/EntryFromPDFCreatorTest.java | 6 +- .../importer/DatabaseFileLookupTest.java | 26 +- .../jabref/logic/importer/ImportDataTest.java | 42 +- 16 files changed, 724 insertions(+), 1429 deletions(-) delete mode 100644 src/main/java/org/jabref/gui/FindUnlinkedFilesDialog.java rename src/main/java/org/jabref/gui/{actions => externalfiles}/FindUnlinkedFilesAction.java (77%) create mode 100644 src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java create mode 100644 src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java diff --git a/src/main/java/org/jabref/gui/FindUnlinkedFilesDialog.java b/src/main/java/org/jabref/gui/FindUnlinkedFilesDialog.java deleted file mode 100644 index e41f30dc616..00000000000 --- a/src/main/java/org/jabref/gui/FindUnlinkedFilesDialog.java +++ /dev/null @@ -1,1226 +0,0 @@ -package org.jabref.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.BorderFactory; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JRootPane; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.KeyStroke; -import javax.swing.SwingConstants; -import javax.swing.WindowConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.filechooser.FileSystemView; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -import org.jabref.Globals; -import org.jabref.JabRefExecutorService; -import org.jabref.JabRefGUI; -import org.jabref.gui.desktop.JabRefDesktop; -import org.jabref.gui.externalfiletype.ExternalFileTypes; -import org.jabref.gui.importer.EntryFromFileCreator; -import org.jabref.gui.importer.EntryFromFileCreatorManager; -import org.jabref.gui.importer.UnlinkedFilesCrawler; -import org.jabref.gui.importer.UnlinkedPDFFileFilter; -import org.jabref.gui.util.DefaultTaskExecutor; -import org.jabref.gui.util.DirectoryDialogConfiguration; -import org.jabref.gui.util.FileDialogConfiguration; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.EntryTypes; -import org.jabref.model.database.BibDatabaseContext; -import org.jabref.model.entry.BibtexEntryType; -import org.jabref.model.entry.EntryType; -import org.jabref.model.entry.FieldName; -import org.jabref.preferences.JabRefPreferences; - -import com.jgoodies.forms.builder.ButtonBarBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * GUI Dialog for the feature "Find unlinked files". - */ -public class FindUnlinkedFilesDialog extends JabRefDialog { - - private static final Logger LOGGER = LoggerFactory.getLogger(FindUnlinkedFilesDialog.class); - private static final String GLOBAL_PREFS_WORKING_DIRECTORY_KEY = "findUnlinkedFilesWD"; - - private static final String GLOBAL_PREFS_DIALOG_SIZE_KEY = "findUnlinkedFilesDialogSize"; - private final JabRefFrame frame; - private final BibDatabaseContext databaseContext; - private final EntryFromFileCreatorManager creatorManager; - - private final UnlinkedFilesCrawler crawler; - private Path lastSelectedDirectory; - - private TreeModel treeModel; - /* PANELS */ - private JPanel panelDirectory; - private JPanel panelSearchArea; - private JPanel panelFiles; - private JPanel panelOptions; - private JPanel panelButtons; - private JPanel panelEntryTypesSelection; - - private JPanel panelImportArea; - private JButton buttonBrowse; - private JButton buttonScan; - private JButton buttonExport; - private JButton buttonApply; - - private JButton buttonClose; - /* Options for the TreeView */ - private JButton buttonOptionSelectAll; - private JButton buttonOptionDeselectAll; - private JButton buttonOptionExpandAll; - private JButton buttonOptionCollapseAll; - - private JCheckBox checkboxCreateKeywords; - private JTextField textfieldDirectoryPath; - private JLabel labelDirectoryDescription; - private JLabel labelFileTypesDescription; - private JLabel labelFilesDescription; - private JLabel labelEntryTypeDescription; - private JLabel labelSearchingDirectoryInfo; - - private JLabel labelImportingInfo; - private JLabel labelExportingInfo; - private JTree tree; - private JScrollPane scrollpaneTree; - private JComboBox comboBoxFileTypeSelection; - - private JComboBox comboBoxEntryTypeSelection; - private JProgressBar progressBarSearching; - private JProgressBar progressBarImporting; - - private MouseListener treeMouseListener; - private Action actionSelectAll; - private Action actionUnselectAll; - private Action actionExpandTree; - - private Action actionCollapseTree; - - private ComponentListener dialogPositionListener; - private final AtomicBoolean threadState = new AtomicBoolean(); - - private boolean checkBoxWhyIsThereNoGetSelectedStupidSwing; - - public FindUnlinkedFilesDialog(JabRefFrame frame) { - super(Localization.lang("Find unlinked files"), true, FindUnlinkedFilesDialog.class); - this.frame = frame; - - restoreSizeOfDialog(); - - databaseContext = frame.getCurrentBasePanel().getBibDatabaseContext(); - creatorManager = new EntryFromFileCreatorManager(ExternalFileTypes.getInstance()); - - crawler = new UnlinkedFilesCrawler(databaseContext); - - lastSelectedDirectory = loadLastSelectedDirectory(); - - initialize(); - buttonApply.setEnabled(false); - buttonExport.setEnabled(false); - } - - /** - * Close dialog when pressing escape - */ - @Override - protected JRootPane createRootPane() { - ActionListener actionListener = actionEvent -> setVisible(false); - JRootPane rPane = new JRootPane(); - KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); - rPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); - - return rPane; - } - - /** - * Stores the current size of this dialog persistently. - */ - private void storeSizeOfDialog() { - Dimension dim = getSize(); - String store = dim.width + ";" + dim.height; - Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY, store); - } - - /** - * Restores the location and size of this dialog from the persistent storage. - */ - private void restoreSizeOfDialog() { - - String store = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY); - - Dimension dimension = null; - - if (store != null) { - try { - String[] dim = store.split(";"); - dimension = new Dimension(Integer.valueOf(dim[0]), Integer.valueOf(dim[1])); - } catch (NumberFormatException ignoredEx) { - LOGGER.debug("RestoreSizeDialog Exception ", ignoredEx); - } - } - if (dimension != null) { - setPreferredSize(dimension); - } - } - - /** - * Initializes the components, the layout, the data structure and the - * actions in this dialog. - */ - private void initialize() { - - initializeActions(); - initComponents(); - createTree(); - createFileTypesCombobox(); - createEntryTypesCombobox(); - initLayout(); - setupActions(); - pack(); - } - - /** - * Initializes action objects.
- * Does not assign actions to components yet! - */ - private void initializeActions() { - - actionSelectAll = new AbstractAction(Localization.lang("Select all")) { - - @Override - public void actionPerformed(ActionEvent e) { - CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot(); - rootNode.setSelected(true); - tree.invalidate(); - tree.repaint(); - } - }; - - actionUnselectAll = new AbstractAction(Localization.lang("Unselect all")) { - - @Override - public void actionPerformed(ActionEvent e) { - CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot(); - rootNode.setSelected(false); - tree.invalidate(); - tree.repaint(); - } - }; - - actionExpandTree = new AbstractAction(Localization.lang("Expand all")) { - - @Override - public void actionPerformed(ActionEvent e) { - CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot(); - expandTree(tree, new TreePath(rootNode), true); - } - }; - - actionCollapseTree = new AbstractAction(Localization.lang("Collapse all")) { - - @Override - public void actionPerformed(ActionEvent e) { - CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot(); - expandTree(tree, new TreePath(rootNode), false); - } - }; - - dialogPositionListener = new ComponentAdapter() { - - /* (non-Javadoc) - * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent) - */ - @Override - public void componentResized(ComponentEvent e) { - storeSizeOfDialog(); - } - - /* (non-Javadoc) - * @see java.awt.event.ComponentAdapter#componentMoved(java.awt.event.ComponentEvent) - */ - @Override - public void componentMoved(ComponentEvent e) { - storeSizeOfDialog(); - } - }; - - } - - /** - * Stores the working directory path for this view in the global - * preferences. - * - * @param lastSelectedDir - * directory that is used as the working directory in this view. - */ - private void storeLastSelectedDirectory(Path lastSelectedDir) { - lastSelectedDirectory = lastSelectedDir; - if (lastSelectedDirectory != null) { - Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY, - lastSelectedDirectory.toAbsolutePath().toString()); - } - } - - /** - * Loads the working directory path which is persistantly stored for this - * view and returns it as a {@link File}-Object.
- *
- * If there is no working directory path stored, the general working - * directory will be consulted. - * - * @return The persistently stored working directory path for this view. - */ - private Path loadLastSelectedDirectory() { - String workingDirectory = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY); - if (workingDirectory == null) { - workingDirectory = Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY); - } - lastSelectedDirectory = Paths.get(workingDirectory); - - return lastSelectedDirectory; - } - - /** - * Disables or enables all visible Elements in this Dialog.
- *
- * This also removes the {@link MouseListener} from the Tree-View to prevent - * it from receiving mouse events when in disabled-state. - * - * @param enable - * true when the elements shall get enabled, - * false when they shall get disabled. - */ - private void disOrEnableDialog(boolean enable) { - - if (enable) { - tree.addMouseListener(treeMouseListener); - } else { - tree.removeMouseListener(treeMouseListener); - } - disOrEnableAllElements(FindUnlinkedFilesDialog.this, enable); - } - - /** - * Recursively disables or enables all swing and awt components in this - * dialog, starting with but not including the container - * startContainer. - * - * @param startContainer - * The GUI Element to start with. - * @param enable - * true, if all elements will get enabled, - * false if all elements will get disabled. - */ - private void disOrEnableAllElements(Container startContainer, boolean enable) { - Component[] children = startContainer.getComponents(); - for (Component child : children) { - if (child instanceof Container) { - disOrEnableAllElements((Container) child, enable); - } - child.setEnabled(enable); - } - } - - /** - * Expands or collapses the specified tree according to the - * expand-parameter. - */ - private void expandTree(JTree currentTree, TreePath parent, boolean expand) { - TreeNode node = (TreeNode) parent.getLastPathComponent(); - if (node.getChildCount() >= 0) { - for (Enumeration e = node.children(); e.hasMoreElements();) { - TreePath path = parent.pathByAddingChild(e.nextElement()); - expandTree(currentTree, path, expand); - } - } - if (expand) { - currentTree.expandPath(parent); - } else { - currentTree.collapsePath(parent); - } - } - - /** - * Starts the search of unlinked files according to the current dialog - * state.
- *
- * This state is made of:
- *
  • The value of the "directory"-input-textfield and
  • The file type - * selection.
    - * The search will process in a seperate thread and the progress bar behind - * the "search" button will be displayed.
    - *
    - * When the search has completed, the - * {@link #searchFinishedHandler(CheckableTreeNode)} handler method is - * invoked. - */ - private void startSearch() { - - Path directory = Paths.get(textfieldDirectoryPath.getText()); - if (Files.notExists(directory)) { - directory = Paths.get(System.getProperty("user.dir")); - } - if (!Files.isDirectory(directory)) { - directory = directory.getParent(); - } - - //this addtional statement is needed because for the lamdba the variable must be effetively final - Path dir = directory; - - storeLastSelectedDirectory(directory); - - progressBarSearching.setMinimumSize( - new Dimension(buttonScan.getSize().width, progressBarSearching.getMinimumSize().height)); - progressBarSearching.setVisible(true); - progressBarSearching.setString(""); - - labelSearchingDirectoryInfo.setVisible(true); - buttonScan.setVisible(false); - - disOrEnableDialog(false); - labelSearchingDirectoryInfo.setEnabled(true); - - final FileFilter selectedFileFilter = (FileFilter) comboBoxFileTypeSelection.getSelectedItem(); - - threadState.set(true); - JabRefExecutorService.INSTANCE.execute(() -> { - UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(selectedFileFilter, - databaseContext); - CheckableTreeNode rootNode = crawler.searchDirectory(dir.toFile(), unlinkedPDFFileFilter, threadState, - new ChangeListener() { - - int counter; - - @Override - public void stateChanged(ChangeEvent e) { - counter++; - String message; - if (counter == 1) { - message = Localization.lang("One file found"); - } else { - message = Localization.lang("%0 files found", Integer.toString(counter)); - } - progressBarSearching.setString(message); - } - }); - searchFinishedHandler(rootNode); - }); - - } - - /** - * This will start the import of all file of all selected nodes in this - * dialogs tree view.
    - *
    - * The import itself will run in a seperate thread, whilst this dialog will - * be showing a progress bar, until the thread has finished its work.
    - *
    - * When the import has finished, the {@link #importFinishedHandler(java.util.List)} is - * invoked. - */ - private void startImport() { - - if (treeModel == null) { - return; - } - setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - - CheckableTreeNode root = (CheckableTreeNode) treeModel.getRoot(); - - final List fileList = getFileListFromNode(root); - - if ((fileList == null) || fileList.isEmpty()) { - return; - } - - progressBarImporting.setVisible(true); - labelImportingInfo.setVisible(true); - buttonExport.setVisible(false); - buttonApply.setVisible(false); - buttonClose.setVisible(false); - disOrEnableDialog(false); - - labelImportingInfo.setEnabled(true); - - progressBarImporting.setMinimum(0); - progressBarImporting.setMaximum(fileList.size()); - progressBarImporting.setValue(0); - progressBarImporting.setString(""); - - final EntryType entryType = ((BibtexEntryTypeWrapper) comboBoxEntryTypeSelection.getSelectedItem()) - .getEntryType(); - - threadState.set(true); - JabRefExecutorService.INSTANCE.execute(() -> { - List errors = new LinkedList<>(); - creatorManager.addEntriesFromFiles(fileList, databaseContext.getDatabase(), frame.getCurrentBasePanel(), - entryType, checkBoxWhyIsThereNoGetSelectedStupidSwing, new ChangeListener() { - - int counter; - - @Override - public void stateChanged(ChangeEvent e) { - counter++; - progressBarImporting.setValue(counter); - progressBarImporting.setString(Localization.lang("%0 of %1", Integer.toString(counter), - Integer.toString(progressBarImporting.getMaximum()))); - } - }, errors); - importFinishedHandler(errors); - }); - } - - /** - * This starts the export of all files of all selected nodes in this - * dialogs tree view.
    - *
    - * The export itself will run in a seperate thread, whilst this dialog will - * be showing a progress bar, until the thread has finished its work.
    - *
    - * When the export has finished, the {@link #exportFinishedHandler()} is - * invoked. - */ - private void startExport() { - if (treeModel == null) { - return; - } - setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - - CheckableTreeNode root = (CheckableTreeNode) treeModel.getRoot(); - - final List fileList = getFileListFromNode(root); - if ((fileList == null) || fileList.isEmpty()) { - return; - } - - buttonExport.setVisible(false); - buttonApply.setVisible(false); - buttonClose.setVisible(false); - disOrEnableDialog(false); - - FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); - DialogService ds = new FXDialogService(); - - Optional exportPath = DefaultTaskExecutor - .runInJavaFXThread(() -> ds.showFileSaveDialog(fileDialogConfiguration)); - - if (!exportPath.isPresent()) { - exportFinishedHandler(); - return; - } - - threadState.set(true); - JabRefExecutorService.INSTANCE.execute(() -> { - try (BufferedWriter writer = - Files.newBufferedWriter(exportPath.get(), StandardCharsets.UTF_8, - StandardOpenOption.CREATE)) { - for (File file : fileList) { - writer.write(file.toString() + "\n"); - } - - } catch (IOException e) { - LOGGER.warn("IO Error.", e); - } - }); - - exportFinishedHandler(); - } - - private void exportFinishedHandler() { - buttonExport.setVisible(true); - buttonApply.setVisible(true); - buttonClose.setVisible(true); - disOrEnableDialog(true); - setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - frame.getCurrentBasePanel().markBaseChanged(); - } - - /** - * - * @param errors - */ - private void importFinishedHandler(List errors) { - - if ((errors != null) && !errors.isEmpty()) { - String message; - if (errors.size() == 1) { - message = Localization.lang("There was one file that could not be imported."); - } else { - message = Localization.lang("There were %0 files which could not be imported.", - Integer.toString(errors.size())); - } - JOptionPane.showMessageDialog(this, - Localization.lang("The import finished with warnings:") + "\n" + message, - Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE); - } - - progressBarImporting.setVisible(false); - labelImportingInfo.setVisible(false); - buttonExport.setVisible(true); - buttonApply.setVisible(true); - buttonClose.setVisible(true); - disOrEnableDialog(true); - setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - frame.getCurrentBasePanel().markBaseChanged(); - } - - /** - * Will be called from the Thread in which the "unlinked files search" is - * processed. As the result of the search, the root node of the determined - * file structure is passed. - * - * @param rootNode - * The root of the file structure as the result of the search. - */ - private void searchFinishedHandler(CheckableTreeNode rootNode) { - treeModel = new DefaultTreeModel(rootNode); - tree.setModel(treeModel); - tree.setRootVisible(rootNode.getChildCount() > 0); - - tree.invalidate(); - tree.repaint(); - - progressBarSearching.setVisible(false); - labelSearchingDirectoryInfo.setVisible(false); - buttonScan.setVisible(true); - actionSelectAll.actionPerformed(null); - - disOrEnableDialog(true); - buttonApply.setEnabled(true); - buttonExport.setEnabled(true); - } - - /** - * Sets up the actions for the components. - */ - private void setupActions() { - - DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder() - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); - DialogService ds = frame.getDialogService(); - /** - * Stores the selected directory. - */ - buttonBrowse.addActionListener(e -> { - Optional selectedDirectory = DefaultTaskExecutor - .runInJavaFXThread(() -> ds.showDirectorySelectionDialog(directoryDialogConfiguration)); - selectedDirectory.ifPresent(d -> { - textfieldDirectoryPath.setText(d.toAbsolutePath().toString()); - storeLastSelectedDirectory(d); - }); - }); - - buttonScan.addActionListener(e -> startSearch()); - - /** - * Action for the button "Import...".
    - *
    - * Actions on this button will start the import of all file of all - * selected nodes in this dialogs tree view.
    - */ - buttonExport.addActionListener(e -> startExport()); - buttonApply.addActionListener(e -> startImport()); - buttonClose.addActionListener(e -> dispose()); - } - - /** - * Creates a list of {@link File}s for all leaf nodes in the tree structure - * node, which have been marked as selected.
    - *
    - * Selected nodes correspond to those entries in the tree, - * whose checkbox is checked. - * - * SIDE EFFECT: The checked nodes are removed from the tree. - * - * @param node - * The root node representing a tree structure. - * @return A list of files of all checked leaf nodes. - */ - private List getFileListFromNode(CheckableTreeNode node) { - List filesList = new ArrayList<>(); - Enumeration children = node.depthFirstEnumeration(); - List nodesToRemove = new ArrayList<>(); - for (CheckableTreeNode child : Collections.list(children)) { - if (child.isLeaf() && child.isSelected()) { - File nodeFile = ((FileNodeWrapper) child.getUserObject()).file; - if ((nodeFile != null) && nodeFile.isFile()) { - filesList.add(nodeFile); - nodesToRemove.add(child); - } - } - } - - // remove imported files from tree - DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); - for (CheckableTreeNode nodeToRemove : nodesToRemove) { - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) nodeToRemove.getParent(); - model.removeNodeFromParent(nodeToRemove); - - // remove empty parent node - while ((parent != null) && parent.isLeaf()) { - DefaultMutableTreeNode pp = (DefaultMutableTreeNode) parent.getParent(); - if (pp != null) { - model.removeNodeFromParent(parent); - } - parent = pp; - } - // TODO: update counter / see: getTreeCellRendererComponent for label generation - } - tree.invalidate(); - tree.repaint(); - - return filesList; - } - - /** - * Initializes the visible components in this dialog. - */ - private void initComponents() { - - this.addComponentListener(dialogPositionListener); - /* Interrupts the searchThread by setting the State-Array to 0 */ - this.addWindowListener(new WindowAdapter() { - - @Override - public void windowClosing(WindowEvent e) { - threadState.set(false); - } - }); - - panelDirectory = new JPanel(); - panelSearchArea = new JPanel(); - panelFiles = new JPanel(); - panelOptions = new JPanel(); - panelEntryTypesSelection = new JPanel(); - panelButtons = new JPanel(); - panelImportArea = new JPanel(); - - buttonBrowse = new JButton(Localization.lang("Browse")); - buttonBrowse.setMnemonic('B'); - buttonBrowse.setToolTipText(Localization.lang("Opens the file browser.")); - buttonScan = new JButton(Localization.lang("Scan directory")); - buttonScan.setMnemonic('S'); - buttonScan.setToolTipText(Localization.lang("Searches the selected directory for unlinked files.")); - buttonExport = new JButton(Localization.lang("Export")); - buttonExport.setMnemonic('E'); - buttonExport.setToolTipText(Localization.lang("Export to text file.")); - buttonApply = new JButton(Localization.lang("Apply")); - buttonApply.setMnemonic('I'); - buttonApply.setToolTipText(Localization.lang("Starts the import of BibTeX entries.")); - buttonClose = new JButton(Localization.lang("Close")); - buttonClose.setToolTipText(Localization.lang("Leave this dialog.")); - buttonClose.setMnemonic('C'); - - /* Options for the TreeView */ - buttonOptionSelectAll = new JButton(); - buttonOptionSelectAll.setMnemonic('A'); - buttonOptionSelectAll.setAction(actionSelectAll); - buttonOptionDeselectAll = new JButton(); - buttonOptionDeselectAll.setMnemonic('U'); - buttonOptionDeselectAll.setAction(actionUnselectAll); - buttonOptionExpandAll = new JButton(); - buttonOptionExpandAll.setMnemonic('E'); - buttonOptionExpandAll.setAction(actionExpandTree); - buttonOptionCollapseAll = new JButton(); - buttonOptionCollapseAll.setMnemonic('L'); - buttonOptionCollapseAll.setAction(actionCollapseTree); - - checkboxCreateKeywords = new JCheckBox(Localization.lang("Create directory based keywords")); - checkboxCreateKeywords - .setToolTipText(Localization.lang("Creates keywords in created entrys with directory pathnames")); - checkboxCreateKeywords.setSelected(checkBoxWhyIsThereNoGetSelectedStupidSwing); - checkboxCreateKeywords.addItemListener( - e -> checkBoxWhyIsThereNoGetSelectedStupidSwing = !checkBoxWhyIsThereNoGetSelectedStupidSwing); - - textfieldDirectoryPath = new JTextField(); - textfieldDirectoryPath - .setText(lastSelectedDirectory == null ? "" : lastSelectedDirectory.toAbsolutePath().toString()); - - labelDirectoryDescription = new JLabel(Localization.lang("Select a directory where the search shall start.")); - labelFileTypesDescription = new JLabel(Localization.lang("Select file type:")); - labelFilesDescription = new JLabel(Localization.lang("These files are not linked in the active library.")); - labelEntryTypeDescription = new JLabel(Localization.lang("Entry type to be created:")); - labelSearchingDirectoryInfo = new JLabel(Localization.lang("Searching file system...")); - labelSearchingDirectoryInfo.setHorizontalAlignment(SwingConstants.CENTER); - labelSearchingDirectoryInfo.setVisible(false); - labelImportingInfo = new JLabel(Localization.lang("Importing into Library...")); - labelImportingInfo.setHorizontalAlignment(SwingConstants.CENTER); - labelImportingInfo.setVisible(false); - labelExportingInfo = new JLabel(Localization.lang("Exporting into file...")); - labelExportingInfo.setHorizontalAlignment(SwingConstants.CENTER); - labelExportingInfo.setVisible(false); - - tree = new JTree(); - - scrollpaneTree = new JScrollPane(tree); - scrollpaneTree.setWheelScrollingEnabled(true); - - progressBarSearching = new JProgressBar(); - progressBarSearching.setIndeterminate(true); - progressBarSearching.setVisible(false); - progressBarSearching.setStringPainted(true); - - progressBarImporting = new JProgressBar(); - progressBarImporting.setIndeterminate(false); - progressBarImporting.setVisible(false); - progressBarImporting.setStringPainted(true); - - } - - /** - * Initializes the layout for the visible components in this menu. A - * {@link GridBagLayout} is used. - */ - private void initLayout() { - - GridBagLayout gbl = new GridBagLayout(); - - panelDirectory.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - Localization.lang("Select directory"))); - panelFiles.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - Localization.lang("Select files"))); - panelEntryTypesSelection.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - Localization.lang("BibTeX entry creation"))); - - Insets basicInsets = new Insets(6, 6, 6, 6); - Insets smallInsets = new Insets(3, 2, 3, 1); - Insets noInsets = new Insets(0, 0, 0, 0); - - // x, y, w, h, wx,wy,ix,iy - FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, buttonScan, GridBagConstraints.HORIZONTAL, - GridBagConstraints.EAST, noInsets, 0, 1, 1, 1, 1, 1, 40, 10); - FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, labelSearchingDirectoryInfo, - GridBagConstraints.HORIZONTAL, GridBagConstraints.EAST, noInsets, 0, 2, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, progressBarSearching, GridBagConstraints.HORIZONTAL, - GridBagConstraints.EAST, noInsets, 0, 3, 1, 1, 0, 0, 0, 0); - - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelDirectoryDescription, null, - GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 3, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, textfieldDirectoryPath, GridBagConstraints.HORIZONTAL, - null, basicInsets, 0, 1, 2, 1, 1, 1, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, buttonBrowse, GridBagConstraints.HORIZONTAL, - GridBagConstraints.EAST, basicInsets, 2, 1, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelFileTypesDescription, GridBagConstraints.NONE, - GridBagConstraints.WEST, new Insets(18, 6, 18, 3), 0, 3, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, comboBoxFileTypeSelection, - GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, new Insets(18, 3, 18, 6), 1, 3, 1, 1, 1, 0, 0, - 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, panelSearchArea, GridBagConstraints.HORIZONTAL, - GridBagConstraints.EAST, new Insets(18, 6, 18, 6), 2, 3, 1, 1, 0, 0, 0, 0); - - FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, labelFilesDescription, GridBagConstraints.HORIZONTAL, - GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, scrollpaneTree, GridBagConstraints.BOTH, - GridBagConstraints.CENTER, basicInsets, 0, 1, 1, 1, 1, 1, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, panelOptions, GridBagConstraints.NONE, - GridBagConstraints.NORTHEAST, basicInsets, 1, 1, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionSelectAll, GridBagConstraints.HORIZONTAL, - GridBagConstraints.NORTH, noInsets, 0, 0, 1, 1, 1, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionDeselectAll, GridBagConstraints.HORIZONTAL, - GridBagConstraints.NORTH, noInsets, 0, 1, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionExpandAll, GridBagConstraints.HORIZONTAL, - GridBagConstraints.NORTH, new Insets(6, 0, 0, 0), 0, 2, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionCollapseAll, GridBagConstraints.HORIZONTAL, - GridBagConstraints.NORTH, noInsets, 0, 3, 1, 1, 0, 0, 0, 0); - - FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, labelEntryTypeDescription, - GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, comboBoxEntryTypeSelection, - GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 1, 0, 1, 1, 1, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, checkboxCreateKeywords, - GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, basicInsets, 0, 1, 2, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, labelImportingInfo, GridBagConstraints.HORIZONTAL, - GridBagConstraints.CENTER, new Insets(6, 6, 0, 6), 0, 1, 1, 1, 1, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, labelExportingInfo, GridBagConstraints.HORIZONTAL, - GridBagConstraints.CENTER, new Insets(6, 6, 0, 6), 0, 1, 1, 1, 1, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, progressBarImporting, GridBagConstraints.HORIZONTAL, - GridBagConstraints.CENTER, new Insets(0, 6, 6, 6), 0, 2, 1, 1, 1, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, panelButtons, panelImportArea, GridBagConstraints.NONE, - GridBagConstraints.EAST, smallInsets, 1, 0, 1, 1, 0, 0, 0, 0); - - FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelDirectory, GridBagConstraints.HORIZONTAL, - GridBagConstraints.CENTER, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelFiles, GridBagConstraints.BOTH, - GridBagConstraints.NORTHWEST, new Insets(12, 6, 2, 2), 0, 1, 1, 1, 1, 1, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelEntryTypesSelection, - GridBagConstraints.HORIZONTAL, GridBagConstraints.SOUTHWEST, new Insets(12, 6, 2, 2), 0, 2, 1, 1, 0, 0, - 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelButtons, GridBagConstraints.HORIZONTAL, - GridBagConstraints.CENTER, new Insets(10, 6, 10, 6), 0, 3, 1, 1, 0, 0, 0, 0); - - ButtonBarBuilder bb = new ButtonBarBuilder(); - bb.addGlue(); - bb.addButton(buttonExport); - bb.addButton(buttonApply); - bb.addButton(buttonClose); - bb.addGlue(); - - bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - panelImportArea.add(bb.getPanel(), GridBagConstraints.NONE); - pack(); - - } - - /** - * Adds a component to a container, using the specified gridbag-layout and - * the supplied parameters.
    - *
    - * This method is simply used to ged rid of thousands of lines of code, - * which inevitably rise when layouts such as the gridbag-layout is being - * used. - * - * @param layout - * The layout to be used. - * @param container - * The {@link Container}, to which the component will be added. - * @param component - * An AWT {@link Component}, that will be added to the container. - * @param fill - * A constant describing the fill behaviour (see - * {@link GridBagConstraints}). Can be null, if no - * filling wants to be specified. - * @param anchor - * A constant describing the anchor of the element in its parent - * container (see {@link GridBagConstraints}). Can be - * null, if no specification is needed. - * @param gridX - * The relative grid-X coordinate. - * @param gridY - * The relative grid-Y coordinate. - * @param width - * The relative width of the component. - * @param height - * The relative height of the component. - * @param weightX - * A value for the horizontal weight. - * @param weightY - * A value for the vertical weight. - * @param insets - * Insets of the component. Can be null. - */ - private static void addComponent(GridBagLayout layout, Container container, Component component, Integer fill, - Integer anchor, Insets insets, int gridX, int gridY, int width, int height, double weightX, double weightY, - int ipadX, int ipadY) { - container.setLayout(layout); - GridBagConstraints constraints = new GridBagConstraints(); - constraints.gridx = gridX; - constraints.gridy = gridY; - constraints.gridwidth = width; - constraints.gridheight = height; - constraints.weightx = weightX; - constraints.weighty = weightY; - constraints.ipadx = ipadX; - constraints.ipady = ipadY; - if (fill != null) { - constraints.fill = fill; - } - if (insets != null) { - constraints.insets = insets; - } - if (anchor != null) { - constraints.anchor = anchor; - } - layout.setConstraints(component, constraints); - container.add(component); - } - - /** - * Creates the tree view, that holds the data structure.
    - *
    - * Initially, the root node is not visible, so that the tree appears empty at the beginning. - */ - private void createTree() { - - /** - * Mouse listener to listen for mouse events on the tree.
    - * This will mark the selected tree entry as "selected" or "unselected", - * which will cause this nodes checkbox to appear as either "checked" or - * "unchecked". - */ - treeMouseListener = new MouseAdapter() { - - @Override - public void mousePressed(MouseEvent e) { - int x = e.getX(); - int y = e.getY(); - - int row = tree.getRowForLocation(x, y); - - TreePath path = tree.getPathForRow(row); - if (path != null) { - CheckableTreeNode node = (CheckableTreeNode) path.getLastPathComponent(); - if (e.getClickCount() == 2) { - Object userObject = node.getUserObject(); - if ((userObject instanceof FileNodeWrapper) && node.isLeaf()) { - FileNodeWrapper fnw = (FileNodeWrapper) userObject; - try { - JabRefDesktop.openExternalViewer( - JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext(), - fnw.file.getAbsolutePath(), FieldName.PDF); - } catch (IOException e1) { - LOGGER.info("Error opening file", e1); - } - } - } else { - node.check(); - tree.invalidate(); - tree.repaint(); - } - } - } - - }; - - CheckableTreeNode startNode = new CheckableTreeNode("ROOT"); - DefaultTreeModel model = new DefaultTreeModel(startNode); - - tree.setModel(model); - tree.setRootVisible(false); - - DefaultTreeCellRenderer renderer = new CheckboxTreeCellRenderer(); - tree.setCellRenderer(renderer); - - tree.addMouseListener(treeMouseListener); - - } - - /** - * Initialises the combobox that contains the available file types which - * bibtex entries can be created of. - */ - private void createFileTypesCombobox() { - - List fileFilterList = creatorManager.getFileFilterList(); - - comboBoxFileTypeSelection = new JComboBox<>(fileFilterList.toArray(new FileFilter[fileFilterList.size()])); - - comboBoxFileTypeSelection.setRenderer(new DefaultListCellRenderer() { - - /* (non-Javadoc) - * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean) - */ - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, - boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, - cellHasFocus); - if (value instanceof EntryFromFileCreator) { - EntryFromFileCreator creator = (EntryFromFileCreator) value; - if (creator.getExternalFileType() != null) { - label.setIcon(creator.getExternalFileType().getIcon().getSmallIcon()); - } - } - return label; - } - }); - - } - - /** - * Creates the ComboBox-View for the Listbox that holds the Bibtex entry - * types. - */ - private void createEntryTypesCombobox() { - - Iterator iterator = EntryTypes - .getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()).iterator(); - List list = new ArrayList<>(); - list.add( - new BibtexEntryTypeWrapper(null)); - while (iterator.hasNext()) { - list.add(new BibtexEntryTypeWrapper(iterator.next())); - } - comboBoxEntryTypeSelection = new JComboBox<>(list.toArray(new BibtexEntryTypeWrapper[list.size()])); - } - - /** - * Wrapper for displaying the Type {@link BibtexEntryType} in a Combobox. - */ - private static class BibtexEntryTypeWrapper { - - private final EntryType entryType; - - BibtexEntryTypeWrapper(EntryType bibtexType) { - this.entryType = bibtexType; - } - - @Override - public String toString() { - if (entryType == null) { - return Localization.lang(""); - } - return entryType.getName(); - } - - public EntryType getEntryType() { - return entryType; - } - } - - public static class CheckableTreeNode extends DefaultMutableTreeNode { - - private boolean isSelected; - private final JCheckBox checkbox; - - public CheckableTreeNode(Object userObject) { - super(userObject); - checkbox = new JCheckBox(); - } - - /** - * @return the checkbox - */ - public JCheckBox getCheckbox() { - return checkbox; - } - - public void check() { - setSelected(!isSelected); - } - - public void setSelected(boolean bSelected) { - isSelected = bSelected; - Enumeration tmpChildren = this.children(); - for (CheckableTreeNode child : Collections.list(tmpChildren)) { - child.setSelected(bSelected); - } - - } - - public boolean isSelected() { - return isSelected; - } - - } - - private static class CheckboxTreeCellRenderer extends DefaultTreeCellRenderer { - - private final FileSystemView fsv = FileSystemView.getFileSystemView(); - - @Override - public Component getTreeCellRendererComponent(final JTree tree, Object value, boolean sel, boolean expanded, - boolean leaf, int row, boolean hasFocus) { - - Component nodeComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, - hasFocus); - CheckableTreeNode node = (CheckableTreeNode) value; - - FileNodeWrapper userObject = (FileNodeWrapper) node.getUserObject(); - - JPanel newPanel = new JPanel(); - - JCheckBox checkbox = node.getCheckbox(); - checkbox.setSelected(node.isSelected()); - - try { - setIcon(fsv.getSystemIcon(userObject.file)); - } catch (Exception ignored) { - // Ignored - } - - newPanel.setBackground(nodeComponent.getBackground()); - checkbox.setBackground(nodeComponent.getBackground()); - - GridBagLayout gbl = new GridBagLayout(); - FindUnlinkedFilesDialog.addComponent(gbl, newPanel, checkbox, null, null, null, 0, 0, 1, 1, 0, 0, 0, 0); - FindUnlinkedFilesDialog.addComponent(gbl, newPanel, nodeComponent, GridBagConstraints.HORIZONTAL, null, - new Insets(1, 2, 0, 0), 1, 0, 1, 1, 1, 0, 0, 0); - - if (userObject.fileCount > 0) { - JLabel label = new JLabel( - "(" + userObject.fileCount + " file" + (userObject.fileCount > 1 ? "s" : "") + ")"); - FindUnlinkedFilesDialog.addComponent(gbl, newPanel, label, null, null, new Insets(1, 2, 0, 0), 2, 0, 1, - 1, 0, 0, 0, 0); - } - return newPanel; - } - - } - - public static class FileNodeWrapper { - - public final File file; - public final int fileCount; - - public FileNodeWrapper(File aFile) { - this(aFile, 0); - } - - /** - * @param aDirectory - * @param fileCount - */ - public FileNodeWrapper(File aDirectory, int fileCount) { - this.file = aDirectory; - this.fileCount = fileCount; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return file.getName(); - } - } - -} diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java index 4803df84fa1..2531456c6f0 100644 --- a/src/main/java/org/jabref/gui/JabRefFrame.java +++ b/src/main/java/org/jabref/gui/JabRefFrame.java @@ -62,7 +62,6 @@ import org.jabref.gui.actions.DatabasePropertiesAction; import org.jabref.gui.actions.EditExternalFileTypesAction; import org.jabref.gui.actions.ErrorConsoleAction; -import org.jabref.gui.actions.FindUnlinkedFilesAction; import org.jabref.gui.actions.IntegrityCheckAction; import org.jabref.gui.actions.LookupIdentifierAction; import org.jabref.gui.actions.ManageCustomExportsAction; @@ -89,6 +88,7 @@ import org.jabref.gui.exporter.ExportToClipboardAction; import org.jabref.gui.exporter.SaveAllAction; import org.jabref.gui.exporter.SaveDatabaseAction; +import org.jabref.gui.externalfiles.FindUnlinkedFilesAction; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.help.AboutAction; import org.jabref.gui.help.HelpAction; diff --git a/src/main/java/org/jabref/gui/actions/FindUnlinkedFilesAction.java b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesAction.java similarity index 77% rename from src/main/java/org/jabref/gui/actions/FindUnlinkedFilesAction.java rename to src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesAction.java index d1a193857eb..5684869d9ff 100644 --- a/src/main/java/org/jabref/gui/actions/FindUnlinkedFilesAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesAction.java @@ -1,7 +1,7 @@ -package org.jabref.gui.actions; +package org.jabref.gui.externalfiles; -import org.jabref.gui.FindUnlinkedFilesDialog; import org.jabref.gui.JabRefFrame; +import org.jabref.gui.actions.SimpleCommand; public class FindUnlinkedFilesAction extends SimpleCommand { @@ -14,7 +14,7 @@ public FindUnlinkedFilesAction(JabRefFrame jabRefFrame) { @Override public void execute() { FindUnlinkedFilesDialog dlg = new FindUnlinkedFilesDialog(jabRefFrame); - dlg.setVisible(true); + dlg.showAndWait(); } } diff --git a/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java new file mode 100644 index 00000000000..5a8b0e8c5a8 --- /dev/null +++ b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java @@ -0,0 +1,440 @@ +package org.jabref.gui.externalfiles; + +import java.io.BufferedWriter; +import java.io.FileFilter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import javafx.collections.FXCollections; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.control.Button; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.CheckBox; +import javafx.scene.control.CheckBoxTreeItem; +import javafx.scene.control.ComboBox; +import javafx.scene.control.Label; +import javafx.scene.control.ProgressIndicator; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.control.Tooltip; +import javafx.scene.control.TreeItem; +import javafx.scene.control.TreeView; +import javafx.scene.layout.BorderPane; +import javafx.scene.layout.HBox; +import javafx.scene.layout.Priority; +import javafx.scene.layout.StackPane; +import javafx.scene.layout.VBox; + +import org.jabref.Globals; +import org.jabref.gui.DialogService; +import org.jabref.gui.JabRefFrame; +import org.jabref.gui.externalfiletype.ExternalFileTypes; +import org.jabref.gui.importer.EntryFromFileCreator; +import org.jabref.gui.importer.EntryFromFileCreatorManager; +import org.jabref.gui.importer.UnlinkedFilesCrawler; +import org.jabref.gui.util.BackgroundTask; +import org.jabref.gui.util.BaseDialog; +import org.jabref.gui.util.DirectoryDialogConfiguration; +import org.jabref.gui.util.FileDialogConfiguration; +import org.jabref.gui.util.ViewModelListCellFactory; +import org.jabref.gui.util.ViewModelTreeCellFactory; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.EntryTypes; +import org.jabref.model.database.BibDatabaseContext; +import org.jabref.model.entry.EntryType; +import org.jabref.preferences.JabRefPreferences; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GUI Dialog for the feature "Find unlinked files". + */ +public class FindUnlinkedFilesDialog extends BaseDialog { + + private static final Logger LOGGER = LoggerFactory.getLogger(FindUnlinkedFilesDialog.class); + private final JabRefFrame frame; + private final BibDatabaseContext databaseContext; + private final EntryFromFileCreatorManager creatorManager; + private final JabRefPreferences preferences = Globals.prefs; + private final DialogService dialogService; + private Button buttonScan; + private Button buttonExport; + private Button buttonApply; + private CheckBox checkboxCreateKeywords; + private TextField textfieldDirectoryPath; + private TreeView tree; + private ComboBox comboBoxFileTypeSelection; + private ComboBox comboBoxEntryTypeSelection; + private VBox panelSearchProgress; + private BackgroundTask findUnlinkedFilesTask; + + public FindUnlinkedFilesDialog(JabRefFrame frame) { + super(); + this.setTitle(Localization.lang("Find unlinked files")); + this.frame = frame; + dialogService = frame.getDialogService(); + + databaseContext = frame.getCurrentBasePanel().getBibDatabaseContext(); + creatorManager = new EntryFromFileCreatorManager(ExternalFileTypes.getInstance()); + + initialize(); + } + + /** + * Initializes the components, the layout, the data structure and the actions in this dialog. + */ + private void initialize() { + Button buttonBrowse = new Button(Localization.lang("Browse")); + buttonBrowse.setTooltip(new Tooltip(Localization.lang("Opens the file browser."))); + buttonBrowse.getStyleClass().add("text-button"); + buttonBrowse.setOnAction(e -> { + DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder() + .withInitialDirectory(preferences.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + dialogService.showDirectorySelectionDialog(directoryDialogConfiguration) + .ifPresent(selectedDirectory -> { + textfieldDirectoryPath.setText(selectedDirectory.toAbsolutePath().toString()); + preferences.put(JabRefPreferences.WORKING_DIRECTORY, selectedDirectory.toAbsolutePath().toString()); + }); + }); + + buttonScan = new Button(Localization.lang("Scan directory")); + buttonScan.setTooltip(new Tooltip((Localization.lang("Searches the selected directory for unlinked files.")))); + buttonScan.setOnAction(e -> startSearch()); + buttonScan.setDefaultButton(true); + buttonScan.setPadding(new Insets(5, 0, 0, 0)); + + buttonExport = new Button(Localization.lang("Export selected entries")); + buttonExport.setTooltip(new Tooltip(Localization.lang("Export to text file."))); + buttonExport.getStyleClass().add("text-button"); + buttonExport.setDisable(true); + buttonExport.setOnAction(e -> startExport()); + + ButtonType buttonTypeImport = new ButtonType(Localization.lang("Import"), ButtonBar.ButtonData.OK_DONE); + getDialogPane().getButtonTypes().setAll( + buttonTypeImport, + ButtonType.CANCEL + ); + buttonApply = (Button) getDialogPane().lookupButton(buttonTypeImport); + buttonApply.setTooltip(new Tooltip((Localization.lang("Starts the import of BibTeX entries.")))); + buttonApply.setDisable(true); + + /* Actions for the TreeView */ + Button buttonOptionSelectAll = new Button(); + buttonOptionSelectAll.setText(Localization.lang("Select all")); + buttonOptionSelectAll.getStyleClass().add("text-button"); + buttonOptionSelectAll.setOnAction(event -> { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + // Need to toggle a twice to make sure everything is selected + root.setSelected(true); + root.setSelected(false); + root.setSelected(true); + }); + Button buttonOptionDeselectAll = new Button(); + buttonOptionDeselectAll.setText(Localization.lang("Unselect all")); + buttonOptionDeselectAll.getStyleClass().add("text-button"); + buttonOptionDeselectAll.setOnAction(event -> { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + // Need to toggle a twice to make sure nothing is selected + root.setSelected(false); + root.setSelected(true); + root.setSelected(false); + }); + Button buttonOptionExpandAll = new Button(); + buttonOptionExpandAll.setText(Localization.lang("Expand all")); + buttonOptionExpandAll.getStyleClass().add("text-button"); + buttonOptionExpandAll.setOnAction(event -> { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + expandTree(root, true); + }); + Button buttonOptionCollapseAll = new Button(); + buttonOptionCollapseAll.setText(Localization.lang("Collapse all")); + buttonOptionCollapseAll.getStyleClass().add("text-button"); + buttonOptionCollapseAll.setOnAction(event -> { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + expandTree(root, false); + root.setExpanded(true); + }); + + checkboxCreateKeywords = new CheckBox(Localization.lang("Create directory based keywords")); + checkboxCreateKeywords.setTooltip(new Tooltip((Localization.lang("Creates keywords in created entrys with directory pathnames")))); + + textfieldDirectoryPath = new TextField(); + Path initialPath = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences()) + .orElse(preferences.getWorkingDir()); + textfieldDirectoryPath.setText(initialPath.toAbsolutePath().toString()); + + Label labelDirectoryDescription = new Label(Localization.lang("Select a directory where the search shall start.")); + Label labelFileTypesDescription = new Label(Localization.lang("Select file type:")); + Label labelFilesDescription = new Label(Localization.lang("These files are not linked in the active library.")); + Label labelEntryTypeDescription = new Label(Localization.lang("Entry type to be created:")); + Label labelSearchingDirectoryInfo = new Label(Localization.lang("Searching file system...")); + + tree = new TreeView<>(); + tree.setPrefWidth(Double.POSITIVE_INFINITY); + + ScrollPane scrollPaneTree = new ScrollPane(tree); + scrollPaneTree.setFitToWidth(true); + + ProgressIndicator progressBarSearching = new ProgressIndicator(); + progressBarSearching.setMaxSize(50, 50); + + setResultConverter(buttonPressed -> { + if (buttonPressed == buttonTypeImport) { + startImport(); + } else { + if (findUnlinkedFilesTask != null) { + findUnlinkedFilesTask.cancel(); + } + } + return null; + }); + + new ViewModelTreeCellFactory() + .withText(node -> { + if (Files.isRegularFile(node.path)) { + // File + return node.path.getFileName().toString(); + } else { + // Directory + return node.path.getFileName() + " (" + node.fileCount + " file" + (node.fileCount > 1 ? "s" : "") + ")"; + } + }) + .install(tree); + List fileFilterList = creatorManager.getFileFilterList(); + comboBoxFileTypeSelection = new ComboBox<>(FXCollections.observableArrayList(fileFilterList)); + comboBoxFileTypeSelection.getSelectionModel().selectFirst(); + new ViewModelListCellFactory() + .withText(Object::toString) + .withIcon(fileFilter -> { + if (fileFilter instanceof EntryFromFileCreator) { + EntryFromFileCreator creator = (EntryFromFileCreator) fileFilter; + if (creator.getExternalFileType() != null) { + return creator.getExternalFileType().getIcon(); + } + } + return null; + }) + .install(comboBoxFileTypeSelection); + + Collection entryTypes = EntryTypes.getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()); + comboBoxEntryTypeSelection = new ComboBox<>(FXCollections.observableArrayList(entryTypes)); + comboBoxEntryTypeSelection.getSelectionModel().selectFirst(); + new ViewModelListCellFactory() + .withText(EntryType::getName) + .install(comboBoxEntryTypeSelection); + + panelSearchProgress = new VBox(5, labelSearchingDirectoryInfo, progressBarSearching); + panelSearchProgress.toFront(); + panelSearchProgress.setVisible(false); + +// panelDirectory.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), +// Localization.lang("Select directory"))); +// panelFiles.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), +// Localization.lang("Select files"))); +// panelEntryTypesSelection.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), +// Localization.lang("BibTeX entry creation"))); + + VBox panelDirectory = new VBox(5); + panelDirectory.getChildren().setAll( + labelDirectoryDescription, + new HBox(10, textfieldDirectoryPath, buttonBrowse), + new HBox(15, labelFileTypesDescription, comboBoxFileTypeSelection), + buttonScan + ); + HBox.setHgrow(textfieldDirectoryPath, Priority.ALWAYS); + + StackPane stackPaneTree = new StackPane(scrollPaneTree, panelSearchProgress); + StackPane.setAlignment(panelSearchProgress, Pos.CENTER); + BorderPane panelFiles = new BorderPane(); + panelFiles.setTop(labelFilesDescription); + panelFiles.setCenter(stackPaneTree); + panelFiles.setBottom(new HBox(5, buttonOptionSelectAll, buttonOptionDeselectAll, buttonOptionExpandAll, buttonOptionCollapseAll, buttonExport)); + + VBox panelEntryTypesSelection = new VBox(5); + panelEntryTypesSelection.getChildren().setAll( + new HBox(15, labelEntryTypeDescription, comboBoxEntryTypeSelection), + checkboxCreateKeywords + ); + + VBox container = new VBox(20); + container.getChildren().addAll( + panelDirectory, + panelFiles, + panelEntryTypesSelection + ); + container.setPrefWidth(600); + getDialogPane().setContent(container); + } + + /** + * Expands or collapses the specified tree according to the expand-parameter. + */ + private void expandTree(TreeItem item, boolean expand) { + if (item != null && !item.isLeaf()) { + item.setExpanded(expand); + for (TreeItem child : item.getChildren()) { + expandTree(child, expand); + } + } + } + + /** + * Starts the search of unlinked files according chosen directory and the file type selection. The search will + * process in a separate thread and a progress indicator will be displayed. + */ + private void startSearch() { + Path directory = getSearchDirectory(); + FileFilter selectedFileFilter = comboBoxFileTypeSelection.getValue(); + + findUnlinkedFilesTask = new UnlinkedFilesCrawler(directory, selectedFileFilter, databaseContext) + .onRunning(() -> { + panelSearchProgress.setVisible(true); + buttonScan.setDisable(true); + tree.setRoot(null); + }) + .onFinished(() -> { + panelSearchProgress.setVisible(false); + buttonScan.setDisable(false); + }) + .onSuccess(root -> { + tree.setRoot(root); + root.setSelected(true); + root.setExpanded(true); + + buttonApply.setDisable(false); + buttonExport.setDisable(false); + buttonScan.setDefaultButton(false); + }); + findUnlinkedFilesTask.executeWith(Globals.TASK_EXECUTOR); + } + + private Path getSearchDirectory() { + Path directory = Paths.get(textfieldDirectoryPath.getText()); + if (Files.notExists(directory)) { + directory = Paths.get(System.getProperty("user.dir")); + textfieldDirectoryPath.setText(directory.toAbsolutePath().toString()); + } + if (!Files.isDirectory(directory)) { + directory = directory.getParent(); + textfieldDirectoryPath.setText(directory.toAbsolutePath().toString()); + } + return directory; + } + + /** + * This will start the import of all file of all selected nodes in the file tree view. + */ + private void startImport() { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + final List fileList = getFileListFromNode(root); + + if (fileList.isEmpty()) { + return; + } + + final EntryType entryType = comboBoxEntryTypeSelection.getValue(); + + List errors = creatorManager.addEntriesFromFiles( + fileList, + databaseContext.getDatabase(), + frame.getCurrentBasePanel(), + entryType, + checkboxCreateKeywords.isSelected()); + + if (!errors.isEmpty()) { + String message; + if (errors.size() == 1) { + message = Localization.lang("There was one file that could not be imported."); + } else { + message = Localization.lang("There were %0 files which could not be imported.", + Integer.toString(errors.size())); + } + dialogService.showWarningDialogAndWait( + Localization.lang("Warning"), + Localization.lang("The import finished with warnings:") + "\n" + message); + } + } + + /** + * This starts the export of all files of all selected nodes in the file tree view. + */ + private void startExport() { + CheckBoxTreeItem root = (CheckBoxTreeItem) tree.getRoot(); + + final List fileList = getFileListFromNode(root); + if (fileList.isEmpty()) { + return; + } + + buttonExport.setVisible(false); + buttonApply.setVisible(false); + + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .withInitialDirectory(preferences.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + Optional exportPath = dialogService.showFileSaveDialog(fileDialogConfiguration); + + if (!exportPath.isPresent()) { + buttonExport.setVisible(true); + buttonApply.setVisible(true); + return; + } + + try (BufferedWriter writer = + Files.newBufferedWriter(exportPath.get(), StandardCharsets.UTF_8, + StandardOpenOption.CREATE)) { + for (Path file : fileList) { + writer.write(file.toString() + "\n"); + } + } catch (IOException e) { + LOGGER.warn("IO Error.", e); + } + + buttonExport.setVisible(true); + buttonApply.setVisible(true); + } + + /** + * Creates a list of all files (leaf nodes in the tree structure), which have been selected. + * + * @param node The root node representing a tree structure. + */ + private List getFileListFromNode(CheckBoxTreeItem node) { + List filesList = new ArrayList<>(); + for (TreeItem childNode : node.getChildren()) { + CheckBoxTreeItem child = (CheckBoxTreeItem) childNode; + if (child.isLeaf() && child.isSelected()) { + Path nodeFile = child.getValue().path; + if ((nodeFile != null) && Files.isRegularFile(nodeFile)) { + filesList.add(nodeFile); + } + } + } + return filesList; + } + + public static class FileNodeWrapper { + + public final Path path; + public final int fileCount; + + public FileNodeWrapper(Path path) { + this(path, 0); + } + + public FileNodeWrapper(Path path, int fileCount) { + this.path = path; + this.fileCount = fileCount; + } + } +} diff --git a/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java b/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java index c1a0d2d0a3d..79b1d93f582 100644 --- a/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java +++ b/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java @@ -2,14 +2,13 @@ import java.io.File; import java.io.FileFilter; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; -import java.util.LinkedList; import java.util.List; import java.util.Optional; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import javax.swing.undo.CompoundEdit; import org.jabref.gui.BasePanel; @@ -67,22 +66,21 @@ private boolean hasSpecialisedCreatorForExternalFileType( } /** - * Returns a EntryFromFileCreator object that is capable of creating a - * BibEntry for the given File. + * Returns a {@link EntryFromFileCreator} object that is capable of creating a entry for the given file. * - * @param file the pdf file - * @return null if there is no EntryFromFileCreator for this File. + * @param file the external file + * @return an empty optional if there is no EntryFromFileCreator for this file. */ - public EntryFromFileCreator getEntryCreator(File file) { - if ((file == null) || !file.exists()) { - return null; + public Optional getEntryCreator(Path file) { + if (!Files.exists(file)) { + return Optional.empty(); } for (EntryFromFileCreator creator : entryCreators) { - if (creator.accept(file)) { - return creator; + if (creator.accept(file.toFile())) { + return Optional.of(creator); } } - return null; + return Optional.empty(); } /** @@ -93,43 +91,32 @@ public EntryFromFileCreator getEntryCreator(File file) { * @param entryType * @return List of unexpected import event messages including failures. */ - public List addEntrysFromFiles(List files, - BibDatabase database, EntryType entryType, - boolean generateKeywordsFromPathToFile) { - List importGUIMessages = new LinkedList<>(); - addEntriesFromFiles(files, database, null, entryType, - generateKeywordsFromPathToFile, null, importGUIMessages); - return importGUIMessages; + public List addEntrysFromFiles(List files, + BibDatabase database, EntryType entryType, + boolean generateKeywordsFromPathToFile) { + return addEntriesFromFiles(files, database, null, entryType, generateKeywordsFromPathToFile); } /** * Tries to add a entry for each file in the List. * - * @param files - * @param database - * @param panel - * @param entryType - * @param generateKeywordsFromPathToFile - * @param changeListener - * @param importGUIMessages list of unexpected import event - Messages including - * failures - * @return Returns The number of entries added + * @return Returns a list of unexpected failures while importing */ - public int addEntriesFromFiles(List files, - BibDatabase database, BasePanel panel, EntryType entryType, - boolean generateKeywordsFromPathToFile, - ChangeListener changeListener, List importGUIMessages) { + public List addEntriesFromFiles(List files, + BibDatabase database, BasePanel panel, EntryType entryType, + boolean generateKeywordsFromPathToFile) { + List importGUIMessages = new ArrayList<>(); int count = 0; CompoundEdit ce = new CompoundEdit(); - for (File f : files) { - EntryFromFileCreator creator = getEntryCreator(f); - if (creator == null) { - importGUIMessages.add("Problem importing " + f.getPath() + ": Unknown filetype."); + for (Path f : files) { + Optional creator = getEntryCreator(f); + if (!creator.isPresent()) { + importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Unknown filetype."); } else { - Optional entry = creator.createEntry(f, generateKeywordsFromPathToFile); + Optional entry = creator.get().createEntry(f.toFile(), generateKeywordsFromPathToFile); if (!entry.isPresent()) { - importGUIMessages.add("Problem importing " + f.getPath() + ": Entry could not be created."); + importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Entry could not be created."); continue; } if (entryType != null) { @@ -147,7 +134,7 @@ public int addEntriesFromFiles(List files, // Work around SIDE EFFECT of creator.createEntry. The EntryFromPDFCreator also creates the entry in the table // Therefore, we only insert the entry if it is not already present if (database.insertEntry(entry.get())) { - importGUIMessages.add("Problem importing " + f.getPath() + ": Insert into BibDatabase failed."); + importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Insert into BibDatabase failed."); } else { count++; if (panel != null) { @@ -156,17 +143,13 @@ public int addEntriesFromFiles(List files, } } } - - if (changeListener != null) { - changeListener.stateChanged(new ChangeEvent(this)); - } } if ((count > 0) && (panel != null)) { ce.end(); panel.getUndoManager().addEdit(ce); } - return count; + return importGUIMessages; } @@ -211,12 +194,9 @@ public String toString() { * @return A List of all known possible file filters. */ public List getFileFilterList() { - List filters = new ArrayList<>(); filters.add(getFileFilter()); - for (FileFilter creator : entryCreators) { - filters.add(creator); - } + filters.addAll(entryCreators); return filters; } } diff --git a/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java b/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java index f3b456fa937..77e57a12ab9 100644 --- a/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java +++ b/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java @@ -2,38 +2,39 @@ import java.io.File; import java.io.FileFilter; +import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; +import javafx.scene.control.CheckBoxTreeItem; -import org.jabref.gui.FindUnlinkedFilesDialog.CheckableTreeNode; -import org.jabref.gui.FindUnlinkedFilesDialog.FileNodeWrapper; +import org.jabref.gui.externalfiles.FindUnlinkedFilesDialog.FileNodeWrapper; +import org.jabref.gui.util.BackgroundTask; +import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; /** * Util class for searching files on the file system which are not linked to a provided {@link BibDatabase}. */ -public class UnlinkedFilesCrawler { - /** - * File filter, that accepts directories only. - */ - private static final FileFilter DIRECTORY_FILTER = pathname -> (pathname != null) && pathname.isDirectory(); +public class UnlinkedFilesCrawler extends BackgroundTask> { + private final Path directory; + private final FileFilter fileFilter; + private int counter; private final BibDatabaseContext databaseContext; - - public UnlinkedFilesCrawler(BibDatabaseContext databaseContext) { + public UnlinkedFilesCrawler(Path directory, FileFilter fileFilter, BibDatabaseContext databaseContext) { + this.directory = directory; + this.fileFilter = fileFilter; this.databaseContext = databaseContext; } - public CheckableTreeNode searchDirectory(File directory, FileFilter filter) { - UnlinkedPDFFileFilter ff = new UnlinkedPDFFileFilter(filter, databaseContext); - return searchDirectory(directory, ff, new AtomicBoolean(true), null); + @Override + protected CheckBoxTreeItem call() throws Exception { + UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(fileFilter, databaseContext); + return searchDirectory(directory.toFile(), unlinkedPDFFileFilter); } /** @@ -43,7 +44,7 @@ public CheckableTreeNode searchDirectory(File directory, FileFilter filter) { * {@link EntryFromFileCreatorManager}, are taken into the resulting tree.
    *
    * The result will be a tree structure of nodes of the type - * {@link CheckableTreeNode}.
    + * {@link CheckBoxTreeItem}.
    *
    * The user objects that are attached to the nodes is the * {@link FileNodeWrapper}, which wraps the {@link File}-Object.
    @@ -53,11 +54,7 @@ public CheckableTreeNode searchDirectory(File directory, FileFilter filter) { * the recursion running. When the states value changes, the method will * resolve its recursion and return what it has saved so far. */ - public CheckableTreeNode searchDirectory(File directory, UnlinkedPDFFileFilter ff, AtomicBoolean state, ChangeListener changeListener) { - /* Cancellation of the search from outside! */ - if ((state == null) || !state.get()) { - return null; - } + private CheckBoxTreeItem searchDirectory(File directory, UnlinkedPDFFileFilter ff) { // Return null if the directory is not valid. if ((directory == null) || !directory.exists() || !directory.isDirectory()) { return null; @@ -70,11 +67,11 @@ public CheckableTreeNode searchDirectory(File directory, UnlinkedPDFFileFilter f } else { files = Arrays.asList(filesArray); } - CheckableTreeNode root = new CheckableTreeNode(null); + CheckBoxTreeItem root = new CheckBoxTreeItem<>(new FileNodeWrapper(directory.toPath(), 0)); int filesCount = 0; - filesArray = directory.listFiles(DIRECTORY_FILTER); + filesArray = directory.listFiles(pathname -> (pathname != null) && pathname.isDirectory()); List subDirectories; if (filesArray == null) { subDirectories = Collections.emptyList(); @@ -82,23 +79,30 @@ public CheckableTreeNode searchDirectory(File directory, UnlinkedPDFFileFilter f subDirectories = Arrays.asList(filesArray); } for (File subDirectory : subDirectories) { - CheckableTreeNode subRoot = searchDirectory(subDirectory, ff, state, changeListener); - if ((subRoot != null) && (subRoot.getChildCount() > 0)) { - filesCount += ((FileNodeWrapper) subRoot.getUserObject()).fileCount; - root.add(subRoot); + if (isCanceled()) { + return root; + } + + CheckBoxTreeItem subRoot = searchDirectory(subDirectory, ff); + if ((subRoot != null) && (!subRoot.getChildren().isEmpty())) { + filesCount += subRoot.getValue().fileCount; + root.getChildren().add(subRoot); } } - root.setUserObject(new FileNodeWrapper(directory, files.size() + filesCount)); + root.setValue(new FileNodeWrapper(directory.toPath(), files.size() + filesCount)); for (File file : files) { - root.add(new CheckableTreeNode(new FileNodeWrapper(file))); - if (changeListener != null) { - changeListener.stateChanged(new ChangeEvent(this)); + root.getChildren().add(new CheckBoxTreeItem<>(new FileNodeWrapper(file.toPath()))); + + counter++; + if (counter == 1) { + updateMessage(Localization.lang("One file found")); + } else { + updateMessage(Localization.lang("%0 files found", Integer.toString(counter))); } } return root; } - } diff --git a/src/main/java/org/jabref/gui/util/BackgroundTask.java b/src/main/java/org/jabref/gui/util/BackgroundTask.java index fbc2abb22e9..bab42164053 100644 --- a/src/main/java/org/jabref/gui/util/BackgroundTask.java +++ b/src/main/java/org/jabref/gui/util/BackgroundTask.java @@ -5,10 +5,14 @@ import java.util.function.Consumer; import java.util.function.Function; +import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; +import javafx.beans.property.SimpleStringProperty; +import javafx.beans.property.StringProperty; import javafx.concurrent.Task; import org.fxmisc.easybind.EasyBind; @@ -26,7 +30,9 @@ public abstract class BackgroundTask { private Consumer onSuccess; private Consumer onException; private Runnable onFinished; + private BooleanProperty isCanceled = new SimpleBooleanProperty(false); private ObjectProperty progress = new SimpleObjectProperty<>(new BackgroundProgress(0, 0)); + private StringProperty message = new SimpleStringProperty(""); private DoubleProperty workDonePercentage = new SimpleDoubleProperty(0); public BackgroundTask() { @@ -52,6 +58,37 @@ protected Void call() throws Exception { }; } + private static Consumer chain(Runnable first, Consumer second) { + if (first != null) { + if (second != null) { + return result -> { + first.run(); + second.accept(result); + }; + } else { + return result -> first.run(); + } + } else { + return second; + } + } + + public boolean isCanceled() { + return isCanceled.get(); + } + + public void cancel() { + this.isCanceled.set(true); + } + + public BooleanProperty isCanceledProperty() { + return isCanceled; + } + + public StringProperty messageProperty() { + return message; + } + public double getWorkDonePercentage() { return workDonePercentage.get(); } @@ -68,21 +105,6 @@ public ObjectProperty progressProperty() { return progress; } - private static Consumer chain(Runnable first, Consumer second) { - if (first != null) { - if (second != null) { - return result -> { - first.run(); - second.accept(result); - }; - } else { - return result -> first.run(); - } - } else { - return second; - } - } - /** * Sets the {@link Runnable} that is invoked after the task is started. */ @@ -197,6 +219,10 @@ protected void updateProgress(double workDone, double max) { updateProgress(new BackgroundProgress(workDone, max)); } + protected void updateMessage(String newMessage) { + message.setValue(newMessage); + } + class BackgroundProgress { private final double workDone; diff --git a/src/main/java/org/jabref/gui/util/DefaultTaskExecutor.java b/src/main/java/org/jabref/gui/util/DefaultTaskExecutor.java index bfed247a73f..fe7f2f64611 100644 --- a/src/main/java/org/jabref/gui/util/DefaultTaskExecutor.java +++ b/src/main/java/org/jabref/gui/util/DefaultTaskExecutor.java @@ -103,6 +103,12 @@ private Task getJavaFXTask(BackgroundTask task) { { EasyBind.subscribe(task.progressProperty(), progress -> updateProgress(progress.getWorkDone(), progress.getMax())); + EasyBind.subscribe(task.messageProperty(), this::updateMessage); + EasyBind.subscribe(task.isCanceledProperty(), cancelled -> { + if (cancelled) { + cancel(); + } + }); } @Override diff --git a/src/main/java/org/jabref/gui/util/ViewModelListCellFactory.java b/src/main/java/org/jabref/gui/util/ViewModelListCellFactory.java index 87295e0b7dd..983e4c4b29e 100644 --- a/src/main/java/org/jabref/gui/util/ViewModelListCellFactory.java +++ b/src/main/java/org/jabref/gui/util/ViewModelListCellFactory.java @@ -49,7 +49,14 @@ public ViewModelListCellFactory withGraphic(Callback toGraphic) { } public ViewModelListCellFactory withIcon(Callback toIcon) { - this.toGraphic = viewModel -> MaterialDesignIconFactory.get().createIcon(toIcon.call(viewModel)); + this.toGraphic = viewModel -> { + GlyphIcons icon = toIcon.call(viewModel); + if (icon != null) { + return MaterialDesignIconFactory.get().createIcon(icon); + } else { + return null; + } + }; return this; } diff --git a/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java b/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java new file mode 100644 index 00000000000..c4d01133406 --- /dev/null +++ b/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java @@ -0,0 +1,84 @@ +package org.jabref.gui.util; + +import javafx.beans.value.ObservableValue; +import javafx.event.EventHandler; +import javafx.scene.Node; +import javafx.scene.control.CheckBoxTreeItem; +import javafx.scene.control.TreeCell; +import javafx.scene.control.TreeItem; +import javafx.scene.control.TreeTableCell; +import javafx.scene.control.TreeView; +import javafx.scene.control.cell.CheckBoxTreeCell; +import javafx.scene.input.MouseEvent; +import javafx.util.Callback; +import javafx.util.StringConverter; + +import org.jabref.gui.icon.JabRefIcon; + +/** + * Constructs a {@link TreeTableCell} based on the view model of the row and a bunch of specified converter methods. + * + * @param view model + * @param cell value + */ +public class ViewModelTreeCellFactory implements Callback, TreeCell> { + + private Callback toText; + private Callback toGraphic; + private Callback> toOnMouseClickedEvent; + private Callback toTooltip; + + public ViewModelTreeCellFactory withText(Callback toText) { + this.toText = toText; + return this; + } + + public ViewModelTreeCellFactory withGraphic(Callback toGraphic) { + this.toGraphic = toGraphic; + return this; + } + + public ViewModelTreeCellFactory withIcon(Callback toIcon) { + this.toGraphic = viewModel -> toIcon.call(viewModel).getGraphicNode(); + return this; + } + + public ViewModelTreeCellFactory withTooltip(Callback toTooltip) { + this.toTooltip = toTooltip; + return this; + } + + public ViewModelTreeCellFactory withOnMouseClickedEvent(Callback> toOnMouseClickedEvent) { + this.toOnMouseClickedEvent = toOnMouseClickedEvent; + return this; + } + + public void install(TreeView treeView) { + treeView.setCellFactory(this); + } + + @Override + public TreeCell call(TreeView tree) { + Callback, ObservableValue> getSelectedProperty = + item -> { + if (item instanceof CheckBoxTreeItem) { + return ((CheckBoxTreeItem) item).selectedProperty(); + } + return null; + }; + + StringConverter> converter = new StringConverter>() { + @Override + public String toString(TreeItem treeItem) { + return (treeItem == null || treeItem.getValue() == null || toText == null) ? + "" : toText.call(treeItem.getValue()); + } + + @Override + public TreeItem fromString(String string) { + throw new UnsupportedOperationException("Not supported."); + } + }; + return new CheckBoxTreeCell<>(getSelectedProperty, converter); + } +} diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index ea96020a5fb..45f724fc252 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -2012,5 +2012,4 @@ public Map getMainTableColumnSortTypes() { } return map; } - } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 65d77c60098..529922c4b94 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1393,7 +1393,6 @@ Opens\ the\ file\ browser.=Opens the file browser. Scan\ directory=Scan directory Searches\ the\ selected\ directory\ for\ unlinked\ files.=Searches the selected directory for unlinked files. Starts\ the\ import\ of\ BibTeX\ entries.=Starts the import of BibTeX entries. -Leave\ this\ dialog.=Leave this dialog. Create\ directory\ based\ keywords=Create directory based keywords Creates\ keywords\ in\ created\ entrys\ with\ directory\ pathnames=Creates keywords in created entrys with directory pathnames Select\ a\ directory\ where\ the\ search\ shall\ start.=Select a directory where the search shall start. @@ -1401,12 +1400,9 @@ Select\ file\ type\:=Select file type: These\ files\ are\ not\ linked\ in\ the\ active\ library.=These files are not linked in the active library. Entry\ type\ to\ be\ created\:=Entry type to be created: Searching\ file\ system...=Searching file system... -Importing\ into\ Library...=Importing into Library... -Exporting\ into\ file...=Exporting into file... Select\ directory=Select directory Select\ files=Select files BibTeX\ entry\ creation=BibTeX entry creation -= Unable\ to\ connect\ to\ FreeCite\ online\ service.=Unable to connect to FreeCite online service. Parse\ with\ FreeCite=Parse with FreeCite How\ would\ you\ like\ to\ link\ to\ '%0'?=How would you like to link to '%0'? @@ -1981,7 +1977,6 @@ You\ must\ enter\ at\ least\ one\ field\ name=You must enter at least one field Non-ASCII\ encoded\ character\ found=Non-ASCII encoded character found Toggle\ web\ search\ interface=Toggle web search interface %0\ files\ found=%0 files found -%0\ of\ %1=%0 of %1 One\ file\ found=One file found The\ import\ finished\ with\ warnings\:=The import finished with warnings: There\ was\ one\ file\ that\ could\ not\ be\ imported.=There was one file that could not be imported. diff --git a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java index ec04c0d99e7..49a5a5c8b91 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java @@ -1,21 +1,21 @@ package org.jabref.gui.importer; -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Stream; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.logic.importer.ImportDataTest; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParserResult; -import org.jabref.logic.importer.fileformat.BibtexParser; +import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.FileFieldParser; +import org.jabref.model.entry.LinkedFile; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.testutils.category.GUITest; @@ -25,69 +25,61 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @GUITest -public class EntryFromFileCreatorManagerTest { +class EntryFromFileCreatorManagerTest { private final ImportFormatPreferences prefs = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); - private ExternalFileTypes externalFileTypes; + private EntryFromFileCreatorManager manager; @BeforeEach - public void setUp() { - externalFileTypes = mock(ExternalFileTypes.class, Answers.RETURNS_DEEP_STUBS); + void setUp() { + ExternalFileTypes externalFileTypes = mock(ExternalFileTypes.class, Answers.RETURNS_DEEP_STUBS); when(externalFileTypes.getExternalFileTypeByExt("pdf")).thenReturn(Optional.empty()); + manager = new EntryFromFileCreatorManager(externalFileTypes); } @Test - public void testGetCreator() { - EntryFromFileCreatorManager manager = new EntryFromFileCreatorManager(externalFileTypes); - EntryFromFileCreator creator = manager.getEntryCreator(ImportDataTest.NOT_EXISTING_PDF); - assertNull(creator); - - creator = manager.getEntryCreator(ImportDataTest.FILE_IN_DATABASE); - assertNotNull(creator); - assertTrue(creator.accept(ImportDataTest.FILE_IN_DATABASE)); + void getEntryCreatorForNotExistingPDFReturnsEmptyOptional() { + assertEquals(Optional.empty(), manager.getEntryCreator(ImportDataTest.NOT_EXISTING_PDF)); } @Test - public void testAddEntrysFromFiles() throws IOException { - try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); - InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = new BibtexParser(prefs, new DummyFileUpdateMonitor()).parse(reader); - BibDatabase database = result.getDatabase(); - - List files = new ArrayList<>(); - - files.add(ImportDataTest.FILE_NOT_IN_DATABASE); - files.add(ImportDataTest.NOT_EXISTING_PDF); - - EntryFromFileCreatorManager manager = new EntryFromFileCreatorManager(externalFileTypes); - List errors = manager.addEntrysFromFiles(files, database, null, true); - - /** - * One file doesn't exist, so adding it as an entry should lead to an error message. - */ - assertEquals(1, errors.size()); - - boolean file1Found = false; - boolean file2Found = false; - for (BibEntry entry : database.getEntries()) { - String filesInfo = entry.getField("file").get(); - if (filesInfo.contains(files.get(0).getName())) { - file1Found = true; - } - if (filesInfo.contains(files.get(1).getName())) { - file2Found = true; - } - } - - assertTrue(file1Found); - assertFalse(file2Found); - } + void getEntryCreatorForExistingPDFReturnsCreatorAcceptingThatFile() { + Optional creator = manager.getEntryCreator(ImportDataTest.FILE_IN_DATABASE); + assertNotEquals(Optional.empty(), creator); + assertTrue(creator.get().accept(ImportDataTest.FILE_IN_DATABASE.toFile())); + } + + @Test + void testAddEntriesFromFiles() throws IOException { + ParserResult result = new BibtexImporter(prefs, new DummyFileUpdateMonitor()) + .importDatabase(ImportDataTest.UNLINKED_FILES_TEST_BIB, StandardCharsets.UTF_8); + BibDatabase database = result.getDatabase(); + + List files = new ArrayList<>(); + files.add(ImportDataTest.FILE_NOT_IN_DATABASE); + files.add(ImportDataTest.NOT_EXISTING_PDF); + + List errors = manager.addEntrysFromFiles(files, database, null, true); + + // One file doesn't exist, so adding it as an entry should lead to an error message. + assertEquals(1, errors.size()); + + Stream linkedFileStream = database.getEntries().stream() + .flatMap(entry -> FileFieldParser.parse(entry.getField("file").get()).stream()); + + boolean file1Found = linkedFileStream + .anyMatch(file -> file.getLink().equalsIgnoreCase(ImportDataTest.FILE_NOT_IN_DATABASE.toString())); + + boolean file2Found = linkedFileStream + .anyMatch(file -> file.getLink().equalsIgnoreCase(ImportDataTest.NOT_EXISTING_PDF.toString())); + + assertTrue(file1Found); + assertFalse(file2Found); } } diff --git a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java index 575d82852b0..0a49334f501 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java @@ -43,17 +43,17 @@ public void testPDFFileFilter() { @Test public void testCreationOfEntryNoPDF() { - Optional entry = entryCreator.createEntry(ImportDataTest.NOT_EXISTING_PDF, false); + Optional entry = entryCreator.createEntry(ImportDataTest.NOT_EXISTING_PDF.toFile(), false); assertFalse(entry.isPresent()); } @Test @Disabled //Can't mock basepanel and maintable public void testCreationOfEntryNotInDatabase() { - Optional entry = entryCreator.createEntry(ImportDataTest.FILE_NOT_IN_DATABASE, false); + Optional entry = entryCreator.createEntry(ImportDataTest.FILE_NOT_IN_DATABASE.toFile(), false); assertTrue(entry.isPresent()); assertTrue(entry.get().getField("file").get().endsWith(":PDF")); - assertEquals(Optional.of(ImportDataTest.FILE_NOT_IN_DATABASE.getName()), + assertEquals(Optional.of(ImportDataTest.FILE_NOT_IN_DATABASE.getFileName().toString()), entry.get().getField("title")); } } diff --git a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java index fdb97e6ed88..d5c93399861 100644 --- a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java +++ b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java @@ -1,11 +1,9 @@ package org.jabref.logic.importer; -import java.io.FileInputStream; -import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Collection; -import org.jabref.logic.importer.fileformat.BibtexParser; +import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; @@ -18,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; -public class DatabaseFileLookupTest { +class DatabaseFileLookupTest { private BibDatabase database; private Collection entries; @@ -27,23 +25,21 @@ public class DatabaseFileLookupTest { private BibEntry entry2; @BeforeEach - public void setUp() throws Exception { - try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); - InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()).parse(reader); - database = result.getDatabase(); - entries = database.getEntries(); - - entry1 = database.getEntryByKey("entry1").get(); - entry2 = database.getEntryByKey("entry2").get(); - } + void setUp() throws Exception { + ParserResult result = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()) + .importDatabase(ImportDataTest.UNLINKED_FILES_TEST_BIB, StandardCharsets.UTF_8); + database = result.getDatabase(); + entries = database.getEntries(); + + entry1 = database.getEntryByKey("entry1").get(); + entry2 = database.getEntryByKey("entry2").get(); } /** * Tests the prerequisites of this test-class itself. */ @Test - public void testTestDatabase() { + void testTestDatabase() { assertEquals(2, database.getEntryCount()); assertEquals(2, entries.size()); assertNotNull(entry1); diff --git a/src/test/java/org/jabref/logic/importer/ImportDataTest.java b/src/test/java/org/jabref/logic/importer/ImportDataTest.java index dc457791f75..3a3fbb98c36 100644 --- a/src/test/java/org/jabref/logic/importer/ImportDataTest.java +++ b/src/test/java/org/jabref/logic/importer/ImportDataTest.java @@ -1,6 +1,7 @@ package org.jabref.logic.importer; -import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; @@ -10,38 +11,29 @@ public class ImportDataTest { - public static final File FILE_IN_DATABASE = Paths - .get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfInDatabase.pdf").toFile(); - public static final File FILE_NOT_IN_DATABASE = Paths - .get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfNotInDatabase.pdf") - .toFile(); - public static final File EXISTING_FOLDER = Paths - .get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder").toFile(); - public static final File NOT_EXISTING_FOLDER = Paths.get("notexistingfolder").toFile(); - public static final File NOT_EXISTING_PDF = Paths - .get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/null.pdf").toFile(); - public static final File UNLINKED_FILES_TEST_BIB = Paths - .get("src/test/resources/org/jabref/util/unlinkedFilesTestBib.bib").toFile(); + public static final Path FILE_IN_DATABASE = Paths.get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfInDatabase.pdf"); + public static final Path FILE_NOT_IN_DATABASE = Paths.get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfNotInDatabase.pdf"); + public static final Path EXISTING_FOLDER = Paths.get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder"); + public static final Path NOT_EXISTING_FOLDER = Paths.get("notexistingfolder"); + public static final Path NOT_EXISTING_PDF = Paths.get("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/null.pdf"); + public static final Path UNLINKED_FILES_TEST_BIB = Paths.get("src/test/resources/org/jabref/util/unlinkedFilesTestBib.bib"); /** * Tests the testing environment. */ @Test - public void testTestingEnvironment() { + void testTestingEnvironment() { - assertTrue(ImportDataTest.EXISTING_FOLDER.exists()); - assertTrue(ImportDataTest.EXISTING_FOLDER.isDirectory()); + assertTrue(Files.exists(ImportDataTest.EXISTING_FOLDER)); + assertTrue(Files.isDirectory(ImportDataTest.EXISTING_FOLDER)); - assertTrue(ImportDataTest.FILE_IN_DATABASE.exists()); - assertTrue(ImportDataTest.FILE_IN_DATABASE.isFile()); + assertTrue(Files.exists(ImportDataTest.FILE_IN_DATABASE)); + assertTrue(Files.isRegularFile(ImportDataTest.FILE_IN_DATABASE)); - assertTrue(ImportDataTest.FILE_NOT_IN_DATABASE.exists()); - assertTrue(ImportDataTest.FILE_NOT_IN_DATABASE.isFile()); - } + assertTrue(Files.exists(ImportDataTest.FILE_NOT_IN_DATABASE)); + assertTrue(Files.isRegularFile(ImportDataTest.FILE_NOT_IN_DATABASE)); - @Test - public void testOpenNotExistingDirectory() { - assertFalse(ImportDataTest.NOT_EXISTING_FOLDER.exists()); - assertFalse(ImportDataTest.NOT_EXISTING_PDF.exists()); + assertFalse(Files.exists(ImportDataTest.NOT_EXISTING_FOLDER)); + assertFalse(Files.exists(ImportDataTest.NOT_EXISTING_PDF)); } } From d37ef3e185b85563d0a68c430b88af3d18833b10 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Wed, 17 Oct 2018 13:35:36 +0200 Subject: [PATCH 09/30] Do not execute checkstyle tasks in main test suite on travis (#4381) --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e270879be38..489044d8ec4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -47,7 +47,7 @@ before_script: script: # --scan enables the Gradle build scan, which can be used to investigate the time each action consumes # For more information see https://gradle.com/scans/get-started - - if [ "$TEST_SUITE" != "guiTest" ] && [ "$TEST_SUITE" != "checkstyle" ] && [ "$TEST_SUITE" != "codecov" ]; then ./gradlew $TEST_SUITE $OPTIONS --scan; fi + - if [ "$TEST_SUITE" != "guiTest" ] && [ "$TEST_SUITE" != "checkstyle" ] && [ "$TEST_SUITE" != "codecov" ]; then ./gradlew $TEST_SUITE $OPTIONS -x checkstyleJmh -x checkstyleMain -x checkstyleTest --scan; fi - if [ "$TEST_SUITE" == "checkstyle" ]; then ./gradlew checkstyleMain checkstyleTest checkstyleJmh; fi - if [ "$TEST_SUITE" == "guiTest" ]; then ./buildres/gui-tests.sh; fi - if [ "$TEST_SUITE" == "codecov" ]; then ./gradlew jacocoTestReport; bash <(curl -s https://codecov.io/bash); fi From f43a367c533ce0d4c7a2f26df509f191e3efe2c6 Mon Sep 17 00:00:00 2001 From: Ali Date: Fri, 19 Oct 2018 18:29:41 +0600 Subject: [PATCH 10/30] fix NPE in AppearancePreferenceTab (#4386) * fix NPE in AppearancePreferenceTab * refactor code * delete unused import * set light theme selected by default --- .../org/jabref/gui/preferences/AppearancePrefsTab.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java b/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java index 92c62d12864..a3a8a349d56 100644 --- a/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java +++ b/src/main/java/org/jabref/gui/preferences/AppearancePrefsTab.java @@ -14,6 +14,7 @@ import org.jabref.gui.DialogService; import org.jabref.gui.util.ControlHelper; import org.jabref.logic.l10n.Localization; +import org.jabref.model.strings.StringUtil; import org.jabref.preferences.JabRefPreferences; class AppearancePrefsTab extends Pane implements PrefsTab { @@ -53,10 +54,12 @@ public AppearancePrefsTab(DialogService dialogService, JabRefPreferences prefs) darkTheme = new RadioButton("Dark theme"); darkTheme.setToggleGroup(themeGroup); - if (prefs.get(JabRefPreferences.FX_THEME).equals(BASE_CSS)) + String cssFileName = prefs.get(JabRefPreferences.FX_THEME); + if (StringUtil.isBlank(cssFileName) || BASE_CSS.equals(cssFileName)) { lightTheme.setSelected(true); - else if (prefs.get(JabRefPreferences.FX_THEME).equals(DARK_CSS)) + } else if (DARK_CSS.equals(cssFileName)) { darkTheme.setSelected(true); + } container.getChildren().addAll(overrideFonts, fontSizeContainer, fontTweaksLAF, lightTheme, darkTheme); From e76a28787491788371938791895a0cc866d7705f Mon Sep 17 00:00:00 2001 From: Vlad Topala Date: Sun, 21 Oct 2018 01:39:50 +0300 Subject: [PATCH 11/30] Fix showing multiple icons for one menu entry - fixes #4384 (#4392) * Fix showing multiple icons for one menu entry - fixes #4384 It currently only applies to the Rank menu; the sub-entries were only showing the first star instead of 5 stars * Fix showing multiple icons for one menu entry - fixes #4384 Removed changelog entry --- .../java/org/jabref/gui/icon/InternalMaterialDesignIcon.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java b/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java index 6eb64b8fc4a..84a02938c6e 100644 --- a/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java +++ b/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java @@ -57,7 +57,7 @@ public Icon getSmallIcon() { public Node getGraphicNode() { GlyphIcons icon = icons.get(0); - Text text = new Text(icon.unicode()); + Text text = new Text(unicode); text.getStyleClass().add("glyph-icon"); text.setStyle(String.format("-fx-font-family: %s;", icon.fontFamily())); From 44f712132fd3f90d908b9fd4288ffa457581a4e2 Mon Sep 17 00:00:00 2001 From: Ali Date: Mon, 22 Oct 2018 19:40:17 +0600 Subject: [PATCH 12/30] Make rank image narrower (#4395) * make rank image width narrower * delete border from rank button --- src/main/java/org/jabref/gui/maintable/MainTable.css | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.css b/src/main/java/org/jabref/gui/maintable/MainTable.css index 5855a86c120..6e5bac6ed4e 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTable.css +++ b/src/main/java/org/jabref/gui/maintable/MainTable.css @@ -22,10 +22,13 @@ } .rating > .container > .button { - -fx-pref-width: 10; + -fx-pref-width: 16; -fx-pref-height: 10; - -fx-background-size: cover; - -fx-padding: 0; + -fx-background-repeat: no-repeat no-repeat; + -fx-background-size: 16 16; + -fx-border-style: none; + -fx-border-width: 0; + -fx-padding: 0; } .rating > .container > .button.strong { From b9f9720d04ed946550231607be06e3ce802c5a88 Mon Sep 17 00:00:00 2001 From: Christoph Date: Mon, 22 Oct 2018 17:15:01 +0200 Subject: [PATCH 13/30] Fix EntryType dialog not closed after generate button (#4390) * Fix EntryType dialog not closed after generate button When generating an entry from an DOI or similar, the entry was inserted, but the dialog not closed. * remove obsolete comment * fix checkstyle --- src/main/java/org/jabref/gui/EntryTypeView.java | 7 +++++++ src/main/java/org/jabref/gui/EntryTypeViewModel.java | 10 +++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/EntryTypeView.java b/src/main/java/org/jabref/gui/EntryTypeView.java index 7eeb35a218c..733eb80ef29 100644 --- a/src/main/java/org/jabref/gui/EntryTypeView.java +++ b/src/main/java/org/jabref/gui/EntryTypeView.java @@ -74,6 +74,13 @@ public EntryTypeView(BasePanel basePanel, DialogService dialogService, JabRefPre btnGenerate.textProperty().bind(EasyBind.map(viewModel.searchingProperty(), searching -> (searching) ? Localization.lang("Searching...") : Localization.lang("Generate"))); btnGenerate.disableProperty().bind(viewModel.searchingProperty()); + + EasyBind.subscribe(viewModel.searchSuccesfulProperty(), value -> { + if (value) { + setEntryTypeForReturnAndClose(null); + } + }); + } private void addEntriesToPane(FlowPane pane, Collection entries) { diff --git a/src/main/java/org/jabref/gui/EntryTypeViewModel.java b/src/main/java/org/jabref/gui/EntryTypeViewModel.java index bc0464a309d..d023aa48900 100644 --- a/src/main/java/org/jabref/gui/EntryTypeViewModel.java +++ b/src/main/java/org/jabref/gui/EntryTypeViewModel.java @@ -36,6 +36,7 @@ public class EntryTypeViewModel { private final JabRefPreferences prefs; private final BooleanProperty searchingProperty = new SimpleBooleanProperty(); + private final BooleanProperty searchSuccesfulProperty = new SimpleBooleanProperty(); private final ObjectProperty selectedItemProperty = new SimpleObjectProperty<>(); private final ListProperty fetchers = new SimpleListProperty<>(FXCollections.observableArrayList()); private final StringProperty idText = new SimpleStringProperty(); @@ -53,6 +54,10 @@ public EntryTypeViewModel(JabRefPreferences preferences, BasePanel basePanel, Di } + public BooleanProperty searchSuccesfulProperty() { + return searchSuccesfulProperty; + } + public BooleanProperty searchingProperty() { return searchingProperty; } @@ -110,6 +115,7 @@ protected Optional call() throws InterruptedException, FetcherExceptio } public void runFetcherWorker() { + searchSuccesfulProperty.set(false); fetcherWorker.run(); fetcherWorker.setOnFailed(event -> { Throwable exception = fetcherWorker.getException(); @@ -124,7 +130,9 @@ public void runFetcherWorker() { LOGGER.error(String.format("Exception during fetching when using fetcher '%s' with entry id '%s'.", searchId, fetcher), exception); searchingProperty.set(false); + fetcherWorker = new FetcherWorker(); + }); fetcherWorker.setOnSucceeded(evt -> { @@ -143,8 +151,8 @@ public void runFetcherWorker() { new BibtexKeyGenerator(basePanel.getBibDatabaseContext(), prefs.getBibtexKeyPatternPreferences()).generateAndSetKey(bibEntry); basePanel.insertEntry(bibEntry); } + searchSuccesfulProperty.set(true); - // close(); } else if (StringUtil.isBlank(idText.getValue())) { dialogService.showWarningDialogAndWait(Localization.lang("Empty search ID"), Localization.lang("The given search ID was empty.")); } From 780c95800e666f123a897dfb3bb01a8f8d0e9527 Mon Sep 17 00:00:00 2001 From: Nivedha Date: Tue, 23 Oct 2018 18:32:28 +0530 Subject: [PATCH 14/30] Fixes for all mods exporter tests (#4396) --- .../org/jabref/logic/exporter/ModsExportFormatTestFiles.java | 3 --- .../jabref/logic/exporter/ModsExportFormatTestAllFields.xml | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java index 7a0d8ac6b6f..009c9f461ac 100644 --- a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java @@ -18,7 +18,6 @@ import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -71,7 +70,6 @@ public void setUp(@TempDirectory.TempDir Path testFolder) throws Exception { modsImporter = new ModsImporter(mock); } - @Disabled @ParameterizedTest @MethodSource("fileNames") public final void testPerformExport(String filename) throws Exception { @@ -99,7 +97,6 @@ public final void testExportAsModsAndThenImportAsMods(String filename) throws Ex BibEntryAssert.assertEquals(entries, tempFile, modsImporter); } - @Disabled @ParameterizedTest @MethodSource("fileNames") public final void testImportAsModsAndExportAsMods(String filename) throws Exception { diff --git a/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml b/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml index f446f136049..15158f3323a 100644 --- a/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml +++ b/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml @@ -57,7 +57,7 @@ 2000-11-10 monographic - Verlag verlag + Verlag verlag From eda8e262837f25d836ccec9db6c54f93121c6fde Mon Sep 17 00:00:00 2001 From: Linus Dietz Date: Tue, 23 Oct 2018 16:34:03 +0200 Subject: [PATCH 15/30] Updates (#4402) * Update Guava from 26 -> 27 * Update mysql-connector-java from 8.0.12 -> 8.0.13 * Update checkstyle from 8.13 -> 8.14 * Add update exception for shadow gradle plugin 4.x * Update install4j gradle plugin from 7.0.7 -> 7.0.8 * Add exception for the gradle build scan plugin --- build.gradle | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 8796658b173..a88052930d2 100644 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ buildscript { plugins { id 'com.gradle.build-scan' version '1.16' - id 'com.install4j.gradle' version '7.0.7' + id 'com.install4j.gradle' version '7.0.8' id 'com.github.johnrengelman.shadow' version '2.0.4' id "de.sebastianboegl.shadow.transformer.log4j" version "2.1.1" id "com.simonharrer.modernizer" version '1.6.0-1' @@ -119,13 +119,13 @@ dependencies { antlr4 'org.antlr:antlr4:4.7.1' compile 'org.antlr:antlr4-runtime:4.7.1' - compile 'mysql:mysql-connector-java:8.0.12' + compile 'mysql:mysql-connector-java:8.0.13' compile 'org.postgresql:postgresql:42.2.5' compile 'net.java.dev.glazedlists:glazedlists_java15:1.9.1' - compile 'com.google.guava:guava:26.0-jre' + compile 'com.google.guava:guava:27.0-jre' // JavaFX stuff compile 'de.jensd:fontawesomefx-materialdesignfont:1.7.22-4' @@ -182,7 +182,7 @@ dependencies { testCompile "org.testfx:testfx-core:4.0.+" testCompile "org.testfx:testfx-junit5:4.0.+" - checkstyle 'com.puppycrawl.tools:checkstyle:8.13' + checkstyle 'com.puppycrawl.tools:checkstyle:8.14' } jacoco { @@ -204,6 +204,11 @@ dependencyUpdates.resolutionStrategy = { selection.reject("Ignore SNAPSHOT releases") } } + rules.withModule("com.gradle.build-scan:com.gradle.build-scan.gradle.plugin") { ComponentSelection selection -> + if (selection.candidate.version ==~ /2.*/) { + selection.reject("Cannot be upgraded to version 2 until we upgrade to gradle 5") + } + } rules.withModule("org.controlsfx:controlsfx") { ComponentSelection selection -> if (selection.candidate.version ==~ /9.*/) { // Reject version 9 or higher selection.reject("Cannot be updated to 9.*.* until Jabref works with Java 9") @@ -216,8 +221,8 @@ dependencyUpdates.resolutionStrategy = { } } rules.withModule("com.github.johnrengelman.shadow:com.github.johnrengelman.shadow.gradle.plugin") { ComponentSelection selection -> - if (selection.candidate.version == /4.0.1/) { - selection.reject("Version 4.0.1 breaks the release process.") + if (selection.candidate.version ==~ /4.*/) { + selection.reject("Version 4.X breaks the release process.") } } rules.withModule("de.jensd:fontawesomefx-materialdesignfont") { ComponentSelection selection -> From 62fb97151ed09563e882a504a06c6408f8742ae1 Mon Sep 17 00:00:00 2001 From: pavlapp <38015475+pavlapp@users.noreply.github.com> Date: Wed, 24 Oct 2018 11:17:38 +0200 Subject: [PATCH 16/30] Scrollbar invisible in Preferences -> BibTex Key Pattern (#4287) (#4398) Fixes #4287. * Scrollbar invisible in Preferences -> BibTex Key Pattern (#4287) * fix invisible scrollbar in preferences * divided gridpane to multiple columns * * change array to arraylist * Improve code quality * Improve code quality * Fix checkstyle * refactoring css code for invisible scroll --- src/main/java/org/jabref/gui/Base.css | 4 +- .../BibtexKeyPatternPanel.java | 59 +++++++++++-------- .../gui/preferences/PreferencesDialog.java | 3 +- 3 files changed, 40 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/gui/Base.css b/src/main/java/org/jabref/gui/Base.css index 6ec8d5c9482..9a7c8b8b223 100644 --- a/src/main/java/org/jabref/gui/Base.css +++ b/src/main/java/org/jabref/gui/Base.css @@ -667,6 +667,7 @@ -fx-background-radius: 0em; } + .scroll-bar:horizontal .thumb, .scroll-bar:vertical .thumb { -fx-background-color: -jr-scrollbar-thumb; @@ -714,7 +715,8 @@ .tree-view:hover .scroll-bar, .table-view:hover .scroll-bar, .tree-table-view:hover .scroll-bar, -.text-input:hover .scroll-bar { +.text-input:hover .scroll-bar, +.scroll-pane:hover .scroll-bar { -fx-opacity: 1; } diff --git a/src/main/java/org/jabref/gui/bibtexkeypattern/BibtexKeyPatternPanel.java b/src/main/java/org/jabref/gui/bibtexkeypattern/BibtexKeyPatternPanel.java index daf7a4ac105..08a101c740d 100644 --- a/src/main/java/org/jabref/gui/bibtexkeypattern/BibtexKeyPatternPanel.java +++ b/src/main/java/org/jabref/gui/bibtexkeypattern/BibtexKeyPatternPanel.java @@ -36,6 +36,8 @@ public class BibtexKeyPatternPanel extends Pane { protected final TextField defaultPat = new TextField(); private final HelpAction help; + private final int COLUMNS = 2; + // one field for each type private final Map textFields = new HashMap<>(); private final BasePanel panel; @@ -44,25 +46,12 @@ public class BibtexKeyPatternPanel extends Pane { public BibtexKeyPatternPanel(BasePanel panel) { this.panel = panel; help = new HelpAction(Localization.lang("Help on key patterns"), HelpFile.BIBTEX_KEY_PATTERN); + gridPane.setHgap(10); + gridPane.setVgap(5); buildGUI(); } private void buildGUI() { - // The header - can be removed - Label label = new Label(Localization.lang("Entry type")); - gridPane.add(label, 1, 1); - - Label keyPattern = new Label(Localization.lang("Key pattern")); - gridPane.add(keyPattern, 3, 1); - - Label defaultPattern = new Label(Localization.lang("Default pattern")); - gridPane.add(defaultPattern, 1, 2); - gridPane.add(defaultPat, 3, 2); - - Button button = new Button("Default"); - button.setOnAction(e-> defaultPat.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN))); - gridPane.add(button, 4, 2); - BibDatabaseMode mode; // check mode of currently used DB if (panel != null) { @@ -72,24 +61,47 @@ private void buildGUI() { mode = Globals.prefs.getDefaultBibDatabaseMode(); } - int rowIndex = 3; + int rowIndex = 1; + int columnIndex = 0; + // The header - can be removed + for (int i = 0; i < COLUMNS; i++) { + Label label = new Label(Localization.lang("Entry type")); + Label keyPattern = new Label(Localization.lang("Key pattern")); + gridPane.add(label, ++columnIndex, rowIndex); + gridPane.add(keyPattern, ++columnIndex, rowIndex); + ++columnIndex; //3 + } + + rowIndex++; + Label defaultPattern = new Label(Localization.lang("Default pattern")); + Button button = new Button("Default"); + button.setOnAction(e-> defaultPat.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN))); + gridPane.add(defaultPattern, 1, rowIndex); + gridPane.add(defaultPat, 2, rowIndex); + gridPane.add(button, 3, rowIndex); + + columnIndex = 1; for (EntryType type : EntryTypes.getAllValues(mode)) { Label label1 = new Label(type.getName()); - TextField textField = new TextField(); - Button button1 = new Button("Default"); button1.setOnAction(e1 -> textField.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN))); - gridPane.add(label1, 1, rowIndex); - gridPane.add(textField, 3, rowIndex); - gridPane.add(button1, 4, rowIndex); + gridPane.add(label1, 1 + (columnIndex * 3) , rowIndex); + gridPane.add(textField, 2 + (columnIndex * 3), rowIndex); + gridPane.add(button1, 3 + (columnIndex * 3), rowIndex); textFields.put(type.getName().toLowerCase(Locale.ROOT), textField); - rowIndex++; + if (columnIndex == COLUMNS - 1) { + columnIndex = 0; + rowIndex++; + } else + columnIndex++; } + rowIndex++; + Button help1 = new Button("?"); help1.setOnAction(e->new HelpAction(Localization.lang("Help on key patterns"), HelpFile.BIBTEX_KEY_PATTERN).getHelpButton().doClick()); gridPane.add(help1, 1, rowIndex); @@ -102,9 +114,10 @@ private void buildGUI() { } defaultPat.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN)); }); - gridPane.add(btnDefaultAll1, 3, rowIndex); + gridPane.add(btnDefaultAll1, 2, rowIndex); } + /** * fill the given LabelPattern by values generated from the text fields */ diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java b/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java index db3e8e22a23..0fe12a13eaf 100644 --- a/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java +++ b/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java @@ -91,8 +91,7 @@ public PreferencesDialog(JabRefFrame parent) { preferenceTabs.add(new AppearancePrefsTab(dialogService, prefs)); container = new BorderPane(); - ScrollPane scroll = new ScrollPane(container); - getDialogPane().setContent(scroll); + getDialogPane().setContent(container); construct(); } From e8daf2606424155acfd0b87aec0e7c2eb033943f Mon Sep 17 00:00:00 2001 From: Ali Date: Thu, 25 Oct 2018 14:33:57 +0600 Subject: [PATCH 17/30] show dialog before creating entry (#4405) * show dialog before creating entry * delete unused import * change new entry to a new article --- src/main/java/org/jabref/gui/JabRefFrame.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java index 2531456c6f0..596fe1972c9 100644 --- a/src/main/java/org/jabref/gui/JabRefFrame.java +++ b/src/main/java/org/jabref/gui/JabRefFrame.java @@ -618,7 +618,7 @@ private Node createToolbar() { PushToApplicationButton pushToExternal = new PushToApplicationButton(this, pushApplications.getApplications()); HBox rightSide = new HBox( - factory.createIconButton(StandardActions.NEW_ENTRY, new NewEntryAction(this, BiblatexEntryTypes.ARTICLE, dialogService, Globals.prefs)), + factory.createIconButton(StandardActions.NEW_ARTICLE, new NewEntryAction(this, BiblatexEntryTypes.ARTICLE, dialogService, Globals.prefs)), factory.createIconButton(StandardActions.DELETE_ENTRY, new OldDatabaseCommandWrapper(Actions.DELETE, this, Globals.stateManager)), factory.createIconButton(StandardActions.UNDO, new OldDatabaseCommandWrapper(Actions.UNDO, this, Globals.stateManager)), From 4d89b0a5511dd9c233c9856632ab48340327b2f2 Mon Sep 17 00:00:00 2001 From: Fancy Zhang Date: Fri, 26 Oct 2018 03:51:50 +0800 Subject: [PATCH 18/30] fix "save" button in preference dialog not response (#4406) Fixes #4391. * fix "save" button in preference dialog not response or work this is because default value for fxTheme is not set, thus cause null exception solution: set default value "Base.css" for key "fxTheme" in preferencewq * avoid repeat adding the same css * fix code style --- .../java/org/jabref/gui/util/ThemeLoader.java | 16 +++++++++++----- .../jabref/preferences/JabRefPreferences.java | 3 +++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/util/ThemeLoader.java b/src/main/java/org/jabref/gui/util/ThemeLoader.java index 7a7004d3445..e9d9a7b40e8 100644 --- a/src/main/java/org/jabref/gui/util/ThemeLoader.java +++ b/src/main/java/org/jabref/gui/util/ThemeLoader.java @@ -36,7 +36,8 @@ */ public class ThemeLoader { - private static final String DEFAULT_PATH_MAIN_CSS = JabRefFrame.class.getResource("Base.css").toExternalForm(); + public static final String DEFAULT_MAIN_CSS = "Base.css"; + private static final String DEFAULT_PATH_MAIN_CSS = JabRefFrame.class.getResource(DEFAULT_MAIN_CSS).toExternalForm(); private static final Logger LOGGER = LoggerFactory.getLogger(ThemeLoader.class); private String cssProperty = System.getProperty("jabref.theme.css"); private final FileUpdateMonitor fileUpdateMonitor; @@ -57,25 +58,31 @@ public ThemeLoader(FileUpdateMonitor fileUpdateMonitor, JabRefPreferences jabRef } } + /** * Installs the base css file as a stylesheet in the given scene. * Changes in the css file lead to a redraw of the scene using the new css file. */ public void installBaseCss(Scene scene, JabRefPreferences preferences) { - addAndWatchForChanges(scene, DEFAULT_PATH_MAIN_CSS, 0); - if (StringUtil.isNotBlank(cssProperty)) { final Path path = Paths.get(cssProperty); if (Files.isReadable(path)) { String cssUrl = path.toUri().toString(); - addAndWatchForChanges(scene, cssUrl, 1); + addAndWatchForChanges(scene, cssUrl, 0); + } else { + LOGGER.warn(path.toAbsolutePath() + " is not readable"); } + } else { + addAndWatchForChanges(scene, DEFAULT_PATH_MAIN_CSS, 0); } preferences.getFontSize().ifPresent(size -> scene.getRoot().setStyle("-fx-font-size: " + size + "pt;")); } private void addAndWatchForChanges(Scene scene, String cssUrl, int index) { + // avoid repeat add + if (scene.getStylesheets().contains(cssUrl)) return; + scene.getStylesheets().add(index, cssUrl); try { @@ -86,7 +93,6 @@ private void addAndWatchForChanges(Scene scene, String cssUrl, int index) { LOGGER.info("Enabling live reloading of " + cssFile); fileUpdateMonitor.addListenerForFile(cssFile, () -> { LOGGER.info("Reload css file " + cssFile); - DefaultTaskExecutor.runInJavaFXThread(() -> { scene.getStylesheets().remove(cssUrl); scene.getStylesheets().add(index, cssUrl); diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 45f724fc252..79d0afc5a5f 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -51,6 +51,7 @@ import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTablePreferences; import org.jabref.gui.preferences.ImportSettingsTab; +import org.jabref.gui.util.ThemeLoader; import org.jabref.logic.bibtex.FieldContentParserPreferences; import org.jabref.logic.bibtex.LatexFieldFormatterPreferences; import org.jabref.logic.bibtexkeypattern.BibtexKeyPatternPreferences; @@ -780,6 +781,8 @@ private JabRefPreferences() { + "\\begin{comment}

    Comment: \\format[HTMLChars]{\\comment} \\end{comment}" + "__NEWLINE__

    "); + // set default theme + defaults.put(JabRefPreferences.FX_THEME, ThemeLoader.DEFAULT_MAIN_CSS); setLanguageDependentDefaultValues(); } From f1c29c2e1ac89a2d7704ed0e4552dd70424174fb Mon Sep 17 00:00:00 2001 From: conorfos <40298107+conorfos@users.noreply.github.com> Date: Fri, 26 Oct 2018 08:53:07 +0100 Subject: [PATCH 19/30] Integrate mrdlib redesign (#4361) * Recommendation retrieval from new Mr. DLib MrDLibImporter and MrDLibFetcher updated to support JSON and new Mr. DLib format. Tests updated and passing. * Create GDPR dialog and update GUI Created dialog to ask for consent to sed data to Mr. DLib Created preference setting to keep track of consent Updated the recommendations GUI to use JavaFX * Privacy dialog text wrapping Changed privacy dialog text and allowed the text to wrap. * Created dev switch based on JabRef version * Adjusted Hyperlink styling * Removed .bib file included by mistake * Simplification of Dev switch Replaced if/else with in-line conditional * Removed unnecessary setting of html_representation Recommendation html_representation field no longer set as it is not used * Removed .orig file mistakenly added * Fixed Codacy issues and removed abstracts from tests Removed html representation test Removed abstracts from tests * Moved root styling to css file * Removed Print Stack Trace call * Replaced UI strings with Localization.lang strings * everted to EntryEditorPreferences * Removed reference to Globals in MrDLibFetcher * Fixed awkward syntax with JSONObject * Implemented Dialogs One to notify the user to restart JabRef after changing preferences Two to show IOExceptions to the user * Reverting unintended change * Set Accept button as default button * Updated CHANGELOG.md * Fix for broken MrDLibFetcherTest * Fix unused imports, refactor event listener to lambda, call static method through classname * Fix localization strings Co-authored-by: halirutan --- CHANGELOG.md | 1 + src/main/java/org/jabref/gui/Base.css | 1 + .../jabref/gui/entryeditor/EntryEditor.css | 10 + .../jabref/gui/entryeditor/EntryEditor.java | 2 +- .../entryeditor/EntryEditorPreferences.java | 8 +- .../gui/entryeditor/RelatedArticlesTab.java | 164 +++++++++---- .../gui/preferences/EntryEditorPrefsTab.java | 10 +- .../logic/importer/fetcher/MrDLibFetcher.java | 46 ++-- .../importer/fileformat/MrDLibImporter.java | 229 +++++++----------- .../jabref/logic/util/StandardFileType.java | 1 + .../jabref/preferences/JabRefPreferences.java | 3 + src/main/resources/l10n/JabRef_en.properties | 20 +- .../importer/fetcher/MrDLibFetcherTest.java | 3 +- .../fileformat/MrDLibImporterTest.java | 38 +-- 14 files changed, 296 insertions(+), 240 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index adc97d7c507..9d32677a43e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We added a minimal height for the entry editor so that it can no longer be hidden by accident. [#4279](https://github.com/JabRef/jabref/issues/4279) - We added a new keyboard shortcut so that the entry editor could be closed by Ctrl + E. [#4222] (https://github.com/JabRef/jabref/issues/4222) - We added an option in the preference dialog box, that allows user to pick the dark or light theme option. [#4130] (https://github.com/JabRef/jabref/issues/4130) +- We updated updated the Related Articles tab to accept JSON from the new version of the Mr. DLib service diff --git a/src/main/java/org/jabref/gui/Base.css b/src/main/java/org/jabref/gui/Base.css index 9a7c8b8b223..a8644b5c180 100644 --- a/src/main/java/org/jabref/gui/Base.css +++ b/src/main/java/org/jabref/gui/Base.css @@ -247,6 +247,7 @@ -fx-underline: false; -fx-border-style: null; -fx-border-color: null; + -fx-text-fill: -jr-theme; } .hyperlink:visited { diff --git a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.css b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.css index 47eefbdde49..313583ed222 100644 --- a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.css +++ b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.css @@ -79,3 +79,13 @@ .code-area .text { -fx-fill: -fx-text-background-color; } + +.gdpr-dialog { + -fx-font-size: 14pt; +} + +.related-articles-tab { + -fx-padding: 20 20 20 20; +} + + diff --git a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java index 75070434db0..46ae9d3d32d 100644 --- a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java +++ b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java @@ -253,7 +253,7 @@ private List createTabs() { // Special tabs tabs.add(new MathSciNetTab()); tabs.add(new FileAnnotationTab(panel.getAnnotationCache())); - tabs.add(new RelatedArticlesTab(preferences)); + tabs.add(new RelatedArticlesTab(preferences, dialogService)); // Source tab sourceTab = new SourceTab(databaseContext, undoManager, preferences.getLatexFieldFormatterPreferences(), preferences.getImportFormatPreferences(), fileMonitor); diff --git a/src/main/java/org/jabref/gui/entryeditor/EntryEditorPreferences.java b/src/main/java/org/jabref/gui/entryeditor/EntryEditorPreferences.java index fd8e1d097b2..ed059ab9f7f 100644 --- a/src/main/java/org/jabref/gui/entryeditor/EntryEditorPreferences.java +++ b/src/main/java/org/jabref/gui/entryeditor/EntryEditorPreferences.java @@ -16,16 +16,18 @@ public class EntryEditorPreferences { private final BibtexKeyPatternPreferences bibtexKeyPatternPreferences; private final List customTabFieldNames; private final boolean shouldShowRecommendationsTab; + private final boolean isMrdlibAccepted; private boolean showSourceTabByDefault; private final KeyBindingRepository keyBindings; private boolean avoidOverwritingCiteKey; - public EntryEditorPreferences(Map> entryEditorTabList, LatexFieldFormatterPreferences latexFieldFormatterPreferences, ImportFormatPreferences importFormatPreferences, List customTabFieldNames, boolean shouldShowRecommendationsTab, boolean showSourceTabByDefault, BibtexKeyPatternPreferences bibtexKeyPatternPreferences, KeyBindingRepository keyBindings, boolean avoidOverwritingCiteKey) { + public EntryEditorPreferences(Map> entryEditorTabList, LatexFieldFormatterPreferences latexFieldFormatterPreferences, ImportFormatPreferences importFormatPreferences, List customTabFieldNames, boolean shouldShowRecommendationsTab, boolean isMrdlibAccepted, boolean showSourceTabByDefault, BibtexKeyPatternPreferences bibtexKeyPatternPreferences, KeyBindingRepository keyBindings, boolean avoidOverwritingCiteKey) { this.entryEditorTabList = entryEditorTabList; this.latexFieldFormatterPreferences = latexFieldFormatterPreferences; this.importFormatPreferences = importFormatPreferences; this.customTabFieldNames = customTabFieldNames; this.shouldShowRecommendationsTab = shouldShowRecommendationsTab; + this.isMrdlibAccepted = isMrdlibAccepted; this.showSourceTabByDefault = showSourceTabByDefault; this.bibtexKeyPatternPreferences = bibtexKeyPatternPreferences; this.keyBindings = keyBindings; @@ -52,6 +54,10 @@ public boolean shouldShowRecommendationsTab() { return shouldShowRecommendationsTab; } + public boolean isMrdlibAccepted() { + return isMrdlibAccepted; + } + public boolean showSourceTabByDefault() { return showSourceTabByDefault; } diff --git a/src/main/java/org/jabref/gui/entryeditor/RelatedArticlesTab.java b/src/main/java/org/jabref/gui/entryeditor/RelatedArticlesTab.java index 233d3207ed2..dbbe9ff096a 100644 --- a/src/main/java/org/jabref/gui/entryeditor/RelatedArticlesTab.java +++ b/src/main/java/org/jabref/gui/entryeditor/RelatedArticlesTab.java @@ -1,82 +1,155 @@ package org.jabref.gui.entryeditor; -import java.net.URL; +import java.io.IOException; import java.util.List; -import java.util.Optional; +import javafx.scene.control.Button; +import javafx.scene.control.Hyperlink; import javafx.scene.control.ProgressIndicator; +import javafx.scene.control.ScrollPane; import javafx.scene.control.Tooltip; +import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; -import javafx.scene.web.WebView; +import javafx.scene.layout.VBox; +import javafx.scene.text.Font; +import javafx.scene.text.FontPosture; +import javafx.scene.text.Text; import org.jabref.Globals; -import org.jabref.gui.icon.IconTheme; +import org.jabref.gui.DialogService; +import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.util.BackgroundTask; -import org.jabref.gui.util.OpenHyperlinksInExternalBrowser; import org.jabref.logic.importer.fetcher.MrDLibFetcher; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.FieldName; import org.jabref.preferences.JabRefPreferences; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GUI for tab displaying article recommendations based on the currently selected BibEntry + */ public class RelatedArticlesTab extends EntryEditorTab { + private static final Logger LOGGER = LoggerFactory.getLogger(RelatedArticlesTab.class); private final EntryEditorPreferences preferences; + private final DialogService dialogService; - public RelatedArticlesTab(EntryEditorPreferences preferences) { + public RelatedArticlesTab(EntryEditorPreferences preferences, DialogService dialogService) { setText(Localization.lang("Related articles")); setTooltip(new Tooltip(Localization.lang("Related articles"))); this.preferences = preferences; + this.dialogService = dialogService; } - private StackPane getPane(BibEntry entry) { + /** + * Gets a StackPane of related article information to be displayed in the Related Articles tab + * @param entry The currently selected BibEntry on the JabRef UI. + * @return A StackPane with related article information to be displayed in the Related Articles tab. + */ + private StackPane getRelatedArticlesPane(BibEntry entry) { StackPane root = new StackPane(); + root.getStyleClass().add("related-articles-tab"); ProgressIndicator progress = new ProgressIndicator(); progress.setMaxSize(100, 100); - WebView browser = new WebView(); - root.getChildren().addAll(browser, progress); MrDLibFetcher fetcher = new MrDLibFetcher(Globals.prefs.get(JabRefPreferences.LANGUAGE), - Globals.BUILD_INFO.getVersion().getFullVersion()); + Globals.BUILD_INFO.getVersion()); BackgroundTask - .wrap(() -> fetcher.performSearch(entry)) - .onRunning(() -> progress.setVisible(true)) - .onSuccess(relatedArticles -> { - progress.setVisible(false); - browser.getEngine().loadContent(convertToHtml(relatedArticles)); - }) - .executeWith(Globals.TASK_EXECUTOR); + .wrap(() -> fetcher.performSearch(entry)) + .onRunning(() -> progress.setVisible(true)) + .onSuccess(relatedArticles -> { + progress.setVisible(false); + root.getChildren().add(getRelatedArticleInfo(relatedArticles)); + }) + .executeWith(Globals.TASK_EXECUTOR); - browser.getEngine().getLoadWorker().stateProperty().addListener(new OpenHyperlinksInExternalBrowser(browser)); + root.getChildren().add(progress); return root; } /** - * Takes a List of HTML snippets stored in the field "html_representation" of a list of bibentries - * - * @param list of bib entries having a field html_representation + * Creates a VBox of the related article information to be used in the StackPane displayed in the Related Articles tab + * @param list List of BibEntries of related articles + * @return VBox of related article descriptions to be displayed in the Related Articles tab */ - private String convertToHtml(List list) { - StringBuilder htmlContent = new StringBuilder(); - URL url = IconTheme.getIconUrl("mdlListIcon"); - htmlContent - .append(""); - htmlContent.append("
      "); - list.stream() - .map(bibEntry -> bibEntry.getField("html_representation")) - .filter(Optional::isPresent) - .map(o -> "
    • " + o.get() + "
    • ") - .forEach(html -> htmlContent.append(html)); - htmlContent.append("
    "); - htmlContent.append("
    "); - htmlContent.append(""); - return htmlContent.toString(); + private VBox getRelatedArticleInfo(List list) { + VBox vBox = new VBox(); + vBox.setSpacing(20.0); + + for (BibEntry entry : list) { + HBox hBox = new HBox(); + hBox.setSpacing(5.0); + + String title = entry.getTitle().orElse(""); + String journal = entry.getField(FieldName.JOURNAL).orElse(""); + String authors = entry.getField(FieldName.AUTHOR).orElse(""); + String year = entry.getField(FieldName.YEAR).orElse(""); + + Hyperlink titleLink = new Hyperlink(title); + Text journalText = new Text(journal); + journalText.setFont(Font.font(Font.getDefault().getFamily(), FontPosture.ITALIC, Font.getDefault().getSize())); + Text authorsText = new Text(authors); + Text yearText = new Text("(" + year + ")"); + titleLink.setOnAction(event -> { + if (entry.getField(FieldName.URL).isPresent()) { + try { + JabRefDesktop.openBrowser(entry.getField(FieldName.URL).get()); + } catch (IOException e) { + LOGGER.error("Error opening the browser to: " + entry.getField(FieldName.URL).get(), e); + dialogService.showErrorDialogAndWait(e); + } + } + }); + + hBox.getChildren().addAll(titleLink, journalText, authorsText, yearText); + vBox.getChildren().add(hBox); + } + return vBox; + } + + /** + * Returns a consent dialog used to ask permission to send data to Mr. DLib. + * @param entry Currently selected BibEntry. (required to allow reloading of pane if accepted) + * @return StackPane returned to be placed into Related Articles tab. + */ + private ScrollPane getPrivacyDialog(BibEntry entry) { + ScrollPane root = new ScrollPane(); + root.getStyleClass().add("related-articles-tab"); + VBox vbox = new VBox(); + vbox.getStyleClass().add("gdpr-dialog"); + vbox.setSpacing(20.0); + + Button button = new Button(Localization.lang("I Agree")); + button.setDefaultButton(true); + Text line1 = new Text(Localization.lang("Mr. DLib is an external service which provides article recommendations based on the currently selected entry. Data about the selected entry must be sent to Mr. DLib in order to provide these recommendations. Do you agree that this data may be sent?")); + + line1.setWrappingWidth(1300.0); + Text line2 = new Text(Localization.lang("This setting may be changed in preferences at any time.")); + Hyperlink mdlLink = new Hyperlink(Localization.lang("Further information about Mr DLib. for JabRef users.")); + mdlLink.setOnAction(event -> { + try { + JabRefDesktop.openBrowser("http://mr-dlib.org/information-for-users/information-about-mr-dlib-for-jabref-users/"); + } catch (IOException e) { + LOGGER.error("Error opening the browser to Mr. DLib information page.", e); + dialogService.showErrorDialogAndWait(e); + } + }); + + button.setOnAction(event -> { + JabRefPreferences prefs = JabRefPreferences.getInstance(); + prefs.putBoolean(JabRefPreferences.ACCEPT_RECOMMENDATIONS, true); + dialogService.showWarningDialogAndWait(Localization.lang("Restart"), Localization.lang("Please restart JabRef for preferences to take effect.")); + setContent(getRelatedArticlesPane(entry)); + }); + + vbox.getChildren().addAll(line1, mdlLink, line2, button); + root.setContent(vbox); + + return root; } @Override @@ -86,6 +159,11 @@ public boolean shouldShow(BibEntry entry) { @Override protected void bindToEntry(BibEntry entry) { - setContent(getPane(entry)); + // Ask for consent to send data to Mr. DLib on first time to tab + if (preferences.isMrdlibAccepted()) { + setContent(getRelatedArticlesPane(entry)); + } else { + setContent(getPrivacyDialog(entry)); + } } } diff --git a/src/main/java/org/jabref/gui/preferences/EntryEditorPrefsTab.java b/src/main/java/org/jabref/gui/preferences/EntryEditorPrefsTab.java index 4530cb88157..ab874bf1287 100644 --- a/src/main/java/org/jabref/gui/preferences/EntryEditorPrefsTab.java +++ b/src/main/java/org/jabref/gui/preferences/EntryEditorPrefsTab.java @@ -27,6 +27,7 @@ class EntryEditorPrefsTab extends Pane implements PrefsTab { private final CheckBox emacsRebindCtrlF; private final CheckBox autoComplete; private final CheckBox recommendations; + private final CheckBox acceptRecommendations; private final CheckBox validation; private final RadioButton autoCompBoth; private final RadioButton autoCompFF; @@ -51,6 +52,7 @@ public EntryEditorPrefsTab(JabRefPreferences prefs) { emacsRebindCtrlF = new CheckBox(Localization.lang("Rebind C-f, too")); autoComplete = new CheckBox(Localization.lang("Enable word/name autocompletion")); recommendations = new CheckBox(Localization.lang("Show 'Related Articles' tab")); + acceptRecommendations = new CheckBox(Localization.lang("Accept recommendations from Mr. DLib")); validation = new CheckBox(Localization.lang("Show validation messages")); // allowed name formats @@ -84,8 +86,9 @@ public EntryEditorPrefsTab(JabRefPreferences prefs) { builder.add(emacsRebindCtrlA, 1, 5); builder.add(emacsRebindCtrlF, 1, 6); builder.add(recommendations, 1, 7); - builder.add(validation, 1, 8); - builder.add(new Label(""), 1, 9); + builder.add(acceptRecommendations, 1, 8); + builder.add(validation, 1, 9); + builder.add(new Label(""), 1, 10); Label autocompletionOptions = new Label(Localization.lang("Autocompletion options")); autocompletionOptions.getStyleClass().add("sectionHeader"); @@ -113,6 +116,7 @@ public EntryEditorPrefsTab(JabRefPreferences prefs) { builder.add(firstNameModeBoth, 1, 22); } + @Override public Node getBuilder() { return builder; } @@ -135,6 +139,7 @@ public void setValues() { emacsRebindCtrlA.setSelected(prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CA)); emacsRebindCtrlF.setSelected(prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CF)); recommendations.setSelected(prefs.getBoolean(JabRefPreferences.SHOW_RECOMMENDATIONS)); + acceptRecommendations.setSelected(prefs.getBoolean(JabRefPreferences.ACCEPT_RECOMMENDATIONS)); autoComplete.setSelected(autoCompletePreferences.shouldAutoComplete()); autoCompFields.setText(autoCompletePreferences.getCompleteNamesAsString()); @@ -171,6 +176,7 @@ public void storeSettings() { prefs.putBoolean(JabRefPreferences.AUTO_OPEN_FORM, autoOpenForm.isSelected()); prefs.putBoolean(JabRefPreferences.DEFAULT_SHOW_SOURCE, defSource.isSelected()); prefs.putBoolean(JabRefPreferences.SHOW_RECOMMENDATIONS, recommendations.isSelected()); + prefs.putBoolean(JabRefPreferences.ACCEPT_RECOMMENDATIONS, acceptRecommendations.isSelected()); prefs.putBoolean(JabRefPreferences.VALIDATE_IN_ENTRY_EDITOR, validation.isSelected()); boolean emacsModeChanged = prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS) != emacsMode.isSelected(); boolean emacsRebindCtrlAChanged = prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CA) != emacsRebindCtrlA.isSelected(); diff --git a/src/main/java/org/jabref/logic/importer/fetcher/MrDLibFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/MrDLibFetcher.java index 199d68dee32..2ae7db36e35 100644 --- a/src/main/java/org/jabref/logic/importer/fetcher/MrDLibFetcher.java +++ b/src/main/java/org/jabref/logic/importer/fetcher/MrDLibFetcher.java @@ -1,6 +1,3 @@ -/** - * - */ package org.jabref.logic.importer.fetcher; import java.io.IOException; @@ -14,8 +11,8 @@ import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.MrDLibImporter; -import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; +import org.jabref.logic.util.Version; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; @@ -25,17 +22,16 @@ import org.slf4j.LoggerFactory; /** - * This class is responible to get the recommendations from MDL + * This class is responsible for getting the recommendations from Mr. DLib */ public class MrDLibFetcher implements EntryBasedFetcher { private static final Logger LOGGER = LoggerFactory.getLogger(MrDLibFetcher.class); - private static final String NAME = "MDL_FETCHER"; private final String LANGUAGE; - private final String VERSION; + private final Version VERSION; - public MrDLibFetcher(String language, String version) { + public MrDLibFetcher(String language, Version version) { LANGUAGE = language; VERSION = version; } @@ -51,22 +47,22 @@ public List performSearch(BibEntry entry) throws FetcherException { if (title.isPresent()) { String response = makeServerRequest(title.get()); MrDLibImporter importer = new MrDLibImporter(); - ParserResult parserResult = new ParserResult(); + ParserResult parserResult; try { if (importer.isRecognizedFormat(response)) { parserResult = importer.importDatabase(response); } else { // For displaying An ErrorMessage + String error = importer.getResponseErrorMessage(response); BibEntry errorBibEntry = new BibEntry(); - errorBibEntry.setField("html_representation", - Localization.lang("Error while fetching from %0", "Mr.DLib")); + errorBibEntry.setField("html_representation", error); BibDatabase errorBibDataBase = new BibDatabase(); errorBibDataBase.insertEntry(errorBibEntry); parserResult = new ParserResult(errorBibDataBase); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); - throw new FetcherException("XML Parser IOException."); + throw new FetcherException("JSON Parser IOException."); } return parserResult.getDatabase().getEntries(); } else { @@ -78,13 +74,13 @@ public List performSearch(BibEntry entry) throws FetcherException { /** * Contact the server with the title of the selected item * - * @param query: The query holds the title of the selected entry. Used to make a query to the MDL Server + * @param queryByTitle: The query holds the title of the selected entry. Used to make a query to the MDL Server * @return Returns the server response. This is an XML document as a String. */ private String makeServerRequest(String queryByTitle) throws FetcherException { try { URLDownload urlDownload = new URLDownload(constructQuery(queryByTitle)); - urlDownload.bypassSSLVerification(); + URLDownload.bypassSSLVerification(); String response = urlDownload.asString(); //Conversion of < and > @@ -97,29 +93,33 @@ private String makeServerRequest(String queryByTitle) throws FetcherException { } /** - * Constructs the query based on title of the bibentry. Adds statistical stuff to the url. + * Constructs the query based on title of the BibEntry. Adds statistical stuff to the url. * - * @param query: the title of the bib entry. + * @param queryWithTitle: the title of the bib entry. * @return the string used to make the query at mdl server */ private String constructQuery(String queryWithTitle) { // The encoding does not work for / so we convert them by our own - queryWithTitle = queryWithTitle.replaceAll("/", "convbckslsh"); + queryWithTitle = queryWithTitle.replaceAll("/", " "); URIBuilder builder = new URIBuilder(); - builder.setScheme("https"); - builder.setHost("api.mr-dlib.org"); - builder.setPath("/v1/documents/" + queryWithTitle + "/related_documents"); + builder.setScheme("http"); + builder.setHost(getMdlUrl()); + builder.setPath("/v2/items/" + queryWithTitle + "/related_items"); builder.addParameter("partner_id", "jabref"); builder.addParameter("app_id", "jabref_desktop"); - builder.addParameter("app_version", VERSION); + builder.addParameter("app_version", VERSION.getFullVersion()); builder.addParameter("app_lang", LANGUAGE); - URI uri = null; try { - uri = builder.build(); + URI uri = builder.build(); + LOGGER.trace("Request: " + uri.toString()); return uri.toString(); } catch (URISyntaxException e) { LOGGER.error(e.getMessage(), e); } return ""; } + + private String getMdlUrl() { + return VERSION.isDevelopmentVersion() ? "api-dev.darwingoliath.com" : "api.darwingoliath.com"; + } } diff --git a/src/main/java/org/jabref/logic/importer/fileformat/MrDLibImporter.java b/src/main/java/org/jabref/logic/importer/fileformat/MrDLibImporter.java index 491eff2c8d1..6320b8d7483 100644 --- a/src/main/java/org/jabref/logic/importer/fileformat/MrDLibImporter.java +++ b/src/main/java/org/jabref/logic/importer/fileformat/MrDLibImporter.java @@ -4,58 +4,45 @@ package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; -import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStream; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.stream.Collectors; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - import org.jabref.logic.importer.Importer; import org.jabref.logic.importer.ParserResult; +import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; /** - * - * + * Handles importing of recommended articles to be displayed in the Related Articles tab. */ public class MrDLibImporter extends Importer { + private static final String DEFAULT_MRDLIB_ERROR_MESSAGE = Localization.lang("Error while fetching from Mr.DLib."); private static final Logger LOGGER = LoggerFactory.getLogger(MrDLibImporter.class); public ParserResult parserResult; + @SuppressWarnings("unused") @Override public boolean isRecognizedFormat(BufferedReader input) throws IOException { String recommendationsAsString = convertToString(input); - // check for valid format try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - SAXParser saxParser = factory.newSAXParser(); - DefaultHandler handler = new DefaultHandler() { - // No Processing here. Just check for valid xml. - // Later here will be the check against the XML schema. - }; - - try (InputStream stream = new ByteArrayInputStream(recommendationsAsString.getBytes())) { - saxParser.parse(stream, handler); - } catch (Exception e) { + JSONObject jsonObject = new JSONObject(recommendationsAsString); + if (!jsonObject.has("recommendations")) { return false; } - } catch (ParserConfigurationException | SAXException e) { + } catch (JSONException ex) { return false; } return true; @@ -74,18 +61,18 @@ public String getName() { @Override public StandardFileType getFileType() { - return StandardFileType.XML; + return StandardFileType.JSON; } @Override public String getDescription() { - return "Takes valid xml documents. Parses from MrDLib API a BibEntry"; + return "Takes valid JSON documents from the Mr. DLib API and parses them into a BibEntry"; } /** - * The SaxParser needs this String. So I convert it here. - * @param Takes a BufferedReader with a reference to the XML document delivered by mdl server. - * @return Returns an String containing the XML file. + * Convert Buffered Reader response to string for JSON parsing. + * @param input Takes a BufferedReader with a reference to the JSON document delivered by mdl server. + * @return Returns an String containing the JSON document. * @throws IOException */ private String convertToString(BufferedReader input) throws IOException { @@ -117,7 +104,7 @@ public RankedBibEntry(BibEntry entry, Integer rank) { /** * Parses the input from the server to a ParserResult - * @param input A BufferedReader with a reference to a string with the servers response + * @param input A BufferedReader with a reference to a string with the server's response * @throws IOException */ private void parse(BufferedReader input) throws IOException { @@ -126,133 +113,95 @@ private void parse(BufferedReader input) throws IOException { // The document to parse String recommendations = convertToString(input); // The sorted BibEntries gets stored here later - List bibEntries = new ArrayList<>(); - //Parsing the response with a SAX parser - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - SAXParser saxParser = factory.newSAXParser(); - MrDlibImporterHandler handler = new MrDlibImporterHandler(); - try (InputStream stream = new ByteArrayInputStream(recommendations.getBytes())) { - saxParser.parse(stream, handler); - } catch (SAXException e) { - LOGGER.error(e.getMessage(), e); - } - List rankedBibEntries = handler.getRankedBibEntries(); - rankedBibEntries.sort((RankedBibEntry rankedBibEntry1, - RankedBibEntry rankedBibEntry2) -> rankedBibEntry1.rank.compareTo(rankedBibEntry2.rank)); - bibEntries = rankedBibEntries.stream().map(e -> e.entry).collect(Collectors.toList()); - } catch (ParserConfigurationException | SAXException e) { - LOGGER.error(e.getMessage(), e); + List rankedBibEntries = new ArrayList<>(); + + // Get recommendations from response and populate bib entries + JSONObject recommendationsJson = new JSONObject(recommendations).getJSONObject("recommendations"); + Iterator keys = recommendationsJson.keys(); + while (keys.hasNext()) { + String key = keys.next(); + JSONObject value = recommendationsJson.getJSONObject(key); + rankedBibEntries.add(populateBibEntry(value)); } + // Sort bib entries according to rank + rankedBibEntries.sort((RankedBibEntry rankedBibEntry1, + RankedBibEntry rankedBibEntry2) -> rankedBibEntry1.rank.compareTo(rankedBibEntry2.rank)); + List bibEntries = rankedBibEntries.stream().map(e -> e.entry).collect(Collectors.toList()); + for (BibEntry bibentry : bibEntries) { bibDatabase.insertEntry(bibentry); } - parserResult = new ParserResult(bibDatabase); } - public ParserResult getParserResult() { - return parserResult; - } - /** - * Handler that parses the response from Mr. DLib to BibEntries + * Parses the JSON recommendations into bib entries + * @param recommendation JSON object of a single recommendation returned by Mr. DLib + * @return A ranked bib entry created from the recommendation input */ - private class MrDlibImporterHandler extends DefaultHandler { - - // The list ob BibEntries with its associated rank - private final List rankedBibEntries = new ArrayList<>(); - - private boolean authors; - private boolean published_in; - private boolean title; - private boolean year; - private boolean snippet; - private boolean rank; - private boolean type; - private String htmlSnippetSingle; - private int htmlSnippetSingleRank = -1; - private BibEntry currentEntry; - - public List getRankedBibEntries() { - return rankedBibEntries; - } + private RankedBibEntry populateBibEntry(JSONObject recommendation) { + BibEntry current = new BibEntry(); + + // parse each of the relevant fields into variables + String authors = isRecommendationFieldPresent(recommendation, "authors") ? getAuthorsString(recommendation) : ""; + String title = isRecommendationFieldPresent(recommendation, "title") ? recommendation.getString("title") : ""; + String year = isRecommendationFieldPresent(recommendation, "year_published") ? Integer.toString(recommendation.getInt("year_published")) : ""; + String journal = isRecommendationFieldPresent(recommendation, "published_in") ? recommendation.getString("published_in") : ""; + String url = isRecommendationFieldPresent(recommendation, "url") ? recommendation.getString("url") : ""; + Integer rank = isRecommendationFieldPresent(recommendation, "url") ? recommendation.getInt("recommendation_id") : 100; + + // Populate bib entry with relevant data + current.setField(FieldName.AUTHOR, authors); + current.setField(FieldName.TITLE, title); + current.setField(FieldName.YEAR, year); + current.setField(FieldName.JOURNAL, journal); + current.setField(FieldName.URL, url); + + return new RankedBibEntry(current, rank); + } - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) - throws SAXException { + private Boolean isRecommendationFieldPresent(JSONObject recommendation, String field) { + return recommendation.has(field) && !recommendation.isNull(field); + } - switch (qName.toLowerCase(Locale.ROOT)) { - case "related_article": - currentEntry = new BibEntry(); - htmlSnippetSingle = null; - htmlSnippetSingleRank = -1; - break; - case "authors": - authors = true; - break; - case "published_in": - published_in = true; - break; - case "title": - title = true; - break; - case "year": - year = true; - break; - case "type": - type = true; - break; - case "suggested_rank": - rank = true; - break; - default: - break; - } - if (qName.equalsIgnoreCase("snippet") - && attributes.getValue(0).equalsIgnoreCase("html_fully_formatted")) { - snippet = true; - } + /** + * Creates an authors string from a JSON recommendation + * @param recommendation JSON Object recommendation from Mr. DLib + * @return A string of all authors, separated by commas and finished with a full stop. + */ + private String getAuthorsString(JSONObject recommendation) { + String authorsString = ""; + JSONArray array = recommendation.getJSONArray("authors"); + for (int i = 0; i < array.length(); ++i) { + authorsString += array.getString(i) + "; "; } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - if (qName.equalsIgnoreCase("related_article")) { - rankedBibEntries.add(new RankedBibEntry(currentEntry, htmlSnippetSingleRank)); - currentEntry = new BibEntry(); - } + int stringLength = authorsString.length(); + if (stringLength > 2) { + authorsString = authorsString.substring(0, stringLength - 2) + "."; } + return authorsString; + } - @Override - public void characters(char ch[], int start, int length) throws SAXException { + public ParserResult getParserResult() { + return parserResult; + } - if (authors) { - currentEntry.setField(FieldName.AUTHOR, new String(ch, start, length)); - authors = false; - } - if (published_in) { - currentEntry.setField(FieldName.JOURNAL, new String(ch, start, length)); - published_in = false; - } - if (title) { - currentEntry.setField(FieldName.TITLE, new String(ch, start, length)); - title = false; - } - if (year) { - currentEntry.setField(FieldName.YEAR, new String(ch, start, length)); - year = false; - } - if (rank) { - htmlSnippetSingleRank = Integer.parseInt(new String(ch, start, length)); - rank = false; - } - if (snippet) { - currentEntry.setField("html_representation", new String(ch, start, length)); - snippet = false; + /** + * Gets the error message to be returned if there has been an error in returning recommendations. + * Returns default error message if there is no message from Mr. DLib. + * @param response The response from the MDL server as a string. + * @return String error message to be shown to the user. + */ + public String getResponseErrorMessage(String response) { + try { + JSONObject jsonObject = new JSONObject(response); + if (!jsonObject.has("message")) { + return jsonObject.getString("message"); } - + } catch (JSONException ex) { + return DEFAULT_MRDLIB_ERROR_MESSAGE; } - + return DEFAULT_MRDLIB_ERROR_MESSAGE; } } diff --git a/src/main/java/org/jabref/logic/util/StandardFileType.java b/src/main/java/org/jabref/logic/util/StandardFileType.java index 5eb21456754..db7766e9811 100644 --- a/src/main/java/org/jabref/logic/util/StandardFileType.java +++ b/src/main/java/org/jabref/logic/util/StandardFileType.java @@ -36,6 +36,7 @@ public enum StandardFileType implements FileType { RTF("rtf"), SXC("sxc"), XML("xml"), + JSON("json"), XMP("xmp"), ZIP("zip"); diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 79d0afc5a5f..a61c1762f99 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -303,6 +303,7 @@ public class JabRefPreferences implements PreferencesService { public static final String NAME_FORMATER_KEY = "nameFormatterNames"; public static final String PUSH_TO_APPLICATION = "pushToApplication"; public static final String SHOW_RECOMMENDATIONS = "showRecommendations"; + public static final String ACCEPT_RECOMMENDATIONS = "acceptRecommendations"; public static final String VALIDATE_IN_ENTRY_EDITOR = "validateInEntryEditor"; // Dropped file handler public static final String DROPPEDFILEHANDLER_RENAME = "DroppedFileHandler_RenameFile"; @@ -571,6 +572,7 @@ private JabRefPreferences() { defaults.put(MERGE_ENTRIES_DIFF_MODE, 2); defaults.put(SHOW_RECOMMENDATIONS, Boolean.TRUE); + defaults.put(ACCEPT_RECOMMENDATIONS, Boolean.FALSE); defaults.put(VALIDATE_IN_ENTRY_EDITOR, Boolean.TRUE); defaults.put(EDITOR_EMACS_KEYBINDINGS, Boolean.FALSE); defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CA, Boolean.TRUE); @@ -903,6 +905,7 @@ public EntryEditorPreferences getEntryEditorPreferences() { getImportFormatPreferences(), getCustomTabFieldNames(), getBoolean(SHOW_RECOMMENDATIONS), + getBoolean(ACCEPT_RECOMMENDATIONS), getBoolean(DEFAULT_SHOW_SOURCE), getBibtexKeyPatternPreferences(), Globals.getKeyPrefs(), diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 529922c4b94..aa3101e4371 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -31,9 +31,9 @@ Accept=Accept Accept\ change=Accept change -Action=Action +Accept\ recommendations\ from\ Mr.\ DLib=Accept recommendations from Mr. DLib -What\ is\ Mr.\ DLib?=What is Mr. DLib? +Action=Action Add=Add @@ -379,6 +379,8 @@ Error\ occurred\ when\ parsing\ entry=Error occurred when parsing entry Error\ opening\ file=Error opening file +Error\ while\ fetching\ from\ Mr.DLib.=Error while fetching from Mr.DLib. + Error\ while\ writing=Error while writing '%0'\ exists.\ Overwrite\ file?='%0' exists. Overwrite file? @@ -466,6 +468,8 @@ found\ in\ AUX\ file=found in AUX file Full\ name=Full name +Further\ information\ about\ Mr\ DLib.\ for\ JabRef\ users.=Further information about Mr DLib. for JabRef users. + General=General General\ Fields=General Fields @@ -560,6 +564,8 @@ Independent\ group\:\ When\ selected,\ view\ only\ this\ group's\ entries=Indepe Work\ options=Work options +I\ Agree=I Agree + Insert=Insert Insert\ rows=Insert rows @@ -656,6 +662,9 @@ Move\ up=Move up Moved\ group\ "%0".=Moved group "%0". +Mr.\ DLib\ is\ an\ external\ service\ which\ provides\ article\ recommendations\ based\ on\ the\ currently\ selected\ entry.\ Data\ about\ the\ selected\ entry\ must\ be\ sent\ to\ Mr.\ DLib\ in\ order\ to\ provide\ these\ recommendations.\ Do\ you\ agree\ that\ this\ data\ may\ be\ sent?=Mr. DLib is an external service which provides article recommendations based on the currently selected entry. Data about the selected entry must be sent to Mr. DLib in order to provide these recommendations. Do you agree that this data may be sent? + + Name=Name Name\ formatter=Name formatter @@ -786,6 +795,8 @@ Please\ enter\ the\ string's\ label=Please enter the string's label Please\ select\ an\ importer.=Please select an importer. +Please\ restart\ JabRef\ for\ preferences\ to\ take\ effect.=Please restart JabRef for preferences to take effect. + Possible\ duplicate\ entries=Possible duplicate entries Possible\ duplicate\ of\ existing\ entry.\ Click\ to\ resolve.=Possible duplicate of existing entry. Click to resolve. @@ -897,6 +908,9 @@ Resolve\ strings\ for\ all\ fields\ except=Resolve strings for all fields except Resolve\ strings\ for\ standard\ BibTeX\ fields\ only=Resolve strings for standard BibTeX fields only resolved=resolved + +Restart=Restart + Review=Review Review\ changes=Review changes Review\ Field\ Migration=Review Field Migration @@ -1063,6 +1077,8 @@ This\ operation\ requires\ all\ selected\ entries\ to\ have\ BibTeX\ keys\ defin This\ operation\ requires\ one\ or\ more\ entries\ to\ be\ selected.=This operation requires one or more entries to be selected. +This\ setting\ may\ be\ changed\ in\ preferences\ at\ any\ time.=This setting may be changed in preferences at any time. + Toggle\ entry\ preview=Toggle entry preview Toggle\ groups\ interface=Toggle groups interface diff --git a/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java index c35684edf48..357e50393fd 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java @@ -3,6 +3,7 @@ import java.util.List; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.util.Version; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; import org.jabref.testutils.category.FetcherTest; @@ -20,7 +21,7 @@ public class MrDLibFetcherTest { @BeforeEach public void setUp() { - fetcher = new MrDLibFetcher("", ""); + fetcher = new MrDLibFetcher("", Version.parse("")); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/MrDLibImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/MrDLibImporterTest.java index 7c2c1e5d837..5af07b4dfa3 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/MrDLibImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/MrDLibImporterTest.java @@ -19,23 +19,18 @@ public class MrDLibImporterTest { private MrDLibImporter importer; - private BufferedReader inputMin; - private BufferedReader inputMax; + private BufferedReader input; @BeforeEach public void setUp() { importer = new MrDLibImporter(); - - String testMin = ""; - String testMax = "https://api-dev.mr-dlib.org/v1/recommendations/204944/original_url?access_key=99ab2fc64f3228ab839e9e3525ac37f8&format=direct_url_forward02.02.033221.0http://sowiport.gesis.org/search/id/gesis-solis-00538797Fachhochschulverl.Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis. . Fachhochschulverl.. 2009.]]>Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis.. Fachhochschulverl.. 2009.]]>Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis. . Fachhochschulverl.. 2009]]>2Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis2009"; - testMax = testMax.replaceAll("&", ""); - inputMin = new BufferedReader(new StringReader(testMin)); - inputMax = new BufferedReader(new StringReader(testMax)); + String testInput = "{ \"label\": { \"label-language\": \"en\", \"label-text\": \"Related Items\" }, \"recommendation-set-id\": \"1\", \"recommendations\": { \"74021358\": { \"abstract\": \"abstract\", \"authors\": [ \"Sajovic, Marija\" ], \"year_published\": \"2006\", \"item_id_original\": \"12088644\", \"keywords\": [ \"visoko\\u0161olski program Geodezija - smer Prostorska informatika\" ], \"language_provided\": \"sl\", \"recommendation_id\": \"1\", \"title\": \"The protection of rural lands with the spatial development strategy on the case of Hrastnik commune\", \"url\": \"http://drugg.fgg.uni-lj.si/701/1/GEV_0199_Sajovic.pdf\" }, \"82005804\": { \"abstract\": \"abstract\", \"year_published\": null, \"item_id_original\": \"30145702\", \"language_provided\": null, \"recommendation_id\": \"2\", \"title\": \"Engagement of the volunteers in the solution to the accidents in the South-Moravia region\" }, \"82149599\": { \"abstract\": \"abstract\", \"year_published\": null, \"item_id_original\": \"97690763\", \"language_provided\": null, \"recommendation_id\": \"3\", \"title\": \"\\\"The only Father's word\\\". The relationship of the Father and the Son in the documents of saint John of the Cross\", \"url\": \"http://www.nusl.cz/ntk/nusl-285711\" }, \"84863921\": { \"abstract\": \"abstract\", \"authors\": [ \"Kaffa, Elena\" ], \"year_published\": null, \"item_id_original\": \"19397104\", \"keywords\": [ \"BX\", \"D111\" ], \"language_provided\": \"en\", \"recommendation_id\": \"4\", \"title\": \"Greek Church of Cyprus, the Morea and Constantinople during the Frankish Era (1196-1303)\" }, \"88950992\": { \"abstract\": \"abstract\", \"authors\": [ \"Yasui, Kono\" ], \"year_published\": null, \"item_id_original\": \"38763657\", \"language_provided\": null, \"recommendation_id\": \"5\", \"title\": \"A Phylogenetic Consideration on the Vascular Plants, Cotyledonary Node Including Hypocotyl Being Taken as the Ancestral Form : A Preliminary Note\" } }}"; + input = new BufferedReader(new StringReader(testInput)); } @Test public void testGetDescription() { - assertEquals("Takes valid xml documents. Parses from MrDLib API a BibEntry", importer.getDescription()); + assertEquals("Takes valid JSON documents from the Mr. DLib API and parses them into a BibEntry", importer.getDescription()); } @Test @@ -45,46 +40,35 @@ public void testGetName() { @Test public void testGetFileExtention() { - assertEquals(StandardFileType.XML, importer.getFileType()); - } - - @Test - public void testImportDatabaseIsHtmlSetCorrectly() throws IOException { - ParserResult parserResult = importer.importDatabase(inputMax); - - List resultList = parserResult.getDatabase().getEntries(); - - assertEquals( - "Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis.. Fachhochschulverl.. 2009.", - resultList.get(0).getField("html_representation").get()); + assertEquals(StandardFileType.JSON, importer.getFileType()); } @Test public void testImportDatabaseIsYearSetCorrectly() throws IOException { - ParserResult parserResult = importer.importDatabase(inputMax); + ParserResult parserResult = importer.importDatabase(input); List resultList = parserResult.getDatabase().getEntries(); - assertEquals("2009", + assertEquals("2006", resultList.get(0).getLatexFreeField(FieldName.YEAR).get()); } @Test public void testImportDatabaseIsTitleSetCorrectly() throws IOException { - ParserResult parserResult = importer.importDatabase(inputMax); + ParserResult parserResult = importer.importDatabase(input); List resultList = parserResult.getDatabase().getEntries(); - assertEquals("Gesundheit von Arbeitslosen fördern!: ein Handbuch für Wissenschaft und Praxis", + assertEquals("The protection of rural lands with the spatial development strategy on the case of Hrastnik commune", resultList.get(0).getLatexFreeField(FieldName.TITLE).get()); } @Test public void testImportDatabaseMin() throws IOException { - ParserResult parserResult = importer.importDatabase(inputMin); + ParserResult parserResult = importer.importDatabase(input); List resultList = parserResult.getDatabase().getEntries(); - assertSame(0, resultList.size()); + assertSame(5, resultList.size()); } } From cf7b31c47f96e2177112bfde9fd3f90b0f01402b Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Fri, 26 Oct 2018 10:21:22 +0200 Subject: [PATCH 20/30] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000000..32a3c7f37fb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + + + +JabRef version on + +- [ ] I have tested the latest development version from http://builds.jabref.org/master/ and the problem persists + + + +Steps to reproduce the behavior: +1. ... +2. ... +3. ... + + + +
    + Log File + + ``` + Paste an excerpt of your log file here + ``` +
    From 2783caf5249b3da65e79e317e4c4389e79f74aa7 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Fri, 26 Oct 2018 10:22:11 +0200 Subject: [PATCH 21/30] Delete ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 26 -------------------------- 1 file changed, 26 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 1426417c5bf..00000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,26 +0,0 @@ - - -- [ ] I have tested the latest master version from http://builds.jabref.org/master/ and the problem persists - - -JabRef version on - - - -Steps to reproduce: - -1. ... -2. ... -3. ... - - - -
    - Log File - - ``` - Paste an excerpt of your log file here - ``` -
    From 3d8570bb7ac854f6feaeb58eab26cd1cb285bb1c Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Fri, 26 Oct 2018 10:27:00 +0200 Subject: [PATCH 22/30] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 9 +++++++++ .github/ISSUE_TEMPLATE/question.md | 9 +++++++++ .../suggestion-for-improvement.md | 20 +++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/question.md create mode 100644 .github/ISSUE_TEMPLATE/suggestion-for-improvement.md diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000000..d2ae96c562d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,9 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +Please use the GitHub issue tracker only for bug reports and suggestions for improvements. +Feature requests, questions and general feedback is now handled at http://discourse.jabref.org. +Thanks! diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000000..7e9c25fe4b4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,9 @@ +--- +name: Question +about: Ask a question about JabRef + +--- + +Please use the GitHub issue tracker only for bug reports and suggestions for improvements. +Feature requests, questions and general feedback is now handled at http://discourse.jabref.org. +Thanks! diff --git a/.github/ISSUE_TEMPLATE/suggestion-for-improvement.md b/.github/ISSUE_TEMPLATE/suggestion-for-improvement.md new file mode 100644 index 00000000000..ec6d48cc1dc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/suggestion-for-improvement.md @@ -0,0 +1,20 @@ +--- +name: Suggestion for improvement +about: Suggest an enhancement + +--- + + + +**Is your suggestion for improvement related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Additional context** +Add any other context or screenshots about the feature request here. From d65ca33af4c6adf85d7aac9d77bc93d59a1fefd6 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Fri, 26 Oct 2018 16:23:31 +0200 Subject: [PATCH 23/30] Fix display of radio buttons (#4411) Previously, unchecked radio buttons were not displayed. --- src/main/java/org/jabref/gui/Base.css | 22 +++- .../org/jabref/styletester/StyleTester.fxml | 119 +++++++++++------- 2 files changed, 96 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/gui/Base.css b/src/main/java/org/jabref/gui/Base.css index a8644b5c180..ed4bbd29f96 100644 --- a/src/main/java/org/jabref/gui/Base.css +++ b/src/main/java/org/jabref/gui/Base.css @@ -391,12 +391,32 @@ } .check-box > .box > .mark { - -fx-background-color: white; + -fx-background-color: -fx-control-inner-background; -fx-padding: 0.2em 0.2em 0.2em 0.2em; -fx-shape: "M6.61 11.89L3.5 8.78 2.44 9.84 6.61 14l8.95-8.95L14.5 4z"; -fx-stroke-width: 5; } +.radio-button > .radio { + -fx-background-radius: 1.0em; /* large value to make sure this remains circular */ + -fx-padding: 0.35em; /* padding from outside edge to the inner dot */ + -fx-background-color: rgba(0, 0, 0, 0.54), -fx-control-inner-background; + -fx-background-insets: 0, 2px; +} + +.radio-button:selected > .radio { + -fx-background-color: -jr-checked, -fx-background; +} + +.radio-button > .radio > .dot { + -fx-padding: 0.25em; /* radius of the inner dot when selected */ + -fx-background-insets: 0; +} + +.radio-button:selected > .radio > .dot { + -fx-background-color: -jr-checked; +} + .menu-bar { -fx-background-color: -jr-menu-background; -fx-background-insets: 0; diff --git a/src/main/java/org/jabref/styletester/StyleTester.fxml b/src/main/java/org/jabref/styletester/StyleTester.fxml index 8ace521ed71..6eaf7bae249 100644 --- a/src/main/java/org/jabref/styletester/StyleTester.fxml +++ b/src/main/java/org/jabref/styletester/StyleTester.fxml @@ -28,147 +28,178 @@ + + - + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - + From e7a65c771de515e184616199082e5bb1f6d69abe Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Fri, 26 Oct 2018 16:29:19 +0200 Subject: [PATCH 24/30] Add a few journal abbreviations (#4412) --- src/main/resources/journals/journalList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/resources/journals/journalList.txt b/src/main/resources/journals/journalList.txt index 3d019b4bfa6..cdb5e36ab78 100644 --- a/src/main/resources/journals/journalList.txt +++ b/src/main/resources/journals/journalList.txt @@ -3544,6 +3544,7 @@ Communication and Medicine = Commun. Med. Communications in Agricultural and Applied Biological Sciences = Commun. Agric. Appl. Biol. Sci. Communications in Behavioral Biology. Part A, Original Articles = Commun. Behav. Biol. Communications in Computational Physics = Comm. Comput. Phys. +Communications in Contemporary Mathematics = Commun. Contemp. Math. Communications in Mathematical PHysics = Commun. Math. Phys. Communications in Nonlinear Science and Numerical Simulation = Commun. Nonlinear Sci. Numer. Simul. Communications in Numerical Methods in Engineering = Commun. Numer. Methods Eng. @@ -7986,6 +7987,7 @@ Journal of Geographical Sciences = J. Geog. Sci. Journal of Geological Education = J. Geol. Educ. Journal of Geology = J. Geol. Journal of Geomagnetism and Geoelectricity = J. Geomagn. Geoelec. +Journal of Geometric Mechanics = J. Geom. Mech. Journal of Geometry and Physics = J. Geom. Phys. Journal of Geophysical Research = J. Geophys. Res. Journal of Geophysical Research, [Atmospheres] = J. Geophys. Res. Atmos. From 940fa2ce3f5579d65b503d4d294f832be5c9d2a9 Mon Sep 17 00:00:00 2001 From: Fancy Zhang Date: Fri, 26 Oct 2018 22:34:36 +0800 Subject: [PATCH 25/30] fixed an issue where corresponding groups are sometimes not highlighted when clicking on entries (#4404) * fixed an issue where corresponding groups are sometimes not highlighted when clicking on entries : the cause of this bug is that the local variable "pseudoClassState" is garbaged by java gc. there is no reference to this variable except an weak one from "bind" function. * Remove unused imports * Update BindingsHelper.java --- CHANGELOG.md | 1 + .../org/jabref/gui/util/BindingsHelper.java | 20 +------------------ 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d32677a43e..91a47bb024c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# ### Fixed +- We fixed an issue where corresponding groups are sometimes not highlighted when clicking on entries [#3112](https://github.com/JabRef/jabref/issues/3112) - We fixed an issue where custom exports could not be selected in the 'Export (selected) entries' dialog [#4013](https://github.com/JabRef/jabref/issues/4013) - Italic text is now rendered correctly. https://github.com/JabRef/jabref/issues/3356 - The entry editor no longer gets corrupted after using the source tab. https://github.com/JabRef/jabref/issues/3532 https://github.com/JabRef/jabref/issues/3608 https://github.com/JabRef/jabref/issues/3616 diff --git a/src/main/java/org/jabref/gui/util/BindingsHelper.java b/src/main/java/org/jabref/gui/util/BindingsHelper.java index 8ae0b7be563..162fb210065 100644 --- a/src/main/java/org/jabref/gui/util/BindingsHelper.java +++ b/src/main/java/org/jabref/gui/util/BindingsHelper.java @@ -9,8 +9,6 @@ import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.StringBinding; -import javafx.beans.property.BooleanProperty; -import javafx.beans.property.BooleanPropertyBase; import javafx.beans.property.ListProperty; import javafx.beans.property.Property; import javafx.beans.value.ChangeListener; @@ -44,23 +42,7 @@ public static BooleanBinding all(ObservableList source, Predicate pred } public static void includePseudoClassWhen(Node node, PseudoClass pseudoClass, ObservableValue condition) { - BooleanProperty pseudoClassState = new BooleanPropertyBase(false) { - @Override - protected void invalidated() { - node.pseudoClassStateChanged(pseudoClass, get()); - } - - @Override - public Object getBean() { - return node; - } - - @Override - public String getName() { - return pseudoClass.getPseudoClassName(); - } - }; - pseudoClassState.bind(condition); + condition.addListener((obs, oldValue, newValue) -> node.pseudoClassStateChanged(pseudoClass, newValue)); } /** From c3fe6818ffd1ba305a00eb10f755376c1cdc1ec2 Mon Sep 17 00:00:00 2001 From: Fancy Zhang Date: Sat, 27 Oct 2018 19:57:38 +0800 Subject: [PATCH 26/30] fix java.nio.file.FileSystemNotFoundException and reorganize code (#4416) --- .../java/org/jabref/gui/util/ThemeLoader.java | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/util/ThemeLoader.java b/src/main/java/org/jabref/gui/util/ThemeLoader.java index e9d9a7b40e8..9c4e84ce3f6 100644 --- a/src/main/java/org/jabref/gui/util/ThemeLoader.java +++ b/src/main/java/org/jabref/gui/util/ThemeLoader.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; @@ -11,7 +10,6 @@ import javafx.scene.Parent; import javafx.scene.Scene; -import org.jabref.JabRefException; import org.jabref.gui.JabRefFrame; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; @@ -39,21 +37,25 @@ public class ThemeLoader { public static final String DEFAULT_MAIN_CSS = "Base.css"; private static final String DEFAULT_PATH_MAIN_CSS = JabRefFrame.class.getResource(DEFAULT_MAIN_CSS).toExternalForm(); private static final Logger LOGGER = LoggerFactory.getLogger(ThemeLoader.class); - private String cssProperty = System.getProperty("jabref.theme.css"); + private String cssToLoad = System.getProperty("jabref.theme.css"); private final FileUpdateMonitor fileUpdateMonitor; - public ThemeLoader(FileUpdateMonitor fileUpdateMonitor, JabRefPreferences jabRefPreferences) throws JabRefException { + public ThemeLoader(FileUpdateMonitor fileUpdateMonitor, JabRefPreferences jabRefPreferences) { this.fileUpdateMonitor = Objects.requireNonNull(fileUpdateMonitor); - if (StringUtil.isNullOrEmpty(cssProperty)) { - String cssFileName = jabRefPreferences.get(JabRefPreferences.FX_THEME); - if (cssFileName != null) { - try { - cssProperty = Paths.get(JabRefFrame.class.getResource(cssFileName).toURI()).toString(); - } catch (URISyntaxException e) { - LOGGER.warn("can't get css file URI"); - throw new JabRefException("can't set custom theme"); - } + if (!StringUtil.isNullOrEmpty(cssToLoad)) { + LOGGER.info("using css from system " + cssToLoad); + return; + } + + // otherwise load css from preference + String cssFileName = jabRefPreferences.get(JabRefPreferences.FX_THEME); + if (cssFileName != null) { + try { + cssToLoad = JabRefFrame.class.getResource(cssFileName).toExternalForm(); + LOGGER.info("using css " + cssToLoad); + } catch (Exception e) { + LOGGER.warn("can't get css file path of " + cssFileName); } } } @@ -64,15 +66,10 @@ public ThemeLoader(FileUpdateMonitor fileUpdateMonitor, JabRefPreferences jabRef * Changes in the css file lead to a redraw of the scene using the new css file. */ public void installBaseCss(Scene scene, JabRefPreferences preferences) { - if (StringUtil.isNotBlank(cssProperty)) { - final Path path = Paths.get(cssProperty); - if (Files.isReadable(path)) { - String cssUrl = path.toUri().toString(); - addAndWatchForChanges(scene, cssUrl, 0); - } else { - LOGGER.warn(path.toAbsolutePath() + " is not readable"); - } + if (!StringUtil.isNullOrEmpty(cssToLoad)) { + addAndWatchForChanges(scene, cssToLoad, 0); } else { + LOGGER.warn("using the last default css " + DEFAULT_PATH_MAIN_CSS); addAndWatchForChanges(scene, DEFAULT_PATH_MAIN_CSS, 0); } @@ -88,7 +85,7 @@ private void addAndWatchForChanges(Scene scene, String cssUrl, int index) { try { // If -Djabref.theme.css is defined and the resources are not part of a .jar bundle, // we watch the file for changes and turn on live reloading - if (!cssUrl.startsWith("jar:") && cssProperty != null) { + if (!cssUrl.startsWith("jar:")) { Path cssFile = Paths.get(new URL(cssUrl).toURI()); LOGGER.info("Enabling live reloading of " + cssFile); fileUpdateMonitor.addListenerForFile(cssFile, () -> { From 72a73a6e1bc8a8206261a6c0e28ea4646ec7844b Mon Sep 17 00:00:00 2001 From: Christoph Date: Sat, 27 Oct 2018 15:28:51 +0200 Subject: [PATCH 27/30] Update README.md Remove obsolete integration test description. Add a note on travis --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 5cd2607dbc4..e4a60dc95da 100644 --- a/README.md +++ b/README.md @@ -101,9 +101,7 @@ When you want to develop, it is necessary to generate additional sources using ` and then generate the Eclipse `gradlew eclipse`. For IntelliJ IDEA, just import the project via a Gradle Import by pointing at the `build.gradle`. -`gradlew test` executes the normal unit tests. -If you want to test the UI, execute `gradlew integrationTest`. -Sources for the integration test are kept in `src/integrationTest`. +`gradlew test` executes all tests. We use Travis CI[https://travis-ci.org/] for executing the tests after each commit. For developing it is sufficient to locally only run the associated test for the classes you changed. Travis will report any other failure. ## Acknowledgements From f5a8f00a892f46ee6f3c8e5cbccdec9d1f36dba7 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Sat, 27 Oct 2018 15:36:07 +0200 Subject: [PATCH 28/30] Fix group hit counter when adding entries (#4413) Fixes #3537 by replacing the EventBus subscription by a JavaFX listener. --- CHANGELOG.md | 1 + .../org/jabref/gui/groups/GroupNodeViewModel.java | 12 +++++------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a47bb024c..9848a45705f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We fixed an issue where the order of fields in customized entry types was not saved correctly. [#4033](http://github.com/JabRef/jabref/issues/4033) - We fixed an issue where the groups tree of the last database was still shown even after the database was already closed. - We fixed an issue where the "Open file dialog" may disappear behind other windows. https://github.com/JabRef/jabref/issues/3410 +- We fixed an issue where the number of entries matched was not updated correctly upon adding or removing an entry. [#3537](https://github.com/JabRef/jabref/issues/3537) - We fixed an issue where the default icon of a group was not colored correctly. - We fixed an issue where the first field in entry editor was not focused when adding a new entry. [#4024](https://github.com/JabRef/jabref/issues/4024) - We reworked the "Edit file" dialog to make it resizeable and improved the workflow for adding and editing files https://github.com/JabRef/jabref/issues/2970 diff --git a/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java b/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java index 2699df22cb6..12abad57d6c 100644 --- a/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java +++ b/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java @@ -11,6 +11,7 @@ import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.FXCollections; +import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.input.Dragboard; import javafx.scene.paint.Color; @@ -29,7 +30,6 @@ import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.event.EntryEvent; import org.jabref.model.groups.AbstractGroup; import org.jabref.model.groups.AutomaticGroup; import org.jabref.model.groups.GroupEntryChanger; @@ -37,7 +37,6 @@ import org.jabref.model.strings.StringUtil; import com.google.common.base.Enums; -import com.google.common.eventbus.Subscribe; import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon; import org.fxmisc.easybind.EasyBind; @@ -85,7 +84,7 @@ public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager state expandedProperty.addListener((observable, oldValue, newValue) -> groupNode.getGroup().setExpanded(newValue)); // Register listener - databaseContext.getDatabase().registerListener(this); + databaseContext.getDatabase().getEntries().addListener(this::onDatabaseChanged); ObservableList selectedEntriesMatchStatus = EasyBind.map(stateManager.getSelectedEntries(), groupNode::matches); anySelectedEntriesMatched = BindingsHelper.any(selectedEntriesMatchStatus, matched -> matched); @@ -212,10 +211,9 @@ public GroupTreeNode getGroupNode() { } /** - * Gets invoked if an entry in the current database changes. - */ - @Subscribe - public void listen(@SuppressWarnings("unused") EntryEvent entryEvent) { + * Gets invoked if an entry in the current database changes. + */ + private void onDatabaseChanged(ListChangeListener.Change change) { calculateNumberOfMatches(); } From b09973f86c4033304135ac422583371db18367fe Mon Sep 17 00:00:00 2001 From: Christoph Date: Sat, 27 Oct 2018 16:00:13 +0200 Subject: [PATCH 29/30] Fix generate bibtex key overwrite warning dialog (#4418) * Fix generate bibtex key overwrite warning dialog Fixes #4417 * split up confirm of overwrite and generate keys put only generate action in background task * fix checkstyle --- .../gui/actions/GenerateBibtexKeyAction.java | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/actions/GenerateBibtexKeyAction.java b/src/main/java/org/jabref/gui/actions/GenerateBibtexKeyAction.java index 5fa5eb5e76c..90b61800215 100644 --- a/src/main/java/org/jabref/gui/actions/GenerateBibtexKeyAction.java +++ b/src/main/java/org/jabref/gui/actions/GenerateBibtexKeyAction.java @@ -14,8 +14,9 @@ import org.jabref.preferences.JabRefPreferences; public class GenerateBibtexKeyAction implements BaseAction { + private final DialogService dialogService; - private BasePanel basePanel; + private final BasePanel basePanel; private List entries; private boolean isCanceled; @@ -29,7 +30,7 @@ public void init() { if (entries.isEmpty()) { dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate BibTeX keys"), - Localization.lang("First select the entries you want keys to be generated for.")); + Localization.lang("First select the entries you want keys to be generated for.")); return; } basePanel.output(formatOutputMessage(Localization.lang("Generating BibTeX key for"), entries.size())); @@ -38,19 +39,20 @@ public void init() { public static boolean confirmOverwriteKeys(DialogService dialogService) { if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) { return dialogService.showConfirmationDialogWithOptOutAndWait( - Localization.lang("Overwrite keys"), - Localization.lang("One or more keys will be overwritten. Continue?"), - Localization.lang("Overwrite keys"), - Localization.lang("Cancel"), - Localization.lang("Disable this confirmation dialog"), - optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !optOut)); + Localization.lang("Overwrite keys"), + Localization.lang("One or more keys will be overwritten. Continue?"), + Localization.lang("Overwrite keys"), + Localization.lang("Cancel"), + Localization.lang("Disable this confirmation dialog"), + optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !optOut)); + } else { // Always overwrite keys by default return true; } } - private void generateKeys() { + private void checkOverwriteKeysChosen() { // We don't want to generate keys for entries which already have one thus remove the entries if (Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) { entries.removeIf(BibEntry::hasCiteKey); @@ -64,7 +66,12 @@ private void generateKeys() { return; } } + } + private void generateKeys() { + if (isCanceled) { + return; + } // generate the new cite keys for each entry final NamedCompound compound = new NamedCompound(Localization.lang("Autogenerate BibTeX keys")); BibtexKeyGenerator keyGenerator = new BibtexKeyGenerator(basePanel.getBibDatabaseContext(), Globals.prefs.getBibtexKeyPatternPreferences()); @@ -79,21 +86,19 @@ private void generateKeys() { basePanel.getUndoManager().addEdit(compound); } - if (isCanceled) { - return; - } basePanel.markBaseChanged(); basePanel.output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), entries.size())); } private String formatOutputMessage(String start, int count) { return String.format("%s %d %s.", start, count, - (count > 1 ? Localization.lang("entries") : Localization.lang("entry"))); + (count > 1 ? Localization.lang("entries") : Localization.lang("entry"))); } @Override public void action() { init(); + checkOverwriteKeysChosen(); BackgroundTask.wrap(this::generateKeys) .executeWith(Globals.TASK_EXECUTOR); } From aeea80969859b219d93c056d6f7284ae032bc997 Mon Sep 17 00:00:00 2001 From: Christoph Date: Sat, 27 Oct 2018 16:17:21 +0200 Subject: [PATCH 30/30] Update README.md (#4419) * Update README.md Remove obsolete integration test description. Add a note on travis * Fix travis link * Update README.md Missing comma --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e4a60dc95da..cec54b33f74 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ When you want to develop, it is necessary to generate additional sources using ` and then generate the Eclipse `gradlew eclipse`. For IntelliJ IDEA, just import the project via a Gradle Import by pointing at the `build.gradle`. -`gradlew test` executes all tests. We use Travis CI[https://travis-ci.org/] for executing the tests after each commit. For developing it is sufficient to locally only run the associated test for the classes you changed. Travis will report any other failure. +`gradlew test` executes all tests. We use [Travis CI](https://travis-ci.org/) for executing the tests after each commit. For developing, it is sufficient to locally only run the associated test for the classes you changed. Travis will report any other failure. ## Acknowledgements