From bf784456d6ef73ccfadf12d3fcc13efc04d38ef1 Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Mon, 21 Sep 2020 10:15:38 +0200 Subject: [PATCH 1/6] Fixes #6863 --- .../java/org/jabref/model/database/BibDatabaseContext.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/database/BibDatabaseContext.java b/src/main/java/org/jabref/model/database/BibDatabaseContext.java index 9c3c76ff593..a1ad8552b66 100644 --- a/src/main/java/org/jabref/model/database/BibDatabaseContext.java +++ b/src/main/java/org/jabref/model/database/BibDatabaseContext.java @@ -136,7 +136,6 @@ public List getFileDirectoriesAsPaths(FilePreferences preferences) { // 4. BIB file directory getDatabasePath().ifPresent(dbPath -> { - Objects.requireNonNull(dbPath, "dbPath is null"); Path parentPath = dbPath.getParent(); if (parentPath == null) { parentPath = Path.of(System.getProperty("user.dir")); @@ -146,6 +145,8 @@ public List getFileDirectoriesAsPaths(FilePreferences preferences) { // Check if we should add it as primary file dir (first in the list) or not: if (preferences.isBibLocationAsPrimary()) { fileDirs.add(0, parentPath); + } else { + fileDirs.add(parentPath); } }); From cd01dc5dcb48e3dc5dd0b58311db082fa9e9cb61 Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Mon, 21 Sep 2020 10:36:16 +0200 Subject: [PATCH 2/6] CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4629e113f0a..7449580429b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ Note that this project **does not** adhere to [Semantic Versioning](http://semve - We fixed an issue changing the icon link_variation_off that is not meaningful. [#6834][https://github.com/JabRef/jabref/issues/6834] - We fixed an issue where the `.sav` file was not deleted upon exiting JabRef. [#6109](https://github.com/JabRef/jabref/issues/6109) +- We fixed an issue about JabRef not looking for attached files to bib entries in the bib directory, if not set as primary. [#6863](https://github.com/JabRef/jabref/issues/6863) - We fixed a linked identifier icon inconsistency. [#6705](https://github.com/JabRef/jabref/issues/6705) - We fixed the wrong behavior that font size changes are not reflected in dialogs. [#6039](https://github.com/JabRef/jabref/issues/6039) - We fixed an issue where the sort order of the entry table was reset after a restart of JabRef. [#6898](https://github.com/JabRef/jabref/pull/6898) From 87caea85de935515fd3b522d54f454e47a9a23be Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Wed, 23 Sep 2020 22:01:34 +0200 Subject: [PATCH 3/6] Reworded bibLocationAsPrimary to reflect real meaning of the preference setting, changed default val to true --- CHANGELOG.md | 2 +- .../preferences/LinkedFilesTabViewModel.java | 2 +- .../model/database/BibDatabaseContext.java | 22 ++++++++----------- .../jabref/preferences/FilePreferences.java | 10 ++++----- .../jabref/preferences/JabRefPreferences.java | 9 ++++---- .../AutoSetFileLinksUtilTest.java | 2 +- .../logic/cleanup/CleanupWorkerTest.java | 4 ++-- .../logic/cleanup/MoveFilesCleanupTest.java | 2 +- .../logic/cleanup/RenamePdfCleanupTest.java | 2 +- .../logic/integrity/IntegrityCheckTest.java | 2 +- .../database/BibDatabaseContextTest.java | 2 +- 11 files changed, 28 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7449580429b..9cd547cc8a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,13 +26,13 @@ Note that this project **does not** adhere to [Semantic Versioning](http://semve - We completed the rebranding of `bibtexkey` as `citationkey` which was started in JabRef 5.1. - JabRef no longer opens the entry editor with the first entry on startup [#6855](https://github.com/JabRef/jabref/issues/6855) - Fetch by ID: (long) "SAO/NASA Astrophysics Data System" replaced by (short) "SAO/NASA ADS" [#6876](https://github.com/JabRef/jabref/pull/6876) +- We changed the default preference option "Search and store files relative to library file location" to on, as this seems to be a more intuitive behaviour. [#6863](https://github.com/JabRef/jabref/issues/6863) - We changed the title of the window "Manage field names and content": to have the same title as the corresponding menu item [#6895](https://github.com/JabRef/jabref/pull/6895) ### Fixed - We fixed an issue changing the icon link_variation_off that is not meaningful. [#6834][https://github.com/JabRef/jabref/issues/6834] - We fixed an issue where the `.sav` file was not deleted upon exiting JabRef. [#6109](https://github.com/JabRef/jabref/issues/6109) -- We fixed an issue about JabRef not looking for attached files to bib entries in the bib directory, if not set as primary. [#6863](https://github.com/JabRef/jabref/issues/6863) - We fixed a linked identifier icon inconsistency. [#6705](https://github.com/JabRef/jabref/issues/6705) - We fixed the wrong behavior that font size changes are not reflected in dialogs. [#6039](https://github.com/JabRef/jabref/issues/6039) - We fixed an issue where the sort order of the entry table was reset after a restart of JabRef. [#6898](https://github.com/JabRef/jabref/pull/6898) diff --git a/src/main/java/org/jabref/gui/preferences/LinkedFilesTabViewModel.java b/src/main/java/org/jabref/gui/preferences/LinkedFilesTabViewModel.java index 66539b9f197..bd9da257c12 100644 --- a/src/main/java/org/jabref/gui/preferences/LinkedFilesTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/LinkedFilesTabViewModel.java @@ -73,7 +73,7 @@ public LinkedFilesTabViewModel(DialogService dialogService, PreferencesService p public void setValues() { // External files preferences / Attached files preferences / File preferences mainFileDirectoryProperty.setValue(initialFilePreferences.getFileDirectory().orElse(Path.of("")).toString()); - useBibLocationAsPrimaryProperty.setValue(initialFilePreferences.isBibLocationAsPrimary()); + useBibLocationAsPrimaryProperty.setValue(initialFilePreferences.shouldStoreFilesRelativeToBib()); searchFilesOnOpenProperty.setValue(initialFilePreferences.shouldSearchFilesOnOpen()); openBrowseOnCreateProperty.setValue(initialFilePreferences.shouldOpenBrowseOnCreate()); fileNamePatternProperty.setValue(initialFilePreferences.getFileNamePattern()); diff --git a/src/main/java/org/jabref/model/database/BibDatabaseContext.java b/src/main/java/org/jabref/model/database/BibDatabaseContext.java index a1ad8552b66..7e09b3ca809 100644 --- a/src/main/java/org/jabref/model/database/BibDatabaseContext.java +++ b/src/main/java/org/jabref/model/database/BibDatabaseContext.java @@ -135,20 +135,16 @@ public List getFileDirectoriesAsPaths(FilePreferences preferences) { preferences.getFileDirectory().ifPresent(fileDirs::add); // 4. BIB file directory - getDatabasePath().ifPresent(dbPath -> { - Path parentPath = dbPath.getParent(); - if (parentPath == null) { - parentPath = Path.of(System.getProperty("user.dir")); - } - Objects.requireNonNull(parentPath, "BibTeX database parent path is null"); - - // Check if we should add it as primary file dir (first in the list) or not: - if (preferences.isBibLocationAsPrimary()) { + if (preferences.shouldStoreFilesRelativeToBib()) { + getDatabasePath().ifPresent(dbPath -> { + Path parentPath = dbPath.getParent(); + if (parentPath == null) { + parentPath = Path.of(System.getProperty("user.dir")); + } + Objects.requireNonNull(parentPath, "BibTeX database parent path is null"); fileDirs.add(0, parentPath); - } else { - fileDirs.add(parentPath); - } - }); + }); + } return fileDirs.stream().map(Path::toAbsolutePath).collect(Collectors.toList()); } diff --git a/src/main/java/org/jabref/preferences/FilePreferences.java b/src/main/java/org/jabref/preferences/FilePreferences.java index ebed675c1a0..28ca322e925 100644 --- a/src/main/java/org/jabref/preferences/FilePreferences.java +++ b/src/main/java/org/jabref/preferences/FilePreferences.java @@ -11,7 +11,7 @@ public class FilePreferences { private final String user; private final String mainFileDirectory; - private final boolean bibLocationAsPrimary; + private final boolean shouldStoreFilesRelativeToBibFile; private final String fileNamePattern; private final String fileDirPattern; private boolean shouldDownloadLinkedFiles; @@ -20,7 +20,7 @@ public class FilePreferences { public FilePreferences(String user, String mainFileDirectory, - boolean bibLocationAsPrimary, + boolean shouldStoreFilesRelativeToBibFile, String fileNamePattern, String fileDirPattern, boolean shouldDownloadLinkedFiles, @@ -28,7 +28,7 @@ public FilePreferences(String user, boolean shouldOpenBrowseOnCreate) { this.user = user; this.mainFileDirectory = mainFileDirectory; - this.bibLocationAsPrimary = bibLocationAsPrimary; + this.shouldStoreFilesRelativeToBibFile = shouldStoreFilesRelativeToBibFile; this.fileNamePattern = fileNamePattern; this.fileDirPattern = fileDirPattern; this.shouldDownloadLinkedFiles = shouldDownloadLinkedFiles; @@ -48,8 +48,8 @@ public Optional getFileDirectory() { } } - public boolean isBibLocationAsPrimary() { - return bibLocationAsPrimary; + public boolean shouldStoreFilesRelativeToBib() { + return shouldStoreFilesRelativeToBibFile; } public String getFileNamePattern() { diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index aea16342d76..01c116cc193 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -240,7 +240,8 @@ public class JabRefPreferences implements PreferencesService { public static final String RUN_AUTOMATIC_FILE_SEARCH = "runAutomaticFileSearch"; public static final String AUTOLINK_REG_EXP_SEARCH_EXPRESSION_KEY = "regExpSearchExpression"; public static final String AUTOLINK_USE_REG_EXP_SEARCH_KEY = "useRegExpSearch"; - public static final String BIB_LOC_AS_PRIMARY_DIR = "bibLocAsPrimaryDir"; + // bibLocAsPrimaryDir is a misleading antique variable name, we keep it for reason of compatibility + public static final String STORE_RELATIVE_TO_BIB = "bibLocAsPrimaryDir"; public static final String SELECTED_FETCHER_INDEX = "selectedFetcherIndex"; public static final String WEB_SEARCH_VISIBLE = "webSearchVisible"; public static final String GROUP_SIDEPANE_VISIBLE = "groupSidepaneVisible"; @@ -622,7 +623,7 @@ private JabRefPreferences() { defaults.put(WEB_SEARCH_VISIBLE, Boolean.TRUE); defaults.put(GROUP_SIDEPANE_VISIBLE, Boolean.TRUE); defaults.put(SELECTED_FETCHER_INDEX, 0); - defaults.put(BIB_LOC_AS_PRIMARY_DIR, Boolean.FALSE); + defaults.put(STORE_RELATIVE_TO_BIB, Boolean.TRUE); defaults.put(DB_CONNECT_SERVER_TYPE, "MySQL"); defaults.put(DB_CONNECT_HOSTNAME, "localhost"); defaults.put(DB_CONNECT_DATABASE, "jabref"); @@ -2265,7 +2266,7 @@ public FilePreferences getFilePreferences() { return new FilePreferences( getUser(), get(MAIN_FILE_DIRECTORY), - getBoolean(BIB_LOC_AS_PRIMARY_DIR), + getBoolean(STORE_RELATIVE_TO_BIB), get(IMPORT_FILENAMEPATTERN), get(IMPORT_FILEDIRPATTERN), getBoolean(DOWNLOAD_LINKED_FILES), @@ -2276,7 +2277,7 @@ public FilePreferences getFilePreferences() { @Override public void storeFilePreferences(FilePreferences filePreferences) { put(MAIN_FILE_DIRECTORY, filePreferences.getFileDirectory().map(Path::toString).orElse("")); - putBoolean(BIB_LOC_AS_PRIMARY_DIR, filePreferences.isBibLocationAsPrimary()); + putBoolean(STORE_RELATIVE_TO_BIB, filePreferences.shouldStoreFilesRelativeToBib()); put(IMPORT_FILENAMEPATTERN, filePreferences.getFileNamePattern()); put(IMPORT_FILEDIRPATTERN, filePreferences.getFileDirectoryPattern()); putBoolean(DOWNLOAD_LINKED_FILES, filePreferences.shouldDownloadLinkedFiles()); diff --git a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java index 61db0d0c264..ef892f1a8d0 100644 --- a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java +++ b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java @@ -53,7 +53,7 @@ public void testFindAssociatedNotLinkedFilesSuccess() throws Exception { @Test public void testFindAssociatedNotLinkedFilesForEmptySearchDir() throws Exception { - when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(false); + when(fileDirPrefs.shouldStoreFilesRelativeToBib()).thenReturn(false); AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(databaseContext, fileDirPrefs, autoLinkPrefs, externalFileTypes); List actual = util.findAssociatedNotLinkedFiles(entry); assertEquals(Collections.emptyList(), actual); diff --git a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java index d4eae696cd2..5188db45e1b 100644 --- a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java @@ -61,8 +61,8 @@ void setUp(@TempDir Path bibFolder) throws IOException { context.setDatabasePath(bibFolder.resolve("test.bib")); FilePreferences fileDirPrefs = mock(FilePreferences.class, Answers.RETURNS_SMART_NULLS); - // Biblocation as Primary overwrites all other dirs - when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(true); + // Search and store files relative to bib file overwrites all other dirs + when(fileDirPrefs.shouldStoreFilesRelativeToBib()).thenReturn(true); worker = new CleanupWorker(context, new CleanupPreferences(mock(LayoutFormatterPreferences.class), fileDirPrefs)); diff --git a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java index 0738a84a535..caea7de7441 100644 --- a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -63,7 +63,7 @@ void setUp(@TempDir Path bibFolder) throws IOException { entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); filePreferences = mock(FilePreferences.class); - when(filePreferences.isBibLocationAsPrimary()).thenReturn(false); // Biblocation as Primary overwrites all other dirs, therefore we set it to false here + when(filePreferences.shouldStoreFilesRelativeToBib()).thenReturn(false); // Biblocation as Primary overwrites all other dirs, therefore we set it to false here cleanup = new MoveFilesCleanup(databaseContext, filePreferences); } diff --git a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java index c2cd3e87ff8..1fae450ca44 100644 --- a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -41,7 +41,7 @@ void setUp(@TempDir Path testFolder) { entry.setCitationKey("Toot"); filePreferences = mock(FilePreferences.class); - when(filePreferences.isBibLocationAsPrimary()).thenReturn(true); // Set Biblocation as Primary Directory, otherwise the tmp folders won't be cleaned up correctly + when(filePreferences.shouldStoreFilesRelativeToBib()).thenReturn(true); // Set Biblocation as Primary Directory, otherwise the tmp folders won't be cleaned up correctly cleanup = new RenamePdfCleanup(false, context, filePreferences); } diff --git a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java index 384f4d39f1a..795195ce10f 100644 --- a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java +++ b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java @@ -179,7 +179,7 @@ private void assertWrong(BibDatabaseContext context) { private void assertCorrect(BibDatabaseContext context) { FilePreferences filePreferencesMock = mock(FilePreferences.class); - when(filePreferencesMock.isBibLocationAsPrimary()).thenReturn(true); + when(filePreferencesMock.shouldStoreFilesRelativeToBib()).thenReturn(true); List messages = new IntegrityCheck(context, filePreferencesMock, createCitationKeyPatternPreferences(), diff --git a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java index f73ae5c2408..f5a57f0e5b8 100644 --- a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java +++ b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java @@ -26,7 +26,7 @@ class BibDatabaseContextTest { void setUp() { fileDirPrefs = mock(FilePreferences.class); currentWorkingDir = Path.of(System.getProperty("user.dir")); - when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(true); + when(fileDirPrefs.shouldStoreFilesRelativeToBib()).thenReturn(true); } @Test From a32e679676898b4e8dc1639dc431b920a64c4d05 Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Wed, 23 Sep 2020 23:58:36 +0200 Subject: [PATCH 4/6] Cleanup of deprecated methods LinkedFiles(String, String, String) and List getFileDirectories(...) --- src/main/java/org/jabref/gui/JabRefGUI.java | 2 +- .../org/jabref/gui/SendAsEMailAction.java | 2 +- .../org/jabref/gui/desktop/JabRefDesktop.java | 2 +- .../gui/exporter/ExportToClipboardAction.java | 3 +- .../externalfiles/AutoSetFileLinksUtil.java | 2 +- .../externalfiles/DownloadFullTextAction.java | 2 +- .../ExternalFilesEntryLinker.java | 4 +- .../gui/fieldeditors/LinkedFileViewModel.java | 2 +- .../gui/fieldeditors/LinkedFilesEditor.java | 6 +- .../LinkedFilesEditorViewModel.java | 6 +- .../jabref/gui/filelist/AttachFileAction.java | 2 +- .../jabref/gui/filelist/FileListEntry.java | 3 +- .../LinkedFilesEditDialogViewModel.java | 4 +- .../importer/actions/OpenDatabaseAction.java | 2 +- .../logic/cleanup/RelativePathsCleanup.java | 4 +- .../cleanup/UpgradePdfPsToFileCleanup.java | 12 ++-- .../externalfiles/LinkedFileHandler.java | 2 +- .../importer/fetcher/SpringerFetcher.java | 3 +- .../fileformat/EndnoteXmlImporter.java | 39 ++++++------ .../fileformat/PdfContentImporter.java | 4 +- .../logic/importer/util/FileFieldParser.java | 7 ++- .../jabref/logic/layout/format/FileLink.java | 7 +-- .../layout/format/FileLinkPreferences.java | 7 ++- .../logic/layout/format/WrapFileLinks.java | 7 +-- .../logic/util/io/DatabaseFileLookup.java | 2 +- .../org/jabref/logic/xmp/XmpUtilReader.java | 2 +- .../model/database/BibDatabaseContext.java | 42 +++++-------- .../org/jabref/model/entry/LinkedFile.java | 18 ++---- .../org/jabref/model/util/FileHelper.java | 2 +- .../jabref/preferences/JabRefPreferences.java | 2 +- .../AutoSetFileLinksUtilTest.java | 4 +- .../fieldeditors/LinkedFileViewModelTest.java | 62 +++++++++---------- .../logic/bibtex/BibEntryWriterTest.java | 3 +- .../logic/bibtex/FileFieldWriterTest.java | 55 +++++++++++----- .../logic/cleanup/CleanupWorkerTest.java | 21 +++---- .../logic/cleanup/MoveFilesCleanupTest.java | 35 ++++++----- .../logic/cleanup/RenamePdfCleanupTest.java | 25 +++++--- .../importer/fileformat/BibtexParserTest.java | 5 +- .../org/jabref/logic/layout/LayoutTest.java | 5 +- .../layout/format/WrapFileLinksTest.java | 5 +- .../pdf/EntryAnnotationImporterTest.java | 2 +- .../jabref/logic/xmp/XmpUtilReaderTest.java | 6 +- .../database/BibDatabaseContextTest.java | 12 ++-- .../org/jabref/model/entry/BibEntryTest.java | 5 +- 44 files changed, 237 insertions(+), 210 deletions(-) diff --git a/src/main/java/org/jabref/gui/JabRefGUI.java b/src/main/java/org/jabref/gui/JabRefGUI.java index 4cdbb7850fa..c107fd46004 100644 --- a/src/main/java/org/jabref/gui/JabRefGUI.java +++ b/src/main/java/org/jabref/gui/JabRefGUI.java @@ -145,7 +145,7 @@ private void openDatabases() { new SharedDatabaseUIManager(mainFrame).openSharedDatabaseFromParserResult(pr); } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) { - pr.getDatabaseContext().clearDatabaseFile(); // do not open the original file + pr.getDatabaseContext().clearDatabasePath(); // do not open the original file pr.getDatabase().clearSharedDatabaseID(); LOGGER.error("Connection error", e); diff --git a/src/main/java/org/jabref/gui/SendAsEMailAction.java b/src/main/java/org/jabref/gui/SendAsEMailAction.java index 2ba19e6798f..c54dc6fa60e 100644 --- a/src/main/java/org/jabref/gui/SendAsEMailAction.java +++ b/src/main/java/org/jabref/gui/SendAsEMailAction.java @@ -90,7 +90,7 @@ private String sendEmail() throws Exception { // the unofficial "mailto:attachment" property boolean openFolders = JabRefPreferences.getInstance().getBoolean(JabRefPreferences.OPEN_FOLDERS_OF_ATTACHED_FILES); - List fileList = FileUtil.getListOfLinkedFiles(entries, databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences())); + List fileList = FileUtil.getListOfLinkedFiles(entries, databaseContext.getFileDirectories(Globals.prefs.getFilePreferences())); for (Path path : fileList) { attachments.add(path.toAbsolutePath().toString()); if (openFolders) { diff --git a/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java b/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java index 3ae0a346f02..eb12f33a2f2 100644 --- a/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java +++ b/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java @@ -55,7 +55,7 @@ public static void openExternalViewer(BibDatabaseContext databaseContext, String Field field = initialField; if (StandardField.PS.equals(field) || StandardField.PDF.equals(field)) { // Find the default directory for this field type: - List directories = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences()); + List directories = databaseContext.getFileDirectories(Globals.prefs.getFilePreferences()); Optional file = FileHelper.find(link, directories); diff --git a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java index b40ff5cb952..cd950e1ad2a 100644 --- a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java +++ b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java @@ -103,7 +103,8 @@ private ExportResult exportToClipboard(Exporter exporter) throws Exception { // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) - Globals.prefs.fileDirForDatabase = panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences()).stream().map(Path::toString).collect(Collectors.toList()); + Globals.prefs.fileDirForDatabase = panel.getBibDatabaseContext() + .getFileDirectories(Globals.prefs.getFilePreferences()); // Add chosen export type to last used pref, to become default Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, exporter.getName()); diff --git a/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java b/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java index 70927daa0a6..2bc5a42b410 100644 --- a/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java +++ b/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java @@ -37,7 +37,7 @@ public class AutoSetFileLinksUtil { private ExternalFileTypes externalFileTypes; public AutoSetFileLinksUtil(BibDatabaseContext databaseContext, FilePreferences filePreferences, AutoLinkPreferences autoLinkPreferences, ExternalFileTypes externalFileTypes) { - this(databaseContext.getFileDirectoriesAsPaths(filePreferences), autoLinkPreferences, externalFileTypes); + this(databaseContext.getFileDirectories(filePreferences), autoLinkPreferences, externalFileTypes); } private AutoSetFileLinksUtil(List directories, AutoLinkPreferences autoLinkPreferences, ExternalFileTypes externalFileTypes) { diff --git a/src/main/java/org/jabref/gui/externalfiles/DownloadFullTextAction.java b/src/main/java/org/jabref/gui/externalfiles/DownloadFullTextAction.java index 019678e7d84..d63f3ff7eda 100644 --- a/src/main/java/org/jabref/gui/externalfiles/DownloadFullTextAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/DownloadFullTextAction.java @@ -160,7 +160,7 @@ private void addLinkedFileFromURL(BibDatabaseContext databaseContext, URL url, B downloadTask.onSuccess(destination -> { LinkedFile downloadedFile = LinkedFilesEditorViewModel.fromFile( destination, - databaseContext.getFileDirectoriesAsPaths(preferences.getFilePreferences()), + databaseContext.getFileDirectories(preferences.getFilePreferences()), ExternalFileTypes.getInstance()); entry.addFile(downloadedFile); dialogService.notify(Localization.lang("Finished downloading full text document for entry %0.", diff --git a/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java b/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java index 2c5dfa66571..dafdf500cf4 100644 --- a/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java +++ b/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java @@ -56,8 +56,8 @@ public void addFilesToEntry(BibEntry entry, List files) { FileUtil.getFileExtension(file).ifPresent(ext -> { ExternalFileType type = externalFileTypes.getExternalFileTypeByExt(ext) .orElse(new UnknownExternalFileType(ext)); - Path relativePath = FileUtil.relativize(file, bibDatabaseContext.getFileDirectoriesAsPaths(filePreferences)); - LinkedFile linkedfile = new LinkedFile("", relativePath.toString(), type.getName()); + Path relativePath = FileUtil.relativize(file, bibDatabaseContext.getFileDirectories(filePreferences)); + LinkedFile linkedfile = new LinkedFile("", relativePath, type.getName()); entry.addFile(linkedfile); }); } diff --git a/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java b/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java index 07a25bf4254..954b85172a4 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java +++ b/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java @@ -426,7 +426,7 @@ public void download() { URLDownload urlDownload = new URLDownload(linkedFile.getLink()); BackgroundTask downloadTask = prepareDownloadTask(targetDirectory.get(), urlDownload); downloadTask.onSuccess(destination -> { - LinkedFile newLinkedFile = LinkedFilesEditorViewModel.fromFile(destination, databaseContext.getFileDirectoriesAsPaths(filePreferences), externalFileTypes); + LinkedFile newLinkedFile = LinkedFilesEditorViewModel.fromFile(destination, databaseContext.getFileDirectories(filePreferences), externalFileTypes); List linkedFiles = entry.getFiles(); int oldFileIndex = -1; diff --git a/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java b/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java index 63e80affa7e..e52594688c9 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java +++ b/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java @@ -54,7 +54,11 @@ public class LinkedFilesEditor extends HBox implements FieldEditorFX { private final BibDatabaseContext databaseContext; private final UiThreadObservableList decoratedModelList; - public LinkedFilesEditor(Field field, DialogService dialogService, BibDatabaseContext databaseContext, TaskExecutor taskExecutor, SuggestionProvider suggestionProvider, + public LinkedFilesEditor(Field field, + DialogService dialogService, + BibDatabaseContext databaseContext, + TaskExecutor taskExecutor, + SuggestionProvider suggestionProvider, FieldCheckers fieldCheckers, JabRefPreferences preferences) { this.viewModel = new LinkedFilesEditorViewModel(field, suggestionProvider, dialogService, databaseContext, taskExecutor, fieldCheckers, preferences); diff --git a/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java b/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java index e4ec2b9e3a2..8fbe92dda7a 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java +++ b/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java @@ -94,11 +94,11 @@ public static LinkedFile fromFile(Path file, List fileDirectories, Externa .getExternalFileTypeByExt(fileExtension) .orElse(new UnknownExternalFileType(fileExtension)); Path relativePath = FileUtil.relativize(file, fileDirectories); - return new LinkedFile("", relativePath.toString(), suggestedFileType.getName()); + return new LinkedFile("", relativePath, suggestedFileType.getName()); } public LinkedFileViewModel fromFile(Path file) { - List fileDirectories = databaseContext.getFileDirectoriesAsPaths(preferences.getFilePreferences()); + List fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences()); LinkedFile linkedFile = fromFile(file, fileDirectories, externalFileTypes); return new LinkedFileViewModel( @@ -150,7 +150,7 @@ public void addNewFile() { .withInitialDirectory(workingDirectory) .build(); - List fileDirectories = databaseContext.getFileDirectoriesAsPaths(preferences.getFilePreferences()); + List fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences()); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(newFile -> { LinkedFile newLinkedFile = fromFile(newFile, fileDirectories, externalFileTypes); files.add(new LinkedFileViewModel( diff --git a/src/main/java/org/jabref/gui/filelist/AttachFileAction.java b/src/main/java/org/jabref/gui/filelist/AttachFileAction.java index e11bff8b4dc..9eaae774342 100644 --- a/src/main/java/org/jabref/gui/filelist/AttachFileAction.java +++ b/src/main/java/org/jabref/gui/filelist/AttachFileAction.java @@ -60,7 +60,7 @@ public void execute() { dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(newFile -> { LinkedFile linkedFile = LinkedFilesEditorViewModel.fromFile(newFile, - databaseContext.getFileDirectoriesAsPaths(preferencesService.getFilePreferences()), + databaseContext.getFileDirectories(preferencesService.getFilePreferences()), ExternalFileTypes.getInstance()); LinkedFileEditDialogView dialog = new LinkedFileEditDialogView(linkedFile); diff --git a/src/main/java/org/jabref/gui/filelist/FileListEntry.java b/src/main/java/org/jabref/gui/filelist/FileListEntry.java index dad983a7755..398623637c9 100644 --- a/src/main/java/org/jabref/gui/filelist/FileListEntry.java +++ b/src/main/java/org/jabref/gui/filelist/FileListEntry.java @@ -1,5 +1,6 @@ package org.jabref.gui.filelist; +import java.nio.file.Path; import java.util.Objects; import java.util.Optional; @@ -48,7 +49,7 @@ public String toString() { } public LinkedFile toParsedFileField() { - return new LinkedFile(getDescription(), getLink(), getType().isPresent() ? getType().get().getName() : ""); + return new LinkedFile(getDescription(), Path.of(getLink()), getType().isPresent() ? getType().get().getName() : ""); } public String getDescription() { diff --git a/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java b/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java index c28444b2a59..abaa718ab22 100644 --- a/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java +++ b/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java @@ -125,11 +125,11 @@ public ObjectProperty selectedExternalFileTypeProperty() { } public LinkedFile getNewLinkedFile() { - return new LinkedFile(description.getValue(), link.getValue(), monadicSelectedExternalFileType.getValue().map(ExternalFileType::toString).orElse("")); + return new LinkedFile(description.getValue(), Path.of(link.getValue()), monadicSelectedExternalFileType.getValue().map(ExternalFileType::toString).orElse("")); } private String relativize(Path filePath) { - List fileDirectories = database.getFileDirectoriesAsPaths(preferences.getFilePreferences()); + List fileDirectories = database.getFileDirectories(preferences.getFilePreferences()); return FileUtil.relativize(filePath, fileDirectories).toString(); } } diff --git a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java index 467675a6a00..80d6f8fc158 100644 --- a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java +++ b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java @@ -192,7 +192,7 @@ private ParserResult loadDatabase(Path file) throws Exception { new SharedDatabaseUIManager(frame).openSharedDatabaseFromParserResult(result); } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) { - result.getDatabaseContext().clearDatabaseFile(); // do not open the original file + result.getDatabaseContext().clearDatabasePath(); // do not open the original file result.getDatabase().clearSharedDatabaseID(); LOGGER.error("Connection error", e); diff --git a/src/main/java/org/jabref/logic/cleanup/RelativePathsCleanup.java b/src/main/java/org/jabref/logic/cleanup/RelativePathsCleanup.java index c7d08c70cf2..f4d6c619a77 100644 --- a/src/main/java/org/jabref/logic/cleanup/RelativePathsCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/RelativePathsCleanup.java @@ -39,12 +39,12 @@ public List cleanup(BibEntry entry) { } else { // only try to transform local file path to relative one newFileName = FileUtil - .relativize(Path.of(oldFileName), databaseContext.getFileDirectoriesAsPaths(filePreferences)) + .relativize(Path.of(oldFileName), databaseContext.getFileDirectories(filePreferences)) .toString(); } LinkedFile newFileEntry = fileEntry; if (!oldFileName.equals(newFileName)) { - newFileEntry = new LinkedFile(fileEntry.getDescription(), newFileName, fileEntry.getFileType()); + newFileEntry = new LinkedFile(fileEntry.getDescription(), Path.of(newFileName), fileEntry.getFileType()); changed = true; } newFileList.add(newFileEntry); diff --git a/src/main/java/org/jabref/logic/cleanup/UpgradePdfPsToFileCleanup.java b/src/main/java/org/jabref/logic/cleanup/UpgradePdfPsToFileCleanup.java index 721cea7d883..731a3ed6f0d 100644 --- a/src/main/java/org/jabref/logic/cleanup/UpgradePdfPsToFileCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/UpgradePdfPsToFileCleanup.java @@ -1,6 +1,6 @@ package org.jabref.logic.cleanup; -import java.io.File; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -36,16 +36,16 @@ public List cleanup(BibEntry entry) { List fileList = new ArrayList<>(entry.getFiles()); int oldItemCount = fileList.size(); for (Map.Entry field : fields.entrySet()) { - entry.getField(field.getKey()).ifPresent(o -> { - if (o.trim().isEmpty()) { + entry.getField(field.getKey()).ifPresent(fieldContent -> { + if (fieldContent.trim().isEmpty()) { return; } - File f = new File(o); - LinkedFile flEntry = new LinkedFile(f.getName(), o, field.getValue()); + Path path = Path.of(fieldContent); + LinkedFile flEntry = new LinkedFile(path.getFileName().toString(), path, field.getValue()); fileList.add(flEntry); entry.clearField(field.getKey()); - changes.add(new FieldChange(entry, field.getKey(), o, null)); + changes.add(new FieldChange(entry, field.getKey(), fieldContent, null)); }); } diff --git a/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java b/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java index 6c1c280ff38..ddd93b88077 100644 --- a/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java +++ b/src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java @@ -117,7 +117,7 @@ public boolean renameToName(String targetFileName, boolean overwriteExistingFile } private String relativize(Path path) { - List fileDirectories = databaseContext.getFileDirectoriesAsPaths(filePreferences); + List fileDirectories = databaseContext.getFileDirectories(filePreferences); return FileUtil.relativize(path, fileDirectories).toString(); } diff --git a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java index 30b63e5004a..be7a0082a0e 100644 --- a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java +++ b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java @@ -5,6 +5,7 @@ import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -118,7 +119,7 @@ public static BibEntry parseSpringerJSONtoBibtex(JSONObject springerJsonEntry) { urls.forEach(data -> { JSONObject url = (JSONObject) data; if (url.optString("format").equalsIgnoreCase("pdf")) { - entry.addFile(new LinkedFile("online", url.optString("value"), "PDF")); + entry.addFile(new LinkedFile("online", Path.of(url.optString("value")), "PDF")); } }); } diff --git a/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java b/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java index 97ebf5c2d7f..77a79883772 100644 --- a/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java +++ b/src/main/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporter.java @@ -4,6 +4,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; @@ -21,7 +23,6 @@ import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.Importer; -import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.Parser; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.endnote.Abstract; @@ -158,23 +159,14 @@ private void initUnmarshaller() throws JAXBException { } private static EntryType convertRefNameToType(String refName) { - switch (refName.toLowerCase().trim()) { - case "artwork": - return StandardEntryType.Misc; - case "generic": - return StandardEntryType.Misc; - case "electronic article": - return IEEETranEntryType.Electronic; - case "book section": - return StandardEntryType.InBook; - case "book": - return StandardEntryType.Book; - case "journal article": - return StandardEntryType.Article; - - default: - return StandardEntryType.Article; - } + return switch (refName.toLowerCase().trim()) { + case "artwork", "generic" -> StandardEntryType.Misc; + case "electronic article" -> IEEETranEntryType.Electronic; + case "book section" -> StandardEntryType.InBook; + case "book" -> StandardEntryType.Book; + // case "journal article" -> StandardEntryType.Article; + default -> StandardEntryType.Article; + }; } private BibEntry parseRecord(Record record) { @@ -247,7 +239,14 @@ private List getLinkedFiles(Record record) { return OptionalUtil.toStream(urls) .flatMap(pdfUrls -> pdfUrls.getUrl().stream()) .flatMap(url -> OptionalUtil.toStream(getUrlValue(url))) - .map(url -> new LinkedFile("", url, "PDF")) + .map(url -> { + try { + return new LinkedFile(new URL(url), "PDF"); + } catch (MalformedURLException e) { + LOGGER.info("Unable to parse {}", url); + return null; + } + }) .collect(Collectors.toList()); } @@ -295,7 +294,7 @@ private String clean(String input) { } @Override - public List parseEntries(InputStream inputStream) throws ParseException { + public List parseEntries(InputStream inputStream) { try { return importDatabase( new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))).getDatabase().getEntries(); diff --git a/src/main/java/org/jabref/logic/importer/fileformat/PdfContentImporter.java b/src/main/java/org/jabref/logic/importer/fileformat/PdfContentImporter.java index baf91641ef8..1a8a9a6e900 100644 --- a/src/main/java/org/jabref/logic/importer/fileformat/PdfContentImporter.java +++ b/src/main/java/org/jabref/logic/importer/fileformat/PdfContentImporter.java @@ -212,7 +212,7 @@ public ParserResult importDatabase(Path filePath, Charset defaultEncoding) { ParserResult parserResult = new ParserResult(result); Optional entry = new DoiFetcher(importFormatPreferences).performSearchById(doi.get().getDOI()); entry.ifPresent(parserResult.getDatabase()::insertEntry); - entry.ifPresent(bibEntry -> bibEntry.addFile(new LinkedFile("", filePath.toAbsolutePath().toString(), "PDF"))); + entry.ifPresent(bibEntry -> bibEntry.addFile(new LinkedFile("", filePath.toAbsolutePath(), "PDF"))); return parserResult; } @@ -226,7 +226,7 @@ public ParserResult importDatabase(Path filePath, Charset defaultEncoding) { return ParserResult.fromErrorMessage(e.getMessage()); } - result.forEach(entry -> entry.addFile(new LinkedFile("", filePath.toAbsolutePath().toString(), "PDF"))); + result.forEach(entry -> entry.addFile(new LinkedFile("", filePath.toAbsolutePath(), "PDF"))); return new ParserResult(result); } diff --git a/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java b/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java index 3f00ab57f62..cdbb1818807 100644 --- a/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java +++ b/src/main/java/org/jabref/logic/importer/util/FileFieldParser.java @@ -1,5 +1,6 @@ package org.jabref.logic.importer.util; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -64,12 +65,12 @@ private static LinkedFile convert(List entry) { while (entry.size() < 3) { entry.add(""); } - LinkedFile field = new LinkedFile(entry.get(0), entry.get(1), entry.get(2)); + LinkedFile field = new LinkedFile(entry.get(0), Path.of(entry.get(1)), entry.get(2)); // link is only mandatory field if (field.getDescription().isEmpty() && field.getLink().isEmpty() && !field.getFileType().isEmpty()) { - field = new LinkedFile("", field.getFileType(), ""); + field = new LinkedFile("", Path.of(field.getFileType()), ""); } else if (!field.getDescription().isEmpty() && field.getLink().isEmpty() && field.getFileType().isEmpty()) { - field = new LinkedFile("", field.getDescription(), ""); + field = new LinkedFile("", Path.of(field.getDescription()), ""); } entry.clear(); return field; diff --git a/src/main/java/org/jabref/logic/layout/format/FileLink.java b/src/main/java/org/jabref/logic/layout/format/FileLink.java index 384d9544f75..ba784043224 100644 --- a/src/main/java/org/jabref/logic/layout/format/FileLink.java +++ b/src/main/java/org/jabref/logic/layout/format/FileLink.java @@ -3,7 +3,6 @@ import java.nio.file.Path; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.layout.ParamLayoutFormatter; @@ -50,18 +49,18 @@ public String format(String field) { return ""; } - List dirs; + List dirs; // We need to resolve the file directory from the database's metadata, // but that is not available from a formatter. Therefore, as an // ugly hack, the export routine has set a global variable before // starting the export, which contains the database's file directory: if (prefs.getFileDirForDatabase() == null) { - dirs = Collections.singletonList(prefs.getMainFileDirectory()); + dirs = Collections.singletonList(Path.of(prefs.getMainFileDirectory())); } else { dirs = prefs.getFileDirForDatabase(); } - return link.findIn(dirs.stream().map(Path::of).collect(Collectors.toList())) + return link.findIn(dirs) .map(path -> path.normalize().toString()) .orElse(link.getLink()); } diff --git a/src/main/java/org/jabref/logic/layout/format/FileLinkPreferences.java b/src/main/java/org/jabref/logic/layout/format/FileLinkPreferences.java index 99000174a74..805c4f5db76 100644 --- a/src/main/java/org/jabref/logic/layout/format/FileLinkPreferences.java +++ b/src/main/java/org/jabref/logic/layout/format/FileLinkPreferences.java @@ -1,13 +1,14 @@ package org.jabref.logic.layout.format; +import java.nio.file.Path; import java.util.List; public class FileLinkPreferences { private final String mainFileDirectory; - private final List fileDirForDatabase; + private final List fileDirForDatabase; - public FileLinkPreferences(String mainFileDirectory, List fileDirForDatabase) { + public FileLinkPreferences(String mainFileDirectory, List fileDirForDatabase) { this.mainFileDirectory = mainFileDirectory; this.fileDirForDatabase = fileDirForDatabase; } @@ -16,7 +17,7 @@ public String getMainFileDirectory() { return mainFileDirectory; } - public List getFileDirForDatabase() { + public List getFileDirForDatabase() { return fileDirForDatabase; } } diff --git a/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java b/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java index a7c44a2a795..5baff04a64c 100644 --- a/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java +++ b/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java @@ -6,7 +6,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.layout.AbstractParamLayoutFormatter; @@ -196,18 +195,18 @@ public String format(String field) { sb.append(piv); break; case FILE_PATH: - List dirs; + List dirs; // We need to resolve the file directory from the database's metadata, // but that is not available from a formatter. Therefore, as an // ugly hack, the export routine has set a global variable before // starting the export, which contains the database's file directory: if ((prefs.getFileDirForDatabase() == null) || prefs.getFileDirForDatabase().isEmpty()) { - dirs = Collections.singletonList(prefs.getMainFileDirectory()); + dirs = Collections.singletonList(Path.of(prefs.getMainFileDirectory())); } else { dirs = prefs.getFileDirForDatabase(); } - String pathString = flEntry.findIn(dirs.stream().map(Path::of).collect(Collectors.toList())) + String pathString = flEntry.findIn(dirs) .map(path -> path.toAbsolutePath().toString()) .orElse(flEntry.getLink()); diff --git a/src/main/java/org/jabref/logic/util/io/DatabaseFileLookup.java b/src/main/java/org/jabref/logic/util/io/DatabaseFileLookup.java index d8e5c0f0265..839a6432a71 100644 --- a/src/main/java/org/jabref/logic/util/io/DatabaseFileLookup.java +++ b/src/main/java/org/jabref/logic/util/io/DatabaseFileLookup.java @@ -31,7 +31,7 @@ public class DatabaseFileLookup { */ public DatabaseFileLookup(BibDatabaseContext databaseContext, FilePreferences filePreferences) { Objects.requireNonNull(databaseContext); - possibleFilePaths = Optional.ofNullable(databaseContext.getFileDirectoriesAsPaths(filePreferences)) + possibleFilePaths = Optional.ofNullable(databaseContext.getFileDirectories(filePreferences)) .orElse(new ArrayList<>()); for (BibEntry entry : databaseContext.getDatabase().getEntries()) { diff --git a/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java b/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java index f58d5fda413..811428316a3 100644 --- a/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java +++ b/src/main/java/org/jabref/logic/xmp/XmpUtilReader.java @@ -93,7 +93,7 @@ public static List readXmp(Path path, XmpPreferences xmpPreferences) } } - result.forEach(entry -> entry.addFile(new LinkedFile("", path.toAbsolutePath().toString(), "PDF"))); + result.forEach(entry -> entry.addFile(new LinkedFile("", path.toAbsolutePath(), "PDF"))); return result; } diff --git a/src/main/java/org/jabref/model/database/BibDatabaseContext.java b/src/main/java/org/jabref/model/database/BibDatabaseContext.java index 7e09b3ca809..2b0e713614f 100644 --- a/src/main/java/org/jabref/model/database/BibDatabaseContext.java +++ b/src/main/java/org/jabref/model/database/BibDatabaseContext.java @@ -27,9 +27,9 @@ public class BibDatabaseContext { private MetaData metaData; /** - * The file where this database was last saved to. + * The path where this database was last saved to. */ - private Optional file; + private Optional path; private DatabaseSynchronizer dbmsSynchronizer; private CoarseChangeFilter dbmsListener; @@ -47,17 +47,17 @@ public BibDatabaseContext(BibDatabase database, MetaData metaData) { this.database = Objects.requireNonNull(database); this.metaData = Objects.requireNonNull(metaData); this.location = DatabaseLocation.LOCAL; - this.file = Optional.empty(); + this.path = Optional.empty(); } - public BibDatabaseContext(BibDatabase database, MetaData metaData, Path file) { - this(database, metaData, file, DatabaseLocation.LOCAL); + public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path) { + this(database, metaData, path, DatabaseLocation.LOCAL); } - public BibDatabaseContext(BibDatabase database, MetaData metaData, Path file, DatabaseLocation location) { + public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path, DatabaseLocation location) { this(database, metaData); Objects.requireNonNull(location); - this.file = Optional.ofNullable(file); + this.path = Optional.ofNullable(path); if (location == DatabaseLocation.LOCAL) { convertToLocalDatabase(); @@ -73,20 +73,20 @@ public void setMode(BibDatabaseMode bibDatabaseMode) { } public void setDatabasePath(Path file) { - this.file = Optional.ofNullable(file); + this.path = Optional.ofNullable(file); } /** - * Get the file where this database was last saved to or loaded from, if any. + * Get the path where this database was last saved to or loaded from, if any. * - * @return Optional of the relevant File, or Optional.empty() if none is defined. + * @return Optional of the relevant Path, or Optional.empty() if none is defined. */ public Optional getDatabasePath() { - return file; + return path; } - public void clearDatabaseFile() { - this.file = Optional.empty(); + public void clearDatabasePath() { + this.path = Optional.empty(); } public BibDatabase getDatabase() { @@ -120,7 +120,7 @@ public boolean isBiblatexMode() { * * @param preferences The fileDirectory preferences */ - public List getFileDirectoriesAsPaths(FilePreferences preferences) { + public List getFileDirectories(FilePreferences preferences) { List fileDirs = new ArrayList<>(); // 1. Metadata user-specific directory @@ -156,17 +156,7 @@ public List getFileDirectoriesAsPaths(FilePreferences preferences) { * @return Optional of Path */ public Optional getFirstExistingFileDir(FilePreferences preferences) { - return getFileDirectoriesAsPaths(preferences).stream().filter(Files::exists).findFirst(); - } - - /** - * @deprecated use {@link #getFileDirectoriesAsPaths(FilePreferences)} instead - */ - @Deprecated - public List getFileDirectories(FilePreferences preferences) { - return getFileDirectoriesAsPaths(preferences).stream() - .map(directory -> directory.toAbsolutePath().toString()) - .collect(Collectors.toList()); + return getFileDirectories(preferences).stream().filter(Files::exists).findFirst(); } private Path getFileDirectoryPath(String directoryName) { @@ -204,7 +194,7 @@ public void convertToSharedDatabase(DatabaseSynchronizer dmbsSynchronizer) { @Override public String toString() { return "BibDatabaseContext{" + - "file=" + file + + "path=" + path + ", location=" + location + '}'; } diff --git a/src/main/java/org/jabref/model/entry/LinkedFile.java b/src/main/java/org/jabref/model/entry/LinkedFile.java index 8730ff13171..d06e4d956e2 100644 --- a/src/main/java/org/jabref/model/entry/LinkedFile.java +++ b/src/main/java/org/jabref/model/entry/LinkedFile.java @@ -26,28 +26,22 @@ */ public class LinkedFile implements Serializable { - private static final LinkedFile NULL_OBJECT = new LinkedFile("", "", ""); + private static final LinkedFile NULL_OBJECT = new LinkedFile("", Path.of(""), ""); // We have to mark these properties as transient because they can't be serialized directly private transient StringProperty description = new SimpleStringProperty(); private transient StringProperty link = new SimpleStringProperty(); private transient StringProperty fileType = new SimpleStringProperty(); public LinkedFile(String description, Path link, String fileType) { - this(description, link.toString(), fileType); - } - - /** - * @deprecated use the other constructor {@link #LinkedFile(String, Path, String)} - */ - @Deprecated - public LinkedFile(String description, String link, String fileType) { this.description.setValue(Objects.requireNonNull(description)); + setLink(Objects.requireNonNull(link).toString()); this.fileType.setValue(Objects.requireNonNull(fileType)); - setLink(Objects.requireNonNull(link)); } public LinkedFile(URL link, String fileType) { - this("", Objects.requireNonNull(link).toString(), fileType); + this.description.setValue(""); + setLink(Objects.requireNonNull(link).toString()); + this.fileType.setValue(Objects.requireNonNull(fileType)); } public StringProperty descriptionProperty() { @@ -167,7 +161,7 @@ public boolean isOnlineLink() { } public Optional findIn(BibDatabaseContext databaseContext, FilePreferences filePreferences) { - List dirs = databaseContext.getFileDirectoriesAsPaths(filePreferences); + List dirs = databaseContext.getFileDirectories(filePreferences); return findIn(dirs); } diff --git a/src/main/java/org/jabref/model/util/FileHelper.java b/src/main/java/org/jabref/model/util/FileHelper.java index f4ee0576cc8..cb93884acfa 100644 --- a/src/main/java/org/jabref/model/util/FileHelper.java +++ b/src/main/java/org/jabref/model/util/FileHelper.java @@ -88,7 +88,7 @@ private static Optional detectExtension(InputStream is, Metadata metaDat * @param fileName The filename, may also be a relative path to the file */ public static Optional find(final BibDatabaseContext databaseContext, String fileName, FilePreferences filePreferences) { - return find(fileName, databaseContext.getFileDirectoriesAsPaths(filePreferences)); + return find(fileName, databaseContext.getFileDirectories(filePreferences)); } /** diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 01c116cc193..4bf0b2a16ba 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -387,7 +387,7 @@ public class JabRefPreferences implements PreferencesService { // that should resolve external file paths can access this field. This is an ugly hack // to solve the problem of formatters not having access to any context except for the // string to be formatted and possible formatter arguments. - public List fileDirForDatabase; + public List fileDirForDatabase; private final Preferences prefs; /** diff --git a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java index ef892f1a8d0..c1b29472eb5 100644 --- a/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java +++ b/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java @@ -44,8 +44,8 @@ public void setUp(@TempDir Path folder) throws Exception { @Test public void testFindAssociatedNotLinkedFilesSuccess() throws Exception { // Due to mocking the externalFileType class, the file extension will not be found - when(databaseContext.getFileDirectoriesAsPaths(any())).thenReturn(Collections.singletonList(path.getParent())); - List expected = Collections.singletonList(new LinkedFile("", "CiteKey.pdf", "")); + when(databaseContext.getFileDirectories(any())).thenReturn(Collections.singletonList(path.getParent())); + List expected = Collections.singletonList(new LinkedFile("", Path.of("CiteKey.pdf"), "")); AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(databaseContext, fileDirPrefs, autoLinkPrefs, externalFileTypes); List actual = util.findAssociatedNotLinkedFiles(entry); assertEquals(expected, actual); diff --git a/src/test/java/org/jabref/gui/fieldeditors/LinkedFileViewModelTest.java b/src/test/java/org/jabref/gui/fieldeditors/LinkedFileViewModelTest.java index 268ff785ef2..b84b6493bfc 100644 --- a/src/test/java/org/jabref/gui/fieldeditors/LinkedFileViewModelTest.java +++ b/src/test/java/org/jabref/gui/fieldeditors/LinkedFileViewModelTest.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; class LinkedFileViewModelTest { @@ -71,26 +71,26 @@ void setUp(@TempDir Path tempFolder) throws Exception { @Test void deleteWhenFilePathNotPresentReturnsTrue() { // Making this a spy, so we can inject an empty optional without digging into the implementation - linkedFile = spy(new LinkedFile("", "nonexistent file", "")); + linkedFile = spy(new LinkedFile("", Path.of("nonexistent file"), "")); doReturn(Optional.empty()).when(linkedFile).findIn(any(BibDatabaseContext.class), any(FilePreferences.class)); LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, xmpPreferences, filePreferences, externalFileType); boolean removed = viewModel.delete(); assertTrue(removed); - verifyZeroInteractions(dialogService); // dialog was never shown + verifyNoInteractions(dialogService); // dialog was never shown } @Test void deleteWhenRemoveChosenReturnsTrueButDoesNotDeletesFile() { - linkedFile = new LinkedFile("", tempFile.toString(), ""); + linkedFile = new LinkedFile("", tempFile, ""); when(dialogService.showCustomButtonDialogAndWait( - any(AlertType.class), - anyString(), - anyString(), - any(ButtonType.class), - any(ButtonType.class), - any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(3))); // first vararg - remove button + any(AlertType.class), + anyString(), + anyString(), + any(ButtonType.class), + any(ButtonType.class), + any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(3))); // first vararg - remove button LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, xmpPreferences, filePreferences, externalFileType); boolean removed = viewModel.delete(); @@ -101,14 +101,14 @@ void deleteWhenRemoveChosenReturnsTrueButDoesNotDeletesFile() { @Test void deleteWhenDeleteChosenReturnsTrueAndDeletesFile() { - linkedFile = new LinkedFile("", tempFile.toString(), ""); + linkedFile = new LinkedFile("", tempFile, ""); when(dialogService.showCustomButtonDialogAndWait( - any(AlertType.class), - anyString(), - anyString(), - any(ButtonType.class), - any(ButtonType.class), - any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button + any(AlertType.class), + anyString(), + anyString(), + any(ButtonType.class), + any(ButtonType.class), + any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, xmpPreferences, filePreferences, externalFileType); boolean removed = viewModel.delete(); @@ -119,14 +119,14 @@ void deleteWhenDeleteChosenReturnsTrueAndDeletesFile() { @Test void deleteMissingFileReturnsTrue() { - linkedFile = new LinkedFile("", "!!nonexistent file!!", ""); + linkedFile = new LinkedFile("", Path.of("!!nonexistent file!!"), ""); when(dialogService.showCustomButtonDialogAndWait( - any(AlertType.class), - anyString(), - anyString(), - any(ButtonType.class), - any(ButtonType.class), - any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button + any(AlertType.class), + anyString(), + anyString(), + any(ButtonType.class), + any(ButtonType.class), + any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, xmpPreferences, filePreferences, externalFileType); boolean removed = viewModel.delete(); @@ -136,14 +136,14 @@ void deleteMissingFileReturnsTrue() { @Test void deleteWhenDialogCancelledReturnsFalseAndDoesNotRemoveFile() { - linkedFile = new LinkedFile("desc", tempFile.toString(), "pdf"); + linkedFile = new LinkedFile("desc", tempFile, "pdf"); when(dialogService.showCustomButtonDialogAndWait( - any(AlertType.class), - anyString(), - anyString(), - any(ButtonType.class), - any(ButtonType.class), - any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(5))); // third vararg - cancel button + any(AlertType.class), + anyString(), + anyString(), + any(ButtonType.class), + any(ButtonType.class), + any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(5))); // third vararg - cancel button LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, xmpPreferences, filePreferences, externalFileType); boolean removed = viewModel.delete(); diff --git a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java index c25b695b066..970fc66ec2f 100644 --- a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java +++ b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; +import java.nio.file.Path; import java.util.Collection; import java.util.Set; @@ -92,7 +93,7 @@ void writeOtherTypeTest() throws Exception { @Test void writeEntryWithFile() throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Article); - LinkedFile file = new LinkedFile("test", "/home/uers/test.pdf", "PDF"); + LinkedFile file = new LinkedFile("test", Path.of("/home/uers/test.pdf"), "PDF"); entry.addFile(file); StringWriter stringWriter = new StringWriter(); diff --git a/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java b/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java index 40b73e45d44..38fdbc465ff 100644 --- a/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java +++ b/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java @@ -1,5 +1,6 @@ package org.jabref.logic.bibtex; +import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; @@ -16,24 +17,27 @@ public class FileFieldWriterTest { @Test public void emptyListForEmptyInput() { String emptyInput = ""; - String nullInput = null; assertEquals(Collections.emptyList(), FileFieldParser.parse(emptyInput)); - assertEquals(Collections.emptyList(), FileFieldParser.parse(nullInput)); + assertEquals(Collections.emptyList(), FileFieldParser.parse(null)); } @Test public void parseCorrectInput() { String input = "Desc:File.PDF:PDF"; - assertEquals(Collections.singletonList(new LinkedFile("Desc", "File.PDF", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("Desc", Path.of("File.PDF"), "PDF")), + FileFieldParser.parse(input)); } @Test public void ingoreMissingDescription() { String input = ":wei2005ahp.pdf:PDF"; - assertEquals(Collections.singletonList(new LinkedFile("", "wei2005ahp.pdf", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("", Path.of("wei2005ahp.pdf"), "PDF")), + FileFieldParser.parse(input)); } @Test @@ -41,29 +45,42 @@ public void interpreteLinkAsOnlyMandatoryField() { String single = "wei2005ahp.pdf"; String multiple = "wei2005ahp.pdf;other.pdf"; - assertEquals(Collections.singletonList(new LinkedFile("", "wei2005ahp.pdf", "")), FileFieldParser.parse(single)); - assertEquals(Arrays.asList(new LinkedFile("", "wei2005ahp.pdf", ""), new LinkedFile("", "other.pdf", "")), FileFieldParser.parse(multiple)); + assertEquals( + Collections.singletonList(new LinkedFile("", Path.of("wei2005ahp.pdf"), "")), + FileFieldParser.parse(single)); + + assertEquals( + Arrays.asList( + new LinkedFile("", Path.of("wei2005ahp.pdf"), ""), + new LinkedFile("", Path.of("other.pdf"), "")), + FileFieldParser.parse(multiple)); } @Test public void escapedCharactersInDescription() { String input = "test\\:\\;:wei2005ahp.pdf:PDF"; - assertEquals(Collections.singletonList(new LinkedFile("test:;", "wei2005ahp.pdf", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("test:;", Path.of("wei2005ahp.pdf"), "PDF")), + FileFieldParser.parse(input)); } @Test public void handleXmlCharacters() { String input = "test,\\;st\\:\\;:wei2005ahp.pdf:PDF"; - assertEquals(Collections.singletonList(new LinkedFile("test,st:;", "wei2005ahp.pdf", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("test,st:;", Path.of("wei2005ahp.pdf"), "PDF")), + FileFieldParser.parse(input)); } @Test public void handleEscapedFilePath() { String input = "desc:C\\:\\\\test.pdf:PDF"; - assertEquals(Collections.singletonList(new LinkedFile("desc", "C:\\test.pdf", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("desc", Path.of("C:\\test.pdf"), "PDF")), + FileFieldParser.parse(input)); } @Test @@ -72,16 +89,26 @@ public void subsetOfFieldsResultsInFileLink() { String fileOnly = ":file.pdf"; String typeOnly = "::file.pdf"; - assertEquals(Collections.singletonList(new LinkedFile("", "file.pdf", "")), FileFieldParser.parse(descOnly)); - assertEquals(Collections.singletonList(new LinkedFile("", "file.pdf", "")), FileFieldParser.parse(fileOnly)); - assertEquals(Collections.singletonList(new LinkedFile("", "file.pdf", "")), FileFieldParser.parse(typeOnly)); + assertEquals( + Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")), + FileFieldParser.parse(descOnly)); + + assertEquals( + Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")), + FileFieldParser.parse(fileOnly)); + + assertEquals( + Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")), + FileFieldParser.parse(typeOnly)); } @Test public void tooManySeparators() { String input = "desc:file.pdf:PDF:asdf"; - assertEquals(Collections.singletonList(new LinkedFile("desc", "file.pdf", "PDF")), FileFieldParser.parse(input)); + assertEquals( + Collections.singletonList(new LinkedFile("desc", Path.of("file.pdf"), "PDF")), + FileFieldParser.parse(input)); } @Test @@ -114,7 +141,7 @@ public void testEncodeStringArray() { @Test public void testFileFieldWriterGetStringRepresentation() { - LinkedFile file = new LinkedFile("test", "X:\\Users\\abc.pdf", "PDF"); + LinkedFile file = new LinkedFile("test", Path.of("X:\\Users\\abc.pdf"), "PDF"); assertEquals("test:X\\:/Users/abc.pdf:PDF", FileFieldWriter.getStringRepresentation(file)); } } diff --git a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java index 5188db45e1b..f2215b97912 100644 --- a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java @@ -96,8 +96,7 @@ void cleanupDoesNothingByDefault(@TempDir Path bibFolder) throws IOException { entry.setField(StandardField.ABSTRACT, "Réflexions"); Path path = bibFolder.resolve("ARandomlyNamedFile"); Files.createFile(path); - File tempFile = path.toFile(); - LinkedFile fileField = new LinkedFile("", tempFile.getAbsolutePath(), ""); + LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); List changes = worker.cleanup(emptyPreset, entry); @@ -221,15 +220,13 @@ void cleanupMoveFilesMovesFileFromSubfolder(@TempDir Path bibFolder) throws IOEx Path path = bibFolder.resolve("AnotherRandomlyNamedFolder"); Files.createDirectory(path); - File subfolder = path.toFile(); - File tempFile = new File(subfolder, "test.pdf"); - tempFile.createNewFile(); + Path tempFile = Files.createFile(path.resolve("test.pdf")); BibEntry entry = new BibEntry(); - LinkedFile fileField = new LinkedFile("", tempFile.getAbsolutePath(), ""); + LinkedFile fileField = new LinkedFile("", tempFile.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); - LinkedFile newFileField = new LinkedFile("", tempFile.getName(), ""); + LinkedFile newFileField = new LinkedFile("", tempFile.getFileName(), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @@ -239,13 +236,12 @@ void cleanupRelativePathsConvertAbsoluteToRelativePath(@TempDir Path bibFolder) Path path = bibFolder.resolve("AnotherRandomlyNamedFile"); Files.createFile(path); - File tempFile = path.toFile(); BibEntry entry = new BibEntry(); - LinkedFile fileField = new LinkedFile("", tempFile.getAbsolutePath(), ""); + LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); - LinkedFile newFileField = new LinkedFile("", tempFile.getName(), ""); + LinkedFile newFileField = new LinkedFile("", path.getFileName(), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @@ -255,14 +251,13 @@ void cleanupRenamePdfRenamesRelativeFile(@TempDir Path bibFolder) throws IOExcep Path path = bibFolder.resolve("AnotherRandomlyNamedFile.tmp"); Files.createFile(path); - File tempFile = path.toFile(); BibEntry entry = new BibEntry(); entry.setCitationKey("Toot"); - LinkedFile fileField = new LinkedFile("", tempFile.getAbsolutePath(), ""); + LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); - LinkedFile newFileField = new LinkedFile("", "Toot.tmp", ""); + LinkedFile newFileField = new LinkedFile("", Path.of("Toot.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } diff --git a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java index caea7de7441..1c96bd82658 100644 --- a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -59,7 +59,7 @@ void setUp(@TempDir Path bibFolder) throws IOException { entry.setCitationKey("Toot"); entry.setField(StandardField.TITLE, "test title"); entry.setField(StandardField.YEAR, "1989"); - LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath().toString(), ""); + LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); filePreferences = mock(FilePreferences.class); @@ -68,23 +68,25 @@ void setUp(@TempDir Path bibFolder) throws IOException { } @Test - void movesFile() throws Exception { + void movesFile() { when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( - Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", "test.pdf", ""))), + Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test - void movesFileWithMulitpleLinked() throws Exception { - LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath().toString(), ""); - entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation( - Arrays.asList(new LinkedFile("", "", ""), fileField, new LinkedFile("", "", "")))); + void movesFileWithMulitpleLinked() { + LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath(), ""); + entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(Arrays.asList( + new LinkedFile("", Path.of(""), ""), + fileField, + new LinkedFile("", Path.of(""), "")))); when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); @@ -92,53 +94,56 @@ void movesFileWithMulitpleLinked() throws Exception { Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation( - Arrays.asList(new LinkedFile("", "", ""), new LinkedFile("", "test.pdf", ""), new LinkedFile("", "", "")))), + Arrays.asList( + new LinkedFile("", Path.of(""), ""), + new LinkedFile("", Path.of("test.pdf"), ""), + new LinkedFile("", Path.of(""), "")))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test - void movesFileWithFileDirPattern() throws Exception { + void movesFileWithFileDirPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]"); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("Misc").resolve("test.pdf"); assertEquals( - Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", "Misc/test.pdf", ""))), + Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("Misc/test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test - void doesNotMoveFileWithEmptyFileDirPattern() throws Exception { + void doesNotMoveFileWithEmptyFileDirPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( - Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", "test.pdf", ""))), + Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test - void movesFileWithSubdirectoryPattern() throws Exception { + void movesFileWithSubdirectoryPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]/[year]/[auth]"); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("Misc").resolve("1989").resolve("test.pdf"); assertEquals( - Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", "Misc/1989/test.pdf", ""))), + Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("Misc/1989/test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test - void movesFileWithNoDirectory() throws Exception { + void movesFileWithNoDirectory() { databaseContext.setMetaData(new MetaData()); when(filePreferences.getFileDirectoryPattern()).thenReturn(""); List changes = cleanup.cleanup(entry); diff --git a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java index 1fae450ca44..bd47aa16471 100644 --- a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -53,13 +53,13 @@ void cleanupRenamePdfRenamesFileEvenIfOnlyDifferenceIsCase(@TempDir Path testFol Path path = testFolder.resolve("toot.tmp"); Files.createFile(path); - LinkedFile fileField = new LinkedFile("", path.toAbsolutePath().toString(), ""); + LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]"); cleanup.cleanup(entry); - LinkedFile newFileField = new LinkedFile("", "Toot.tmp", ""); + LinkedFile newFileField = new LinkedFile("", Path.of("Toot.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @@ -70,14 +70,19 @@ void cleanupRenamePdfRenamesWithMultipleFiles(@TempDir Path testFolder) throws I entry.setField(StandardField.TITLE, "test title"); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation( - Arrays.asList(new LinkedFile("", "", ""), new LinkedFile("", path.toAbsolutePath().toString(), ""), new LinkedFile("", "", "")))); + Arrays.asList( + new LinkedFile("", Path.of(""), ""), + new LinkedFile("", path.toAbsolutePath(), ""), + new LinkedFile("", Path.of(""), "")))); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); - assertEquals( - Optional.of(FileFieldWriter.getStringRepresentation( - Arrays.asList(new LinkedFile("", "", ""), new LinkedFile("", "Toot - test title.tmp", ""), new LinkedFile("", "", "")))), + assertEquals(Optional.of(FileFieldWriter.getStringRepresentation( + Arrays.asList( + new LinkedFile("", Path.of(""), ""), + new LinkedFile("", Path.of("Toot - test title.tmp"), ""), + new LinkedFile("", Path.of(""), "")))), entry.getField(StandardField.FILE)); } @@ -86,14 +91,14 @@ void cleanupRenamePdfRenamesFileStartingWithCitationKey(@TempDir Path testFolder Path path = testFolder.resolve("Toot.tmp"); Files.createFile(path); - LinkedFile fileField = new LinkedFile("", path.toAbsolutePath().toString(), ""); + LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); entry.setField(StandardField.TITLE, "test title"); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); - LinkedFile newFileField = new LinkedFile("", "Toot - test title.tmp", ""); + LinkedFile newFileField = new LinkedFile("", Path.of("Toot - test title.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @@ -101,14 +106,14 @@ void cleanupRenamePdfRenamesFileStartingWithCitationKey(@TempDir Path testFolder void cleanupRenamePdfRenamesFileInSameFolder(@TempDir Path testFolder) throws IOException { Path path = testFolder.resolve("Toot.pdf"); Files.createFile(path); - LinkedFile fileField = new LinkedFile("", "Toot.pdf", "PDF"); + LinkedFile fileField = new LinkedFile("", Path.of("Toot.pdf"), "PDF"); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); entry.setField(StandardField.TITLE, "test title"); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); - LinkedFile newFileField = new LinkedFile("", "Toot - test title.pdf", "PDF"); + LinkedFile newFileField = new LinkedFile("", Path.of("Toot - test title.pdf"), "PDF"); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } } 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 60dc838cd98..2879938f5ba 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.io.StringReader; import java.net.InetAddress; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -1414,8 +1415,8 @@ void integrationTestTexGroup() throws Exception { GroupTreeNode root = result.getMetaData().getGroups().get(); - assertEquals("src/test/resources/org/jabref/model/groups/paper.aux", - ((TexGroup) root.getChildren().get(0).getGroup()).getFilePath().toString()); + assertEquals(((TexGroup) root.getChildren().get(0).getGroup()).getFilePath(), + Path.of("src/test/resources/org/jabref/model/groups/paper.aux")); } @Test diff --git a/src/test/java/org/jabref/logic/layout/LayoutTest.java b/src/test/java/org/jabref/logic/layout/LayoutTest.java index 415b1573016..46ffe8edd21 100644 --- a/src/test/java/org/jabref/logic/layout/LayoutTest.java +++ b/src/test/java/org/jabref/logic/layout/LayoutTest.java @@ -3,6 +3,7 @@ import java.io.File; import java.io.IOException; import java.io.StringReader; +import java.nio.file.Path; import java.util.Collections; import org.jabref.logic.layout.format.FileLinkPreferences; @@ -135,9 +136,9 @@ void beginConditionals() throws IOException { @Test void wrapFileLinksExpandFile() throws IOException { when(layoutFormatterPreferences.getFileLinkPreferences()).thenReturn( - new FileLinkPreferences("", Collections.singletonList("src/test/resources/pdfs/"))); + new FileLinkPreferences("", Collections.singletonList(Path.of("src/test/resources/pdfs/")))); BibEntry entry = new BibEntry(StandardEntryType.Article); - entry.addFile(new LinkedFile("Test file", "encrypted.pdf", "PDF")); + entry.addFile(new LinkedFile("Test file", Path.of("encrypted.pdf"), "PDF")); String layoutText = layout("\\begin{file}\\format[WrapFileLinks(\\i. \\d (\\p))]{\\file}\\end{file}", entry); 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 84f5562ced6..aad1356ab1d 100644 --- a/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java +++ b/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java @@ -2,6 +2,7 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; @@ -97,7 +98,7 @@ void testEndingBracket() { @Test void testPath() throws IOException { FileLinkPreferences preferences = new FileLinkPreferences("", - Collections.singletonList("src/test/resources/pdfs/")); + Collections.singletonList(Path.of("src/test/resources/pdfs/"))); formatter = new WrapFileLinks(preferences); formatter.setArgument("\\p"); assertEquals(new File("src/test/resources/pdfs/encrypted.pdf").getCanonicalPath(), @@ -117,7 +118,7 @@ void testPathFallBackToGeneratedDir() throws IOException { @Test void testPathReturnsRelativePathIfNotFound() { FileLinkPreferences preferences = new FileLinkPreferences("", - Collections.singletonList("src/test/resources/pdfs/")); + Collections.singletonList(Path.of("src/test/resources/pdfs/"))); formatter = new WrapFileLinks(preferences); formatter.setArgument("\\p"); assertEquals("test.pdf", formatter.format("Preferences:test.pdf:PDF")); diff --git a/src/test/java/org/jabref/logic/pdf/EntryAnnotationImporterTest.java b/src/test/java/org/jabref/logic/pdf/EntryAnnotationImporterTest.java index 8c2f8bb91b6..d48982b4f53 100644 --- a/src/test/java/org/jabref/logic/pdf/EntryAnnotationImporterTest.java +++ b/src/test/java/org/jabref/logic/pdf/EntryAnnotationImporterTest.java @@ -27,7 +27,7 @@ public class EntryAnnotationImporterTest { @BeforeEach public void setUp() { entry = new BibEntry(); - when(databaseContext.getFileDirectoriesAsPaths(any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs/"))); + when(databaseContext.getFileDirectories(any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs/"))); } @Test diff --git a/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java b/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java index 6158930f2da..b923e54675e 100644 --- a/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java +++ b/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java @@ -77,8 +77,8 @@ void testReadArticleDublinCoreReadXmp() throws IOException, URISyntaxException, String bibString = Resources.toString(XmpUtilShared.class.getResource("article_dublinCore.bib"), StandardCharsets.UTF_8); Optional entryFromBibFile = parser.parseSingleEntry(bibString); entryFromBibFile.get().setFiles(Arrays.asList( - new LinkedFile("", "paper.pdf", "PDF"), - new LinkedFile("", pathPdf.toAbsolutePath().toString(), "PDF")) + new LinkedFile("", Path.of("paper.pdf"), "PDF"), + new LinkedFile("", pathPdf.toAbsolutePath(), "PDF")) ); assertEquals(entryFromBibFile.get(), entry); @@ -104,7 +104,7 @@ void testReadPDMetadata() throws IOException, URISyntaxException, ParseException String bibString = Resources.toString(XmpUtilShared.class.getResource("PD_metadata.bib"), StandardCharsets.UTF_8); Optional entryFromBibFile = parser.parseSingleEntry(bibString); entryFromBibFile.get().setFiles(Collections.singletonList( - new LinkedFile("", pathPdf.toAbsolutePath().toString(), "PDF")) + new LinkedFile("", pathPdf.toAbsolutePath(), "PDF")) ); assertEquals(entryFromBibFile.get(), entries.get(0)); diff --git a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java index f5a57f0e5b8..cc834a61ca7 100644 --- a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java +++ b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java @@ -34,7 +34,7 @@ void getFileDirectoriesWithEmptyDbParent() { BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(Path.of("biblio.bib")); assertEquals(Collections.singletonList(currentWorkingDir), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test @@ -44,7 +44,7 @@ void getFileDirectoriesWithRelativeDbParent() { BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test @@ -54,7 +54,7 @@ void getFileDirectoriesWithRelativeDottedDbParent() { BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test @@ -64,7 +64,7 @@ void getFileDirectoriesWithAbsoluteDbParent() { BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test @@ -75,7 +75,7 @@ void getFileDirectoriesWithRelativeMetadata() { database.setDatabasePath(file); database.getMetaData().setDefaultFileDirectory("../Literature"); assertEquals(Arrays.asList(currentWorkingDir.resolve(file.getParent()), Path.of("/absolute/Literature").toAbsolutePath()), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test @@ -86,7 +86,7 @@ void getFileDirectoriesWithMetadata() { database.setDatabasePath(file); database.getMetaData().setDefaultFileDirectory("Literature"); assertEquals(Arrays.asList(currentWorkingDir.resolve(file.getParent()), Path.of("/absolute/subdir/Literature").toAbsolutePath()), - database.getFileDirectoriesAsPaths(fileDirPrefs)); + database.getFileDirectories(fileDirPrefs)); } @Test diff --git a/src/test/java/org/jabref/model/entry/BibEntryTest.java b/src/test/java/org/jabref/model/entry/BibEntryTest.java index 71d956daa2f..7147ae78577 100644 --- a/src/test/java/org/jabref/model/entry/BibEntryTest.java +++ b/src/test/java/org/jabref/model/entry/BibEntryTest.java @@ -1,5 +1,6 @@ package org.jabref.model.entry; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -254,9 +255,9 @@ void getFieldOrAliasLatexFreeComplexConversionInAlias() { @Test void testGetAndAddToLinkedFileList() { List files = entry.getFiles(); - files.add(new LinkedFile("", "", "")); + files.add(new LinkedFile("", Path.of(""), "")); entry.setFiles(files); - assertEquals(Arrays.asList(new LinkedFile("", "", "")), entry.getFiles()); + assertEquals(Arrays.asList(new LinkedFile("", Path.of(""), "")), entry.getFiles()); } @Test From 696f884a5b27a1c92cc0c6ed065a306a9ded36b4 Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Fri, 25 Sep 2020 19:18:47 +0200 Subject: [PATCH 5/6] Reworded package filelist to linkedfile --- .../gui/fieldeditors/LinkedFileViewModel.java | 4 +- .../jabref/gui/filelist/FileListEntry.java | 78 ------------------- .../AttachFileAction.java | 2 +- .../LinkedFileEditDialog.fxml | 30 +++---- .../LinkedFileEditDialogView.java | 2 +- .../LinkedFilesEditDialogViewModel.java | 2 +- .../jabref/gui/maintable/RightClickMenu.java | 2 +- 7 files changed, 22 insertions(+), 98 deletions(-) delete mode 100644 src/main/java/org/jabref/gui/filelist/FileListEntry.java rename src/main/java/org/jabref/gui/{filelist => linkedfile}/AttachFileAction.java (98%) rename src/main/java/org/jabref/gui/{filelist => linkedfile}/LinkedFileEditDialog.fxml (52%) rename src/main/java/org/jabref/gui/{filelist => linkedfile}/LinkedFileEditDialogView.java (98%) rename src/main/java/org/jabref/gui/{filelist => linkedfile}/LinkedFilesEditDialogViewModel.java (99%) diff --git a/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java b/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java index 954b85172a4..995718ce75d 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java +++ b/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java @@ -29,9 +29,9 @@ import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.externalfiletype.StandardExternalFileType; -import org.jabref.gui.filelist.LinkedFileEditDialogView; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; +import org.jabref.gui.linkedfile.LinkedFileEditDialogView; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.TaskExecutor; @@ -187,7 +187,7 @@ public Observable[] getObservables() { observables.add(downloadOngoing); observables.add(downloadProgress); observables.add(isAutomaticallyFound); - return observables.toArray(new Observable[observables.size()]); + return observables.toArray(new Observable[0]); } public void open() { diff --git a/src/main/java/org/jabref/gui/filelist/FileListEntry.java b/src/main/java/org/jabref/gui/filelist/FileListEntry.java deleted file mode 100644 index 398623637c9..00000000000 --- a/src/main/java/org/jabref/gui/filelist/FileListEntry.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.jabref.gui.filelist; - -import java.nio.file.Path; -import java.util.Objects; -import java.util.Optional; - -import org.jabref.gui.externalfiletype.ExternalFileType; -import org.jabref.model.entry.LinkedFile; - -/** - * This class represents a file link for a Bibtex entry. - */ - -public class FileListEntry { - - private String description; - - private String link; - - private Optional type; - - public FileListEntry(String description, String link) { - this(description, link, Optional.empty()); - } - - public FileListEntry(String description, String link, ExternalFileType type) { - this.setDescription(Objects.requireNonNull(description)); - this.setLink(Objects.requireNonNull(link)); - this.setType(Optional.of(Objects.requireNonNull(type))); - } - - public FileListEntry(String description, String link, Optional type) { - this.setDescription(Objects.requireNonNull(description)); - this.setLink(Objects.requireNonNull(link)); - this.setType(Objects.requireNonNull(type)); - } - - public String[] getStringArrayRepresentation() { - return new String[] {getDescription(), getLink(), getTypeName()}; - } - - private String getTypeName() { - return this.getType().isPresent() ? this.getType().get().getName() : ""; - } - - @Override - public String toString() { - return getDescription() + " : " + getLink() + " : " + getType().orElse(null); - } - - public LinkedFile toParsedFileField() { - return new LinkedFile(getDescription(), Path.of(getLink()), getType().isPresent() ? getType().get().getName() : ""); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getLink() { - return link; - } - - public void setLink(String link) { - this.link = link; - } - - public Optional getType() { - return type; - } - - public void setType(Optional type) { - this.type = type; - } -} diff --git a/src/main/java/org/jabref/gui/filelist/AttachFileAction.java b/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java similarity index 98% rename from src/main/java/org/jabref/gui/filelist/AttachFileAction.java rename to src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java index 9eaae774342..8892e6cc450 100644 --- a/src/main/java/org/jabref/gui/filelist/AttachFileAction.java +++ b/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java @@ -1,4 +1,4 @@ -package org.jabref.gui.filelist; +package org.jabref.gui.linkedfile; import java.nio.file.Path; import java.util.Optional; diff --git a/src/main/java/org/jabref/gui/filelist/LinkedFileEditDialog.fxml b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialog.fxml similarity index 52% rename from src/main/java/org/jabref/gui/filelist/LinkedFileEditDialog.fxml rename to src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialog.fxml index c50eecb2fe6..592a99d1567 100644 --- a/src/main/java/org/jabref/gui/filelist/LinkedFileEditDialog.fxml +++ b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialog.fxml @@ -9,7 +9,7 @@ - + @@ -22,19 +22,21 @@ - - + diff --git a/src/main/java/org/jabref/gui/filelist/LinkedFileEditDialogView.java b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java similarity index 98% rename from src/main/java/org/jabref/gui/filelist/LinkedFileEditDialogView.java rename to src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java index 3833f493437..5ea1e9fb344 100644 --- a/src/main/java/org/jabref/gui/filelist/LinkedFileEditDialogView.java +++ b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java @@ -1,4 +1,4 @@ -package org.jabref.gui.filelist; +package org.jabref.gui.linkedfile; import javax.inject.Inject; diff --git a/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java b/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java similarity index 99% rename from src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java rename to src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java index abaa718ab22..4ea7e26e149 100644 --- a/src/main/java/org/jabref/gui/filelist/LinkedFilesEditDialogViewModel.java +++ b/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java @@ -1,4 +1,4 @@ -package org.jabref.gui.filelist; +package org.jabref.gui.linkedfile; import java.nio.file.Path; import java.util.List; diff --git a/src/main/java/org/jabref/gui/maintable/RightClickMenu.java b/src/main/java/org/jabref/gui/maintable/RightClickMenu.java index a8bfe7ba478..f7f46026857 100644 --- a/src/main/java/org/jabref/gui/maintable/RightClickMenu.java +++ b/src/main/java/org/jabref/gui/maintable/RightClickMenu.java @@ -15,8 +15,8 @@ import org.jabref.gui.edit.CopyMoreAction; import org.jabref.gui.edit.EditAction; import org.jabref.gui.exporter.ExportToClipboardAction; -import org.jabref.gui.filelist.AttachFileAction; import org.jabref.gui.keyboard.KeyBindingRepository; +import org.jabref.gui.linkedfile.AttachFileAction; import org.jabref.gui.menus.ChangeEntryTypeMenu; import org.jabref.gui.mergeentries.MergeEntriesAction; import org.jabref.gui.mergeentries.MergeWithFetchedEntryAction; From 1924c6ffa98835e2ed4bf04c5978641f85be8adb Mon Sep 17 00:00:00 2001 From: Carl Christian Snethlage Date: Fri, 25 Sep 2020 19:27:33 +0200 Subject: [PATCH 6/6] Fixed SpringerFetcher --- .../logic/importer/fetcher/SpringerFetcher.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java index be7a0082a0e..2b15fd4eb4e 100644 --- a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java +++ b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java @@ -5,14 +5,12 @@ import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.help.HelpFile; -import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.Parser; import org.jabref.logic.importer.SearchBasedParserFetcher; import org.jabref.logic.util.BuildInfo; @@ -119,7 +117,11 @@ public static BibEntry parseSpringerJSONtoBibtex(JSONObject springerJsonEntry) { urls.forEach(data -> { JSONObject url = (JSONObject) data; if (url.optString("format").equalsIgnoreCase("pdf")) { - entry.addFile(new LinkedFile("online", Path.of(url.optString("value")), "PDF")); + try { + entry.addFile(new LinkedFile(new URL(url.optString("value")), "PDF")); + } catch (MalformedURLException e) { + LOGGER.info("Malformed URL: {}", url.optString("value")); + } } }); } @@ -156,7 +158,7 @@ public Optional getHelpPage() { } @Override - public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException { + public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException { URIBuilder uriBuilder = new URIBuilder(API_URL); uriBuilder.addParameter("q", query); // Search query uriBuilder.addParameter("api_key", API_KEY); // API key @@ -166,7 +168,7 @@ public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLE } @Override - public URL getComplexQueryURL(ComplexSearchQuery complexSearchQuery) throws URISyntaxException, MalformedURLException, FetcherException { + public URL getComplexQueryURL(ComplexSearchQuery complexSearchQuery) throws URISyntaxException, MalformedURLException { return getURLForQuery(constructComplexQueryString(complexSearchQuery)); }