From 1b28863f3c5b46264afc2d564b5a0cae78bdf6d8 Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Wed, 21 Dec 2016 13:05:22 +0100 Subject: [PATCH 01/27] Pass fileDirPattern to MoveFiles in Cleanup, so it respects the directory --- .../jabref/logic/cleanup/CleanupWorker.java | 2 +- .../logic/cleanup/MoveFilesCleanup.java | 31 +++++++++--- .../logic/cleanup/RenamePdfCleanup.java | 2 +- .../logic/cleanup/MoveFilesCleanupTest.java | 47 ++++++++++++++++--- 4 files changed, 67 insertions(+), 15 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java index 323b120fb02..8d92eed903d 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java @@ -69,7 +69,7 @@ private List determineCleanupActions(CleanupPreset preset) { jobs.add(new FileLinksCleanup()); } if (preset.isMovePDF()) { - jobs.add(new MoveFilesCleanup(databaseContext, fileDirectoryPreferences)); + jobs.add(new MoveFilesCleanup(databaseContext, fileDirPattern, fileDirectoryPreferences, prefs)); } if (preset.isMakePathsRelative()) { jobs.add(new RelativePathsCleanup(databaseContext, fileDirectoryPreferences)); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 9c246fe9b56..b14c809095d 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -1,6 +1,7 @@ package net.sf.jabref.logic.cleanup; import java.io.File; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -8,6 +9,7 @@ import java.util.Optional; import net.sf.jabref.logic.TypedBibEntry; +import net.sf.jabref.logic.layout.LayoutFormatterPreferences; import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.model.FieldChange; import net.sf.jabref.model.cleanup.CleanupJob; @@ -20,41 +22,58 @@ public class MoveFilesCleanup implements CleanupJob { private final BibDatabaseContext databaseContext; private final FileDirectoryPreferences fileDirectoryPreferences; + private final LayoutFormatterPreferences prefs; + private final String fileDirPattern; - public MoveFilesCleanup(BibDatabaseContext databaseContext, FileDirectoryPreferences fileDirectoryPreferences) { + public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, + FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences prefs) { this.databaseContext = Objects.requireNonNull(databaseContext); + this.fileDirPattern = Objects.requireNonNull(fileDirPattern); this.fileDirectoryPreferences = Objects.requireNonNull(fileDirectoryPreferences); + this.prefs = Objects.requireNonNull(prefs); } @Override public List cleanup(BibEntry entry) { - if(!databaseContext.getMetaData().getDefaultFileDirectory().isPresent()) { + if (!databaseContext.getMetaData().getDefaultFileDirectory().isPresent()) { return Collections.emptyList(); } List paths = databaseContext.getFileDirectories(fileDirectoryPreferences); String defaultFileDirectory = databaseContext.getMetaData().getDefaultFileDirectory().get(); Optional targetDirectory = FileUtil.expandFilename(defaultFileDirectory, paths); - if(!targetDirectory.isPresent()) { + + if (!targetDirectory.isPresent()) { return Collections.emptyList(); } TypedBibEntry typedEntry = new TypedBibEntry(entry, databaseContext); List fileList = typedEntry.getFiles(); List newFileList = new ArrayList<>(); + boolean changed = false; for (ParsedFileField fileEntry : fileList) { String oldFileName = fileEntry.getLink(); Optional oldFile = FileUtil.expandFilename(oldFileName, paths); - if(!oldFile.isPresent() || !oldFile.get().exists()) { + if (!oldFile.isPresent() || !oldFile.get().exists()) { newFileList.add(fileEntry); continue; } + System.out.println(fileDirPattern); + String targetDirName = ""; + if (!fileDirPattern.isEmpty()) { + targetDirName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, fileDirPattern, + prefs); + } + + Path newTargetFile = targetDirectory.get().toPath().resolve(targetDirName).resolve(oldFile.get().getName()); + System.out.println("Target Path " + newTargetFile); + File targetFile = new File(targetDirectory.get(), oldFile.get().getName()); - if(targetFile.exists()) { + if (targetFile.exists()) { // We do not overwrite already existing files newFileList.add(fileEntry); continue; @@ -73,7 +92,7 @@ public List cleanup(BibEntry entry) { if (changed) { Optional change = entry.setFiles(newFileList); - if(change.isPresent()) { + if (change.isPresent()) { return Collections.singletonList(change.get()); } else { return Collections.emptyList(); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 83f5bf4da33..6da7473cbe0 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -92,7 +92,7 @@ public List cleanup(BibEntry entry) { String expandedOldFilePath = expandedOldFile.get().toString(); boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) - && !newPath.equals(expandedOldFilePath); + && !newPath.toString().equals(expandedOldFilePath); if (Files.exists(newPath) && !pathsDifferOnlyByCase) { // we do not overwrite files diff --git a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java index d17330aef00..bb2dbee5d3a 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.Optional; +import net.sf.jabref.logic.layout.LayoutFormatterPreferences; +import net.sf.jabref.model.Defaults; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.database.BibDatabaseContext; import net.sf.jabref.model.entry.BibEntry; @@ -21,6 +23,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class MoveFilesCleanupTest { @@ -30,15 +33,21 @@ public class MoveFilesCleanupTest { private File pdfFolder; private BibDatabaseContext databaseContext; private MoveFilesCleanup cleanup; + private JabRefPreferences prefs; + private BibEntry entry; @Before public void setUp() throws IOException { - pdfFolder = bibFolder.newFolder(); + prefs = JabRefPreferences.getInstance(); MetaData metaData = new MetaData(); + pdfFolder = bibFolder.newFolder(); metaData.setDefaultFileDirectory(pdfFolder.getAbsolutePath()); - databaseContext = new BibDatabaseContext(new BibDatabase(), metaData, bibFolder.newFile("test.bib")); + databaseContext = new BibDatabaseContext(new BibDatabase(), metaData, new Defaults()); + databaseContext.setDatabaseFile(bibFolder.newFile("test.bib")); + entry = new BibEntry(); + entry.setCiteKey("Toot"); + entry.setField("title", "test title"); - cleanup = new MoveFilesCleanup(databaseContext, JabRefPreferences.getInstance().getFileDirectoryPreferences()); } @Test @@ -48,10 +57,10 @@ public void movesFileFromSubfolder() throws IOException { assertTrue(fileBefore.createNewFile()); assertTrue(new File(subfolder, "test.pdf").exists()); - BibEntry entry = new BibEntry(); ParsedFileField fileField = new ParsedFileField("", fileBefore.getAbsolutePath(), ""); entry.setField("file", FileField.getStringRepresentation(fileField)); - + cleanup = new MoveFilesCleanup(databaseContext, "", prefs.getFileDirectoryPreferences(), + mock(LayoutFormatterPreferences.class)); cleanup.cleanup(entry); assertFalse(fileBefore.exists()); @@ -69,10 +78,12 @@ public void movesFileFromSubfolderMultiple() throws IOException { assertTrue(fileBefore.createNewFile()); assertTrue(fileBefore.exists()); - BibEntry entry = new BibEntry(); ParsedFileField fileField = new ParsedFileField("", fileBefore.getAbsolutePath(), ""); - entry.setField("file", FileField.getStringRepresentation(Arrays.asList(new ParsedFileField("","",""), fileField, new ParsedFileField("","","")))); + entry.setField("file", FileField.getStringRepresentation( + Arrays.asList(new ParsedFileField("", "", ""), fileField, new ParsedFileField("", "", "")))); + cleanup = new MoveFilesCleanup(databaseContext, "", prefs.getFileDirectoryPreferences(), + mock(LayoutFormatterPreferences.class)); cleanup.cleanup(entry); assertFalse(fileBefore.exists()); @@ -84,4 +95,26 @@ public void movesFileFromSubfolderMultiple() throws IOException { new ParsedFileField("", fileAfter.getName(), ""), new ParsedFileField("", "", "")))), entry.getField("file")); } + + @Test + public void movesFileFromSubfolderWithFileDirPattern() throws IOException { + File subfolder = bibFolder.newFolder(); + File fileBefore = new File(subfolder, "test.pdf"); + assertTrue(fileBefore.createNewFile()); + assertTrue(new File(subfolder, "test.pdf").exists()); + + ParsedFileField fileField = new ParsedFileField("", fileBefore.getAbsolutePath(), ""); + entry.setField("file", FileField.getStringRepresentation(fileField)); + + cleanup = new MoveFilesCleanup(databaseContext, "\\EntryType", prefs.getFileDirectoryPreferences(), + mock(LayoutFormatterPreferences.class)); + cleanup.cleanup(entry); + + assertFalse(fileBefore.exists()); + File fileAfter = new File(pdfFolder, "test.pdf"); + assertTrue(fileAfter.exists()); + + assertEquals(Optional.of(FileField.getStringRepresentation(new ParsedFileField("", fileAfter.getName(), ""))), + entry.getField("file")); + } } From 54b8a53074079c69f6b979b378f0bd42c883bd66 Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Wed, 21 Dec 2016 14:42:18 +0100 Subject: [PATCH 02/27] Cleanup move files works, but change report not yet --- .../logic/cleanup/MoveFilesCleanup.java | 28 +++++++++++++++---- .../logic/cleanup/MoveFilesCleanupTest.java | 10 +++++-- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index b14c809095d..d61d216b239 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -1,6 +1,8 @@ package net.sf.jabref.logic.cleanup; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -18,6 +20,9 @@ import net.sf.jabref.model.entry.ParsedFileField; import net.sf.jabref.model.metadata.FileDirectoryPreferences; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + public class MoveFilesCleanup implements CleanupJob { private final BibDatabaseContext databaseContext; @@ -25,6 +30,7 @@ public class MoveFilesCleanup implements CleanupJob { private final LayoutFormatterPreferences prefs; private final String fileDirPattern; + private static final Log LOGGER = LogFactory.getLog(MoveFilesCleanup.class); public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences prefs) { @@ -62,6 +68,7 @@ public List cleanup(BibEntry entry) { continue; } + System.out.println("Old File:" + oldFile.get()); System.out.println(fileDirPattern); String targetDirName = ""; if (!fileDirPattern.isEmpty()) { @@ -72,19 +79,28 @@ public List cleanup(BibEntry entry) { Path newTargetFile = targetDirectory.get().toPath().resolve(targetDirName).resolve(oldFile.get().getName()); System.out.println("Target Path " + newTargetFile); - File targetFile = new File(targetDirectory.get(), oldFile.get().getName()); - if (targetFile.exists()) { + if (Files.exists(newTargetFile)) { // We do not overwrite already existing files newFileList.add(fileEntry); continue; } - oldFile.get().renameTo(targetFile); - String newFileName = targetFile.getName(); + try { + if (!Files.exists(newTargetFile)) { + Files.createDirectories(newTargetFile); + } + } catch (IOException e) { + LOGGER.error("Could no create target necessary target directoires for renaming", e); + } + + if (FileUtil.renameFile(oldFile.get().toPath(), newTargetFile, true)) { + changed = true; + } ParsedFileField newFileEntry = fileEntry; - if (!oldFileName.equals(newFileName)) { - newFileEntry = new ParsedFileField(fileEntry.getDescription(), newFileName, fileEntry.getFileType()); + if (!oldFileName.equals(newTargetFile.toString())) { + newFileEntry = new ParsedFileField(fileEntry.getDescription(), newTargetFile.getFileName().toString(), + fileEntry.getFileType()); changed = true; } newFileList.add(newFileEntry); diff --git a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java index bb2dbee5d3a..48337dec93b 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -2,6 +2,8 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; @@ -100,6 +102,7 @@ public void movesFileFromSubfolderMultiple() throws IOException { public void movesFileFromSubfolderWithFileDirPattern() throws IOException { File subfolder = bibFolder.newFolder(); File fileBefore = new File(subfolder, "test.pdf"); + assertTrue(fileBefore.createNewFile()); assertTrue(new File(subfolder, "test.pdf").exists()); @@ -111,10 +114,11 @@ public void movesFileFromSubfolderWithFileDirPattern() throws IOException { cleanup.cleanup(entry); assertFalse(fileBefore.exists()); - File fileAfter = new File(pdfFolder, "test.pdf"); - assertTrue(fileAfter.exists()); + Path after = pdfFolder.toPath().resolve("Misc").resolve("test.pdf"); + assertTrue(Files.exists(after)); - assertEquals(Optional.of(FileField.getStringRepresentation(new ParsedFileField("", fileAfter.getName(), ""))), + assertEquals(Optional + .of(FileField.getStringRepresentation(new ParsedFileField("", after.getFileName().toString(), ""))), entry.getField("file")); } } From 1c536ad03c5766ec88bbec00088822b6054f3d63 Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Fri, 23 Dec 2016 11:38:06 +0100 Subject: [PATCH 03/27] Make paths relative in MoveFileCleanup --- .../logic/cleanup/MoveFilesCleanup.java | 20 +++++++++---------- .../logic/cleanup/RenamePdfCleanup.java | 4 +--- .../logic/cleanup/MoveFilesCleanupTest.java | 3 ++- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index d61d216b239..9aba1c995a9 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -77,8 +78,6 @@ public List cleanup(BibEntry entry) { } Path newTargetFile = targetDirectory.get().toPath().resolve(targetDirName).resolve(oldFile.get().getName()); - System.out.println("Target Path " + newTargetFile); - if (Files.exists(newTargetFile)) { // We do not overwrite already existing files newFileList.add(fileEntry); @@ -90,20 +89,21 @@ public List cleanup(BibEntry entry) { Files.createDirectories(newTargetFile); } } catch (IOException e) { - LOGGER.error("Could no create target necessary target directoires for renaming", e); + LOGGER.error("Could no create necessary target directoires for renaming", e); } if (FileUtil.renameFile(oldFile.get().toPath(), newTargetFile, true)) { changed = true; - } - ParsedFileField newFileEntry = fileEntry; - if (!oldFileName.equals(newTargetFile.toString())) { - newFileEntry = new ParsedFileField(fileEntry.getDescription(), newTargetFile.getFileName().toString(), - fileEntry.getFileType()); - changed = true; + String newEntryFilePath = Paths.get(defaultFileDirectory).relativize(newTargetFile).toString(); + ParsedFileField newFileEntry = fileEntry; + if (!oldFileName.equals(newTargetFile.toString())) { + newFileEntry = new ParsedFileField(fileEntry.getDescription(), newEntryFilePath, + fileEntry.getFileType()); + changed = true; + } + newFileList.add(newFileEntry); } - newFileList.add(newFileEntry); } if (changed) { diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 6da7473cbe0..8587b26ad8c 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -125,13 +125,11 @@ public List cleanup(BibEntry entry) { Path parent = settingsDir.get(); String newFileEntryFileName; - if ((parent == null)) { + if (parent == null) { newFileEntryFileName = targetFileName.toString(); - } else { newFileEntryFileName = parent.relativize(newPath).toString(); } - newFileList.add(new ParsedFileField(description, newFileEntryFileName, type)); } } else { diff --git a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java index 48337dec93b..4fd3f37f4f8 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -115,10 +115,11 @@ public void movesFileFromSubfolderWithFileDirPattern() throws IOException { assertFalse(fileBefore.exists()); Path after = pdfFolder.toPath().resolve("Misc").resolve("test.pdf"); + Path relativefileDir = pdfFolder.toPath().relativize(after); assertTrue(Files.exists(after)); assertEquals(Optional - .of(FileField.getStringRepresentation(new ParsedFileField("", after.getFileName().toString(), ""))), + .of(FileField.getStringRepresentation(new ParsedFileField("", relativefileDir.toString(), ""))), entry.getField("file")); } } From 456f08494b27f55e052ff91faf0a6c0c812b8ddb Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Fri, 23 Dec 2016 11:41:17 +0100 Subject: [PATCH 04/27] Merge remote-tracking branch 'upstream/master' into moveFileDir # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. # # Lines starting with '#' will be ignored, and an empty message aborts # the commit. --- CHANGELOG.md | 29 +- jabref.install4j | 5 + .../java/net/sf/jabref/cli/XMPUtilMain.java | 14 +- .../java/net/sf/jabref/gui/BasePanel.java | 3 +- .../jabref/gui/FindUnlinkedFilesDialog.java | 1 - .../sf/jabref/gui/date/DatePickerButton.java | 29 +- .../gui/entryeditor/FieldExtraComponents.java | 20 + .../sf/jabref/gui/exporter/SaveAllAction.java | 3 +- .../gui/exporter/SaveDatabaseAction.java | 3 +- .../gui/groups/GroupTreeNodeViewModel.java | 5 +- .../importer/fetcher/ACMPortalFetcher.java | 2 +- .../gui/importer/fetcher/EntryFetchers.java | 8 +- .../importer/fetcher/IEEEXploreFetcher.java | 7 +- .../gui/importer/fetcher/INSPIREFetcher.java | 8 +- .../sf/jabref/gui/worker/AbstractWorker.java | 8 +- .../java/net/sf/jabref/gui/worker/Worker.java | 8 - .../net/sf/jabref/logic/help/HelpFile.java | 9 +- .../importer/fetcher/AbstractIsbnFetcher.java | 2 +- .../importer/fetcher/BibsonomyScraper.java | 4 + .../jabref/logic/importer/fetcher/DiVA.java | 2 +- .../logic/importer/fetcher/DoiFetcher.java | 23 +- .../logic/importer/fetcher/TitleFetcher.java | 45 ++ .../importer/fileformat/BibtexImporter.java | 2 +- .../importer/fileformat/BibtexParser.java | 26 +- .../format/AuthorLastFirstAbbreviator.java | 7 - .../sf/jabref/logic/net/ProxyRegisterer.java | 6 + .../jabref/logic/openoffice/OOBibStyle.java | 7 +- .../net/sf/jabref/cli/AuxCommandLineTest.java | 3 +- .../sf/jabref/gui/groups/GroupsUtilTest.java | 3 +- .../EntryFromFileCreatorManagerTest.java | 2 +- .../jabref/logic/auxparser/AuxParserTest.java | 10 +- .../logic/bibtex/BibEntryWriterTest.java | 22 +- .../BibtexKeyPatternUtilTest.java | 19 +- .../java/net/sf/jabref/logic/bst/TestVM.java | 3 +- .../exporter/BibtexDatabaseWriterTest.java | 12 +- .../importer/BibDatabaseTestsWithFiles.java | 2 +- .../importer/DatabaseFileLookupTest.java | 3 +- .../logic/importer/ParsedBibEntryTests.java | 2 +- .../logic/importer/fetcher/DiVATest.java | 2 +- .../importer/fetcher/DoiFetcherTest.java | 2 - .../importer/fetcher/TitleFetcherTest.java | 66 ++ .../importer/fileformat/BibtexParserTest.java | 574 ++++++++---------- .../sf/jabref/logic/layout/LayoutTest.java | 24 +- .../AuthorLastFirstAbbreviatorTester.java | 9 +- .../logic/openoffice/OOBibStyleTest.java | 16 +- .../net/sf/jabref/logic/xmp/XMPUtilTest.java | 90 ++- 46 files changed, 604 insertions(+), 546 deletions(-) delete mode 100644 src/main/java/net/sf/jabref/gui/worker/Worker.java create mode 100644 src/main/java/net/sf/jabref/logic/importer/fetcher/TitleFetcher.java create mode 100644 src/test/java/net/sf/jabref/logic/importer/fetcher/TitleFetcherTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index b06f03f308c..e0b03fae34f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,18 +11,25 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# ## [Unreleased] ### Changed +- When [adding a new entry](http://help.jabref.org/en/BaseFrame#adding-a-new-entry), one can select "title" to create a full BibTeX entry based on a title. - When editing an article, the tab "Optional fields" now shows "ISSN". - When editing a book, the tab "Optional fields" now shows "ISBN". - When using "Copy citation (HTML)" and pasting into a text editor, plain text is always pasted. - When using the "Download from URL" functionality, one is not limited to http(s) URLs, but can, for instance, enter ftp URLs. - When using the "Look up full text documents" functionality, JabRef warns more explicitly about multiple requests. +- The entry received from DOI does no longer contain the DOI as URL. Implements [#2417](https://github.com/JabRef/jabref/issues/2417). +- We use following parameters for the JVM on Windows and OSX: `-XX:+UseG1GC -XX:+UseStringDeduplication -XX:StringTableSize=1000003`. ### Fixed - Fixed [#2391](https://github.com/JabRef/jabref/issues/2391): Clicking on "Get Fulltext" button sets links correctly for the entry being edited. - The integrity check now determines the set of BibLaTeX-only fields differently. Fixes [#2390](https://github.com/JabRef/jabref/issues/2390). - We fixed an issue where groups containing brackets were not working properly. Fixes [#2394](https://github.com/JabRef/jabref/issues/2394). -- We fixed issues with the [timestamp](http://help.jabref.org/en/TimeStamp) field. Today and clear work again. Fixes [#2403](https://github.com/JabRef/jabref/issues/2403). +- We fixed issues with the [timestamp](http://help.jabref.org/en/TimeStamp) field. However, clearing with the clear button is not possible if timestamp format does not match the current settings. Fixes [#2403](https://github.com/JabRef/jabref/issues/2403). - Fixes [#2406](https://github.com/JabRef/jabref/issues/2406) so that the integrity check filter works again +- Closing of subtrees in the groups panel using "close subtree" is working again. Fixes [#2319](https://github.com/JabRef/jabref/issues/2319). +- The proxy settings are now also applied to HTTPS connections. Fixes [#2249](https://github.com/JabRef/jabref/issues/2249). + + ### Removed @@ -67,7 +74,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# -## [3.8] - 2016-12-16 +## [3.8] – 2016-12-16 ### Changed - Bibliographic information from web resources can now be used to complete existing entries. @@ -119,7 +126,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We fixed an issue which prevented the preference dialog to open on systems with Java 9. -## [3.7] - 2016-11-14 +## [3.7] – 2016-11-14 ### Changed - Implementation of eventbased autosave and backup functionality and file synchronization for shared DBs. Related to [#344](https://github.com/JabRef/jabref/issues/344) @@ -234,7 +241,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Removed optional fields from `other fields` (BibTeX), Removed deprecated fields from `other fields` (BibLaTeX) -## [3.6] - 2016-08-26 +## [3.6] – 2016-08-26 ### Changed - [#462](https://github.com/JabRef/jabref/issues/462) Extend the OpenConsoleFeature by offering a selection between default terminal emulator and configurable command execution. @@ -327,7 +334,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Removed preview toolbar (since long disabled) -## [3.5] - 2016-07-13 +## [3.5] – 2016-07-13 ### Changed - Implemented [#1356](https://github.com/JabRef/jabref/issues/1356): Added a formatter for converting HTML to Unicode @@ -357,7 +364,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Alleviate multiuser concurrency issue when near simultaneous saves occur to a shared database file -## [3.4] - 2016-06-02 +## [3.4] – 2016-06-02 ### Changed - Implemented [#629](https://github.com/JabRef/jabref/issues/629): Explicit groups are now written in the "groups" field of the entry instead of at the end of the bib file @@ -422,7 +429,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Removed not-working option "Select Matches" under Groups -> Settings. -## [3.3] - 2016-04-17 +## [3.3] – 2016-04-17 ### Changed - Migrated JabRef help to markdown at https://github.com/JabRef/help.jabref.org @@ -524,7 +531,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Removed double click listener from `doi` and `url` fields -## [3.2] - 2016-01-10 +## [3.2] – 2016-01-10 ### Changed - All import/open database warnings are now shown in a scrolling text area @@ -544,7 +551,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - OpenOffice/LibreOffice is removed from the push-to-application button and only accessed through the side panel -## [3.1] - 2015-12-24 +## [3.1] – 2015-12-24 ### Changed - Added new DoiResolution fetcher that tries to download full text PDF from DOI link @@ -598,7 +605,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Removed the ability to export references on the CLI interface based on year ranges -## [3.0] - 2015-11-29 +## [3.0] – 2015-11-29 ### Changed - Updated to support OpenOffice 4 and LibreOffice 5 @@ -706,7 +713,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Remove non-working web searches: JSTOR and Sciencedirect (planned to be fixed for the next release) - Remove option Tools -> Open PDF or PS which is replaced by Tools -> Open File -## 2.80 - never released +## 2.80 – never released Version 2.80 was intended as intermediate step to JabRef 3.0. Since much functionality has changed during development, a release of this version was skipped. diff --git a/jabref.install4j b/jabref.install4j index 210e8554a8d..727fb7488ad 100644 --- a/jabref.install4j +++ b/jabref.install4j @@ -750,4 +750,9 @@ return true; + + -XX:+UseG1GC + -XX:+UseStringDeduplication + -XX:StringTableSize=1000003 + diff --git a/src/main/java/net/sf/jabref/cli/XMPUtilMain.java b/src/main/java/net/sf/jabref/cli/XMPUtilMain.java index 816fbd8f73c..34284cd5c70 100644 --- a/src/main/java/net/sf/jabref/cli/XMPUtilMain.java +++ b/src/main/java/net/sf/jabref/cli/XMPUtilMain.java @@ -1,11 +1,8 @@ package net.sf.jabref.cli; -import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; -import java.io.InputStreamReader; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Collection; @@ -87,7 +84,7 @@ public static void main(String[] args) throws IOException, TransformerException } else if (args[0].endsWith(".bib")) { // Read from BIB and write as XMP try (FileReader fr = new FileReader(args[0])) { - ParserResult result = BibtexParser.parse(fr, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(fr); Collection entries = result.getDatabase().getEntries(); if (entries.isEmpty()) { @@ -114,10 +111,7 @@ public static void main(String[] args) throws IOException, TransformerException } if (args[0].endsWith(".bib") && args[1].endsWith(".pdf")) { - - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), StandardCharsets.UTF_8)); - // we need ParserResult as we access result.getDatabase() later - ParserResult result = new BibtexParser(importFormatPreferences).parse(reader); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new FileReader(args[0])); Collection entries = result.getDatabase().getEntries(); @@ -138,7 +132,7 @@ public static void main(String[] args) throws IOException, TransformerException break; } - ParserResult result = BibtexParser.parse(new FileReader(args[1]), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new FileReader(args[1])); Optional bibEntry = result.getDatabase().getEntryByKey(args[0]); @@ -176,7 +170,7 @@ private static void usage() { System.out.println(" xmpUtil "); System.out.println(""); System.out - .println("To report bugs visit http://jabref.sourceforge.net"); + .println("To report bugs visit https://issues.jabref.org"); } } diff --git a/src/main/java/net/sf/jabref/gui/BasePanel.java b/src/main/java/net/sf/jabref/gui/BasePanel.java index ad57fa9d337..709b171e301 100644 --- a/src/main/java/net/sf/jabref/gui/BasePanel.java +++ b/src/main/java/net/sf/jabref/gui/BasePanel.java @@ -94,7 +94,6 @@ import net.sf.jabref.gui.worker.CitationStyleToClipboardWorker; import net.sf.jabref.gui.worker.MarkEntriesAction; import net.sf.jabref.gui.worker.SendAsEMailAction; -import net.sf.jabref.gui.worker.Worker; import net.sf.jabref.logic.autocompleter.AutoCompletePreferences; import net.sf.jabref.logic.autocompleter.AutoCompleter; import net.sf.jabref.logic.autocompleter.AutoCompleterFactory; @@ -988,7 +987,7 @@ public void runCommand(final String _command) { ((BaseAction) o).action(); } else { // This part uses Spin's features: - Worker wrk = ((AbstractWorker) o).getWorker(); + Runnable wrk = ((AbstractWorker) o).getWorker(); // The Worker returned by getWorker() has been wrapped // by Spin.off(), which makes its methods be run in // a different thread from the EDT. diff --git a/src/main/java/net/sf/jabref/gui/FindUnlinkedFilesDialog.java b/src/main/java/net/sf/jabref/gui/FindUnlinkedFilesDialog.java index 70f17114225..5677ab974b4 100644 --- a/src/main/java/net/sf/jabref/gui/FindUnlinkedFilesDialog.java +++ b/src/main/java/net/sf/jabref/gui/FindUnlinkedFilesDialog.java @@ -164,7 +164,6 @@ public class FindUnlinkedFilesDialog extends JDialog { private boolean checkBoxWhyIsThereNoGetSelectedStupidSwing; - /** * For Unit-testing only. Don't remove!
* Used via reflection in {@link net.sf.jabref.importer.DatabaseFileLookup} to construct this diff --git a/src/main/java/net/sf/jabref/gui/date/DatePickerButton.java b/src/main/java/net/sf/jabref/gui/date/DatePickerButton.java index 82c248afd76..30affabc6b7 100644 --- a/src/main/java/net/sf/jabref/gui/date/DatePickerButton.java +++ b/src/main/java/net/sf/jabref/gui/date/DatePickerButton.java @@ -3,6 +3,7 @@ import java.awt.BorderLayout; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import javax.swing.JComponent; import javax.swing.JPanel; @@ -16,12 +17,16 @@ import com.github.lgooddatepicker.components.DatePickerSettings; import com.github.lgooddatepicker.optionalusertools.DateChangeListener; import com.github.lgooddatepicker.zinternaltools.DateChangeEvent; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; /** * wrapper and service class for the DatePicker handling at the EntryEditor */ public class DatePickerButton implements DateChangeListener { + private static final Log LOGGER = LogFactory.getLog(DatePickerButton.class); + private final DatePicker datePicker; private final JPanel panel = new JPanel(); private final FieldEditor editor; @@ -53,11 +58,12 @@ public DatePickerButton(FieldEditor pEditor, boolean useIsoFormat) { @Override public void dateChanged(DateChangeEvent dateChangeEvent) { LocalDate date = datePicker.getDate(); + String newDate = ""; if (date != null) { - editor.setText(dateTimeFormatter.format(date.atStartOfDay())); - } else { - // in this case the user selected "clear" in the date picker, so we just clear the field - editor.setText(""); + newDate = dateTimeFormatter.format(date.atStartOfDay()); + } + if (!newDate.equals(editor.getText())) { + editor.setText(newDate); } // Set focus to editor component after changing its text: editor.getTextComponent().requestFocus(); @@ -67,4 +73,19 @@ public JComponent getDatePicker() { //return datePicker; return panel; } + + /** + * Used to set the calender popup to the currently used Date + * @param dateString + */ + public void updateDatePickerDate(String dateString) { + if(dateString!=null && !dateString.isEmpty()) { + try { + datePicker.setDate(LocalDate.parse(dateString, dateTimeFormatter)); + } catch (DateTimeParseException exception) { + LOGGER.warn("Unable to parse stored date for field '"+editor.getFieldName()+"' with current settings. " + + "Clear button in calender popup will not work."); + } + } + } } diff --git a/src/main/java/net/sf/jabref/gui/entryeditor/FieldExtraComponents.java b/src/main/java/net/sf/jabref/gui/entryeditor/FieldExtraComponents.java index 7e9bd20d55d..b5d4731966a 100644 --- a/src/main/java/net/sf/jabref/gui/entryeditor/FieldExtraComponents.java +++ b/src/main/java/net/sf/jabref/gui/entryeditor/FieldExtraComponents.java @@ -444,6 +444,26 @@ public void mouseClicked(MouseEvent e) { // insert a datepicker, if the extras field contains this command if (useDatePicker) { DatePickerButton datePicker = new DatePickerButton(editor, useIsoFormat); + + // register a DocumentListener on the underlying text document which notifies the DatePicker which date is currently set + ((JTextArea) editor).getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void insertUpdate(DocumentEvent e) { + datePicker.updateDatePickerDate(editor.getText()); + } + + @Override + public void removeUpdate(DocumentEvent e) { + datePicker.updateDatePickerDate(editor.getText()); + } + + @Override + public void changedUpdate(DocumentEvent e) { + datePicker.updateDatePickerDate(editor.getText()); + } + }); + return Optional.of(datePicker.getDatePicker()); } else { return Optional.empty(); diff --git a/src/main/java/net/sf/jabref/gui/exporter/SaveAllAction.java b/src/main/java/net/sf/jabref/gui/exporter/SaveAllAction.java index bad33e4dbfa..5491cf9b0aa 100644 --- a/src/main/java/net/sf/jabref/gui/exporter/SaveAllAction.java +++ b/src/main/java/net/sf/jabref/gui/exporter/SaveAllAction.java @@ -11,7 +11,6 @@ import net.sf.jabref.gui.actions.Actions; import net.sf.jabref.gui.actions.MnemonicAwareAction; import net.sf.jabref.gui.keyboard.KeyBinding; -import net.sf.jabref.gui.worker.Worker; import net.sf.jabref.logic.l10n.Localization; import spin.Spin; @@ -20,7 +19,7 @@ * * @author alver */ -public class SaveAllAction extends MnemonicAwareAction implements Worker { +public class SaveAllAction extends MnemonicAwareAction implements Runnable { private final JabRefFrame frame; private int databases; diff --git a/src/main/java/net/sf/jabref/gui/exporter/SaveDatabaseAction.java b/src/main/java/net/sf/jabref/gui/exporter/SaveDatabaseAction.java index 68376cdb0ec..abffa8ce36f 100644 --- a/src/main/java/net/sf/jabref/gui/exporter/SaveDatabaseAction.java +++ b/src/main/java/net/sf/jabref/gui/exporter/SaveDatabaseAction.java @@ -21,7 +21,6 @@ import net.sf.jabref.gui.autosaveandbackup.AutosaveUIManager; import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.gui.worker.CallBack; -import net.sf.jabref.gui.worker.Worker; import net.sf.jabref.logic.autosaveandbackup.AutosaveManager; import net.sf.jabref.logic.autosaveandbackup.BackupManager; import net.sf.jabref.logic.exporter.BibtexDatabaseWriter; @@ -282,7 +281,7 @@ private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) */ public void runCommand() throws Exception { // This part uses Spin's features: - Worker worker = getWorker(); + Runnable worker = getWorker(); // The Worker returned by getWorker() has been wrapped // by Spin.off(), which makes its methods be run in // a different thread from the EDT. diff --git a/src/main/java/net/sf/jabref/gui/groups/GroupTreeNodeViewModel.java b/src/main/java/net/sf/jabref/gui/groups/GroupTreeNodeViewModel.java index 2ee0e261683..b1be569ffd5 100644 --- a/src/main/java/net/sf/jabref/gui/groups/GroupTreeNodeViewModel.java +++ b/src/main/java/net/sf/jabref/gui/groups/GroupTreeNodeViewModel.java @@ -151,11 +151,10 @@ public GroupTreeNode getNode() { /** Collapse this node and all its children. */ public void collapseSubtree(JTree tree) { - tree.collapsePath(this.getTreePath()); - - for(GroupTreeNodeViewModel child : getChildren()) { + for (GroupTreeNodeViewModel child : getChildren()) { child.collapseSubtree(tree); } + tree.collapsePath(this.getTreePath()); } /** Expand this node and all its children. */ diff --git a/src/main/java/net/sf/jabref/gui/importer/fetcher/ACMPortalFetcher.java b/src/main/java/net/sf/jabref/gui/importer/fetcher/ACMPortalFetcher.java index e5ed5241646..8ff338d2a26 100644 --- a/src/main/java/net/sf/jabref/gui/importer/fetcher/ACMPortalFetcher.java +++ b/src/main/java/net/sf/jabref/gui/importer/fetcher/ACMPortalFetcher.java @@ -313,7 +313,7 @@ private static Optional downloadEntryBibTeX(String id, boolean downloa Collection items = null; try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { - items = BibtexParser.parse(in, Globals.prefs.getImportFormatPreferences()).getDatabase() + items = new BibtexParser(Globals.prefs.getImportFormatPreferences()).parse(in).getDatabase() .getEntries(); } catch (IOException e) { LOGGER.info("Download of BibTeX information from ACM Portal failed.", e); diff --git a/src/main/java/net/sf/jabref/gui/importer/fetcher/EntryFetchers.java b/src/main/java/net/sf/jabref/gui/importer/fetcher/EntryFetchers.java index 0f081e90cdf..30974ed766c 100644 --- a/src/main/java/net/sf/jabref/gui/importer/fetcher/EntryFetchers.java +++ b/src/main/java/net/sf/jabref/gui/importer/fetcher/EntryFetchers.java @@ -2,12 +2,14 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.LinkedList; import java.util.List; import net.sf.jabref.Globals; import net.sf.jabref.logic.importer.EntryBasedFetcher; import net.sf.jabref.logic.importer.IdBasedFetcher; +import net.sf.jabref.logic.importer.WebFetcher; import net.sf.jabref.logic.importer.fetcher.ArXiv; import net.sf.jabref.logic.importer.fetcher.AstrophysicsDataSystem; import net.sf.jabref.logic.importer.fetcher.DBLPFetcher; @@ -18,6 +20,7 @@ import net.sf.jabref.logic.importer.fetcher.IsbnFetcher; import net.sf.jabref.logic.importer.fetcher.MathSciNet; import net.sf.jabref.logic.importer.fetcher.MedlineFetcher; +import net.sf.jabref.logic.importer.fetcher.TitleFetcher; import net.sf.jabref.logic.importer.fetcher.zbMATH; import net.sf.jabref.logic.journals.JournalAbbreviationLoader; @@ -56,7 +59,8 @@ public static ArrayList getIdFetchers() { list.add(new DiVA(Globals.prefs.getImportFormatPreferences())); list.add(new DoiFetcher(Globals.prefs.getImportFormatPreferences())); list.add(new MedlineFetcher()); - list.sort((fetcher1, fetcher2) -> fetcher1.getName().compareTo(fetcher2.getName())); + list.add(new TitleFetcher(Globals.prefs.getImportFormatPreferences())); + list.sort(Comparator.comparing(WebFetcher::getName)); return list; } @@ -64,7 +68,7 @@ public static ArrayList getEntryBasedFetchers() { ArrayList list = new ArrayList<>(); list.add(new AstrophysicsDataSystem(Globals.prefs.getImportFormatPreferences())); list.add(new MathSciNet(Globals.prefs.getImportFormatPreferences())); - list.sort((fetcher1, fetcher2) -> fetcher1.getName().compareTo(fetcher2.getName())); + list.sort(Comparator.comparing(WebFetcher::getName)); return list; } } diff --git a/src/main/java/net/sf/jabref/gui/importer/fetcher/IEEEXploreFetcher.java b/src/main/java/net/sf/jabref/gui/importer/fetcher/IEEEXploreFetcher.java index 9df5b946566..12d0a815d44 100644 --- a/src/main/java/net/sf/jabref/gui/importer/fetcher/IEEEXploreFetcher.java +++ b/src/main/java/net/sf/jabref/gui/importer/fetcher/IEEEXploreFetcher.java @@ -26,6 +26,7 @@ import net.sf.jabref.logic.help.HelpFile; import net.sf.jabref.logic.importer.ImportInspector; import net.sf.jabref.logic.importer.OutputPrinter; +import net.sf.jabref.logic.importer.ParseException; import net.sf.jabref.logic.importer.fileformat.BibtexParser; import net.sf.jabref.logic.journals.JournalAbbreviationLoader; import net.sf.jabref.logic.l10n.Localization; @@ -146,8 +147,8 @@ public boolean processQuery(String query, ImportInspector dialog, OutputPrinter bibtexPage = preprocessBibtexResultsPage(bibtexPage); //parse the page into Bibtex entries - Collection parsedBibtexCollection = BibtexParser.fromString(bibtexPage, - Globals.prefs.getImportFormatPreferences()); + Collection parsedBibtexCollection = new BibtexParser(Globals.prefs.getImportFormatPreferences()) + .parseEntries(bibtexPage); int nEntries = parsedBibtexCollection.size(); Iterator parsedBibtexCollectionIterator = parsedBibtexCollection.iterator(); while (parsedBibtexCollectionIterator.hasNext() && shouldContinue) { @@ -158,7 +159,7 @@ public boolean processQuery(String query, ImportInspector dialog, OutputPrinter return true; - } catch (IOException | JSONException e) { + } catch (ParseException | IOException | JSONException e) { LOGGER.error("Error while fetching from " + getTitle(), e); ((ImportInspectionDialog)dialog).showErrorMessage(this.getTitle(), e.getLocalizedMessage()); } diff --git a/src/main/java/net/sf/jabref/gui/importer/fetcher/INSPIREFetcher.java b/src/main/java/net/sf/jabref/gui/importer/fetcher/INSPIREFetcher.java index d59bfe0714a..93d078388b7 100644 --- a/src/main/java/net/sf/jabref/gui/importer/fetcher/INSPIREFetcher.java +++ b/src/main/java/net/sf/jabref/gui/importer/fetcher/INSPIREFetcher.java @@ -99,7 +99,7 @@ private String constructUrl(String key) { * @param key The OAI2 key to fetch from ArXiv. * @return The imported BibEntry or null if none. */ - private BibDatabase importInspireEntries(String key, OutputPrinter frame) throws IOException { + private BibDatabase importInspireEntries(String key) throws IOException { String url = constructUrl(key); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "JabRef"); @@ -107,13 +107,11 @@ private BibDatabase importInspireEntries(String key, OutputPrinter frame) throws try (INSPIREBibtexFilterReader reader = new INSPIREBibtexFilterReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { - - ParserResult pr = BibtexParser.parse(reader, Globals.prefs.getImportFormatPreferences()); + ParserResult pr = new BibtexParser(Globals.prefs.getImportFormatPreferences()).parse(reader); return pr.getDatabase(); } } - /* * @see net.sf.jabref.imports.fetcher.EntryFetcher */ @@ -146,7 +144,7 @@ public boolean processQuery(String query, ImportInspector dialog, OutputPrinter try { status.setStatus(Localization.lang("Fetching entries from Inspire")); /* query the archive and load the results into the BibEntry */ - BibDatabase bd = importInspireEntries(query, status); + BibDatabase bd = importInspireEntries(query); status.setStatus(Localization.lang("Adding fetched entries")); /* add the entry to the inspection dialog */ diff --git a/src/main/java/net/sf/jabref/gui/worker/AbstractWorker.java b/src/main/java/net/sf/jabref/gui/worker/AbstractWorker.java index ba68bedf9e6..642519ddc88 100644 --- a/src/main/java/net/sf/jabref/gui/worker/AbstractWorker.java +++ b/src/main/java/net/sf/jabref/gui/worker/AbstractWorker.java @@ -11,14 +11,14 @@ * the CallBack interface. This procedure ensures that run() cannot freeze * the GUI, and that update() can safely update GUI components. */ -public abstract class AbstractWorker implements Worker, CallBack { +public abstract class AbstractWorker implements Runnable, CallBack { - private final Worker worker; + private final Runnable worker; private final CallBack callBack; public AbstractWorker() { - worker = (Worker) Spin.off(this); + worker = (Runnable) Spin.off(this); callBack = (CallBack) Spin.over(this); } @@ -31,7 +31,7 @@ public void init() throws Exception { * This method returns a wrapped Worker instance of this AbstractWorker. * whose methods will automatically be run off the EDT (Swing) thread. */ - public Worker getWorker() { + public Runnable getWorker() { return worker; } diff --git a/src/main/java/net/sf/jabref/gui/worker/Worker.java b/src/main/java/net/sf/jabref/gui/worker/Worker.java deleted file mode 100644 index fd284b2cc2b..00000000000 --- a/src/main/java/net/sf/jabref/gui/worker/Worker.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.sf.jabref.gui.worker; - -/** - * Represents a task that is not to be executed on the GUI thread - */ -public interface Worker extends Runnable { - // Nothing -} diff --git a/src/main/java/net/sf/jabref/logic/help/HelpFile.java b/src/main/java/net/sf/jabref/logic/help/HelpFile.java index 2f98677f1a0..9958d3ddbb6 100644 --- a/src/main/java/net/sf/jabref/logic/help/HelpFile.java +++ b/src/main/java/net/sf/jabref/logic/help/HelpFile.java @@ -32,21 +32,22 @@ public enum HelpFile { OPENOFFICE_LIBREOFFICE("OpenOfficeIntegration"), FETCHER_ACM("ACMPortal"), FETCHER_ADS("ADS"), + FETCHER_BIBSONOMY_SCRAPER(""), FETCHER_CITESEERX("CiteSeer"), FETCHER_DBLP("DBLP"), - FETCHER_DIVA_TO_BIBTEX("DiVAtoBibTeX"), + FETCHER_DIVA("DiVAtoBibTeX"), FETCHER_DOAJ("DOAJ"), - FETCHER_DOI_TO_BIBTEX("DOItoBibTeX"), + FETCHER_DOI("DOItoBibTeX"), FETCHER_GOOGLE_SCHOLAR("GoogleScholar"), FETCHER_GVK("GVK"), FETCHER_IEEEXPLORE("IEEEXplore"), FETCHER_INSPIRE("INSPIRE"), - FETCHER_ISBN_TO_BIBTEX("ISBNtoBibTeX"), + FETCHER_ISBN("ISBNtoBibTeX"), FETCHER_MEDLINE("Medline"), FETCHER_OAI2_ARXIV("arXiv"), FETCHER_SPRINGER("Springer"), + FETCHER_TITLE("TitleToBibTeX"), FETCHER_SCIENCEDIRECT(""), - FETCHER_BIBSONOMY_SCRAPER(""), DATABASE_PROPERTIES("DatabaseProperties"), FIND_DUPLICATES("FindDuplicates"), SQL_DATABASE_MIGRATION("SQLDatabaseMigration"), diff --git a/src/main/java/net/sf/jabref/logic/importer/fetcher/AbstractIsbnFetcher.java b/src/main/java/net/sf/jabref/logic/importer/fetcher/AbstractIsbnFetcher.java index 2ae06d266ca..e0f245ce3cc 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fetcher/AbstractIsbnFetcher.java +++ b/src/main/java/net/sf/jabref/logic/importer/fetcher/AbstractIsbnFetcher.java @@ -19,7 +19,7 @@ public AbstractIsbnFetcher(ImportFormatPreferences importFormatPreferences) { @Override public HelpFile getHelpPage() { - return HelpFile.FETCHER_ISBN_TO_BIBTEX; + return HelpFile.FETCHER_ISBN; } protected void ensureThatIsbnIsValid(String identifier) throws FetcherException { diff --git a/src/main/java/net/sf/jabref/logic/importer/fetcher/BibsonomyScraper.java b/src/main/java/net/sf/jabref/logic/importer/fetcher/BibsonomyScraper.java index f2a2ca52976..f2afe76b468 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fetcher/BibsonomyScraper.java +++ b/src/main/java/net/sf/jabref/logic/importer/fetcher/BibsonomyScraper.java @@ -6,6 +6,7 @@ import java.util.Optional; import net.sf.jabref.logic.importer.ImportFormatPreferences; +import net.sf.jabref.logic.importer.ParseException; import net.sf.jabref.logic.importer.fileformat.BibtexParser; import net.sf.jabref.logic.net.URLDownload; import net.sf.jabref.model.entry.BibEntry; @@ -41,6 +42,9 @@ public static Optional getEntry(String entryUrl, ImportFormatPreferenc } catch (IOException ex) { LOGGER.warn("Could not download entry", ex); return Optional.empty(); + } catch (ParseException ex) { + LOGGER.warn("Could not parse entry", ex); + return Optional.empty(); } catch (RuntimeException ex) { LOGGER.warn("Could not get entry", ex); return Optional.empty(); diff --git a/src/main/java/net/sf/jabref/logic/importer/fetcher/DiVA.java b/src/main/java/net/sf/jabref/logic/importer/fetcher/DiVA.java index e0fac8bc84f..8405a67d12c 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fetcher/DiVA.java +++ b/src/main/java/net/sf/jabref/logic/importer/fetcher/DiVA.java @@ -32,7 +32,7 @@ public String getName() { @Override public HelpFile getHelpPage() { - return HelpFile.FETCHER_DIVA_TO_BIBTEX; + return HelpFile.FETCHER_DIVA; } @Override diff --git a/src/main/java/net/sf/jabref/logic/importer/fetcher/DoiFetcher.java b/src/main/java/net/sf/jabref/logic/importer/fetcher/DoiFetcher.java index 0542a0b6cda..d4dcd7b4409 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fetcher/DoiFetcher.java +++ b/src/main/java/net/sf/jabref/logic/importer/fetcher/DoiFetcher.java @@ -5,29 +5,29 @@ import java.nio.charset.StandardCharsets; import java.util.Optional; +import net.sf.jabref.logic.formatter.bibtexfields.ClearFormatter; import net.sf.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import net.sf.jabref.logic.help.HelpFile; import net.sf.jabref.logic.importer.FetcherException; import net.sf.jabref.logic.importer.IdBasedFetcher; import net.sf.jabref.logic.importer.ImportFormatPreferences; +import net.sf.jabref.logic.importer.ParseException; import net.sf.jabref.logic.importer.fileformat.BibtexParser; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.net.URLDownload; import net.sf.jabref.logic.util.DOI; +import net.sf.jabref.model.cleanup.FieldFormatterCleanup; import net.sf.jabref.model.entry.BibEntry; +import net.sf.jabref.model.entry.FieldName; public class DoiFetcher implements IdBasedFetcher { - private ImportFormatPreferences preferences; + private final ImportFormatPreferences preferences; public DoiFetcher(ImportFormatPreferences preferences) { this.preferences = preferences; } - private String cleanupEncoding(String bibtex) { - return new NormalizePagesFormatter().format(bibtex); - } - @Override public String getName() { return "DOI"; @@ -35,7 +35,7 @@ public String getName() { @Override public HelpFile getHelpPage() { - return HelpFile.FETCHER_DOI_TO_BIBTEX; + return HelpFile.FETCHER_DOI; } @Override @@ -52,12 +52,21 @@ public Optional performSearchById(String identifier) throws FetcherExc String bibtexString = download.downloadToString(StandardCharsets.UTF_8); // BibTeX entry - return BibtexParser.singleFromString(cleanupEncoding(bibtexString), preferences); + Optional fetchedEntry = BibtexParser.singleFromString(bibtexString, preferences); + fetchedEntry.ifPresent(this::doPostCleanup); + return fetchedEntry; } else { throw new FetcherException(Localization.lang("Invalid_DOI:_'%0'.", identifier)); } } catch (IOException e) { throw new FetcherException(Localization.lang("Invalid URL"), e); + } catch (ParseException e) { + throw new FetcherException("Could not parse BibTeX entry", e); } } + + private void doPostCleanup(BibEntry entry) { + new FieldFormatterCleanup(FieldName.PAGES, new NormalizePagesFormatter()).cleanup(entry); + new FieldFormatterCleanup(FieldName.URL, new ClearFormatter()).cleanup(entry); + } } diff --git a/src/main/java/net/sf/jabref/logic/importer/fetcher/TitleFetcher.java b/src/main/java/net/sf/jabref/logic/importer/fetcher/TitleFetcher.java new file mode 100644 index 00000000000..58d581081b5 --- /dev/null +++ b/src/main/java/net/sf/jabref/logic/importer/fetcher/TitleFetcher.java @@ -0,0 +1,45 @@ +package net.sf.jabref.logic.importer.fetcher; + +import java.util.Optional; + +import net.sf.jabref.logic.help.HelpFile; +import net.sf.jabref.logic.importer.FetcherException; +import net.sf.jabref.logic.importer.IdBasedFetcher; +import net.sf.jabref.logic.importer.ImportFormatPreferences; +import net.sf.jabref.logic.util.DOI; +import net.sf.jabref.model.entry.BibEntry; +import net.sf.jabref.model.entry.FieldName; + +public class TitleFetcher implements IdBasedFetcher { + + private ImportFormatPreferences preferences; + + public TitleFetcher(ImportFormatPreferences preferences) { + this.preferences = preferences; + } + + @Override + public String getName() { + return "Title"; + } + + @Override + public HelpFile getHelpPage() { + return HelpFile.FETCHER_TITLE; + } + + @Override + public Optional performSearchById(String identifier) throws FetcherException { + BibEntry entry = new BibEntry(); + entry.setField(FieldName.TITLE, identifier); + Optional doi = DOI.fromBibEntry(entry); + if (!doi.isPresent()) { + return Optional.empty(); + } + + DoiFetcher doiFetcher = new DoiFetcher(this.preferences); + + return doiFetcher.performSearchById(doi.get().getDOI()); + } + +} diff --git a/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexImporter.java b/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexImporter.java index a9eb8779951..51654f74f34 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexImporter.java +++ b/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexImporter.java @@ -67,7 +67,7 @@ public ParserResult importDatabase(Path filePath, Charset defaultEncoding) throw @Override public ParserResult importDatabase(BufferedReader reader) throws IOException { - return BibtexParser.parse(reader, importFormatPreferences); + return new BibtexParser(importFormatPreferences).parse(reader); } @Override diff --git a/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexParser.java b/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexParser.java index eb02ebb277e..77abc4417b1 100644 --- a/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexParser.java +++ b/src/main/java/net/sf/jabref/logic/importer/fileformat/BibtexParser.java @@ -9,7 +9,6 @@ import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Collection; -import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; @@ -85,29 +84,11 @@ public BibtexParser(ImportFormatPreferences importFormatPreferences) { * @throws IOException * @deprecated inline this method */ + @Deprecated public static ParserResult parse(Reader in, ImportFormatPreferences importFormatPreferences) throws IOException { return new BibtexParser(importFormatPreferences).parse(in); } - /** - * Parses BibtexEntries from the given string and returns the collection of all entries found. - * - * @param bibtexString - * @return Returns returns an empty collection if no entries where found or if an error occurred. - * @deprecated use parseEntries - */ - @Deprecated - public static List fromString(String bibtexString, ImportFormatPreferences importFormatPreferences) { - BibtexParser parser = new BibtexParser(importFormatPreferences); - - try { - return parser.parseEntries(bibtexString); - } catch (Exception e) { - LOGGER.warn("BibtexParser.fromString(String): " + e.getMessage(), e); - return Collections.emptyList(); - } - } - /** * Parses BibtexEntries from the given string and returns one entry found (or null if none found) *

@@ -115,10 +96,11 @@ public static List fromString(String bibtexString, ImportFormatPrefere * * @param bibtexString * @return An Optional. Optional.empty() if non was found or an error occurred. + * @throws ParseException */ public static Optional singleFromString(String bibtexString, - ImportFormatPreferences importFormatPreferences) { - Collection entries = BibtexParser.fromString(bibtexString, importFormatPreferences); + ImportFormatPreferences importFormatPreferences) throws ParseException { + Collection entries = new BibtexParser(importFormatPreferences).parseEntries(bibtexString); if ((entries == null) || entries.isEmpty()) { return Optional.empty(); } diff --git a/src/main/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviator.java b/src/main/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviator.java index 3069cf57fed..4e88cd47719 100644 --- a/src/main/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviator.java +++ b/src/main/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviator.java @@ -8,13 +8,6 @@ * This formater enables to abbreviate the authors name in the following way: * * Ex: Someone, Van Something will be abbreviated as Someone, V.S. - * - * @author Carlos Silla - * @author Christopher Oezbek - * - * @version 1.0 Created on 12/10/2004 - * @version 1.1 Fixed bug - * http://sourceforge.net/tracker/index.php?func=detail&aid=1466924&group_id=92314&atid=600306 */ public class AuthorLastFirstAbbreviator implements LayoutFormatter { diff --git a/src/main/java/net/sf/jabref/logic/net/ProxyRegisterer.java b/src/main/java/net/sf/jabref/logic/net/ProxyRegisterer.java index 4796280f4ec..78eb977e62b 100644 --- a/src/main/java/net/sf/jabref/logic/net/ProxyRegisterer.java +++ b/src/main/java/net/sf/jabref/logic/net/ProxyRegisterer.java @@ -8,10 +8,16 @@ public static void register(ProxyPreferences proxyPrefs) { System.setProperty("http.proxyHost", proxyPrefs.getHostname()); System.setProperty("http.proxyPort", proxyPrefs.getPort()); + System.setProperty("https.proxyHost", proxyPrefs.getHostname()); + System.setProperty("https.proxyPort", proxyPrefs.getPort()); + // NetworkTab.java ensures that proxyUsername and proxyPassword are neither null nor empty if (proxyPrefs.isUseAuthentication()) { System.setProperty("http.proxyUser", proxyPrefs.getUsername()); System.setProperty("http.proxyPassword", proxyPrefs.getPassword()); + + System.setProperty("https.proxyUser", proxyPrefs.getUsername()); + System.setProperty("https.proxyPassword", proxyPrefs.getPassword()); } } else { // The following two lines signal that the system proxy settings diff --git a/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java index a05a63b1187..b06fb072fe6 100644 --- a/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java @@ -149,12 +149,12 @@ public OOBibStyle(File styleFile, LayoutFormatterPreferences prefs, path = styleFile.getPath(); } - public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) - throws IOException { + public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws IOException { this.prefs = Objects.requireNonNull(prefs); + Objects.requireNonNull(resourcePath); this.encoding = StandardCharsets.UTF_8; setDefaultProperties(); - initialize(OOBibStyle.class.getResource(resourcePath).openStream()); + initialize(OOBibStyle.class.getResourceAsStream(resourcePath)); fromResource = true; path = resourcePath; } @@ -216,6 +216,7 @@ public Set getJournals() { } private void initialize(InputStream stream) throws IOException { + Objects.requireNonNull(stream); try (Reader reader = new InputStreamReader(stream, encoding)) { readFormatFile(reader); diff --git a/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java b/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java index be880e41379..e5151f5f0e5 100644 --- a/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java +++ b/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java @@ -24,8 +24,7 @@ public void test() throws URISyntaxException, IOException { File auxFile = Paths.get(AuxCommandLineTest.class.getResource("paper.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(originalReader); AuxCommandLine auxCommandLine = new AuxCommandLine(auxFile.getAbsolutePath(), result.getDatabase()); BibDatabase newDB = auxCommandLine.perform(); diff --git a/src/test/java/net/sf/jabref/gui/groups/GroupsUtilTest.java b/src/test/java/net/sf/jabref/gui/groups/GroupsUtilTest.java index ad417ac22f6..87fbf2ea5e1 100644 --- a/src/test/java/net/sf/jabref/gui/groups/GroupsUtilTest.java +++ b/src/test/java/net/sf/jabref/gui/groups/GroupsUtilTest.java @@ -25,8 +25,7 @@ public void test() throws IOException { try (BufferedReader fr = Files.newBufferedReader(Paths.get("src/test/resources/testbib/testjabref.bib"), StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(fr, - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(fr); BibDatabase db = result.getDatabase(); diff --git a/src/test/java/net/sf/jabref/gui/importer/EntryFromFileCreatorManagerTest.java b/src/test/java/net/sf/jabref/gui/importer/EntryFromFileCreatorManagerTest.java index 639b7e2e553..7d8446f32b0 100644 --- a/src/test/java/net/sf/jabref/gui/importer/EntryFromFileCreatorManagerTest.java +++ b/src/test/java/net/sf/jabref/gui/importer/EntryFromFileCreatorManagerTest.java @@ -49,7 +49,7 @@ public void testGetCreator() { public void testAddEntrysFromFiles() throws FileNotFoundException, IOException { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(reader, Globals.prefs.getImportFormatPreferences()); + ParserResult result = new BibtexParser(Globals.prefs.getImportFormatPreferences()).parse(reader); BibDatabase database = result.getDatabase(); List files = new ArrayList<>(); diff --git a/src/test/java/net/sf/jabref/logic/auxparser/AuxParserTest.java b/src/test/java/net/sf/jabref/logic/auxparser/AuxParserTest.java index 7ca72117a19..e8b63530a2c 100644 --- a/src/test/java/net/sf/jabref/logic/auxparser/AuxParserTest.java +++ b/src/test/java/net/sf/jabref/logic/auxparser/AuxParserTest.java @@ -41,7 +41,7 @@ public void testNormal() throws URISyntaxException, IOException { InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib"); File auxFile = Paths.get(AuxParserTest.class.getResource("paper.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxParser auxParser = new AuxParser(auxFile.getAbsolutePath(), result.getDatabase()); AuxParserResult auxResult = auxParser.parse(); @@ -64,7 +64,7 @@ public void testNotAllFound() throws URISyntaxException, IOException { File auxFile = Paths.get(AuxParserTest.class.getResource("badpaper.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxParser auxParser = new AuxParser(auxFile.getAbsolutePath(), result.getDatabase()); AuxParserResult auxResult = auxParser.parse(); @@ -86,7 +86,7 @@ public void duplicateBibDatabaseConfiguration() throws URISyntaxException, IOExc InputStream originalStream = AuxParserTest.class.getResourceAsStream("config.bib"); File auxFile = Paths.get(AuxParserTest.class.getResource("paper.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxParser auxParser = new AuxParser(auxFile.getAbsolutePath(), result.getDatabase()); AuxParserResult auxResult = auxParser.parse(); @@ -102,7 +102,7 @@ public void testNestedAux() throws URISyntaxException, IOException { InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib"); File auxFile = Paths.get(AuxParserTest.class.getResource("nested.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxParser auxParser = new AuxParser(auxFile.getAbsolutePath(), result.getDatabase()); AuxParserResult auxResult = auxParser.parse(); @@ -124,7 +124,7 @@ public void testCrossRef() throws URISyntaxException, IOException { InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib"); File auxFile = Paths.get(AuxParserTest.class.getResource("crossref.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(originalReader, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxParser auxParser = new AuxParser(auxFile.getAbsolutePath(), result.getDatabase()); AuxParserResult auxResult = auxParser.parse(); diff --git a/src/test/java/net/sf/jabref/logic/bibtex/BibEntryWriterTest.java b/src/test/java/net/sf/jabref/logic/bibtex/BibEntryWriterTest.java index f4c9bad4ea4..2fcba1b0e2d 100644 --- a/src/test/java/net/sf/jabref/logic/bibtex/BibEntryWriterTest.java +++ b/src/test/java/net/sf/jabref/logic/bibtex/BibEntryWriterTest.java @@ -111,7 +111,7 @@ public void roundTripTest() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -135,7 +135,7 @@ public void roundTripWithPrependingNewlines() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -159,7 +159,7 @@ public void roundTripWithModification() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -195,7 +195,7 @@ public void roundTripWithCamelCasingInTheOriginalEntryAndResultInLowerCase() thr // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -232,7 +232,7 @@ public void testEntryTypeChange() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(expected), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(expected)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -269,7 +269,7 @@ public void roundTripWithAppendedNewlines() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -302,7 +302,7 @@ public void multipleWritesWithoutModification() throws IOException { private String testSingleWrite(String bibtexEntry) throws IOException { // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -326,7 +326,7 @@ public void monthFieldSpecialSyntax() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -355,7 +355,7 @@ public void addFieldWithLongerLength() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -429,7 +429,7 @@ public void roundTripWithPrecedingCommentTest() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -454,7 +454,7 @@ public void roundTripWithPrecedingCommentAndModificationTest() throws IOExceptio // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); diff --git a/src/test/java/net/sf/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java b/src/test/java/net/sf/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java index 6047f23e134..dc04456175a 100644 --- a/src/test/java/net/sf/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java +++ b/src/test/java/net/sf/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java @@ -3,6 +3,7 @@ import java.util.Optional; import net.sf.jabref.logic.importer.ImportFormatPreferences; +import net.sf.jabref.logic.importer.ParseException; import net.sf.jabref.logic.importer.fileformat.BibtexParser; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; @@ -46,7 +47,7 @@ public void setUp() { } @Test - public void testAndInAuthorName() { + public void testAndInAuthorName() throws ParseException { Optional entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Simon Holland}}", importFormatPreferences); assertEquals("Holland", @@ -55,7 +56,7 @@ public void testAndInAuthorName() { } @Test - public void testAndAuthorNames() { + public void testAndAuthorNames() throws ParseException { String bibtexString = "@ARTICLE{whatevery, author={Mari D. Herland and Mona-Iren Hauge and Ingeborg M. Helgeland}}"; Optional entry = BibtexParser.singleFromString(bibtexString, importFormatPreferences); assertEquals("HerlandHaugeHelgeland", @@ -64,7 +65,7 @@ public void testAndAuthorNames() { } @Test - public void testSpecialLatexCharacterInAuthorName() { + public void testSpecialLatexCharacterInAuthorName() throws ParseException { Optional entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={Simon Popovi\\v{c}ov\\'{a}}}", importFormatPreferences); assertEquals("Popovicova", @@ -77,7 +78,7 @@ public void testSpecialLatexCharacterInAuthorName() { * Ć ć É é Í í Ĺ ĺ Ń ń Ó ó Ŕ ŕ Ś ś Ú ú Ý ý Ź ź */ @Test - public void testMakeLabelAndCheckLegalKeys() { + public void testMakeLabelAndCheckLegalKeys() throws ParseException { Optional entry0 = BibtexParser.singleFromString( "@ARTICLE{kohn, author={Andreas Köning}, year={2000}}", importFormatPreferences); @@ -156,7 +157,7 @@ public void testMakeLabelAndCheckLegalKeys() { * Test the Labelmaker and with accent grave Chars to test: "ÀÈÌÒÙ"; */ @Test - public void testMakeLabelAndCheckLegalKeysAccentGrave() { + public void testMakeLabelAndCheckLegalKeysAccentGrave() throws ParseException { Optional entry0 = BibtexParser.singleFromString( "@ARTICLE{kohn, author={Andreas Àöning}, year={2000}}", importFormatPreferences); assertEquals("Aoen", @@ -269,7 +270,7 @@ public void testFirstAuthorNull() { } @Test - public void testUniversity() { + public void testUniversity() throws ParseException { Optional entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University}}}", importFormatPreferences); assertEquals("UniLinkoeping", @@ -278,7 +279,7 @@ public void testUniversity() { } @Test - public void testDepartment() { + public void testDepartment() throws ParseException { Optional entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University, Department of Electrical Engineering}}}", importFormatPreferences); @@ -288,7 +289,7 @@ public void testDepartment() { } @Test - public void testSchool() { + public void testSchool() throws ParseException { Optional entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University, School of Computer Engineering}}}", importFormatPreferences); @@ -298,7 +299,7 @@ public void testSchool() { } @Test - public void testInstituteOfTechnology() { + public void testInstituteOfTechnology() throws ParseException { Optional entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Massachusetts Institute of Technology}}}", importFormatPreferences); assertEquals("MIT", diff --git a/src/test/java/net/sf/jabref/logic/bst/TestVM.java b/src/test/java/net/sf/jabref/logic/bst/TestVM.java index 1a3a39a5073..091df58a995 100644 --- a/src/test/java/net/sf/jabref/logic/bst/TestVM.java +++ b/src/test/java/net/sf/jabref/logic/bst/TestVM.java @@ -640,8 +640,7 @@ public void testVMSwap() throws RecognitionException { } private static BibEntry bibtexString2BibtexEntry(String s) throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(s), - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); return c.iterator().next(); diff --git a/src/test/java/net/sf/jabref/logic/exporter/BibtexDatabaseWriterTest.java b/src/test/java/net/sf/jabref/logic/exporter/BibtexDatabaseWriterTest.java index db076eccd68..9cde3e5211d 100644 --- a/src/test/java/net/sf/jabref/logic/exporter/BibtexDatabaseWriterTest.java +++ b/src/test/java/net/sf/jabref/logic/exporter/BibtexDatabaseWriterTest.java @@ -266,8 +266,7 @@ public void writeEntryWithCustomizedTypeAlsoWritesTypeDeclaration() throws Excep public void roundtrip() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); Charset encoding = StandardCharsets.UTF_8; - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, encoding), - importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, encoding)); SavePreferences preferences = new SavePreferences().withEncoding(encoding).withSaveInOriginalOrder(true); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData(), @@ -283,8 +282,7 @@ public void roundtrip() throws Exception { public void roundtripWithUserComment() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/bibWithUserComments.bib"); Charset encoding = StandardCharsets.UTF_8; - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, encoding), - importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, encoding)); SavePreferences preferences = new SavePreferences().withEncoding(encoding).withSaveInOriginalOrder(true); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData(), @@ -300,8 +298,7 @@ public void roundtripWithUserComment() throws Exception { public void roundtripWithUserCommentAndEntryChange() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/bibWithUserComments.bib"); Charset encoding = StandardCharsets.UTF_8; - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, encoding), - importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, encoding)); BibEntry entry = result.getDatabase().getEntryByKey("1137631").get(); entry.setField("author", "Mr. Author"); @@ -321,8 +318,7 @@ public void roundtripWithUserCommentAndEntryChange() throws Exception { public void roundtripWithUserCommentBeforeStringAndChange() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); Charset encoding = StandardCharsets.UTF_8; - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, encoding), - importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, encoding)); for (BibtexString string : result.getDatabase().getStringValues()) { // Mark them as changed diff --git a/src/test/java/net/sf/jabref/logic/importer/BibDatabaseTestsWithFiles.java b/src/test/java/net/sf/jabref/logic/importer/BibDatabaseTestsWithFiles.java index d62a17f5c20..0533be1c2f3 100644 --- a/src/test/java/net/sf/jabref/logic/importer/BibDatabaseTestsWithFiles.java +++ b/src/test/java/net/sf/jabref/logic/importer/BibDatabaseTestsWithFiles.java @@ -27,7 +27,7 @@ public void setUp() { public void resolveStrings() throws IOException { try (FileInputStream stream = new FileInputStream("src/test/resources/net/sf/jabref/util/twente.bib"); InputStreamReader fr = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(fr, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(fr); BibDatabase db = result.getDatabase(); diff --git a/src/test/java/net/sf/jabref/logic/importer/DatabaseFileLookupTest.java b/src/test/java/net/sf/jabref/logic/importer/DatabaseFileLookupTest.java index 249652d4f23..90e21e42b56 100644 --- a/src/test/java/net/sf/jabref/logic/importer/DatabaseFileLookupTest.java +++ b/src/test/java/net/sf/jabref/logic/importer/DatabaseFileLookupTest.java @@ -33,8 +33,7 @@ public class DatabaseFileLookupTest { public void setUp() throws FileNotFoundException, IOException { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(reader, - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(reader); database = result.getDatabase(); entries = database.getEntries(); diff --git a/src/test/java/net/sf/jabref/logic/importer/ParsedBibEntryTests.java b/src/test/java/net/sf/jabref/logic/importer/ParsedBibEntryTests.java index ecebc8b1f1f..1a68f6f442a 100644 --- a/src/test/java/net/sf/jabref/logic/importer/ParsedBibEntryTests.java +++ b/src/test/java/net/sf/jabref/logic/importer/ParsedBibEntryTests.java @@ -21,7 +21,7 @@ public void setUp() { } @Test - public void testGetPublicationDate() { + public void testGetPublicationDate() throws ParseException { Assert.assertEquals(Optional.of("2003-02"), (BibtexParser.singleFromString("@ARTICLE{HipKro03, year = {2003}, month = #FEB# }", diff --git a/src/test/java/net/sf/jabref/logic/importer/fetcher/DiVATest.java b/src/test/java/net/sf/jabref/logic/importer/fetcher/DiVATest.java index 60a4eec1f65..83038afe3e2 100644 --- a/src/test/java/net/sf/jabref/logic/importer/fetcher/DiVATest.java +++ b/src/test/java/net/sf/jabref/logic/importer/fetcher/DiVATest.java @@ -32,7 +32,7 @@ public void testGetName() { @Test public void testGetHelpPage() { - assertEquals(HelpFile.FETCHER_DIVA_TO_BIBTEX, HelpFile.FETCHER_DIVA_TO_BIBTEX); + assertEquals(HelpFile.FETCHER_DIVA, HelpFile.FETCHER_DIVA); } @Test diff --git a/src/test/java/net/sf/jabref/logic/importer/fetcher/DoiFetcherTest.java b/src/test/java/net/sf/jabref/logic/importer/fetcher/DoiFetcherTest.java index 1eb3d200ab1..5dc08dc7a70 100644 --- a/src/test/java/net/sf/jabref/logic/importer/fetcher/DoiFetcherTest.java +++ b/src/test/java/net/sf/jabref/logic/importer/fetcher/DoiFetcherTest.java @@ -34,7 +34,6 @@ public void setUp() { bibEntryBurd2011.setField("author", "Barry Burd"); bibEntryBurd2011.setField("month", "jul"); bibEntryBurd2011.setField("doi", "10.1002/9781118257517"); - bibEntryBurd2011.setField("url", "http://dx.doi.org/10.1002/9781118257517"); bibEntryDecker2007 = new BibEntry(); bibEntryDecker2007.setType(BibLatexEntryTypes.INPROCEEDINGS); @@ -44,7 +43,6 @@ public void setUp() { bibEntryDecker2007.setField("month", "jul"); bibEntryDecker2007.setField("publisher", "Institute of Electrical and Electronics Engineers ({IEEE})"); bibEntryDecker2007.setField("title", "{BPEL}4Chor: Extending {BPEL} for Modeling Choreographies"); - bibEntryDecker2007.setField("url", "http://dx.doi.org/10.1109/ICWS.2007.59"); bibEntryDecker2007.setField("year", "2007"); bibEntryDecker2007.setField("doi", "10.1109/icws.2007.59"); } diff --git a/src/test/java/net/sf/jabref/logic/importer/fetcher/TitleFetcherTest.java b/src/test/java/net/sf/jabref/logic/importer/fetcher/TitleFetcherTest.java new file mode 100644 index 00000000000..08ed4fb6587 --- /dev/null +++ b/src/test/java/net/sf/jabref/logic/importer/fetcher/TitleFetcherTest.java @@ -0,0 +1,66 @@ +package net.sf.jabref.logic.importer.fetcher; + +import java.util.Optional; + +import net.sf.jabref.logic.importer.FetcherException; +import net.sf.jabref.model.entry.BibEntry; +import net.sf.jabref.model.entry.BibLatexEntryTypes; +import net.sf.jabref.preferences.JabRefPreferences; +import net.sf.jabref.testutils.category.FetcherTests; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import static org.junit.Assert.assertEquals; + +@Category(FetcherTests.class) +public class TitleFetcherTest { + + private TitleFetcher fetcher; + private BibEntry bibEntryBischof2009; + + @Before + public void setUp() { + fetcher = new TitleFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + + bibEntryBischof2009 = new BibEntry(); + bibEntryBischof2009.setType(BibLatexEntryTypes.INPROCEEDINGS); + bibEntryBischof2009.setField("bibtexkey", "Bischof_2009"); + bibEntryBischof2009.setField("author", "Marc Bischof and Oliver Kopp and Tammo van Lessen and Frank Leymann"); + bibEntryBischof2009.setField("booktitle", "2009 35th Euromicro Conference on Software Engineering and Advanced Applications"); + bibEntryBischof2009.setField("publisher", "Institute of Electrical and Electronics Engineers ({IEEE})"); + bibEntryBischof2009.setField("title", "{BPELscript}: A Simplified Script Syntax for {WS}-{BPEL} 2.0"); + bibEntryBischof2009.setField("year", "2009"); + bibEntryBischof2009.setField("doi", "10.1109/seaa.2009.21"); + } + + @Test + public void testGetName() { + assertEquals("Title", fetcher.getName()); + } + + @Test + public void testGetHelpPage() { + assertEquals("TitleToBibTeX", fetcher.getHelpPage().getPageName()); + } + + @Test + public void testPerformSearchKopp2007() throws FetcherException { + Optional fetchedEntry = fetcher.performSearchById("BPELscript: A simplified script syntax for WS-BPEL 2.0"); + assertEquals(Optional.of(bibEntryBischof2009), fetchedEntry); + } + + @Test + public void testPerformSearchEmptyTitle() throws FetcherException { + Optional fetchedEntry = fetcher.performSearchById(""); + assertEquals(Optional.empty(), fetchedEntry); + } + + @Test + public void testPerformSearchInvalidTitle() throws FetcherException { + Optional fetchedEntry = fetcher.performSearchById("An unknown title where noi DOI can be determined"); + assertEquals(Optional.empty(), fetchedEntry); + } + +} diff --git a/src/test/java/net/sf/jabref/logic/importer/fileformat/BibtexParserTest.java b/src/test/java/net/sf/jabref/logic/importer/fileformat/BibtexParserTest.java index a9e577b8145..e191ee3be16 100644 --- a/src/test/java/net/sf/jabref/logic/importer/fileformat/BibtexParserTest.java +++ b/src/test/java/net/sf/jabref/logic/importer/fileformat/BibtexParserTest.java @@ -27,6 +27,7 @@ import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.BibtexString; import net.sf.jabref.model.entry.EntryType; +import net.sf.jabref.model.entry.FieldName; import net.sf.jabref.model.groups.AllEntriesGroup; import net.sf.jabref.model.groups.ExplicitGroup; import net.sf.jabref.model.groups.GroupHierarchyType; @@ -36,8 +37,7 @@ import net.sf.jabref.model.metadata.SaveOrderConfig; import net.sf.jabref.preferences.JabRefPreferences; -import org.junit.BeforeClass; -import org.junit.Ignore; +import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -50,22 +50,26 @@ */ public class BibtexParserTest { - private static ImportFormatPreferences importFormatPreferences; + private ImportFormatPreferences importFormatPreferences; + private BibtexParser parser; - @BeforeClass - public static void setUp() { + @Before + public void setUp() { importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + parser = new BibtexParser(importFormatPreferences); } + @SuppressWarnings("unused") @Test(expected = NullPointerException.class) public void parseWithNullThrowsNullPointerException() throws Exception { - new BibtexParser(importFormatPreferences).parse(null); + parser.parse(null); } @Test - public void fromStringRecognizesEntry() { - List parsed = BibtexParser.fromString("@article{test,author={Ed von Test}}", importFormatPreferences); + public void fromStringRecognizesEntry() throws ParseException { + List parsed = parser + .parseEntries("@article{test,author={Ed von Test}}"); BibEntry expected = new BibEntry(); expected.setType("article"); @@ -75,21 +79,22 @@ public void fromStringRecognizesEntry() { } @Test - public void fromStringReturnsEmptyListFromEmptyString() { - Collection parsed = BibtexParser.fromString("", importFormatPreferences); + public void fromStringReturnsEmptyListFromEmptyString() throws ParseException { + Collection parsed = parser.parseEntries(""); assertNotNull(parsed); assertEquals(Collections.emptyList(), parsed); } @Test - public void fromStringReturnsEmptyListIfNoEntryRecognized() { - Collection parsed = BibtexParser.fromString("@@article@@{{{{{{}", importFormatPreferences); + public void fromStringReturnsEmptyListIfNoEntryRecognized() throws ParseException { + Collection parsed = parser + .parseEntries("@@article@@{{{{{{}"); assertNotNull(parsed); assertEquals(Collections.emptyList(), parsed); } @Test - public void singleFromStringRecognizesEntry() { + public void singleFromStringRecognizesEntry() throws ParseException { Optional parsed = BibtexParser.singleFromString( "@article{canh05," + " author = {Crowston, K. and Annabi, H.},\n" + " title = {Title A}}\n", importFormatPreferences); @@ -103,7 +108,7 @@ public void singleFromStringRecognizesEntry() { } @Test - public void singleFromStringRecognizesEntryInMultiple() { + public void singleFromStringRecognizesEntryInMultiple() throws ParseException { Optional parsed = BibtexParser.singleFromString( "@article{canh05," + " author = {Crowston, K. and Annabi, H.},\n" + " title = {Title A}}\n" + "@inProceedings{foo," + " author={Norton Bar}}", @@ -114,21 +119,21 @@ public void singleFromStringRecognizesEntryInMultiple() { } @Test - public void singleFromStringReturnsNullFromEmptyString() { + public void singleFromStringReturnsEmptyFromEmptyString() throws ParseException { Optional parsed = BibtexParser.singleFromString("", importFormatPreferences); assertEquals(Optional.empty(), parsed); } @Test - public void singleFromStringReturnsNullIfNoEntryRecognized() { + public void singleFromStringReturnsEmptyIfNoEntryRecognized() throws ParseException { Optional parsed = BibtexParser.singleFromString("@@article@@{{{{{{}", importFormatPreferences); assertEquals(Optional.empty(), parsed); } @Test public void parseRecognizesEntry() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test}}")); List parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size()); @@ -143,8 +148,8 @@ public void parseRecognizesEntry() throws IOException { @Test public void parseQuotedEntries() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"Ed von Test\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"Ed von Test\"}")); List parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size()); @@ -159,7 +164,7 @@ public void parseQuotedEntries() throws IOException { @Test public void parseRecognizesEntryOnlyWithKey() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test}"), importFormatPreferences); + ParserResult result = parser.parse(new StringReader("@article{test}")); List parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size()); @@ -172,8 +177,8 @@ public void parseRecognizesEntryOnlyWithKey() throws IOException { @Test public void parseRecognizesEntryWithWhitespaceAtBegining() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(" @article{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(" @article{test,author={Ed von Test}}")); List parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size()); @@ -188,8 +193,8 @@ public void parseRecognizesEntryWithWhitespaceAtBegining() throws IOException { @Test public void parseRecognizesEntryWithWhitespace() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article { test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article { test,author={Ed von Test}}")); List parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size()); @@ -204,8 +209,8 @@ public void parseRecognizesEntryWithWhitespace() throws IOException { @Test public void parseRecognizesEntryWithNewlines() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article\n{\ntest,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article\n{\ntest,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -220,8 +225,8 @@ public void parseRecognizesEntryWithNewlines() throws IOException { @Test public void parseRecognizesEntryWithUnknownType() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@unknown{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@unknown{test,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -233,44 +238,11 @@ public void parseRecognizesEntryWithUnknownType() throws IOException { assertEquals(Optional.of("Ed von Test"), e.getField("author")); } - @Test - public void parseReallyUnknownType() throws Exception { - String bibtexEntry = "@ReallyUnknownType{test," + OS.NEWLINE + - " Comment = {testentry}" + OS.NEWLINE + - "}"; - - Collection entries = new BibtexParser(importFormatPreferences).parseEntries(bibtexEntry); - - BibEntry expectedEntry = new BibEntry(); - expectedEntry.setType("Reallyunknowntype"); - expectedEntry.setCiteKey("test"); - expectedEntry.setField("comment", "testentry"); - - assertEquals(Collections.singletonList(expectedEntry), entries); - } - - @Test - public void parseOtherTypeTest() throws Exception { - String bibtexEntry = "@Other{test," + OS.NEWLINE + - " Comment = {testentry}" + OS.NEWLINE + - "}"; - - Collection entries = new BibtexParser(importFormatPreferences).parseEntries(bibtexEntry); - - BibEntry expectedEntry = new BibEntry(); - expectedEntry.setType("Other"); - expectedEntry.setCiteKey("test"); - expectedEntry.setField("comment", "testentry"); - - assertEquals(Collections.singletonList(expectedEntry), entries); - } - @Test public void parseRecognizesEntryWithVeryLongType() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@thisIsALongStringToTestMaybeItIsToLongWhoKnowsNOTme{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader("@thisIsALongStringToTestMaybeItIsToLongWhoKnowsNOTme{test,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -285,8 +257,8 @@ public void parseRecognizesEntryWithVeryLongType() throws IOException { @Test public void parseRecognizesEntryInParenthesis() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article(test,author={Ed von Test})"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article(test,author={Ed von Test})")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -321,9 +293,8 @@ public void parseRecognizesEntryWithBigNumbers() throws IOException { @Test public void parseRecognizesBibtexKeyWithSpecialCharacters() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{te_st:with-special(characters),author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{te_st:with-special(characters),author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -337,8 +308,8 @@ public void parseRecognizesBibtexKeyWithSpecialCharacters() throws IOException { @Test public void parseRecognizesEntryWhereLastFieldIsFinishedWithComma() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={Ed von Test},}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test},}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -352,8 +323,8 @@ public void parseRecognizesEntryWhereLastFieldIsFinishedWithComma() throws IOExc @Test public void parseRecognizesEntryWithAtInField() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={Ed von T@st}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von T@st}}")); List parsed = result.getDatabase().getEntries(); @@ -368,7 +339,7 @@ public void parseRecognizesEntryPrecedingComment() throws IOException { String comment = "@Comment{@article{myarticle,}" + OS.NEWLINE + "@inproceedings{blabla, title={the proceedings of bl@bl@}; }" + OS.NEWLINE + "}"; String entryWithComment = comment + OS.NEWLINE + "@article{test,author={Ed von T@st}}"; - ParserResult result = BibtexParser.parse(new StringReader(entryWithComment), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(entryWithComment)); List parsed = result.getDatabase().getEntries(); @@ -413,7 +384,8 @@ public void parseSetsParsedSerialization() throws IOException { + " title = {Title A}}" + OS.NEWLINE; String secondEntry = "@inProceedings{foo," + " author={Norton Bar}}"; - ParserResult result = BibtexParser.parse(new StringReader(firstEntry + secondEntry), importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(firstEntry + secondEntry)); for (BibEntry entry : result.getDatabase().getEntries()) { if (entry.getCiteKeyOptional().get().equals("canh05")) { @@ -427,8 +399,8 @@ public void parseSetsParsedSerialization() throws IOException { @Test public void parseRecognizesMultipleEntriesOnSameLine() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{canh05}" + "@inProceedings{foo}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{canh05}" + "@inProceedings{foo}")); List parsed = result.getDatabase().getEntries(); List expected = new ArrayList<>(); @@ -448,9 +420,8 @@ public void parseRecognizesMultipleEntriesOnSameLine() throws IOException { @Test public void parseCombinesMultipleAuthorFields() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,author={Ed von Test},author={Second Author},author={Third Author}}"), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader("@article{test,author={Ed von Test},author={Second Author},author={Third Author}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -465,9 +436,8 @@ public void parseCombinesMultipleAuthorFields() throws IOException { @Test public void parseCombinesMultipleEditorFields() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,editor={Ed von Test},editor={Second Author},editor={Third Author}}"), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader("@article{test,editor={Ed von Test},editor={Second Author},editor={Third Author}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -485,9 +455,8 @@ public void parseCombinesMultipleEditorFields() throws IOException { @Test public void parseCombinesMultipleKeywordsFields() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,Keywords={Test},Keywords={Second Keyword},Keywords={Third Keyword}}"), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader("@article{test,Keywords={Test},Keywords={Second Keyword},Keywords={Third Keyword}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -518,8 +487,7 @@ public void parseRecognizesHeaderButIgnoresEncoding() throws IOException { assertEquals("inproceedings", e.getType()); assertEquals(8, e.getFieldNames().size()); assertEquals(Optional.of("CroAnnHow05"), e.getCiteKeyOptional()); - assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), - e.getField("author")); + assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), e.getField("author")); assertEquals(Optional.of("Effective work practices for floss development: A model and propositions"), e.getField("title")); assertEquals(Optional.of("Hawaii International Conference On System Sciences (HICSS)"), @@ -547,8 +515,7 @@ public void parseRecognizesFormatedEntry() throws IOException { assertEquals("inproceedings", e.getType()); assertEquals(8, e.getFieldNames().size()); assertEquals(Optional.of("CroAnnHow05"), e.getCiteKeyOptional()); - assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), - e.getField("author")); + assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), e.getField("author")); assertEquals(Optional.of("Effective work practices for floss development: A model and propositions"), e.getField("title")); assertEquals(Optional.of("Hawaii International Conference On System Sciences (HICSS)"), @@ -562,8 +529,8 @@ public void parseRecognizesFormatedEntry() throws IOException { @Test public void parseRecognizesFieldValuesInQuotationMarks() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"Ed von Test\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"Ed von Test\"}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -578,8 +545,8 @@ public void parseRecognizesFieldValuesInQuotationMarks() throws IOException { @Test public void parseRecognizesNumbersWithoutBracketsOrQuotationMarks() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,year = 2005}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,year = 2005}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -594,8 +561,8 @@ public void parseRecognizesNumbersWithoutBracketsOrQuotationMarks() throws IOExc @Test public void parseRecognizesUppercaseFields() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,AUTHOR={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,AUTHOR={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -613,9 +580,8 @@ public void parseRecognizesUppercaseFields() throws IOException { @Test public void parseRecognizesAbsoluteFile() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,file = {D:\\Documents\\literature\\Tansel-PRL2006.pdf}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,file = {D:\\Documents\\literature\\Tansel-PRL2006.pdf}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -633,8 +599,8 @@ public void parseRecognizesAbsoluteFile() throws IOException { @Test public void parseRecognizesDateFieldWithConcatenation() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,date = {1-4~} # nov}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,date = {1-4~} # nov}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -662,9 +628,8 @@ public void parseReturnsEmptyListIfNoEntryRecognized() throws IOException { @Test public void parseReturnsEmptyListIfNoEntryExistent() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("This was created with JabRef 2.1 beta 2." + "\n" + "Encoding: Cp1252" + "\n"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("This was created with JabRef 2.1 beta 2." + "\n" + "Encoding: Cp1252" + "\n")); Collection c = result.getDatabase().getEntries(); assertEquals(0, c.size()); } @@ -685,8 +650,8 @@ public void parseRecognizesDuplicateBibtexKeys() throws IOException { @Test public void parseWarnsAboutEntryWithoutBibtexKey() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{,author={Ed von Test}}")); assertTrue(result.hasWarnings()); @@ -702,8 +667,8 @@ public void parseWarnsAboutEntryWithoutBibtexKey() throws IOException { @Test public void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracket() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author missing bracket}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={author missing bracket}")); assertTrue(result.hasWarnings()); @@ -717,8 +682,8 @@ public void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracket() throws IOEx @Test public void parseAddsEscapedOpenBracketToFieldValue() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,review={escaped \\{ bracket}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,review={escaped \\{ bracket}}")); assertFalse(result.hasWarnings()); @@ -734,8 +699,8 @@ public void parseAddsEscapedOpenBracketToFieldValue() throws IOException { @Test public void parseAddsEscapedClosingBracketToFieldValue() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,review={escaped \\} bracket}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,review={escaped \\} bracket}}")); assertFalse(result.hasWarnings()); @@ -751,8 +716,8 @@ public void parseAddsEscapedClosingBracketToFieldValue() throws IOException { @Test public void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracketInQuotationMarks() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"author {missing bracket\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"author {missing bracket\"}")); assertTrue(result.hasWarnings()); @@ -763,8 +728,8 @@ public void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracketInQuotationMar @Test public void parseIgnoresArbitraryContentAfterEntry() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author bracket }}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={author bracket }}}")); Collection c = result.getDatabase().getEntries(); assertEquals("Size should be one, but was " + c.size(), 1, c.size()); @@ -772,39 +737,32 @@ public void parseIgnoresArbitraryContentAfterEntry() throws IOException { } @Test - public void parseWarnsAboutUnmatchedContentInEntry() throws IOException { - - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author bracket }, too much}"), + public void parseWarnsAboutUnmatchedContentInEntryWithoutComma() throws IOException { + ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author bracket } too much}"), importFormatPreferences); - assertTrue("There should be warnings", result.hasWarnings()); - - Collection c = result.getDatabase().getEntries(); - assertEquals("Size should be zero, but was " + c.size(), 0, c.size()); + List entries = result.getDatabase().getEntries(); + assertEquals(Optional.of("author bracket #too##much#"), entries.get(0).getField("author")); } @Test - @Ignore("Ignoring because this is an edge case") - public void parseWarnsAboutUnmatchedContentInEntryWithoutComma() throws IOException { - - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author bracket } too much}"), + public void parseWarnsAboutUnmatchedContentInEntry() throws IOException { + ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author bracket }, too much}"), importFormatPreferences); assertTrue("There should be warnings", result.hasWarnings()); - Collection c = result.getDatabase().getEntries(); - assertEquals("Size should be zero, but was " + c.size(), 0, c.size()); + List entries = result.getDatabase().getEntries(); + assertEquals("Size should be zero, but was " + entries.size(), 0, entries.size()); } @Test public void parseAcceptsEntryWithAtSymbolInBrackets() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={author @ good}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={author @ good}}")); - Collection c = result.getDatabase().getEntries(); - List entries = new ArrayList<>(1); - entries.addAll(c); + List entries = result.getDatabase().getEntries(); assertEquals(1, entries.size()); assertEquals(Optional.of("author @ good"), entries.get(0).getField("author")); @@ -813,8 +771,8 @@ public void parseAcceptsEntryWithAtSymbolInBrackets() throws IOException { @Test public void parseRecognizesEntryWithAtSymbolInQuotationMarks() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"author @ good\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"author @ good\"}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -829,8 +787,8 @@ public void parseRecognizesEntryWithAtSymbolInQuotationMarks() throws IOExceptio @Test public void parseRecognizesFieldsWithBracketsEnclosedInQuotationMarks() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"Test {Ed {von} Test}\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"Test {Ed {von} Test}\"}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -846,8 +804,8 @@ public void parseRecognizesFieldsWithBracketsEnclosedInQuotationMarks() throws I public void parseRecognizesFieldsWithEscapedQuotationMarks() throws IOException { // Quotes in fields of the form key = "value" have to be escaped by putting them into braces - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author=\"Test {\" Test}\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author=\"Test {\" Test}\"}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -862,8 +820,8 @@ public void parseRecognizesFieldsWithEscapedQuotationMarks() throws IOException @Test public void parseIgnoresAndWarnsAboutEntryWithFieldsThatAreNotSeperatedByComma() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={Ed von Test} year=2005}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test} year=2005}")); assertTrue(result.hasWarnings()); @@ -897,8 +855,8 @@ public void parseIgnoresAndWarnsAboutCorruptedEntryButRecognizeOthers() throws I @Test public void parseRecognizesMonthFieldsWithFollowingComma() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author={Ed von Test},month={8,}},"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test},month={8,}},")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -914,48 +872,48 @@ public void parseRecognizesMonthFieldsWithFollowingComma() throws IOException { @Test public void parseRecognizesPreamble() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@preamble{some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@preamble{some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test public void parseRecognizesUppercasePreamble() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@PREAMBLE{some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@PREAMBLE{some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test public void parseRecognizesPreambleWithWhitespace() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@preamble {some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@preamble {some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test public void parseRecognizesPreambleInParenthesis() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@preamble(some text and \\latex)"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@preamble(some text and \\latex)")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test public void parseRecognizesPreambleWithConcatenation() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@preamble{\"some text\" # \"and \\latex\"}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@preamble{\"some text\" # \"and \\latex\"}")); assertEquals(Optional.of("\"some text\" # \"and \\latex\""), result.getDatabase().getPreamble()); } @Test public void parseRecognizesString() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}")); assertEquals(1, result.getDatabase().getStringCount()); BibtexString s = result.getDatabase().getStringValues().iterator().next(); @@ -967,8 +925,8 @@ public void parseRecognizesString() throws IOException { public void parseSavesOneNewlineAfterStringInParsedSerialization() throws IOException { String string = "@string{bourdieu = {Bourdieu, Pierre}}" + OS.NEWLINE; - ParserResult result = BibtexParser.parse(new StringReader(string + OS.NEWLINE + OS.NEWLINE), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(string + OS.NEWLINE + OS.NEWLINE)); assertEquals(1, result.getDatabase().getStringCount()); BibtexString s = result.getDatabase().getStringValues().iterator().next(); @@ -978,8 +936,8 @@ public void parseSavesOneNewlineAfterStringInParsedSerialization() throws IOExce @Test public void parseRecognizesStringWithWhitespace() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@string {bourdieu = {Bourdieu, Pierre}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@string {bourdieu = {Bourdieu, Pierre}}")); assertEquals(1, result.getDatabase().getStringCount()); BibtexString s = result.getDatabase().getStringValues().iterator().next(); @@ -990,8 +948,8 @@ public void parseRecognizesStringWithWhitespace() throws IOException { @Test public void parseRecognizesStringInParenthesis() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@string(bourdieu = {Bourdieu, Pierre})"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@string(bourdieu = {Bourdieu, Pierre})")); assertEquals(1, result.getDatabase().getStringCount()); BibtexString s = result.getDatabase().getStringValues().iterator().next(); @@ -1002,9 +960,8 @@ public void parseRecognizesStringInParenthesis() throws IOException { @Test public void parseRecognizesMultipleStrings() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{adieu = {Adieu, Pierre}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{adieu = {Adieu, Pierre}}")); assertEquals(2, result.getDatabase().getStringCount()); Iterator iterator = result.getDatabase().getStringValues().iterator(); @@ -1057,9 +1014,8 @@ public void parseRecognizesStringAndEntry() throws IOException { @Test public void parseWarnsAboutStringsWithSameNameAndOnlyKeepsOne() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{bourdieu = {Other}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{bourdieu = {Other}}")); assertTrue(result.hasWarnings()); assertEquals(1, result.getDatabase().getStringCount()); } @@ -1067,25 +1023,24 @@ public void parseWarnsAboutStringsWithSameNameAndOnlyKeepsOne() throws IOExcepti @Test public void parseIgnoresComments() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@comment{some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@comment{some text and \\latex}")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test public void parseIgnoresUpercaseComments() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@COMMENT{some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@COMMENT{some text and \\latex}")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test public void parseIgnoresCommentsBeforeEntry() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@comment{some text and \\latex}" + "@article{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@comment{some text and \\latex}" + "@article{test,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1099,9 +1054,8 @@ public void parseIgnoresCommentsBeforeEntry() throws IOException { @Test public void parseIgnoresCommentsAfterEntry() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,author={Ed von Test}}" + "@comment{some text and \\latex}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test}}" + "@comment{some text and \\latex}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1115,17 +1069,16 @@ public void parseIgnoresCommentsAfterEntry() throws IOException { @Test public void parseIgnoresText() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("comment{some text and \\latex"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("comment{some text and \\latex")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test public void parseIgnoresTextBeforeEntry() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("comment{some text and \\latex" + "@article{test,author={Ed von Test}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("comment{some text and \\latex" + "@article{test,author={Ed von Test}}")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1139,9 +1092,8 @@ public void parseIgnoresTextBeforeEntry() throws IOException { @Test public void parseIgnoresTextAfterEntry() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,author={Ed von Test}}" + "comment{some text and \\latex"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author={Ed von Test}}" + "comment{some text and \\latex")); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1155,8 +1107,8 @@ public void parseIgnoresTextAfterEntry() throws IOException { @Test public void parseConvertsNewlineToSpace() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,a = {a\nb}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,a = {a\nb}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -1166,9 +1118,8 @@ public void parseConvertsNewlineToSpace() throws IOException { @Test public void parseConvertsMultipleNewlinesToSpace() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,a = {a\n\nb}," + "b = {a\n \nb}," + "c = {a \n \n b}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,a = {a\n\nb}," + "b = {a\n \nb}," + "c = {a \n \n b}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -1180,8 +1131,8 @@ public void parseConvertsMultipleNewlinesToSpace() throws IOException { @Test public void parseConvertsTabToSpace() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,a = {a\tb}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,a = {a\tb}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -1191,9 +1142,8 @@ public void parseConvertsTabToSpace() throws IOException { @Test public void parseConvertsMultipleTabsToSpace() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{test,a = {a\t\tb}," + "b = {a\t \tb}," + "c = {a \t \t b}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,a = {a\t\tb}," + "b = {a\t \tb}," + "c = {a \t \t b}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -1210,46 +1160,31 @@ public void parseConvertsMultipleTabsToSpace() throws IOException { */ @Test public void parsePreservesMultipleSpacesInFileField() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{canh05,file = {ups sala}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{canh05,file = {ups sala}}")); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); assertEquals(Optional.of("ups sala"), e.getField("file")); } - /** - * Test for [2022983] - * - * @author Uwe Kuehn - * @author Andrei Haralevich - */ @Test - @Ignore("Ignoring, since the parser is not responsible for fixing the content. This should be done later") - public void parseRemovesTabsInFileField() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{canh05,file = {ups \tsala}}"), + public void parsePreservesTabsInAbstractField() throws IOException { + ParserResult result = BibtexParser.parse(new StringReader("@article{canh05,abstract = {ups \tsala}}"), importFormatPreferences); - Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); - assertEquals(Optional.of("ups sala"), e.getField("file")); + assertEquals(Optional.of("ups \tsala"), e.getField(FieldName.ABSTRACT)); } - /** - * Test for [2022983] - * - * @author Uwe Kuehn - * @author Andrei Haralevich - */ @Test - @Ignore("Ignoring, since the parser is not responsible for fixing the content. This should be done later") - public void parseRemovesNewlineInFileField() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{canh05,file = {ups \n\tsala}}"), + public void parsePreservesNewlineInAbstractField() throws IOException { + ParserResult result = BibtexParser.parse(new StringReader("@article{canh05,abstract = {ups \nsala}}"), importFormatPreferences); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); - assertEquals(Optional.of("ups sala"), e.getField("file")); + assertEquals(Optional.of("ups " + OS.NEWLINE + "sala"), e.getField(FieldName.ABSTRACT)); } /** @@ -1258,8 +1193,8 @@ public void parseRemovesNewlineInFileField() throws IOException { @Test public void parseHandlesAccentsCorrectly() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@article{test,author = {H\'{e}lne Fiaux}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{test,author = {H\'{e}lne Fiaux}}")); assertFalse(result.hasWarnings()); Collection c = result.getDatabase().getEntries(); @@ -1277,9 +1212,8 @@ public void parseHandlesAccentsCorrectly() throws IOException { @Test public void parsePreambleAndEntryWithoutNewLine() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@preamble{some text and \\latex}@article{test,author = {H\'{e}lne Fiaux}}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@preamble{some text and \\latex}@article{test,author = {H\'{e}lne Fiaux}}")); assertFalse(result.hasWarnings()); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); @@ -1299,8 +1233,8 @@ public void parsePreambleAndEntryWithoutNewLine() throws IOException { @Test public void parseFileHeaderAndPreambleWithoutNewLine() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("% Encoding: US-ASCII@preamble{some text and \\latex}"), importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("% Encoding: US-ASCII@preamble{some text and \\latex}")); assertFalse(result.hasWarnings()); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); @@ -1309,7 +1243,7 @@ public void parseFileHeaderAndPreambleWithoutNewLine() throws IOException { @Test public void parseSavesEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse(new StringReader(testEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(testEntry)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1320,8 +1254,8 @@ public void parseSavesEntryInParsedSerialization() throws IOException { @Test public void parseSavesOneNewlineAfterEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1332,8 +1266,8 @@ public void parseSavesOneNewlineAfterEntryInParsedSerialization() throws IOExcep @Test public void parseSavesNewlinesBeforeEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse(new StringReader(OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1344,9 +1278,8 @@ public void parseSavesNewlinesBeforeEntryInParsedSerialization() throws IOExcept @Test public void parseRemovesEncodingLineInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse( - new StringReader(SavePreferences.ENCODING_PREFIX + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader(SavePreferences.ENCODING_PREFIX + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1358,9 +1291,8 @@ public void parseRemovesEncodingLineInParsedSerialization() throws IOException { public void parseSavesNewlinesBetweenEntriesInParsedSerialization() throws IOException { String testEntryOne = "@article{test1,author={Ed von Test}}"; String testEntryTwo = "@article{test2,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse( - new StringReader(testEntryOne + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntryTwo), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(testEntryOne + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntryTwo)); Collection c = result.getDatabase().getEntries(); assertEquals(2, c.size()); @@ -1381,7 +1313,7 @@ public void parseSavesNewlinesBetweenEntriesInParsedSerialization() throws IOExc @Test public void parseIgnoresWhitespaceInEpilogue() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(" " + OS.NEWLINE), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(" " + OS.NEWLINE)); assertEquals("", result.getDatabase().getEpilog()); } @@ -1389,9 +1321,8 @@ public void parseIgnoresWhitespaceInEpilogue() throws IOException { @Test public void parseIgnoresWhitespaceInEpilogueAfterEntry() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse( - new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " " + OS.NEWLINE), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " " + OS.NEWLINE)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1403,9 +1334,8 @@ public void parseIgnoresWhitespaceInEpilogueAfterEntry() throws IOException { @Test public void parseTrimsWhitespaceInEpilogueAfterEntry() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; - ParserResult result = BibtexParser.parse( - new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " epilogue " + OS.NEWLINE), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " epilogue " + OS.NEWLINE)); Collection c = result.getDatabase().getEntries(); assertEquals(1, c.size()); @@ -1416,7 +1346,7 @@ public void parseTrimsWhitespaceInEpilogueAfterEntry() throws IOException { @Test public void parseRecognizesSaveActionsAfterEntry() throws IOException { - BibtexParser parser = new BibtexParser(importFormatPreferences); + BibtexParser parser = this.parser; ParserResult parserResult = parser.parse( new StringReader("@InProceedings{6055279,\n" + " Title = {Educational session 1},\n" @@ -1426,8 +1356,7 @@ public void parseRecognizesSaveActionsAfterEntry() throws IOException { + " Abstract = {Start of the above-titled section of the conference proceedings record.},\n" + " DOI = {10.1109/CICC.2011.6055279},\n" + " ISSN = {0886-5930}\n" + "}\n" + "\n" - + "@comment{jabref-meta: saveActions:enabled;title[lower_case]}") - ); + + "@comment{jabref-meta: saveActions:enabled;title[lower_case]}")); FieldFormatterCleanups saveActions = parserResult.getMetaData().getSaveActions().get(); @@ -1436,45 +1365,12 @@ public void parseRecognizesSaveActionsAfterEntry() throws IOException { saveActions.getConfiguredActions()); } - @Test - public void parseRecognizesDatabaseID() throws Exception { - BibtexParser parser = new BibtexParser(importFormatPreferences); - - String expectedDatabaseID = "q1w2e3r4t5z6"; - - StringBuilder sharedDatabaseFileContent = new StringBuilder() - .append("% DBID: ").append(expectedDatabaseID) - .append(OS.NEWLINE) - .append("@Article{a}"); - - ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); - - String actualDatabaseID = parserResult.getDatabase().getSharedDatabaseID().get(); - - assertEquals(expectedDatabaseID, actualDatabaseID); - } - - @Test - public void parseDoesNotRecognizeDatabaseIDasUserComment() throws Exception { - BibtexParser parser = new BibtexParser(importFormatPreferences); - StringBuilder sharedDatabaseFileContent = new StringBuilder() - .append("% Encoding: UTF-8").append(OS.NEWLINE) - .append("% DBID: q1w2e3r4t5z6").append(OS.NEWLINE) - .append("@Article{a}"); - - ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); - List entries = parserResult.getDatabase().getEntries(); - - assertEquals(1, entries.size()); - assertEquals("", entries.get(0).getUserComments()); - } - @Test public void integrationTestSaveActions() throws IOException { - BibtexParser parser = new BibtexParser(importFormatPreferences); + BibtexParser parser = this.parser; - ParserResult parserResult = parser.parse( - new StringReader("@comment{jabref-meta: saveActions:enabled;title[lower_case]}")); + ParserResult parserResult = parser + .parse(new StringReader("@comment{jabref-meta: saveActions:enabled;title[lower_case]}")); FieldFormatterCleanups saveActions = parserResult.getMetaData().getSaveActions().get(); assertTrue(saveActions.isEnabled()); @@ -1484,9 +1380,8 @@ public void integrationTestSaveActions() throws IOException { @Test public void integrationTestCustomEntryType() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@comment{jabref-entrytype: Lecturenotes: req[author;title] opt[language;url]}"), - importFormatPreferences); + ParserResult result = parser.parse( + new StringReader("@comment{jabref-entrytype: Lecturenotes: req[author;title] opt[language;url]}")); Map customEntryTypes = result.getEntryTypes(); @@ -1530,8 +1425,8 @@ public void integrationTestCustomKeyPattern() throws IOException { @Test public void integrationTestBiblatexMode() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@comment{jabref-meta: databaseType:biblatex;}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@comment{jabref-meta: databaseType:biblatex;}")); Optional mode = result.getMetaData().getMode(); @@ -1562,14 +1457,14 @@ public void integrationTestGroupTree() throws IOException, ParseException { @Test public void integrationTestProtectedFlag() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@comment{jabref-meta: protectedFlag:true;}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@comment{jabref-meta: protectedFlag:true;}")); assertTrue(result.getMetaData().isProtected()); } @Test - public void integrationTestOldContentSelectorsAreIgnored() throws IOException { + public void integrationTestContentSelectors() throws IOException { ParserResult result = BibtexParser.parse( new StringReader("@Comment{jabref-meta: selector_status:approved;captured;received;status;}"), importFormatPreferences); @@ -1582,6 +1477,72 @@ public void integrationTestOldContentSelectorsAreIgnored() throws IOException { assertEquals(values, result.getMetaData().getContentSelectors().getSelectorValuesForField("status")); } + @Test + public void parseReallyUnknownType() throws Exception { + String bibtexEntry = "@ReallyUnknownType{test," + OS.NEWLINE + + " Comment = {testentry}" + OS.NEWLINE + + "}"; + + Collection entries = parser.parseEntries(bibtexEntry); + + BibEntry expectedEntry = new BibEntry(); + expectedEntry.setType("Reallyunknowntype"); + expectedEntry.setCiteKey("test"); + expectedEntry.setField("comment", "testentry"); + + assertEquals(Collections.singletonList(expectedEntry), entries); + } + + @Test + public void parseOtherTypeTest() throws Exception { + String bibtexEntry = "@Other{test," + OS.NEWLINE + + " Comment = {testentry}" + OS.NEWLINE + + "}"; + + Collection entries = parser.parseEntries(bibtexEntry); + + BibEntry expectedEntry = new BibEntry(); + expectedEntry.setType("Other"); + expectedEntry.setCiteKey("test"); + expectedEntry.setField("comment", "testentry"); + + assertEquals(Collections.singletonList(expectedEntry), entries); + } + + + @Test + public void parseRecognizesDatabaseID() throws Exception { + BibtexParser parser = this.parser; + + String expectedDatabaseID = "q1w2e3r4t5z6"; + + StringBuilder sharedDatabaseFileContent = new StringBuilder() + .append("% DBID: ").append(expectedDatabaseID) + .append(OS.NEWLINE) + .append("@Article{a}"); + + ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); + + String actualDatabaseID = parserResult.getDatabase().getSharedDatabaseID().get(); + + assertEquals(expectedDatabaseID, actualDatabaseID); + } + + @Test + public void parseDoesNotRecognizeDatabaseIDasUserComment() throws Exception { + BibtexParser parser = this.parser; + StringBuilder sharedDatabaseFileContent = new StringBuilder() + .append("% Encoding: UTF-8").append(OS.NEWLINE) + .append("% DBID: q1w2e3r4t5z6").append(OS.NEWLINE) + .append("@Article{a}"); + + ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); + List entries = parserResult.getDatabase().getEntries(); + + assertEquals(1, entries.size()); + assertEquals("", entries.get(0).getUserComments()); + } + @Test public void integrationTestFileDirectories() throws IOException { ParserResult result = BibtexParser.parse( @@ -1595,9 +1556,8 @@ public void integrationTestFileDirectories() throws IOException { @Test public void parseReturnsEntriesInSameOrder() throws IOException { - ParserResult result = BibtexParser.parse( - new StringReader("@article{a}" + OS.NEWLINE + "@article{b}" + OS.NEWLINE + "@inProceedings{c}"), - importFormatPreferences); + ParserResult result = parser + .parse(new StringReader("@article{a}" + OS.NEWLINE + "@article{b}" + OS.NEWLINE + "@inProceedings{c}")); List expected = new ArrayList<>(); BibEntry a = new BibEntry(); @@ -1631,7 +1591,7 @@ public void parsePrecedingComment() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); assertEquals(1, entries.size()); @@ -1657,7 +1617,7 @@ public void parseCommentAndEntryInOneLine() throws IOException { // @formatter:on // read in bibtex string - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); assertEquals(1, entries.size()); @@ -1672,9 +1632,9 @@ public void parseCommentAndEntryInOneLine() throws IOException { } @Test - public void preserveEncodingPrefixInsideEntry() { - List parsed = BibtexParser - .fromString("@article{test,author={" + SavePreferences.ENCODING_PREFIX + "}}", importFormatPreferences); + public void preserveEncodingPrefixInsideEntry() throws ParseException { + List parsed = parser + .parseEntries("@article{test,author={" + SavePreferences.ENCODING_PREFIX + "}}"); BibEntry expected = new BibEntry(); expected.setType("article"); @@ -1686,7 +1646,7 @@ public void preserveEncodingPrefixInsideEntry() { @Test public void parseBracketedComment() throws IOException { String commentText = "@Comment{someComment}"; - ParserResult result = BibtexParser.parse(new StringReader(commentText), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(commentText)); assertEquals(commentText, result.getDatabase().getEpilog()); } @@ -1703,7 +1663,7 @@ public void parseRegularCommentBeforeEntry() throws IOException { "}"; // @formatter:on - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -1713,7 +1673,7 @@ public void parseRegularCommentBeforeEntry() throws IOException { @Test public void parseCommentWithoutBrackets() throws IOException { String commentText = "@Comment someComment"; - ParserResult result = BibtexParser.parse(new StringReader(commentText), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(commentText)); assertEquals(commentText, result.getDatabase().getEpilog()); } @@ -1730,7 +1690,7 @@ public void parseCommentWithoutBracketsBeforeEntry() throws IOException { "}"; // @formatter:on - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -1751,7 +1711,7 @@ public void parseCommentContainingEntries() throws IOException { "}"; // @formatter:on - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -1772,7 +1732,7 @@ public void parseCommentContainingEntriesAndAtSymbols() throws IOException { "}"; // @formatter:on - ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry), importFormatPreferences); + ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); @@ -1781,14 +1741,14 @@ public void parseCommentContainingEntriesAndAtSymbols() throws IOException { @Test public void parseEmptyPreambleLeadsToEmpty() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader("@preamble{}"), importFormatPreferences); + ParserResult result = parser.parse(new StringReader("@preamble{}")); assertFalse(result.hasWarnings()); assertEquals(Optional.empty(), result.getDatabase().getPreamble()); } @Test public void parseEmptyFileLeadsToPreamble() throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(""), importFormatPreferences); + ParserResult result = parser.parse(new StringReader("")); assertFalse(result.hasWarnings()); assertEquals(Optional.empty(), result.getDatabase().getPreamble()); } diff --git a/src/test/java/net/sf/jabref/logic/layout/LayoutTest.java b/src/test/java/net/sf/jabref/logic/layout/LayoutTest.java index 7da69c09621..ab7e1458e01 100644 --- a/src/test/java/net/sf/jabref/logic/layout/LayoutTest.java +++ b/src/test/java/net/sf/jabref/logic/layout/LayoutTest.java @@ -17,16 +17,13 @@ import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import static org.mockito.Mockito.mock; public class LayoutTest { - private LayoutFormatterPreferences prefs; - /** * Initialize Preferences. */ @@ -48,15 +45,13 @@ public String t1BibtexString() { } public static BibEntry bibtexString2BibtexEntry(String s) throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(s), -JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); return c.iterator().next(); } public String layout(String layoutFile, String entry) throws IOException { - BibEntry be = LayoutTest.bibtexString2BibtexEntry(entry); StringReader sr = new StringReader(layoutFile.replace("__NEWLINE__", "\n")); Layout layout = new LayoutHelper(sr, prefs) @@ -85,15 +80,6 @@ public void testHTMLChar() throws IOException { Assert.assertEquals("This is a text", layoutText); } - @Test - @Ignore - public void testHTMLCharDoubleLineBreak() throws IOException { - String layoutText = layout("\\begin{author}\\format[HTMLChars]{\\author}\\end{author} ", - "@other{bla, author={This\nis\na\n\ntext}}"); - - Assert.assertEquals("This is a
text ", layoutText); - } - @Test public void testPluginLoading() throws IOException { String layoutText = layout("\\begin{author}\\format[NameFormatter]{\\author}\\end{author}", @@ -102,6 +88,14 @@ public void testPluginLoading() throws IOException { Assert.assertEquals("Joe Doe, Moon Jane", layoutText); } + @Test + public void testHTMLCharDoubleLineBreak() throws IOException { + String layoutText = layout("\\begin{author}\\format[HTMLChars]{\\author}\\end{author} ", + "@other{bla, author={This\nis\na\n\ntext}}"); + + Assert.assertEquals("This is a text ", layoutText); + } + /** * [ 1495181 ] Dotless i and tilde not handled in preview * diff --git a/src/test/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java b/src/test/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java index d921db678bd..e952f19379c 100644 --- a/src/test/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java +++ b/src/test/java/net/sf/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java @@ -1,7 +1,6 @@ package net.sf.jabref.logic.layout.format; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; /** @@ -46,15 +45,9 @@ public void testTwoAuthorsCommonName() { Assert.assertEquals("Abbreviator Test", expectedResult, result); } - /** - * Testcase for - * http://sourceforge.net/tracker/index.php?func=detail&aid=1466924&group_id=92314&atid=600306 - */ @Test - @Ignore public void testJrAuthor() { - //TODO what should be done here? reimplement it? - Assert.assertEquals("Other, A. N.", abbreviate("Other, Jr., Anthony N.")); + Assert.assertEquals("Other, Jr., A. N.", abbreviate("Other, Jr., Anthony N.")); } @Test diff --git a/src/test/java/net/sf/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/net/sf/jabref/logic/openoffice/OOBibStyleTest.java index 4568c6b5ec8..f2c653675bf 100644 --- a/src/test/java/net/sf/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/net/sf/jabref/logic/openoffice/OOBibStyleTest.java @@ -25,7 +25,6 @@ import net.sf.jabref.preferences.JabRefPreferences; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -35,10 +34,8 @@ import static org.mockito.Mockito.mock; public class OOBibStyleTest { - private LayoutFormatterPreferences layoutFormatterPreferences; - @Before public void setUp() { layoutFormatterPreferences = JabRefPreferences.getInstance() @@ -142,8 +139,7 @@ public void testGetCitProperty() throws IOException { @Test public void testGetCitationMarker() throws IOException { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8), - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); Map entryDBMap = new HashMap<>(); @@ -164,8 +160,7 @@ public void testGetCitationMarker() throws IOException { @Test public void testLayout() throws IOException { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); - ParserResult result = BibtexParser.parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8), - JabRefPreferences.getInstance().getImportFormatPreferences()); + ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); BibDatabase db = result.getDatabase(); @@ -497,11 +492,8 @@ public void testCompareToNotEqual() throws IOException { } @Test - @Ignore public void testEmptyStringPropertyAndOxfordComma() throws URISyntaxException, IOException { - String fileName = Paths.get(OOBibStyleTest.class.getResource("test.jstyle").toURI()).toString(); - OOBibStyle style = new OOBibStyle(fileName, - layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle("test.jstyle", layoutFormatterPreferences); Map entryDBMap = new HashMap<>(); List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); @@ -514,7 +506,7 @@ public void testEmptyStringPropertyAndOxfordComma() throws URISyntaxException, I database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("von Beta, Epsilon, and Tau, 2016", + assertEquals("von Beta, Epsilon, & Tau, 2016", style.getCitationMarker(entries, entryDBMap, true, null, null)); } diff --git a/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java b/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java index c690b447a00..ba1ab7951a6 100644 --- a/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java +++ b/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java @@ -55,14 +55,17 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; /** * Limitations: The test suite only handles UTF8. Not UTF16. */ public class XMPUtilTest { + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); /** * The PDF file that basically all operations are done upon. */ @@ -139,7 +142,7 @@ public void writeManually(File tempFile, String xmpString) throws IOException, C public static BibEntry bibtexString2BibtexEntry(String s, ImportFormatPreferences importFormatPreferences) throws IOException { - ParserResult result = BibtexParser.parse(new StringReader(s), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); return c.iterator().next(); @@ -229,10 +232,7 @@ public String t3XMP() { @Before public void setUp() throws IOException, COSVisitorException { - pdfFile = File.createTempFile("JabRef", ".pdf"); - - // ensure that the file will be deleted upon exit - pdfFile.deleteOnExit(); + pdfFile = tempFolder.newFile("JabRef.pdf"); try (PDDocument pdf = new PDDocument()) { pdf.addPage(new PDPage()); // Need page to open in Acrobat @@ -1110,7 +1110,7 @@ public void testReadRawXMP() throws IOException, TransformerException { public void testCommandLineSingleBib() throws IOException, TransformerException, COSVisitorException { // First check conversion from .bib to .xmp - File tempBib = File.createTempFile("JabRef", ".bib"); + File tempBib = tempFolder.newFile("JabRef.bib"); try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { fileWriter.write(t1BibtexString()); fileWriter.close(); @@ -1128,10 +1128,6 @@ public void testCommandLineSingleBib() throws IOException, TransformerException, Assert.assertEquals(1, l.size()); assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); - } finally { - if (!tempBib.delete()) { - System.err.println("Cannot delete temporary file"); - } } } @@ -1157,7 +1153,7 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, System.setOut(oldOut); String bibtex = s.toString(); - ParserResult result = BibtexParser.parse(new StringReader(bibtex), importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtex)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); BibEntry x = c.iterator().next(); @@ -1204,51 +1200,44 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, * Test whether the command-line client can pick one of several entries from a bibtex file * @throws IOException * @throws TransformerException - * */ @Test - @Ignore public void testCommandLineByKey() throws IOException, TransformerException { - - File tempBib = File.createTempFile("JabRef", ".bib"); + File tempBib = tempFolder.newFile("JabRef.bib"); try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { fileWriter.write(t1BibtexString()); fileWriter.write(t2BibtexString()); + } - { // First try canh05 - PrintStream oldOut = System.out; - try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { - System.setOut(new PrintStream(s)); - XMPUtilMain.main(new String[] {"canh05", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); - } finally { - System.setOut(oldOut); - } + PrintStream sysOut = System.out; - // PDF should be annotated: - List l = XMPUtil.readXMP(pdfFile, xmpPreferences); - Assert.assertEquals(1, l.size()); - assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); - } - // Now try OezbekC06 - try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { - PrintStream oldOut = System.out; - System.setOut(new PrintStream(s)); - try { - XMPUtilMain.main(new String[] {"OezbekC06", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); - } finally { - System.setOut(oldOut); - } - } - - // PDF should be annotated: - List l = XMPUtil.readXMP(pdfFile, xmpPreferences); - Assert.assertEquals(1, l.size()); - assertEqualsBibtexEntry(t2BibtexEntry(), l.get(0)); + // First try canh05 + try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { + System.setOut(new PrintStream(s)); + XMPUtilMain.main(new String[]{"canh05", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); } finally { - if (!tempBib.delete()) { - System.err.println("Cannot delete temporary file"); + System.setOut(sysOut); + } + + // PDF should be annotated: + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); + Assert.assertEquals(1, l.size()); + assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); + + // Now try OezbekC06 + try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { + System.setOut(new PrintStream(s)); + try { + XMPUtilMain.main(new String[]{"OezbekC06", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); + } finally { + System.setOut(sysOut); } } + + // PDF should be annotated: + l = XMPUtil.readXMP(pdfFile, xmpPreferences); + Assert.assertEquals(1, l.size()); + assertEqualsBibtexEntry(t2BibtexEntry(), l.get(0)); } /** @@ -1259,7 +1248,7 @@ public void testCommandLineByKey() throws IOException, TransformerException { @Test public void testCommandLineSeveral() throws IOException, TransformerException { - File tempBib = File.createTempFile("JabRef", ".bib"); + File tempBib = tempFolder.newFile("JabRef.bib"); try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { @@ -1294,11 +1283,6 @@ public void testCommandLineSeveral() throws IOException, TransformerException { assertEqualsBibtexEntry(t1, a); assertEqualsBibtexEntry(t3, b); - - } finally { - if (!tempBib.delete()) { - System.err.println("Cannot delete temporary file"); - } } } @@ -1362,7 +1346,7 @@ public void testResolveStrings2() throws IOException, TransformerException { try (BufferedReader fr = Files.newBufferedReader(Paths.get("src/test/resources/net/sf/jabref/util/twente.bib"), StandardCharsets.UTF_8)) { - ParserResult result = BibtexParser.parse(fr, importFormatPreferences); + ParserResult result = new BibtexParser(importFormatPreferences).parse(fr); Assert.assertEquals("Arvind", result.getDatabase().resolveForStrings("#Arvind#")); From de02b3dae7aa2d7dbc2ec7b8d85ccddef597c1d1 Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Fri, 23 Dec 2016 11:54:02 +0100 Subject: [PATCH 05/27] Remove system.out --- .../java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 9aba1c995a9..3067c609381 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -68,9 +68,6 @@ public List cleanup(BibEntry entry) { newFileList.add(fileEntry); continue; } - - System.out.println("Old File:" + oldFile.get()); - System.out.println(fileDirPattern); String targetDirName = ""; if (!fileDirPattern.isEmpty()) { targetDirName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, fileDirPattern, From 24c0f311079f0c4f66504bd4d1333b2593edebe6 Mon Sep 17 00:00:00 2001 From: Siedlerkiller Date: Fri, 23 Dec 2016 18:40:09 +0100 Subject: [PATCH 06/27] Use paths in findFiles --- .../sf/jabref/gui/externalfiles/MoveFileAction.java | 2 ++ .../java/net/sf/jabref/logic/util/io/FileFinder.java | 9 ++++----- .../java/net/sf/jabref/logic/util/io/FileUtil.java | 10 +++++----- .../net/sf/jabref/logic/util/io/FileBasedTestCase.java | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java index 682261d41bc..f77406fa580 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java @@ -51,12 +51,14 @@ public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor edi @Override public void actionPerformed(ActionEvent event) { + int selected = editor.getSelectedRow(); if (selected == -1) { return; } + // MoveFilesCleanup cleanup = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.get, fileDirectoryPreferences, prefs) FileListEntry entry = editor.getTableModel().getEntry(selected); // Check if the current file exists: diff --git a/src/main/java/net/sf/jabref/logic/util/io/FileFinder.java b/src/main/java/net/sf/jabref/logic/util/io/FileFinder.java index b50e7e51aed..75af5269394 100644 --- a/src/main/java/net/sf/jabref/logic/util/io/FileFinder.java +++ b/src/main/java/net/sf/jabref/logic/util/io/FileFinder.java @@ -20,8 +20,7 @@ public class FileFinder { private static final Log LOGGER = LogFactory.getLog(FileFinder.class); - - public static Set findFiles(List extensions, List directories) { + public static Set findFiles(List extensions, List directories) { Objects.requireNonNull(directories, "Directories must not be null!"); Objects.requireNonNull(extensions, "Extensions must not be null!"); @@ -30,11 +29,11 @@ public static Set findFiles(List extensions, List directorie attr) -> !Files.isDirectory(path) && extensions.contains(FileUtil.getFileExtension(path.toFile()).orElse("")); - Set result = new HashSet<>(); + Set result = new HashSet<>(); for (File directory : directories) { - try (Stream files = Files.find(directory.toPath(), Integer.MAX_VALUE, isDirectoryAndContainsExtension) - .map(x -> x.toFile())) { + try (Stream files = Files.find(directory.toPath(), Integer.MAX_VALUE, + isDirectoryAndContainsExtension)) { result.addAll(files.collect(Collectors.toSet())); } catch (IOException e) { diff --git a/src/main/java/net/sf/jabref/logic/util/io/FileUtil.java b/src/main/java/net/sf/jabref/logic/util/io/FileUtil.java index 83c1657ef85..60658a72f9f 100644 --- a/src/main/java/net/sf/jabref/logic/util/io/FileUtil.java +++ b/src/main/java/net/sf/jabref/logic/util/io/FileUtil.java @@ -350,7 +350,7 @@ public static Map> findAssociatedFiles(List entri Map> result = new HashMap<>(); // First scan directories - Set filesWithExtension = FileFinder.findFiles(extensions, directories); + Set filesWithExtension = FileFinder.findFiles(extensions, directories); // Initialize Result-Set for (BibEntry entry : entries) { @@ -358,16 +358,16 @@ public static Map> findAssociatedFiles(List entri } // Now look for keys - nextFile: for (File file : filesWithExtension) { + nextFile: for (Path file : filesWithExtension) { - String name = file.getName(); + String name = file.getFileName().toString(); int dot = name.lastIndexOf('.'); // First, look for exact matches: for (BibEntry entry : entries) { Optional citeKey = entry.getCiteKeyOptional(); if ((citeKey.isPresent()) && !citeKey.get().isEmpty() && (dot > 0) && name.substring(0, dot).equals(citeKey.get())) { - result.get(entry).add(file); + result.get(entry).add(file.toFile()); continue nextFile; } } @@ -377,7 +377,7 @@ public static Map> findAssociatedFiles(List entri for (BibEntry entry : entries) { Optional citeKey = entry.getCiteKeyOptional(); if ((citeKey.isPresent()) && !citeKey.get().isEmpty() && name.startsWith(citeKey.get())) { - result.get(entry).add(file); + result.get(entry).add(file.toFile()); continue nextFile; } } diff --git a/src/test/java/net/sf/jabref/logic/util/io/FileBasedTestCase.java b/src/test/java/net/sf/jabref/logic/util/io/FileBasedTestCase.java index 3be42872316..52b27942ad0 100644 --- a/src/test/java/net/sf/jabref/logic/util/io/FileBasedTestCase.java +++ b/src/test/java/net/sf/jabref/logic/util/io/FileBasedTestCase.java @@ -99,7 +99,7 @@ public void testFindAssociatedFiles() { public void testFindFilesException() { List extensions = Arrays.asList("jpg", "pdf"); List dirs = Arrays.asList(rootDir.resolve("asdfasdf/asdfasdf").toFile()); - Set results = FileFinder.findFiles(extensions, dirs); + Set results = FileFinder.findFiles(extensions, dirs); assertEquals(Collections.emptySet(), results); } From a44d8e6345fe832da108a97a1aedc03f7c3cd01d Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Fri, 13 Jan 2017 20:45:13 +0100 Subject: [PATCH 07/27] New Behaviour: Bib Location as primary dir in settings overwrites all other file directories Enable move files cleanup checkbox then, too Mock prefs in tests --- .../net/sf/jabref/gui/actions/CleanupAction.java | 1 - .../sf/jabref/gui/cleanup/CleanupPresetPanel.java | 12 +++++++----- .../sf/jabref/logic/cleanup/MoveFilesCleanup.java | 6 ++++-- .../jabref/logic/cleanup/MoveFilesCleanupTest.java | 14 ++++++++------ 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/actions/CleanupAction.java b/src/main/java/net/sf/jabref/gui/actions/CleanupAction.java index 50ba23cae03..45a675a5607 100644 --- a/src/main/java/net/sf/jabref/gui/actions/CleanupAction.java +++ b/src/main/java/net/sf/jabref/gui/actions/CleanupAction.java @@ -34,7 +34,6 @@ public class CleanupAction extends AbstractWorker { private int modifiedEntriesCount; private final JabRefPreferences preferences; - public CleanupAction(BasePanel panel, JabRefPreferences preferences) { this.panel = panel; this.frame = panel.frame(); diff --git a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java index b53fa6e0c67..bffa98720a6 100644 --- a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java +++ b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java @@ -1,7 +1,9 @@ package net.sf.jabref.gui.cleanup; +import java.nio.file.Path; import java.util.EnumSet; import java.util.Objects; +import java.util.Optional; import java.util.Set; import javax.swing.JCheckBox; @@ -35,8 +37,6 @@ public class CleanupPresetPanel { private JPanel panel; private CleanupPreset cleanupPreset; - - public CleanupPresetPanel(BibDatabaseContext databaseContext, CleanupPreset cleanupPreset) { this.cleanupPreset = Objects.requireNonNull(cleanupPreset); this.databaseContext = Objects.requireNonNull(databaseContext); @@ -47,16 +47,18 @@ private void init() { cleanUpDOI = new JCheckBox( Localization.lang("Move DOIs from note and URL field to DOI field and remove http prefix")); cleanUpISSN = new JCheckBox(Localization.lang("Reformat ISSN")); - if (databaseContext.getMetaData().getDefaultFileDirectory().isPresent()) { + + Optional firstExistingDir = databaseContext + .getFirstExistingFileDir(JabRefPreferences.getInstance().getFileDirectoryPreferences()); + if (firstExistingDir.isPresent()) { cleanUpMovePDF = new JCheckBox(Localization.lang("Move linked files to default file directory %0", - databaseContext.getMetaData().getDefaultFileDirectory().get())); + firstExistingDir.get().toString())); } else { cleanUpMovePDF = new JCheckBox(Localization.lang("Move linked files to default file directory %0", "...")); cleanUpMovePDF.setEnabled(false); cleanUpMovePDF.setSelected(false); } - cleanUpMakePathsRelative = new JCheckBox( Localization.lang("Make paths of linked files relative (if possible)")); cleanUpRenamePDF = new JCheckBox(Localization.lang("Rename PDFs to given filename format pattern")); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 3067c609381..063284ae0ca 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -43,12 +43,14 @@ public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPatter @Override public List cleanup(BibEntry entry) { - if (!databaseContext.getMetaData().getDefaultFileDirectory().isPresent()) { + Optional firstExistingFileDir = databaseContext.getFirstExistingFileDir(fileDirectoryPreferences); + + if (!firstExistingFileDir.isPresent()) { return Collections.emptyList(); } List paths = databaseContext.getFileDirectories(fileDirectoryPreferences); - String defaultFileDirectory = databaseContext.getMetaData().getDefaultFileDirectory().get(); + String defaultFileDirectory = firstExistingFileDir.get().toString(); Optional targetDirectory = FileUtil.expandFilename(defaultFileDirectory, paths); if (!targetDirectory.isPresent()) { diff --git a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java index 4fd3f37f4f8..ebb47d94199 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -14,8 +14,8 @@ import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.FileField; import net.sf.jabref.model.entry.ParsedFileField; +import net.sf.jabref.model.metadata.FileDirectoryPreferences; import net.sf.jabref.model.metadata.MetaData; -import net.sf.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Rule; @@ -26,6 +26,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class MoveFilesCleanupTest { @@ -35,12 +36,11 @@ public class MoveFilesCleanupTest { private File pdfFolder; private BibDatabaseContext databaseContext; private MoveFilesCleanup cleanup; - private JabRefPreferences prefs; private BibEntry entry; + private FileDirectoryPreferences fileDirPrefs; @Before public void setUp() throws IOException { - prefs = JabRefPreferences.getInstance(); MetaData metaData = new MetaData(); pdfFolder = bibFolder.newFolder(); metaData.setDefaultFileDirectory(pdfFolder.getAbsolutePath()); @@ -50,6 +50,8 @@ public void setUp() throws IOException { entry.setCiteKey("Toot"); entry.setField("title", "test title"); + fileDirPrefs = mock(FileDirectoryPreferences.class); + when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(false); //Biblocation as Primary overwrites all other dirs, therefore we set it to false here } @Test @@ -61,7 +63,7 @@ public void movesFileFromSubfolder() throws IOException { ParsedFileField fileField = new ParsedFileField("", fileBefore.getAbsolutePath(), ""); entry.setField("file", FileField.getStringRepresentation(fileField)); - cleanup = new MoveFilesCleanup(databaseContext, "", prefs.getFileDirectoryPreferences(), + cleanup = new MoveFilesCleanup(databaseContext, "", fileDirPrefs, mock(LayoutFormatterPreferences.class)); cleanup.cleanup(entry); @@ -84,7 +86,7 @@ public void movesFileFromSubfolderMultiple() throws IOException { entry.setField("file", FileField.getStringRepresentation( Arrays.asList(new ParsedFileField("", "", ""), fileField, new ParsedFileField("", "", "")))); - cleanup = new MoveFilesCleanup(databaseContext, "", prefs.getFileDirectoryPreferences(), + cleanup = new MoveFilesCleanup(databaseContext, "", fileDirPrefs, mock(LayoutFormatterPreferences.class)); cleanup.cleanup(entry); @@ -109,7 +111,7 @@ public void movesFileFromSubfolderWithFileDirPattern() throws IOException { ParsedFileField fileField = new ParsedFileField("", fileBefore.getAbsolutePath(), ""); entry.setField("file", FileField.getStringRepresentation(fileField)); - cleanup = new MoveFilesCleanup(databaseContext, "\\EntryType", prefs.getFileDirectoryPreferences(), + cleanup = new MoveFilesCleanup(databaseContext, "\\EntryType", fileDirPrefs, mock(LayoutFormatterPreferences.class)); cleanup.cleanup(entry); From 4afd520b8911ecfd77eff74e3c061274dd6fd14b Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Thu, 26 Jan 2017 21:13:58 +0100 Subject: [PATCH 08/27] Call cleanup method from EntryEditor MoveFile contextmenu action --- .../gui/externalfiles/MoveFileAction.java | 23 +++++++++++-------- .../metadata/FileDirectoryPreferences.java | 3 ++- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java index f77406fa580..1d66ab332c9 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java @@ -2,26 +2,22 @@ import java.awt.event.ActionEvent; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import java.util.Locale; -import java.util.Optional; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import net.sf.jabref.Globals; -import net.sf.jabref.gui.FileDialog; import net.sf.jabref.gui.JabRefFrame; import net.sf.jabref.gui.entryeditor.EntryEditor; import net.sf.jabref.gui.fieldeditors.FileListEditor; import net.sf.jabref.gui.filelist.FileListEntry; -import net.sf.jabref.gui.util.component.CheckBoxMessage; +import net.sf.jabref.logic.cleanup.CleanupPreferences; +import net.sf.jabref.logic.cleanup.MoveFilesCleanup; +import net.sf.jabref.logic.journals.JournalAbbreviationLoader; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; -import net.sf.jabref.preferences.JabRefPreferences; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -41,7 +37,6 @@ public class MoveFileAction extends AbstractAction { private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); - public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor, boolean toFileDir) { this.frame = frame; this.eEditor = eEditor; @@ -91,7 +86,15 @@ public void actionPerformed(ActionEvent event) { if ((file != null) && file.exists()) { // Ok, we found the file. Now get a new name: - File newFile = null; + CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); + + MoveFilesCleanup myCleanUp = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), + prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), + prefs.getLayoutFormatterPreferences()); + + myCleanUp.cleanup((eEditor.getEntry())); + //myCleanUp.cleanup(); + /* File newFile = null; boolean repeat = true; while (repeat) { repeat = false; @@ -186,7 +189,7 @@ public void actionPerformed(ActionEvent event) { MOVE_RENAME, JOptionPane.ERROR_MESSAGE); } - } + }*/ } else { // File doesn't exist, so we can't move it. JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link), diff --git a/src/main/java/net/sf/jabref/model/metadata/FileDirectoryPreferences.java b/src/main/java/net/sf/jabref/model/metadata/FileDirectoryPreferences.java index 1016911f8fc..2addb3714b4 100644 --- a/src/main/java/net/sf/jabref/model/metadata/FileDirectoryPreferences.java +++ b/src/main/java/net/sf/jabref/model/metadata/FileDirectoryPreferences.java @@ -15,6 +15,7 @@ public class FileDirectoryPreferences { private final Map fieldFileDirectories; private final boolean bibLocationAsPrimary; + public FileDirectoryPreferences(String user, Map fieldFileDirectories, boolean bibLocationAsPrimary) { this.user = user; this.fieldFileDirectories = fieldFileDirectories; @@ -29,7 +30,7 @@ public Optional getFileDirectory(String field) { try { String value = fieldFileDirectories.get(field); // filter empty paths - if (value != null && !value.isEmpty()) { + if ((value != null) && !value.isEmpty()) { Path path = Paths.get(value); return Optional.of(path); } From 7cb1c353a8699572006c365c71a36e0f86cb3694 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Wed, 1 Feb 2017 16:29:55 +0100 Subject: [PATCH 09/27] Separate Rename and MoveFile Action TODO: Find a way to cleanup only one file --- .../gui/externalfiles/MoveFileAction.java | 36 ++++---- .../gui/externalfiles/RenameFileAction.java | 90 +++++++++++++++++++ .../gui/fieldeditors/FileListEditor.java | 5 +- .../sf/jabref/gui/filelist/FileListEntry.java | 5 ++ 4 files changed, 114 insertions(+), 22 deletions(-) create mode 100644 src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java index 1d66ab332c9..255ddfdc2e6 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java @@ -2,8 +2,11 @@ import java.awt.event.ActionEvent; import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Locale; +import java.util.Optional; import javax.swing.AbstractAction; import javax.swing.JOptionPane; @@ -23,7 +26,7 @@ import org.apache.commons.logging.LogFactory; /** - * Action for moving or renaming a file that is linked to from an entry in JabRef. + * Action for moving a file that is linked from an entry in JabRef. */ public class MoveFileAction extends AbstractAction { @@ -32,16 +35,14 @@ public class MoveFileAction extends AbstractAction { private final JabRefFrame frame; private final EntryEditor eEditor; private final FileListEditor editor; - - private final boolean toFileDir; + private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); - public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor, boolean toFileDir) { + public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; this.eEditor = eEditor; this.editor = editor; - this.toFileDir = toFileDir; } @Override @@ -53,7 +54,6 @@ public void actionPerformed(ActionEvent event) { return; } - // MoveFilesCleanup cleanup = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.get, fileDirectoryPreferences, prefs) FileListEntry entry = editor.getTableModel().getEntry(selected); // Check if the current file exists: @@ -66,15 +66,10 @@ public void actionPerformed(ActionEvent event) { // Get an absolute path representation: List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); - int found = -1; - for (int i = 0; i < dirs.size(); i++) { - if (new File(dirs.get(i)).exists()) { - found = i; - break; - } - } - if (found < 0) { + .getFileDirectories(prefs.getFileDirectoryPreferences()); + Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() + .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); + if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); return; @@ -83,16 +78,17 @@ public void actionPerformed(ActionEvent event) { if (!file.isAbsolute()) { file = FileUtil.expandFilename(ln, dirs).orElse(null); } - if ((file != null) && file.exists()) { - // Ok, we found the file. Now get a new name: - CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); + if ((file != null) && Files.exists(file.toPath())) { + // Ok, we found the file. Now get a new name: + System.out.println("Cleanup of file " + file); - MoveFilesCleanup myCleanUp = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), + //Problem: All listed files are cleaned up + MoveFilesCleanup moveFiles = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), prefs.getLayoutFormatterPreferences()); - myCleanUp.cleanup((eEditor.getEntry())); + moveFiles.cleanup((eEditor.getEntry())); //myCleanUp.cleanup(); /* File newFile = null; boolean repeat = true; diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java new file mode 100644 index 00000000000..cdec4423bda --- /dev/null +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -0,0 +1,90 @@ +package net.sf.jabref.gui.externalfiles; + +import java.awt.event.ActionEvent; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +import javax.swing.AbstractAction; +import javax.swing.JOptionPane; + +import net.sf.jabref.Globals; +import net.sf.jabref.gui.JabRefFrame; +import net.sf.jabref.gui.entryeditor.EntryEditor; +import net.sf.jabref.gui.fieldeditors.FileListEditor; +import net.sf.jabref.gui.filelist.FileListEntry; +import net.sf.jabref.logic.cleanup.CleanupPreferences; +import net.sf.jabref.logic.cleanup.RenamePdfCleanup; +import net.sf.jabref.logic.journals.JournalAbbreviationLoader; +import net.sf.jabref.logic.l10n.Localization; +import net.sf.jabref.logic.util.io.FileUtil; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class RenameFileAction extends AbstractAction { + + private static final Log LOGGER = LogFactory.getLog(RenameFileAction.class); + + private final JabRefFrame frame; + private final EntryEditor eEditor; + private final FileListEditor editor; + private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); + + private final boolean toFileDir = false; + private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); + + public RenameFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { + this.frame = frame; + this.eEditor = eEditor; + this.editor = editor; + } + + @Override + public void actionPerformed(ActionEvent e) { + + int selected = editor.getSelectedRow(); + + if (selected == -1) { + return; + } + + FileListEntry entry = editor.getTableModel().getEntry(selected); + + // Check if the current file exists: + String ln = entry.link; + boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); + if (httpLink) { + // TODO: notify that this operation cannot be done on remote links + return; + } + List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() + .getFileDirectories(prefs.getFileDirectoryPreferences()); + Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() + .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); + if (!fileDir.isPresent()) { + JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), + MOVE_RENAME, JOptionPane.ERROR_MESSAGE); + return; + } + File file = new File(ln); + if (!file.isAbsolute()) { + file = FileUtil.expandFilename(ln, dirs).orElse(null); + } + + if ((file != null) && Files.exists(file.toPath())) { + System.out.println("Cleanup Rename of file " + file); + + RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, + frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), + prefs.getFileDirPattern(), prefs.getLayoutFormatterPreferences(), + prefs.getFileDirectoryPreferences()); + pdfCleanup.cleanup(eEditor.getEntry()); + + } + } + +} diff --git a/src/main/java/net/sf/jabref/gui/fieldeditors/FileListEditor.java b/src/main/java/net/sf/jabref/gui/fieldeditors/FileListEditor.java index ff0d151ef6c..8461086644b 100644 --- a/src/main/java/net/sf/jabref/gui/fieldeditors/FileListEditor.java +++ b/src/main/java/net/sf/jabref/gui/fieldeditors/FileListEditor.java @@ -43,6 +43,7 @@ import net.sf.jabref.gui.externalfiles.AutoSetLinks; import net.sf.jabref.gui.externalfiles.DownloadExternalFile; import net.sf.jabref.gui.externalfiles.MoveFileAction; +import net.sf.jabref.gui.externalfiles.RenameFileAction; import net.sf.jabref.gui.externalfiletype.ExternalFileType; import net.sf.jabref.gui.externalfiletype.ExternalFileTypes; import net.sf.jabref.gui.filelist.FileListEntry; @@ -212,11 +213,11 @@ public void actionPerformed(ActionEvent actionEvent) { JMenuItem rename = new JMenuItem(Localization.lang("Move/Rename file")); menu.add(rename); - rename.addActionListener(new MoveFileAction(frame, entryEditor, this, false)); + rename.addActionListener(new RenameFileAction(frame, entryEditor, this)); JMenuItem moveToFileDir = new JMenuItem(Localization.lang("Move file to file directory")); menu.add(moveToFileDir); - moveToFileDir.addActionListener(new MoveFileAction(frame, entryEditor, this, true)); + moveToFileDir.addActionListener(new MoveFileAction(frame, entryEditor, this)); JMenuItem deleteFile = new JMenuItem(Localization.lang("Delete local file")); menu.add(deleteFile); diff --git a/src/main/java/net/sf/jabref/gui/filelist/FileListEntry.java b/src/main/java/net/sf/jabref/gui/filelist/FileListEntry.java index 4fb7f88d797..df5df602f7f 100644 --- a/src/main/java/net/sf/jabref/gui/filelist/FileListEntry.java +++ b/src/main/java/net/sf/jabref/gui/filelist/FileListEntry.java @@ -4,6 +4,7 @@ import java.util.Optional; import net.sf.jabref.gui.externalfiletype.ExternalFileType; +import net.sf.jabref.model.entry.ParsedFileField; /** * This class represents a file link for a Bibtex entry. @@ -42,4 +43,8 @@ private String getTypeName() { public String toString() { return description + " : " + link + " : " + type.orElse(null); } + + public ParsedFileField toParsedFileField() { + return new ParsedFileField(description, link, type.isPresent() ? type.get().getName() : ""); + } } From 234259769d27f18f9ae222838599707da588efb2 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Wed, 1 Feb 2017 21:05:33 +0100 Subject: [PATCH 10/27] Convert FileListEntry to parsedFileField to use it in rename --- .../jabref/gui/externalfiles/RenameFileAction.java | 6 +++++- .../sf/jabref/logic/cleanup/RenamePdfCleanup.java | 14 +++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java index cdec4423bda..edea4c082ca 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -4,6 +4,7 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; @@ -21,6 +22,7 @@ import net.sf.jabref.logic.journals.JournalAbbreviationLoader; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.model.entry.ParsedFileField; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,6 +56,8 @@ public void actionPerformed(ActionEvent e) { FileListEntry entry = editor.getTableModel().getEntry(selected); + ParsedFileField field = entry.toParsedFileField(); + System.out.println("Parsed file Field " + field); // Check if the current file exists: String ln = entry.link; boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); @@ -81,7 +85,7 @@ public void actionPerformed(ActionEvent e) { RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), prefs.getFileDirPattern(), prefs.getLayoutFormatterPreferences(), - prefs.getFileDirectoryPreferences()); + prefs.getFileDirectoryPreferences(), Arrays.asList(field)); pdfCleanup.cleanup(eEditor.getEntry()); } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 8587b26ad8c..e1fba79e25b 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -34,6 +34,7 @@ public class RenamePdfCleanup implements CleanupJob { private final String fileDirPattern; private final LayoutFormatterPreferences prefs; private final FileDirectoryPreferences fileDirectoryPreferences; + private List fileList = new ArrayList<>(); private int unsuccessfulRenames; public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, @@ -47,10 +48,21 @@ public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseCo this.fileDirectoryPreferences = fileDirectoryPreferences; } + public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, + String fileDirPattern, LayoutFormatterPreferences prefs, + FileDirectoryPreferences fileDirectoryPreferences, List parsedFields) { + this(onlyRelativePaths, databaseContext, fileNamePattern, fileDirPattern, prefs, + fileDirectoryPreferences); + this.fileList = parsedFields; + } + @Override public List cleanup(BibEntry entry) { TypedBibEntry typedEntry = new TypedBibEntry(entry, databaseContext); - List fileList = typedEntry.getFiles(); + + if (fileList.isEmpty()) { + fileList = typedEntry.getFiles(); + } List newFileList = new ArrayList<>(); boolean changed = false; From bdd349fe113bfbf9594aa8c306eb4dd6b8a25a47 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Wed, 1 Feb 2017 21:32:43 +0100 Subject: [PATCH 11/27] Add all entries back to new list excep thte one we want to rename --- .../gui/externalfiles/RenameFileAction.java | 3 +-- .../logic/cleanup/RenamePdfCleanup.java | 22 ++++++++++++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java index edea4c082ca..6c24ce15845 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -4,7 +4,6 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; @@ -85,7 +84,7 @@ public void actionPerformed(ActionEvent e) { RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), prefs.getFileDirPattern(), prefs.getLayoutFormatterPreferences(), - prefs.getFileDirectoryPreferences(), Arrays.asList(field)); + prefs.getFileDirectoryPreferences(), field); pdfCleanup.cleanup(eEditor.getEntry()); } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index e1fba79e25b..76e8d34c28d 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -6,10 +6,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import net.sf.jabref.logic.TypedBibEntry; import net.sf.jabref.logic.layout.LayoutFormatterPreferences; @@ -34,8 +36,8 @@ public class RenamePdfCleanup implements CleanupJob { private final String fileDirPattern; private final LayoutFormatterPreferences prefs; private final FileDirectoryPreferences fileDirectoryPreferences; - private List fileList = new ArrayList<>(); private int unsuccessfulRenames; + private ParsedFileField singleFieldCleanup; public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, String fileDirPattern, LayoutFormatterPreferences prefs, @@ -50,20 +52,28 @@ public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseCo public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, String fileDirPattern, LayoutFormatterPreferences prefs, - FileDirectoryPreferences fileDirectoryPreferences, List parsedFields) { + FileDirectoryPreferences fileDirectoryPreferences, ParsedFileField singleField) { this(onlyRelativePaths, databaseContext, fileNamePattern, fileDirPattern, prefs, fileDirectoryPreferences); - this.fileList = parsedFields; + this.singleFieldCleanup = singleField; + } @Override public List cleanup(BibEntry entry) { TypedBibEntry typedEntry = new TypedBibEntry(entry, databaseContext); - - if (fileList.isEmpty()) { + List newFileList; + List fileList; + if (singleFieldCleanup != null) { + fileList = Arrays.asList(singleFieldCleanup); + + newFileList = typedEntry.getFiles().stream().filter(x -> !x.equals(singleFieldCleanup)) + .collect(Collectors.toList()); + } else { + newFileList = new ArrayList<>(); fileList = typedEntry.getFiles(); } - List newFileList = new ArrayList<>(); + boolean changed = false; for (ParsedFileField flEntry : fileList) { From eb89e46979d9fdc741be037e34a86f6ace04e7f3 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Wed, 1 Feb 2017 21:39:19 +0100 Subject: [PATCH 12/27] Option for single field cleanup in MoveFiles Cleanup analog to Rename pdf Files get not overwritten --- .../gui/externalfiles/MoveFileAction.java | 7 +++-- .../logic/cleanup/MoveFilesCleanup.java | 26 +++++++++++++++++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java index 255ddfdc2e6..1ea4dc5c9db 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java @@ -21,6 +21,7 @@ import net.sf.jabref.logic.journals.JournalAbbreviationLoader; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.model.entry.ParsedFileField; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -58,12 +59,14 @@ public void actionPerformed(ActionEvent event) { // Check if the current file exists: String ln = entry.link; + ParsedFileField field = entry.toParsedFileField(); + boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); if (httpLink) { // TODO: notify that this operation cannot be done on remote links return; } - + System.out.println("Parsed file Field " + field); // Get an absolute path representation: List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() .getFileDirectories(prefs.getFileDirectoryPreferences()); @@ -86,7 +89,7 @@ public void actionPerformed(ActionEvent event) { //Problem: All listed files are cleaned up MoveFilesCleanup moveFiles = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), - prefs.getLayoutFormatterPreferences()); + prefs.getLayoutFormatterPreferences(), field); moveFiles.cleanup((eEditor.getEntry())); //myCleanUp.cleanup(); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 063284ae0ca..91698547f98 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -6,10 +6,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import net.sf.jabref.logic.TypedBibEntry; import net.sf.jabref.logic.layout.LayoutFormatterPreferences; @@ -33,6 +35,8 @@ public class MoveFilesCleanup implements CleanupJob { private final String fileDirPattern; private static final Log LOGGER = LogFactory.getLog(MoveFilesCleanup.class); + private ParsedFileField singleFieldCleanup = null; + public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences prefs) { this.databaseContext = Objects.requireNonNull(databaseContext); @@ -41,6 +45,14 @@ public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPatter this.prefs = Objects.requireNonNull(prefs); } + public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, + FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences prefs, + ParsedFileField field) { + + this(databaseContext, fileDirPattern, fileDirectoryPreferences, prefs); + this.singleFieldCleanup = field; + } + @Override public List cleanup(BibEntry entry) { Optional firstExistingFileDir = databaseContext.getFirstExistingFileDir(fileDirectoryPreferences); @@ -58,8 +70,18 @@ public List cleanup(BibEntry entry) { } TypedBibEntry typedEntry = new TypedBibEntry(entry, databaseContext); - List fileList = typedEntry.getFiles(); - List newFileList = new ArrayList<>(); + List fileList; + List newFileList; + + if (singleFieldCleanup != null) { + fileList = Arrays.asList(singleFieldCleanup); + + newFileList = typedEntry.getFiles().stream().filter(x -> !x.equals(singleFieldCleanup)) + .collect(Collectors.toList()); + } else { + newFileList = new ArrayList<>(); + fileList = typedEntry.getFiles(); + } boolean changed = false; for (ParsedFileField fileEntry : fileList) { From 07a1c447754291f3ecc01a996e1a2db757c0b164 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Fri, 3 Feb 2017 18:06:54 +0100 Subject: [PATCH 13/27] Try to fix layout Add fileDirPattern to Rename File --- .../sf/jabref/gui/cleanup/CleanupPresetPanel.java | 12 ++++++++---- .../gui/cleanup/FieldFormatterCleanupsPanel.java | 6 +++--- .../sf/jabref/gui/preftabs/ImportSettingsTab.java | 3 --- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java index bffa98720a6..e6214a5e68b 100644 --- a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java +++ b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java @@ -75,8 +75,8 @@ private void init() { updateDisplay(cleanupPreset); - FormLayout layout = new FormLayout("left:15dlu, pref:grow", - "pref, pref, pref, pref, pref, pref, pref,pref, pref,190dlu, fill:pref:grow,"); + FormLayout layout = new FormLayout("left:15dlu, fill:pref:grow", + "pref, pref, pref, pref, pref, fill:pref:grow, pref,pref, pref,190dlu, fill:pref:grow,"); FormBuilder builder = FormBuilder.create().layout(layout); builder.add(cleanUpDOI).xyw(1, 1, 2); @@ -84,8 +84,12 @@ private void init() { builder.add(cleanUpMovePDF).xyw(1, 3, 2); builder.add(cleanUpMakePathsRelative).xyw(1, 4, 2); builder.add(cleanUpRenamePDF).xyw(1, 5, 2); - String currentPattern = Localization.lang("Filename format pattern").concat(": ") - .concat(Globals.prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)); + String currentPattern = Localization.lang("Filename format pattern").concat(": "); + String fileDirPattern = Globals.prefs.get(JabRefPreferences.IMPORT_FILEDIRPATTERN); + if (!fileDirPattern.isEmpty()) { + currentPattern = currentPattern.concat(fileDirPattern).concat("/"); + } + currentPattern = currentPattern.concat(Globals.prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)); builder.add(new JLabel(currentPattern)).xy(2, 6); builder.add(cleanUpRenamePDFonlyRelativePaths).xy(2, 7); builder.add(cleanUpBibLatex).xyw(1, 8, 2); diff --git a/src/main/java/net/sf/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java b/src/main/java/net/sf/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java index 700420691ff..fa59a88c9f7 100644 --- a/src/main/java/net/sf/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java +++ b/src/main/java/net/sf/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java @@ -83,7 +83,7 @@ public void setValues(FieldFormatterCleanups formatterCleanups) { private void buildLayout(List actionsToDisplay) { FormBuilder builder = FormBuilder.create().layout(new FormLayout( "left:pref, 13dlu, left:pref:grow, 4dlu, pref, 4dlu, pref", - "pref, 2dlu, pref, 2dlu, pref, 4dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, fill:pref:grow, 2dlu")); + "pref, 2dlu, pref, 2dlu, pref, 4dlu, pref, 2dlu, fill:pref:grow, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu")); builder.add(cleanupEnabled).xyw(1, 1, 7); actionsList = new JList<>(new CleanupActionsListModel(actionsToDisplay)); @@ -206,8 +206,8 @@ private void updateDescription() { */ private JPanel getSelectorPanel() { FormBuilder builder = FormBuilder.create() - .layout(new FormLayout("left:pref:grow, 4dlu, left:pref:grow, 4dlu, pref:grow, 4dlu, right:pref", - "pref, 2dlu, pref:grow, 2dlu")); + .layout(new FormLayout("left:pref:grow, 4dlu, left:pref:grow, 4dlu, fill:pref:grow, 4dlu, right:pref", + "fill:pref:grow, 2dlu, pref, 2dlu")); List fieldNames = InternalBibtexFields.getAllPublicAndInteralFieldNames(); fieldNames.add(BibEntry.KEY_FIELD); diff --git a/src/main/java/net/sf/jabref/gui/preftabs/ImportSettingsTab.java b/src/main/java/net/sf/jabref/gui/preftabs/ImportSettingsTab.java index 3eaf62b8948..0d4a4b10f80 100644 --- a/src/main/java/net/sf/jabref/gui/preftabs/ImportSettingsTab.java +++ b/src/main/java/net/sf/jabref/gui/preftabs/ImportSettingsTab.java @@ -41,7 +41,6 @@ public class ImportSettingsTab extends JPanel implements PrefsTab { private final JTextField fileDirPattern; - public ImportSettingsTab(JabRefPreferences prefs) { this.prefs = Objects.requireNonNull(prefs); @@ -135,8 +134,6 @@ public void setValues() { break; } fileNamePattern.setText(prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)); - - String pattern = ""; fileDirPattern.setText(prefs.get(JabRefPreferences.IMPORT_FILEDIRPATTERN)); } From 367f99236bb2df7f043dd951a0d1b9d4801df95f Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Wed, 8 Feb 2017 18:18:12 +0100 Subject: [PATCH 14/27] Rename pref variable --- .../net/sf/jabref/logic/cleanup/CleanupWorker.java | 8 ++++---- .../sf/jabref/logic/cleanup/MoveFilesCleanup.java | 8 ++++---- .../sf/jabref/logic/cleanup/RenamePdfCleanup.java | 14 ++++++++------ 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java index 8d92eed903d..f945092ff76 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java @@ -16,7 +16,7 @@ public class CleanupWorker { private final BibDatabaseContext databaseContext; private final String fileNamePattern; private final String fileDirPattern; - private final LayoutFormatterPreferences prefs; + private final LayoutFormatterPreferences layoutPrefs; private final FileDirectoryPreferences fileDirectoryPreferences; private int unsuccessfulRenames; @@ -25,7 +25,7 @@ public CleanupWorker(BibDatabaseContext databaseContext, CleanupPreferences clea this.databaseContext = databaseContext; this.fileNamePattern = cleanupPreferences.getFileNamePattern(); this.fileDirPattern = cleanupPreferences.getFileDirPattern(); - this.prefs = cleanupPreferences.getLayoutFormatterPreferences(); + this.layoutPrefs = cleanupPreferences.getLayoutFormatterPreferences(); this.fileDirectoryPreferences = cleanupPreferences.getFileDirectoryPreferences(); } @@ -69,14 +69,14 @@ private List determineCleanupActions(CleanupPreset preset) { jobs.add(new FileLinksCleanup()); } if (preset.isMovePDF()) { - jobs.add(new MoveFilesCleanup(databaseContext, fileDirPattern, fileDirectoryPreferences, prefs)); + jobs.add(new MoveFilesCleanup(databaseContext, fileDirPattern, fileDirectoryPreferences, layoutPrefs)); } if (preset.isMakePathsRelative()) { jobs.add(new RelativePathsCleanup(databaseContext, fileDirectoryPreferences)); } if (preset.isRenamePDF()) { RenamePdfCleanup cleaner = new RenamePdfCleanup(preset.isRenamePdfOnlyRelativePaths(), databaseContext, - fileNamePattern, fileDirPattern, prefs, fileDirectoryPreferences); + fileNamePattern, fileDirPattern, layoutPrefs, fileDirectoryPreferences); jobs.add(cleaner); unsuccessfulRenames += cleaner.getUnsuccessfulRenames(); } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 91698547f98..6191ad598e0 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -30,7 +30,7 @@ public class MoveFilesCleanup implements CleanupJob { private final BibDatabaseContext databaseContext; private final FileDirectoryPreferences fileDirectoryPreferences; - private final LayoutFormatterPreferences prefs; + private final LayoutFormatterPreferences layoutPrefs; private final String fileDirPattern; private static final Log LOGGER = LogFactory.getLog(MoveFilesCleanup.class); @@ -38,11 +38,11 @@ public class MoveFilesCleanup implements CleanupJob { private ParsedFileField singleFieldCleanup = null; public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, - FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences prefs) { + FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences layoutPrefs) { this.databaseContext = Objects.requireNonNull(databaseContext); this.fileDirPattern = Objects.requireNonNull(fileDirPattern); this.fileDirectoryPreferences = Objects.requireNonNull(fileDirectoryPreferences); - this.prefs = Objects.requireNonNull(prefs); + this.layoutPrefs = Objects.requireNonNull(layoutPrefs); } public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, @@ -95,7 +95,7 @@ public List cleanup(BibEntry entry) { String targetDirName = ""; if (!fileDirPattern.isEmpty()) { targetDirName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, fileDirPattern, - prefs); + layoutPrefs); } Path newTargetFile = targetDirectory.get().toPath().resolve(targetDirName).resolve(oldFile.get().getName()); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 76e8d34c28d..06408527ab3 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -34,25 +34,26 @@ public class RenamePdfCleanup implements CleanupJob { private final boolean onlyRelativePaths; private final String fileNamePattern; private final String fileDirPattern; - private final LayoutFormatterPreferences prefs; + private final LayoutFormatterPreferences layoutPrefs; private final FileDirectoryPreferences fileDirectoryPreferences; private int unsuccessfulRenames; private ParsedFileField singleFieldCleanup; public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, - String fileDirPattern, LayoutFormatterPreferences prefs, + String fileDirPattern, LayoutFormatterPreferences layoutPrefs, FileDirectoryPreferences fileDirectoryPreferences) { this.databaseContext = Objects.requireNonNull(databaseContext); this.onlyRelativePaths = onlyRelativePaths; this.fileNamePattern = Objects.requireNonNull(fileNamePattern); this.fileDirPattern = Objects.requireNonNull(fileDirPattern); - this.prefs = Objects.requireNonNull(prefs); + this.layoutPrefs = Objects.requireNonNull(layoutPrefs); this.fileDirectoryPreferences = fileDirectoryPreferences; } public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, String fileDirPattern, LayoutFormatterPreferences prefs, FileDirectoryPreferences fileDirectoryPreferences, ParsedFileField singleField) { + this(onlyRelativePaths, databaseContext, fileNamePattern, fileDirPattern, prefs, fileDirectoryPreferences); this.singleFieldCleanup = singleField; @@ -85,12 +86,13 @@ public List cleanup(BibEntry entry) { } StringBuilder targetFileName = new StringBuilder(FileUtil - .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, prefs).trim()); + .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, layoutPrefs) + .trim()); String targetDirName = ""; if (!fileDirPattern.isEmpty()) { targetDirName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, fileDirPattern, - prefs); + layoutPrefs); } //Add extension to newFilename @@ -131,7 +133,7 @@ public List cleanup(BibEntry entry) { } } catch (IOException e) { // TODO Auto-generated catch block - LOGGER.error("Could no create target necessary target directoires for renaming", e); + LOGGER.error("Could no create necessary target directoires for renaming", e); } //do rename boolean renameSuccessful = FileUtil.renameFile(Paths.get(expandedOldFilePath), newPath, true); From 0581e0da2ae36d2ffd012865270ad5635da05bb7 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Thu, 9 Feb 2017 17:51:22 +0100 Subject: [PATCH 15/27] Split Rename and Move files cleanup now completely Rename only performs a rename no longer a move --- .../logic/cleanup/RenamePdfCleanup.java | 99 +++++++++---------- .../logic/cleanup/RenamePdfCleanupTest.java | 4 +- 2 files changed, 50 insertions(+), 53 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 06408527ab3..7b78ae40685 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -98,67 +98,64 @@ public List cleanup(BibEntry entry) { //Add extension to newFilename targetFileName.append('.').append(FileUtil.getFileExtension(realOldFilename).orElse("pdf")); - //get new Filename with path - //Create new Path based on old Path and new filename - Optional expandedOldFile = FileUtil.expandFilename(realOldFilename, - databaseContext.getFileDirectories(fileDirectoryPreferences)); + //old path and old filename + Optional expandedOldFile = FileUtil.expandFilename(realOldFilename, + databaseContext.getFileDirectories(fileDirectoryPreferences)).map(File::toPath); if ((!expandedOldFile.isPresent()) || (expandedOldFile.get().getParent() == null)) { // something went wrong. Just skip this entry newFileList.add(flEntry); continue; } - Path newPath = null; - Optional dir = databaseContext.getFirstExistingFileDir(fileDirectoryPreferences); - if (dir.isPresent()) { - - newPath = dir.get().resolve(targetDirName).resolve(targetFileName.toString()); - - String expandedOldFilePath = expandedOldFile.get().toString(); - boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) - && !newPath.toString().equals(expandedOldFilePath); - - if (Files.exists(newPath) && !pathsDifferOnlyByCase) { - // we do not overwrite files - // Since File.exists is sometimes not case-sensitive, the check pathsDifferOnlyByCase ensures that we - // nonetheless rename files to a new name which just differs by case. - // TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link - newFileList.add(flEntry); - continue; - } - try { - if (!Files.exists(newPath)) { - Files.createDirectories(newPath); - } - } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error("Could no create necessary target directoires for renaming", e); + Path newPath = expandedOldFile.get().getParent().resolve(targetDirName).resolve(targetFileName.toString()); + + String expandedOldFilePath = expandedOldFile.get().toString(); + boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) + && !newPath.toString().equals(expandedOldFilePath); + + if (Files.exists(newPath) && !pathsDifferOnlyByCase) { + // we do not overwrite files + // Since File.exists is sometimes not case-sensitive, the check pathsDifferOnlyByCase ensures that we + // nonetheless rename files to a new name which just differs by case. + // TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link + newFileList.add(flEntry); + continue; + } + + try { + if (!Files.exists(newPath)) { + Files.createDirectories(newPath); } - //do rename - boolean renameSuccessful = FileUtil.renameFile(Paths.get(expandedOldFilePath), newPath, true); - if (renameSuccessful) { - changed = true; - - //Change the path for this entry - String description = flEntry.getDescription(); - String type = flEntry.getFileType(); - - Optional settingsDir = databaseContext.getFirstExistingFileDir(fileDirectoryPreferences); - if (settingsDir.isPresent()) { - - Path parent = settingsDir.get(); - String newFileEntryFileName; - if (parent == null) { - newFileEntryFileName = targetFileName.toString(); - } else { - newFileEntryFileName = parent.relativize(newPath).toString(); - } - newFileList.add(new ParsedFileField(description, newFileEntryFileName, type)); + } catch (IOException e) { + // TODO Auto-generated catch block + LOGGER.error("Could no create necessary target directoires for renaming", e); + } + //do rename + boolean renameSuccessful = FileUtil.renameFile(Paths.get(expandedOldFilePath), newPath, true); + if (renameSuccessful) { + changed = true; + + //Change the path for this entry + String description = flEntry.getDescription(); + String type = flEntry.getFileType(); + + //We use the file directory (if none is set - then bib file) to create relative file links + Optional settingsDir = databaseContext.getFirstExistingFileDir(fileDirectoryPreferences); + if (settingsDir.isPresent()) { + + Path parent = settingsDir.get(); + String newFileEntryFileName; + if (parent == null) { + newFileEntryFileName = targetFileName.toString(); + } else { + newFileEntryFileName = parent.relativize(newPath).toString(); + } - } else { - unsuccessfulRenames++; + newFileList.add(new ParsedFileField(description, newFileEntryFileName, type)); } + } else { + unsuccessfulRenames++; } } if (changed) { diff --git a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java index b3d218935a9..52417327ce7 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -154,7 +154,7 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOEx String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; String fileDirPattern = "\\EntryType"; - File subFolder = testFolder.newFolder("subbfolder"); + File subFolder = testFolder.newFolder("subfolder"); Path file = Files.createTempFile(subFolder.toPath(), "Toot", "pdf"); ParsedFileField fileField = new ParsedFileField("", file.toString(), "PDF"); @@ -167,7 +167,7 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOEx cleanup.cleanup(entry); Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("Misc/Toot - test title.pdf")).toString(); + String relativeFile = parent.relativize(parent.resolve("subfolder/Misc/Toot - test title.pdf")).toString(); ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); From ad9e62ff38530d127fdd3d299ff9b59939aa3347 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Thu, 9 Feb 2017 18:18:46 +0100 Subject: [PATCH 16/27] Fix cleanup Worker Test folder --- .../net/sf/jabref/logic/cleanup/RenamePdfCleanup.java | 2 +- .../sf/jabref/logic/cleanup/CleanupWorkerTest.java | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 7b78ae40685..c975f6a4308 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -107,7 +107,7 @@ public List cleanup(BibEntry entry) { newFileList.add(flEntry); continue; } - + //check if expandeOldFile already has targetDirname inside Path newPath = expandedOldFile.get().getParent().resolve(targetDirName).resolve(targetFileName.toString()); String expandedOldFilePath = expandedOldFile.get().toString(); diff --git a/src/test/java/net/sf/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/net/sf/jabref/logic/cleanup/CleanupWorkerTest.java index 280f996b9fe..756dd57ec0a 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/CleanupWorkerTest.java @@ -18,6 +18,7 @@ import net.sf.jabref.logic.journals.JournalAbbreviationLoader; import net.sf.jabref.logic.protectedterms.ProtectedTermsLoader; import net.sf.jabref.logic.protectedterms.ProtectedTermsPreferences; +import net.sf.jabref.model.Defaults; import net.sf.jabref.model.FieldChange; import net.sf.jabref.model.cleanup.FieldFormatterCleanup; import net.sf.jabref.model.cleanup.FieldFormatterCleanups; @@ -26,6 +27,7 @@ import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.FileField; import net.sf.jabref.model.entry.ParsedFileField; +import net.sf.jabref.model.metadata.FileDirectoryPreferences; import net.sf.jabref.model.metadata.MetaData; import net.sf.jabref.preferences.JabRefPreferences; @@ -36,6 +38,7 @@ import org.junit.rules.TemporaryFolder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class CleanupWorkerTest { @@ -52,7 +55,11 @@ public void setUp() throws IOException { MetaData metaData = new MetaData(); metaData.setDefaultFileDirectory(pdfFolder.getAbsolutePath()); - BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(), metaData, bibFolder.newFile("test.bib")); + BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(), metaData, new Defaults()); + context.setDatabaseFile(bibFolder.newFile("test.bib")); + + FileDirectoryPreferences fileDirPrefs = mock(FileDirectoryPreferences.class); + when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(true); //Biblocation as Primary overwrites all other dirs JabRefPreferences prefs = JabRefPreferences.getInstance(); @@ -60,7 +67,7 @@ public void setUp() throws IOException { new CleanupPreferences(JabRefPreferences.getInstance().get(JabRefPreferences.IMPORT_FILENAMEPATTERN), "", //empty fileDirPattern for backwards compatibility prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), - prefs.getFileDirectoryPreferences())); + fileDirPrefs)); } From 2af1d3f6e0494cc8434516b038862c02aa571434 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Fri, 10 Feb 2017 11:26:49 +0100 Subject: [PATCH 17/27] Remove fileDirPattern from Rename FileDirPattern is only used in MoveFiles Better distinction between rename and move --- .../gui/cleanup/CleanupPresetPanel.java | 4 -- .../gui/externalfiles/RenameFileAction.java | 2 +- .../jabref/logic/cleanup/CleanupWorker.java | 2 +- .../logic/cleanup/RenamePdfCleanup.java | 16 ++------ .../logic/cleanup/RenamePdfCleanupTest.java | 38 ++++++------------- 5 files changed, 18 insertions(+), 44 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java index e6214a5e68b..748d45c6665 100644 --- a/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java +++ b/src/main/java/net/sf/jabref/gui/cleanup/CleanupPresetPanel.java @@ -85,10 +85,6 @@ private void init() { builder.add(cleanUpMakePathsRelative).xyw(1, 4, 2); builder.add(cleanUpRenamePDF).xyw(1, 5, 2); String currentPattern = Localization.lang("Filename format pattern").concat(": "); - String fileDirPattern = Globals.prefs.get(JabRefPreferences.IMPORT_FILEDIRPATTERN); - if (!fileDirPattern.isEmpty()) { - currentPattern = currentPattern.concat(fileDirPattern).concat("/"); - } currentPattern = currentPattern.concat(Globals.prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)); builder.add(new JLabel(currentPattern)).xy(2, 6); builder.add(cleanUpRenamePDFonlyRelativePaths).xy(2, 7); diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java index 6c24ce15845..144d45f86e5 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -83,7 +83,7 @@ public void actionPerformed(ActionEvent e) { RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), - prefs.getFileDirPattern(), prefs.getLayoutFormatterPreferences(), + prefs.getLayoutFormatterPreferences(), prefs.getFileDirectoryPreferences(), field); pdfCleanup.cleanup(eEditor.getEntry()); diff --git a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java index f945092ff76..d99fd0812ec 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/CleanupWorker.java @@ -76,7 +76,7 @@ private List determineCleanupActions(CleanupPreset preset) { } if (preset.isRenamePDF()) { RenamePdfCleanup cleaner = new RenamePdfCleanup(preset.isRenamePdfOnlyRelativePaths(), databaseContext, - fileNamePattern, fileDirPattern, layoutPrefs, fileDirectoryPreferences); + fileNamePattern, layoutPrefs, fileDirectoryPreferences); jobs.add(cleaner); unsuccessfulRenames += cleaner.getUnsuccessfulRenames(); } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index c975f6a4308..f515bc0e1f0 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -33,28 +33,26 @@ public class RenamePdfCleanup implements CleanupJob { private final BibDatabaseContext databaseContext; private final boolean onlyRelativePaths; private final String fileNamePattern; - private final String fileDirPattern; private final LayoutFormatterPreferences layoutPrefs; private final FileDirectoryPreferences fileDirectoryPreferences; private int unsuccessfulRenames; private ParsedFileField singleFieldCleanup; public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, - String fileDirPattern, LayoutFormatterPreferences layoutPrefs, + LayoutFormatterPreferences layoutPrefs, FileDirectoryPreferences fileDirectoryPreferences) { this.databaseContext = Objects.requireNonNull(databaseContext); this.onlyRelativePaths = onlyRelativePaths; this.fileNamePattern = Objects.requireNonNull(fileNamePattern); - this.fileDirPattern = Objects.requireNonNull(fileDirPattern); this.layoutPrefs = Objects.requireNonNull(layoutPrefs); this.fileDirectoryPreferences = fileDirectoryPreferences; } public RenamePdfCleanup(boolean onlyRelativePaths, BibDatabaseContext databaseContext, String fileNamePattern, - String fileDirPattern, LayoutFormatterPreferences prefs, + LayoutFormatterPreferences layoutPrefs, FileDirectoryPreferences fileDirectoryPreferences, ParsedFileField singleField) { - this(onlyRelativePaths, databaseContext, fileNamePattern, fileDirPattern, prefs, + this(onlyRelativePaths, databaseContext, fileNamePattern, layoutPrefs, fileDirectoryPreferences); this.singleFieldCleanup = singleField; @@ -89,12 +87,6 @@ public List cleanup(BibEntry entry) { .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, layoutPrefs) .trim()); - String targetDirName = ""; - if (!fileDirPattern.isEmpty()) { - targetDirName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, fileDirPattern, - layoutPrefs); - } - //Add extension to newFilename targetFileName.append('.').append(FileUtil.getFileExtension(realOldFilename).orElse("pdf")); @@ -108,7 +100,7 @@ public List cleanup(BibEntry entry) { continue; } //check if expandeOldFile already has targetDirname inside - Path newPath = expandedOldFile.get().getParent().resolve(targetDirName).resolve(targetFileName.toString()); + Path newPath = expandedOldFile.get().getParent().resolve(targetFileName.toString()); String expandedOldFilePath = expandedOldFile.get().toString(); boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) diff --git a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java index 52417327ce7..53dda42a6cb 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -58,12 +58,11 @@ public void setUp() throws Exception { @Test public void cleanupRenamePdfRenamesFileEvenIfOnlyDifferenceIsCase() throws IOException { String fileNamePattern = "\\bibtexkey"; - String fileDirPattern = ""; File tempFile = testFolder.newFile("toot.tmp"); ParsedFileField fileField = new ParsedFileField("", tempFile.getAbsolutePath(), ""); entry.setField("file", FileField.getStringRepresentation(fileField)); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, mock(LayoutFormatterPreferences.class), fileDirPrefs); cleanup.cleanup(entry); @@ -74,14 +73,13 @@ public void cleanupRenamePdfRenamesFileEvenIfOnlyDifferenceIsCase() throws IOExc @Test public void cleanupRenamePdfRenamesWithMultipleFiles() throws IOException { String fileNamePattern = "\\bibtexkey - \\title"; - String fileDirPattern = ""; File tempFile = testFolder.newFile("Toot.tmp"); entry.setField("title", "test title"); entry.setField("file", FileField.getStringRepresentation(Arrays.asList(new ParsedFileField("", "", ""), new ParsedFileField("", tempFile.getAbsolutePath(), ""), new ParsedFileField("", "", "")))); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, mock(LayoutFormatterPreferences.class), fileDirPrefs); cleanup.cleanup(entry); @@ -94,14 +92,13 @@ public void cleanupRenamePdfRenamesWithMultipleFiles() throws IOException { @Test public void cleanupRenamePdfRenamesFileStartingWithBibtexKey() throws IOException { String fileNamePattern = "\\bibtexkey - \\title"; - String fileDirPattern = ""; File tempFile = testFolder.newFile("Toot.tmp"); ParsedFileField fileField = new ParsedFileField("", tempFile.getAbsolutePath(), ""); entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, mock(LayoutFormatterPreferences.class), fileDirPrefs); cleanup.cleanup(entry); @@ -112,13 +109,12 @@ public void cleanupRenamePdfRenamesFileStartingWithBibtexKey() throws IOExceptio @Test public void cleanupRenamePdfRenamesFileInSameFolder() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - String fileDirPattern = ""; testFolder.newFile("Toot.pdf"); ParsedFileField fileField = new ParsedFileField("", "Toot.pdf", "PDF"); entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); cleanup.cleanup(entry); @@ -130,20 +126,19 @@ public void cleanupRenamePdfRenamesFileInSameFolder() throws IOException { @Test public void cleanUpRenamePdfRenameFileDirectoryPattern() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - String fileDirPattern = "\\EntryType"; testFolder.newFile("Toot.pdf"); ParsedFileField fileField = new ParsedFileField("", "Toot.pdf", "PDF"); entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); cleanup.cleanup(entry); Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("Misc/Toot - test title.pdf")).toString(); + String relativeFile = parent.relativize(parent.resolve("Toot - test title.pdf")).toString(); ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); @@ -152,7 +147,6 @@ public void cleanUpRenamePdfRenameFileDirectoryPattern() throws IOException { @Test public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - String fileDirPattern = "\\EntryType"; File subFolder = testFolder.newFolder("subfolder"); Path file = Files.createTempFile(subFolder.toPath(), "Toot", "pdf"); @@ -161,13 +155,13 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOEx entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); cleanup.cleanup(entry); Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("subfolder/Misc/Toot - test title.pdf")).toString(); + String relativeFile = parent.relativize(parent.resolve("subfolder/Toot - test title.pdf")).toString(); ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); @@ -176,7 +170,6 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOEx @Test public void cleanUpRenamePdfRenameFileDirectoryPatternSameAsFilePattern() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - String fileDirPattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; testFolder.newFile("Toot.pdf"); @@ -184,22 +177,18 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternSameAsFilePattern() throws entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); cleanup.cleanup(entry); - Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("Toot - test title/Toot - test title.pdf")).toString(); - - ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); + ParsedFileField newFileField = new ParsedFileField("", "Toot - test title.pdf", "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); } @Test public void cleanUpRenamePdfRenameFileDirectoryPatternEmptyFileName() throws IOException { String fileNamePattern = ""; - String fileDirPattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; testFolder.newFile("Toot.pdf"); @@ -207,15 +196,12 @@ public void cleanUpRenamePdfRenameFileDirectoryPatternEmptyFileName() throws IOE entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, fileDirPattern, + RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); cleanup.cleanup(entry); - Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("Toot - test title/Toot.pdf")).toString(); - - ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); + ParsedFileField newFileField = new ParsedFileField("", "Toot.pdf", "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); } From d4320a6c03da30ae3cc75a51ce5591f649a53556 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sun, 12 Feb 2017 18:16:44 +0100 Subject: [PATCH 18/27] Move targetFileName generation to new method Rework tests, delete tests with filedirpattern --- .../gui/externalfiles/MoveFileAction.java | 7 +- .../gui/externalfiles/RenameFileAction.java | 12 ++-- .../logic/cleanup/MoveFilesCleanup.java | 1 - .../logic/cleanup/RenamePdfCleanup.java | 36 ++++++---- .../logic/cleanup/RenamePdfCleanupTest.java | 65 ++----------------- 5 files changed, 40 insertions(+), 81 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java index 1ea4dc5c9db..dd2b115d816 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/MoveFileAction.java @@ -4,6 +4,7 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Locale; import java.util.Optional; @@ -77,12 +78,12 @@ public void actionPerformed(ActionEvent event) { MOVE_RENAME, JOptionPane.ERROR_MESSAGE); return; } - File file = new File(ln); + Path file = Paths.get(ln); if (!file.isAbsolute()) { - file = FileUtil.expandFilename(ln, dirs).orElse(null); + file = FileUtil.expandFilename(ln, dirs).map(File::toPath).orElse(null); } - if ((file != null) && Files.exists(file.toPath())) { + if ((file != null) && Files.exists(file)) { // Ok, we found the file. Now get a new name: System.out.println("Cleanup of file " + file); diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java index 144d45f86e5..6bf00332d28 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -4,6 +4,7 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Locale; import java.util.Optional; @@ -35,7 +36,6 @@ public class RenameFileAction extends AbstractAction { private final FileListEditor editor; private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); - private final boolean toFileDir = false; private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); public RenameFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { @@ -73,18 +73,22 @@ public void actionPerformed(ActionEvent e) { MOVE_RENAME, JOptionPane.ERROR_MESSAGE); return; } - File file = new File(ln); + Path file = Paths.get(ln); if (!file.isAbsolute()) { - file = FileUtil.expandFilename(ln, dirs).orElse(null); + file = FileUtil.expandFilename(ln, dirs).map(File::toPath).orElse(null); } - if ((file != null) && Files.exists(file.toPath())) { + if ((file != null) && Files.exists(file)) { System.out.println("Cleanup Rename of file " + file); RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), prefs.getLayoutFormatterPreferences(), prefs.getFileDirectoryPreferences(), field); + + String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry()); + System.out.println("TargetFileName " + targetFileName); + pdfCleanup.cleanup(eEditor.getEntry()); } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index 6191ad598e0..b6ffc3acf0f 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -138,5 +138,4 @@ public List cleanup(BibEntry entry) { return Collections.emptyList(); } - } diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index f515bc0e1f0..7bc8587b6b0 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -78,18 +78,11 @@ public List cleanup(BibEntry entry) { for (ParsedFileField flEntry : fileList) { String realOldFilename = flEntry.getLink(); - if (onlyRelativePaths && (new File(realOldFilename).isAbsolute())) { + if (onlyRelativePaths && Paths.get(realOldFilename).isAbsolute()) { newFileList.add(flEntry); continue; } - StringBuilder targetFileName = new StringBuilder(FileUtil - .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, layoutPrefs) - .trim()); - - //Add extension to newFilename - targetFileName.append('.').append(FileUtil.getFileExtension(realOldFilename).orElse("pdf")); - //old path and old filename Optional expandedOldFile = FileUtil.expandFilename(realOldFilename, databaseContext.getFileDirectories(fileDirectoryPreferences)).map(File::toPath); @@ -99,8 +92,8 @@ public List cleanup(BibEntry entry) { newFileList.add(flEntry); continue; } - //check if expandeOldFile already has targetDirname inside - Path newPath = expandedOldFile.get().getParent().resolve(targetFileName.toString()); + String targetFileName = getTargetFileName(flEntry, entry); + Path newPath = expandedOldFile.get().getParent().resolve(targetFileName); String expandedOldFilePath = expandedOldFile.get().toString(); boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) @@ -111,6 +104,8 @@ public List cleanup(BibEntry entry) { // Since File.exists is sometimes not case-sensitive, the check pathsDifferOnlyByCase ensures that we // nonetheless rename files to a new name which just differs by case. // TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link + LOGGER.debug("There already exists a file with that name " + newPath.getFileName() + + " so I won't rename it"); newFileList.add(flEntry); continue; } @@ -120,10 +115,9 @@ public List cleanup(BibEntry entry) { Files.createDirectories(newPath); } } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error("Could no create necessary target directoires for renaming", e); + LOGGER.error("Could not create necessary target directoires for renaming", e); } - //do rename + boolean renameSuccessful = FileUtil.renameFile(Paths.get(expandedOldFilePath), newPath, true); if (renameSuccessful) { changed = true; @@ -142,7 +136,6 @@ public List cleanup(BibEntry entry) { newFileEntryFileName = targetFileName.toString(); } else { newFileEntryFileName = parent.relativize(newPath).toString(); - } newFileList.add(new ParsedFileField(description, newFileEntryFileName, type)); } @@ -164,7 +157,22 @@ public List cleanup(BibEntry entry) { return Collections.emptyList(); } + public String getTargetFileName(ParsedFileField flEntry, BibEntry entry) { + String realOldFilename = flEntry.getLink(); + + StringBuilder targetFileName = new StringBuilder(FileUtil + .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, layoutPrefs) + .trim()); + + //Add extension to newFilename + targetFileName.append('.').append(FileUtil.getFileExtension(realOldFilename).orElse("pdf")); + + return targetFileName.toString(); + + } + public int getUnsuccessfulRenames() { return unsuccessfulRenames; } + } diff --git a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java index 53dda42a6cb..dd5ad905c04 100644 --- a/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/net/sf/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -2,8 +2,6 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; @@ -23,7 +21,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -124,85 +121,35 @@ public void cleanupRenamePdfRenamesFileInSameFolder() throws IOException { } @Test - public void cleanUpRenamePdfRenameFileDirectoryPattern() throws IOException { + public void cleanupSingleField() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - testFolder.newFile("Toot.pdf"); ParsedFileField fileField = new ParsedFileField("", "Toot.pdf", "PDF"); entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), - fileDirPrefs); - cleanup.cleanup(entry); - - Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("Toot - test title.pdf")).toString(); - - ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); - assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); - } - - @Test - public void cleanUpRenamePdfRenameFileDirectoryPatternSubDirectory() throws IOException { - String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - - File subFolder = testFolder.newFolder("subfolder"); - Path file = Files.createTempFile(subFolder.toPath(), "Toot", "pdf"); - - ParsedFileField fileField = new ParsedFileField("", file.toString(), "PDF"); - entry.setField("file", FileField.getStringRepresentation(fileField)); - entry.setField("title", "test title"); + fileDirPrefs, fileField); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), - fileDirPrefs); cleanup.cleanup(entry); - Path parent = context.getFirstExistingFileDir(prefs.getFileDirectoryPreferences()).get(); - String relativeFile = parent.relativize(parent.resolve("subfolder/Toot - test title.pdf")).toString(); - - ParsedFileField newFileField = new ParsedFileField("", relativeFile, "PDF"); + ParsedFileField newFileField = new ParsedFileField("", "Toot - test title.pdf", "PDF"); assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); + } @Test - public void cleanUpRenamePdfRenameFileDirectoryPatternSameAsFilePattern() throws IOException { + public void cleanupGetTargetFilename() throws IOException { String fileNamePattern = "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"; - testFolder.newFile("Toot.pdf"); - ParsedFileField fileField = new ParsedFileField("", "Toot.pdf", "PDF"); - entry.setField("file", FileField.getStringRepresentation(fileField)); - entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), fileDirPrefs); - cleanup.cleanup(entry); - - ParsedFileField newFileField = new ParsedFileField("", "Toot - test title.pdf", "PDF"); - assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); - } - - @Test - public void cleanUpRenamePdfRenameFileDirectoryPatternEmptyFileName() throws IOException { - String fileNamePattern = ""; - - testFolder.newFile("Toot.pdf"); - - ParsedFileField fileField = new ParsedFileField("", "Toot.pdf", "PDF"); entry.setField("file", FileField.getStringRepresentation(fileField)); entry.setField("title", "test title"); - RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), - fileDirPrefs); - cleanup.cleanup(entry); - - ParsedFileField newFileField = new ParsedFileField("", "Toot.pdf", "PDF"); - assertEquals(Optional.of(FileField.getStringRepresentation(newFileField)), entry.getField("file")); + assertEquals("Toot - test title.pdf", cleanup.getTargetFileName(fileField, entry)); } } From f05070ced72b5380531e02ac028bd756b1e74729 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sun, 12 Feb 2017 18:25:14 +0100 Subject: [PATCH 19/27] Fix codacy --- .../net/sf/jabref/gui/externalfiles/RenameFileAction.java | 5 ----- .../java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java | 2 +- .../java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java index 6bf00332d28..f974fd6007c 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java @@ -24,13 +24,8 @@ import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.model.entry.ParsedFileField; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - public class RenameFileAction extends AbstractAction { - private static final Log LOGGER = LogFactory.getLog(RenameFileAction.class); - private final JabRefFrame frame; private final EntryEditor eEditor; private final FileListEditor editor; diff --git a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java index b6ffc3acf0f..5855e9ec08c 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/MoveFilesCleanup.java @@ -35,7 +35,7 @@ public class MoveFilesCleanup implements CleanupJob { private final String fileDirPattern; private static final Log LOGGER = LogFactory.getLog(MoveFilesCleanup.class); - private ParsedFileField singleFieldCleanup = null; + private ParsedFileField singleFieldCleanup; public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences layoutPrefs) { diff --git a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java index 7bc8587b6b0..467ff95f225 100644 --- a/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/net/sf/jabref/logic/cleanup/RenamePdfCleanup.java @@ -133,7 +133,7 @@ public List cleanup(BibEntry entry) { Path parent = settingsDir.get(); String newFileEntryFileName; if (parent == null) { - newFileEntryFileName = targetFileName.toString(); + newFileEntryFileName = targetFileName; } else { newFileEntryFileName = parent.relativize(newPath).toString(); } From b39f29931bda7422f0d767391586f50a59e9dbfd Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Fri, 17 Feb 2017 11:42:17 +0100 Subject: [PATCH 20/27] Fix merge conflicts --- .../gui/externalfiles/MoveFileAction.java | 6 ++--- .../gui/externalfiles/RenameFileAction.java | 24 +++++++++---------- .../gui/fieldeditors/FileListEditor.java | 13 ++++++---- .../logic/cleanup/MoveFilesCleanup.java | 4 ++++ .../logic/cleanup/CleanupWorkerTest.java | 2 ++ .../logic/cleanup/MoveFilesCleanupTest.java | 4 +++- .../logic/cleanup/RenamePdfCleanupTest.java | 1 + 7 files changed, 33 insertions(+), 21 deletions(-) rename src/main/java/{net/sf => org}/jabref/gui/externalfiles/RenameFileAction.java (83%) diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 5482e469982..20e8ddb1e7a 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -13,15 +13,15 @@ import javax.swing.JOptionPane; import org.jabref.Globals; -import org.jabref.gui.FileDialog; import org.jabref.gui.JabRefFrame; import org.jabref.gui.entryeditor.EntryEditor; import org.jabref.gui.fieldeditors.FileListEditor; import org.jabref.gui.filelist.FileListEntry; -import org.jabref.gui.util.component.CheckBoxMessage; +import org.jabref.logic.cleanup.CleanupPreferences; +import org.jabref.logic.cleanup.MoveFilesCleanup; +import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; -import org.jabref.preferences.JabRefPreferences; import org.jabref.model.entry.ParsedFileField; import org.apache.commons.logging.Log; diff --git a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java similarity index 83% rename from src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java rename to src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index f974fd6007c..9853c410bf8 100644 --- a/src/main/java/net/sf/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -1,4 +1,4 @@ -package net.sf.jabref.gui.externalfiles; +package org.jabref.gui.externalfiles; import java.awt.event.ActionEvent; import java.io.File; @@ -12,17 +12,17 @@ import javax.swing.AbstractAction; import javax.swing.JOptionPane; -import net.sf.jabref.Globals; -import net.sf.jabref.gui.JabRefFrame; -import net.sf.jabref.gui.entryeditor.EntryEditor; -import net.sf.jabref.gui.fieldeditors.FileListEditor; -import net.sf.jabref.gui.filelist.FileListEntry; -import net.sf.jabref.logic.cleanup.CleanupPreferences; -import net.sf.jabref.logic.cleanup.RenamePdfCleanup; -import net.sf.jabref.logic.journals.JournalAbbreviationLoader; -import net.sf.jabref.logic.l10n.Localization; -import net.sf.jabref.logic.util.io.FileUtil; -import net.sf.jabref.model.entry.ParsedFileField; +import org.jabref.Globals; +import org.jabref.gui.JabRefFrame; +import org.jabref.gui.entryeditor.EntryEditor; +import org.jabref.gui.fieldeditors.FileListEditor; +import org.jabref.gui.filelist.FileListEntry; +import org.jabref.logic.cleanup.CleanupPreferences; +import org.jabref.logic.cleanup.RenamePdfCleanup; +import org.jabref.logic.journals.JournalAbbreviationLoader; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.util.io.FileUtil; +import org.jabref.model.entry.ParsedFileField; public class RenameFileAction extends AbstractAction { diff --git a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java index d0d5f65bb0f..fdf935983b6 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java +++ b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java @@ -43,6 +43,7 @@ import org.jabref.gui.externalfiles.AutoSetLinks; import org.jabref.gui.externalfiles.DownloadExternalFile; import org.jabref.gui.externalfiles.MoveFileAction; +import org.jabref.gui.externalfiles.RenameFileAction; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.filelist.FileListEntry; @@ -60,6 +61,7 @@ import org.apache.commons.logging.LogFactory; public class FileListEditor extends JTable implements FieldEditor, DownloadExternalFile.DownloadCallback { + private static final Log LOGGER = LogFactory.getLog(FileListEditor.class); private final FieldNameLabel label; @@ -74,7 +76,7 @@ public class FileListEditor extends JTable implements FieldEditor, DownloadExter private final JPopupMenu menu = new JPopupMenu(); public FileListEditor(JabRefFrame frame, BibDatabaseContext databaseContext, String fieldName, String content, - EntryEditor entryEditor) { + EntryEditor entryEditor) { this.frame = frame; this.databaseContext = databaseContext; this.fieldName = fieldName; @@ -108,8 +110,7 @@ public FileListEditor(JabRefFrame frame, BibDatabaseContext databaseContext, Str download.addActionListener(e -> downloadFile()); FormBuilder builder = FormBuilder.create() - .layout(new FormLayout - ("fill:pref,1dlu,fill:pref,1dlu,fill:pref", "fill:pref,fill:pref")); + .layout(new FormLayout("fill:pref,1dlu,fill:pref,1dlu,fill:pref", "fill:pref,fill:pref")); builder.add(up).xy(1, 1); builder.add(add).xy(3, 1); builder.add(auto).xy(5, 1); @@ -265,7 +266,8 @@ private void openSelectedFile() { try { Optional type = ExternalFileTypes.getInstance() .getExternalFileTypeByName(entry.type.get().getName()); - JabRefDesktop.openExternalFileAnyFormat(databaseContext, entry.link, type.isPresent() ? type : entry.type); + JabRefDesktop.openExternalFileAnyFormat(databaseContext, entry.link, + type.isPresent() ? type : entry.type); } catch (IOException e) { LOGGER.warn("Cannot open selected file.", e); } @@ -436,7 +438,7 @@ public void autoSetLinks() { } // reset auto.setEnabled(true); - } , dialog)); + }, dialog)); } /** @@ -478,6 +480,7 @@ public void downloadComplete(FileListEntry file) { } class TableClickListener extends MouseAdapter { + @Override public void mouseClicked(MouseEvent e) { if ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 2)) { diff --git a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java index 852213a90c7..7b3f1fe395b 100644 --- a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java @@ -14,6 +14,7 @@ import java.util.stream.Collectors; import org.jabref.logic.TypedBibEntry; +import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.FieldChange; import org.jabref.model.cleanup.CleanupJob; @@ -22,6 +23,9 @@ import org.jabref.model.entry.ParsedFileField; import org.jabref.model.metadata.FileDirectoryPreferences; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + public class MoveFilesCleanup implements CleanupJob { private final BibDatabaseContext databaseContext; diff --git a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java index 20716390419..7747efced6c 100644 --- a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java @@ -18,6 +18,7 @@ import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; +import org.jabref.model.Defaults; import org.jabref.model.FieldChange; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.cleanup.FieldFormatterCleanups; @@ -26,6 +27,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FileField; import org.jabref.model.entry.ParsedFileField; +import org.jabref.model.metadata.FileDirectoryPreferences; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.JabRefPreferences; diff --git a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java index 01123fcf67d..4b17fd54486 100644 --- a/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java @@ -7,13 +7,15 @@ import java.util.Arrays; import java.util.Optional; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FileField; import org.jabref.model.entry.ParsedFileField; +import org.jabref.model.metadata.FileDirectoryPreferences; import org.jabref.model.metadata.MetaData; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Rule; diff --git a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java index 3375f08b628..1d63483f627 100644 --- a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -21,6 +21,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; + import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; From 3a7b9eda9d6fd10741f020d99e441d5b3accf0f9 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sat, 18 Feb 2017 13:00:30 +0100 Subject: [PATCH 21/27] Add dialog, change localization --- .../jabref/gui/externalfiles/MoveFileAction.java | 12 ++++++++++-- .../jabref/gui/externalfiles/RenameFileAction.java | 13 ++++++++----- .../org/jabref/logic/cleanup/MoveFilesCleanup.java | 5 +++-- src/main/resources/l10n/JabRef_da.properties | 5 ++++- src/main/resources/l10n/JabRef_in.properties | 5 ++++- src/main/resources/l10n/JabRef_it.properties | 5 ++++- src/main/resources/l10n/JabRef_no.properties | 5 ++++- src/main/resources/l10n/JabRef_pt_BR.properties | 5 ++++- src/main/resources/l10n/JabRef_ru.properties | 5 ++++- src/main/resources/l10n/JabRef_tr.properties | 5 ++++- src/main/resources/l10n/JabRef_vi.properties | 5 ++++- src/main/resources/l10n/JabRef_zh.properties | 5 ++++- 12 files changed, 57 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 20e8ddb1e7a..6eca4338f63 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -22,6 +22,7 @@ import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; +import org.jabref.model.FieldChange; import org.jabref.model.entry.ParsedFileField; import org.apache.commons.logging.Log; @@ -75,7 +76,7 @@ public void actionPerformed(ActionEvent event) { .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), - MOVE_RENAME, JOptionPane.ERROR_MESSAGE); + Localization.lang("Move_file"), JOptionPane.ERROR_MESSAGE); return; } Path file = Paths.get(ln); @@ -92,7 +93,14 @@ public void actionPerformed(ActionEvent event) { prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), prefs.getLayoutFormatterPreferences(), field); - moveFiles.cleanup((eEditor.getEntry())); + String[] options = {Localization.lang("Move_file"), Localization.lang("Cancel")}; + + JOptionPane.showOptionDialog(frame, "Move file to " + " ", "Move", + JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); + + List fieldChanges = moveFiles.cleanup((eEditor.getEntry())); + fieldChanges.stream().findFirst().ifPresent(x -> System.out.println(x.getNewValue())); + //myCleanUp.cleanup(); /* File newFile = null; boolean repeat = true; diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index 9853c410bf8..e875db4d913 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.Locale; import java.util.Optional; - import javax.swing.AbstractAction; import javax.swing.JOptionPane; @@ -22,6 +21,7 @@ import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; +import org.jabref.model.FieldChange; import org.jabref.model.entry.ParsedFileField; public class RenameFileAction extends AbstractAction { @@ -31,8 +31,6 @@ public class RenameFileAction extends AbstractAction { private final FileListEditor editor; private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); - private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); - public RenameFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; this.eEditor = eEditor; @@ -65,7 +63,7 @@ public void actionPerformed(ActionEvent e) { .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), - MOVE_RENAME, JOptionPane.ERROR_MESSAGE); + Localization.lang("Rename_file"), JOptionPane.ERROR_MESSAGE); return; } Path file = Paths.get(ln); @@ -84,8 +82,13 @@ public void actionPerformed(ActionEvent e) { String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry()); System.out.println("TargetFileName " + targetFileName); - pdfCleanup.cleanup(eEditor.getEntry()); + String[] options = {Localization.lang("Rename_file"), Localization.lang("Cancel")}; + + JOptionPane.showOptionDialog(frame, "Rename file to " + targetFileName, "Rename", + JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); + List fieldChanges = pdfCleanup.cleanup(eEditor.getEntry()); + fieldChanges.stream().findFirst().ifPresent(System.out::println); } } diff --git a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java index 7b3f1fe395b..5649cd3582c 100644 --- a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java @@ -63,7 +63,7 @@ public List cleanup(BibEntry entry) { List paths = databaseContext.getFileDirectories(fileDirectoryPreferences); String defaultFileDirectory = firstExistingFileDir.get().toString(); - Optional targetDirectory = FileUtil.expandFilename(defaultFileDirectory, paths); + Optional targetDirectory = FileUtil.expandFilename(defaultFileDirectory, paths).map(File::toPath); if (!targetDirectory.isPresent()) { return Collections.emptyList(); @@ -98,7 +98,7 @@ public List cleanup(BibEntry entry) { layoutPrefs); } - Path newTargetFile = targetDirectory.get().toPath().resolve(targetDirName).resolve(oldFile.get().getName()); + Path newTargetFile = targetDirectory.get().resolve(targetDirName).resolve(oldFile.get().getName()); if (Files.exists(newTargetFile)) { // We do not overwrite already existing files newFileList.add(fileEntry); @@ -138,4 +138,5 @@ public List cleanup(BibEntry entry) { return Collections.emptyList(); } + } diff --git a/src/main/resources/l10n/JabRef_da.properties b/src/main/resources/l10n/JabRef_da.properties index d60a79c4192..941e1bae326 100644 --- a/src/main/resources/l10n/JabRef_da.properties +++ b/src/main/resources/l10n/JabRef_da.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Følgende_henteværktøjer_er_tilgængeli Could_not_find_fetcher_'%0'=Kunne_ikke_finde_henteværktøjet_'%0' Running_query_'%0'_with_fetcher_'%1'.=Kører_forespørgsel_'%0'_med_henteværktøjet_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Forespørgsel_'%0'_med_henteværktøjet_'%1'_returnerede_ingen_resultater. -Move/Rename_file=Flyt/omdøb_fil + +Move_file=Flyt_fil +Rename_file=omdøb_fil + File_moved=Fil_flyttet Move_file_failed=Flytning_af_fil_mislykkedes Could_not_move_file_'%0'.=Kunne_ikke_flytte_fil_'%0'. diff --git a/src/main/resources/l10n/JabRef_in.properties b/src/main/resources/l10n/JabRef_in.properties index c3eaf37417c..380f8135d21 100644 --- a/src/main/resources/l10n/JabRef_in.properties +++ b/src/main/resources/l10n/JabRef_in.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Pengambil_berikut_tersedia\: Could_not_find_fetcher_'%0'=Tidak_bisa_menemukan_pengambil_'%0' Running_query_'%0'_with_fetcher_'%1'.=Jalankan_Kueri_'%0'_dengan_pengambil_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Kueri_'%0'_dengan_pengambil_'%1'_tidak_ada_hasilnya. -Move/Rename_file=Memindah/Menamai_berkas + +Move_file=Memindah_berkas +Rename_file=Menamai_berkas + File_moved=Berkas_dipindah Move_file_failed=Gagal_memindah_berkas Could_not_move_file_'%0'.=Tidak_bisa_meindah_berkas_'%0'. diff --git a/src/main/resources/l10n/JabRef_it.properties b/src/main/resources/l10n/JabRef_it.properties index c55080529f3..bf7a323bff9 100644 --- a/src/main/resources/l10n/JabRef_it.properties +++ b/src/main/resources/l10n/JabRef_it.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Le_utilità_di_ricerca_seguenti_sono_disp Could_not_find_fetcher_'%0'=Impossibile_trovare_l'utilità_di_ricerca_'%0' Running_query_'%0'_with_fetcher_'%1'.=Esecuzione_della_query_'%0'_con_l'utilità_di_ricerca_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=La_query_'%0'_con_l'utilità_di_ricerca_'%1'_non_ha_prodotto_alcun_risultato. -Move/Rename_file=Sposta/Rinomina_il_file + +Move_file=Sposta_file +Rename_file=Rinomina_il_file + File_moved=File_spostato Move_file_failed=Spostamento_del_file_fallito Could_not_move_file_'%0'.=Impossibile_spostare_il_file_'%0'. diff --git a/src/main/resources/l10n/JabRef_no.properties b/src/main/resources/l10n/JabRef_no.properties index 7bbc374a2cd..b1425e9a1fa 100644 --- a/src/main/resources/l10n/JabRef_no.properties +++ b/src/main/resources/l10n/JabRef_no.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=De_f\u00f8lgende_nedlasterne_er_tilgjenge Could_not_find_fetcher_'%0'=Kunne_ikke_finne_nedlasteren_'%0' Running_query_'%0'_with_fetcher_'%1'.=Utf\u00f8rer_s\u00f8k_'%0'_med_nedlaster_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=S\u00f8ket_'%0'_med_nedlaster_'%1'_ga_ingen_resultater. -Move/Rename_file=Flytt/endre_navn_p\u00e5_fil + +Move_file=Flytt_fil +Rename_file=endre_navn_p\u00e5_fil + File_moved=Flyttet_fil Move_file_failed=Flytting_av_fil_mislyktes Could_not_move_file_'%0'.=Kunne_ikke_flytte_filen_'%0'. diff --git a/src/main/resources/l10n/JabRef_pt_BR.properties b/src/main/resources/l10n/JabRef_pt_BR.properties index b414b3ef407..d79d251a10b 100644 --- a/src/main/resources/l10n/JabRef_pt_BR.properties +++ b/src/main/resources/l10n/JabRef_pt_BR.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=As_seguintes_ferramentas_de_pesquisa_est Could_not_find_fetcher_'%0'=Não_foi_possível_encontrar_a_ferramenta_de_pesquisa_'%0' Running_query_'%0'_with_fetcher_'%1'.=Executando_consulta_'%0'_com_ferramenta_de_pesquisa_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Consulta_'%0'_com_ferramenta_de_pesquisa_'%1'_não_retornou_resultados. -Move/Rename_file=Mover/Renomear_arquivo + +Move_file=Mover_arquivo +Rename_file=Renomear_arquivo + File_moved=Arquivo_movido Move_file_failed=Movimentação_do_arquivo_falhou Could_not_move_file_'%0'.=Não_foi_possível_mover_o_arquivo_'%0'. diff --git a/src/main/resources/l10n/JabRef_ru.properties b/src/main/resources/l10n/JabRef_ru.properties index 5ec623f34e7..046044c86da 100644 --- a/src/main/resources/l10n/JabRef_ru.properties +++ b/src/main/resources/l10n/JabRef_ru.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Доступны_следующие_ин Could_not_find_fetcher_'%0'=Не_удалось_найти_инструмент_выборки_'%0' Running_query_'%0'_with_fetcher_'%1'.=Выполняется_запрос_'%0'_для_инструмента_выборки_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Не_найдено_результатов_запроса_'%0'_для_инструмента_выборки_'%1'. -Move/Rename_file=Переместить/Ппереименовать_файл + +Move_file=Переместить_файл +Rename_file=Ппереименовать_файл + File_moved=Файл_перемещен Move_file_failed=Ошибка_перемещения_файла Could_not_move_file_'%0'.=Не_удалось_переместить_файл_'%0'. diff --git a/src/main/resources/l10n/JabRef_tr.properties b/src/main/resources/l10n/JabRef_tr.properties index 7001b9c56ff..e56759a76fa 100644 --- a/src/main/resources/l10n/JabRef_tr.properties +++ b/src/main/resources/l10n/JabRef_tr.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Aşağıdaki_getiriciler_kullanıma_hazı Could_not_find_fetcher_'%0'='%0'_getiricisi_bulunamadı Running_query_'%0'_with_fetcher_'%1'.='%0'_sorgusu_'%1'_getiricisiyle_çalıştırılıyor. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.='%1'_getiricisiyle_'%0'_sorgusu_hiçbir_sonuç_döndürmedi. -Move/Rename_file=Dosya_Taşı/Yeniden_adlandır + +Move_file=Dosya_Taşı_adlandır +Rename_file=Yeniden_adlandır + File_moved=Dosya_taşındı Move_file_failed=Dosya_taşıma_başarısız Could_not_move_file_'%0'.='%0'_dosya_taşınamıyor. diff --git a/src/main/resources/l10n/JabRef_vi.properties b/src/main/resources/l10n/JabRef_vi.properties index 997740e2a8d..e56b3f1fa23 100644 --- a/src/main/resources/l10n/JabRef_vi.properties +++ b/src/main/resources/l10n/JabRef_vi.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Các_trình_lấy_về_sau_có_thể_dùn Could_not_find_fetcher_'%0'=Không_thể_tìm_thấy_trình_lầy_về_'%0' Running_query_'%0'_with_fetcher_'%1'.=Đang_chạy_truy_vấn_'%0'_với_trình_lấy_về_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Phép_truy_vấn_'%0'_bằng_trình_lấy_về_'%1'_không_trả_lại_kết_quả_nào. -Move/Rename_file=Chuyển/Đặt_lại_tên_tập_tin + +Move_file=Chuyển_tin +Rename_file=Đặt_lại_tên_tập_tin + File_moved=Tập_tin_bị_di_chuyển Move_file_failed=Việc_chuyển_tập_tin_thất_bại Could_not_move_file_'%0'.=Không_thể_chuyển_tập_tin_'%0'. diff --git a/src/main/resources/l10n/JabRef_zh.properties b/src/main/resources/l10n/JabRef_zh.properties index b438be00661..9aeb596cc97 100644 --- a/src/main/resources/l10n/JabRef_zh.properties +++ b/src/main/resources/l10n/JabRef_zh.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=下面列出的是可用的抓取器\: Could_not_find_fetcher_'%0'=无法找到抓取器_'%0' Running_query_'%0'_with_fetcher_'%1'.=使用抓取器'%1'执行请求'%0' Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=使用抓取器'%1'请求'%0'未返回任何结果。 -Move/Rename_file=移动/重命名_文件 + +Move_file=移动_文件 +Rename_file=重命名_文件 + File_moved=文件移动完成 Move_file_failed=移动文件失败 Could_not_move_file_'%0'.=无法移动文件_'%0' From b35b5668fb47aa79b489b1794630de6a20907c3e Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sat, 18 Feb 2017 13:14:36 +0100 Subject: [PATCH 22/27] fix checkstyle --- src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index e875db4d913..fa37cf5a600 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Locale; import java.util.Optional; + import javax.swing.AbstractAction; import javax.swing.JOptionPane; From e776223ddd9ca210e2fb86051bc4f5e04479885a Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sat, 18 Feb 2017 14:29:39 +0100 Subject: [PATCH 23/27] Fix localization --- .../java/org/jabref/gui/externalfiles/MoveFileAction.java | 5 ++--- .../java/org/jabref/gui/externalfiles/RenameFileAction.java | 4 ++-- .../java/org/jabref/gui/fieldeditors/FileListEditor.java | 2 +- src/main/resources/l10n/JabRef_de.properties | 5 ++++- src/main/resources/l10n/JabRef_en.properties | 5 ++++- src/main/resources/l10n/JabRef_es.properties | 5 ++++- src/main/resources/l10n/JabRef_fa.properties | 5 ++++- src/main/resources/l10n/JabRef_fr.properties | 5 ++++- src/main/resources/l10n/JabRef_ja.properties | 5 ++++- src/main/resources/l10n/JabRef_nl.properties | 5 ++++- src/main/resources/l10n/JabRef_sv.properties | 5 ++++- 11 files changed, 37 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 6eca4338f63..194aaf53163 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -40,7 +40,6 @@ public class MoveFileAction extends AbstractAction { private final FileListEditor editor; private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); - private static final String MOVE_RENAME = Localization.lang("Move/Rename file"); public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; @@ -76,7 +75,7 @@ public void actionPerformed(ActionEvent event) { .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), - Localization.lang("Move_file"), JOptionPane.ERROR_MESSAGE); + Localization.lang("Move file"), JOptionPane.ERROR_MESSAGE); return; } Path file = Paths.get(ln); @@ -93,7 +92,7 @@ public void actionPerformed(ActionEvent event) { prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), prefs.getLayoutFormatterPreferences(), field); - String[] options = {Localization.lang("Move_file"), Localization.lang("Cancel")}; + String[] options = {Localization.lang("Move file"), Localization.lang("Cancel")}; JOptionPane.showOptionDialog(frame, "Move file to " + " ", "Move", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index fa37cf5a600..7e4a89164f8 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -64,7 +64,7 @@ public void actionPerformed(ActionEvent e) { .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), - Localization.lang("Rename_file"), JOptionPane.ERROR_MESSAGE); + Localization.lang("Rename file"), JOptionPane.ERROR_MESSAGE); return; } Path file = Paths.get(ln); @@ -83,7 +83,7 @@ public void actionPerformed(ActionEvent e) { String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry()); System.out.println("TargetFileName " + targetFileName); - String[] options = {Localization.lang("Rename_file"), Localization.lang("Cancel")}; + String[] options = {Localization.lang("Rename file"), Localization.lang("Cancel")}; JOptionPane.showOptionDialog(frame, "Rename file to " + targetFileName, "Rename", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); diff --git a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java index fdf935983b6..05b88b7ef0a 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java +++ b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java @@ -211,7 +211,7 @@ public void actionPerformed(ActionEvent actionEvent) { } }); - JMenuItem rename = new JMenuItem(Localization.lang("Move/Rename file")); + JMenuItem rename = new JMenuItem(Localization.lang("Rename file")); menu.add(rename); rename.addActionListener(new RenameFileAction(frame, entryEditor, this)); diff --git a/src/main/resources/l10n/JabRef_de.properties b/src/main/resources/l10n/JabRef_de.properties index bf15facf2ba..0d772e0febb 100644 --- a/src/main/resources/l10n/JabRef_de.properties +++ b/src/main/resources/l10n/JabRef_de.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Folgende_Recherchetools_stehen_zur_Verfü Could_not_find_fetcher_'%0'=Recherchetool_'%0'_konnte_nicht_gefunden_werden Running_query_'%0'_with_fetcher_'%1'.=Abfrage_'%0'_wird_mit_dem_Recherchetool_'%1'_durchgeführt. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Die_Abfrage_'%0'_mit_dem_Recherchetool_'%1'_lieferte_keine_Ergebnisse. -Move/Rename_file=Datei_verschieben/umbenennen + +Move_file=Datei_verschoben +Rename_file=Datei_umbenennen + File_moved=Datei_verschoben Move_file_failed=Fehler_beim_Verschieben_der_Datei Could_not_move_file_'%0'.=Datei_'%0'_konnte_nicht_verschoben_werden. diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index e12ee39d079..b9c9e99ada8 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=The_following_fetchers_are_available\: Could_not_find_fetcher_'%0'=Could_not_find_fetcher_'%0' Running_query_'%0'_with_fetcher_'%1'.=Running_query_'%0'_with_fetcher_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Query_'%0'_with_fetcher_'%1'_did_not_return_any_results. -Move/Rename_file=Move/Rename_file + +Move_file=Move_file +Rename_file=Rename_file + File_moved=File_moved Move_file_failed=Move_file_failed Could_not_move_file_'%0'.=Could_not_move_file_'%0'. diff --git a/src/main/resources/l10n/JabRef_es.properties b/src/main/resources/l10n/JabRef_es.properties index 4b44a5cc7cf..1e8c0d8566a 100644 --- a/src/main/resources/l10n/JabRef_es.properties +++ b/src/main/resources/l10n/JabRef_es.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Están_disponibles_los_siguientes_recuper Could_not_find_fetcher_'%0'=No_se_puede_encontrar_el_recuperador_de_datos_'%0' Running_query_'%0'_with_fetcher_'%1'.=Ejecutando_consulta_'%0'_con_recuperador_'%1' Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=La_consulta_'%0'_con_el_recuperador_¡%1'_no_devolvió_ningún_resultado. -Move/Rename_file=Mover/renombrar_archivo + +Move_file=Mover_archivo +Rename_file=renombrar_archivo + File_moved=Archivo_movido Move_file_failed=Error_al_mover_de_archivos Could_not_move_file_'%0'.=No_se_puede_mover_el_archivo_'%0'. diff --git a/src/main/resources/l10n/JabRef_fa.properties b/src/main/resources/l10n/JabRef_fa.properties index 1cf411b6642..6428b4f4ded 100644 --- a/src/main/resources/l10n/JabRef_fa.properties +++ b/src/main/resources/l10n/JabRef_fa.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:= Could_not_find_fetcher_'%0'= Running_query_'%0'_with_fetcher_'%1'.= Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= -Move/Rename_file= + +Move_file= +Rename_file= + File_moved= Move_file_failed= Could_not_move_file_'%0'.= diff --git a/src/main/resources/l10n/JabRef_fr.properties b/src/main/resources/l10n/JabRef_fr.properties index bb4f3a9f105..8e78d0db290 100644 --- a/src/main/resources/l10n/JabRef_fr.properties +++ b/src/main/resources/l10n/JabRef_fr.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=Les_outils_de_recherche_suivants_sont_dis Could_not_find_fetcher_'%0'=L'outil_de_recherche_'%0'_n'a_pas_pu_être_trouvé Running_query_'%0'_with_fetcher_'%1'.=Execution_de_la_requête_'%0'_avec_l'outil_de_recherche_'%1'. Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Le_requête_'%0'_pour_l'outil_de_recherche_'%1'_n'a_retourné_aucun_résultats. -Move/Rename_file=Déplacer/Renommer_le_fichier + +Move_file=Déplacer_fichier +Rename_file=Renommer_le_fichier + File_moved=Fichier_déplacé Move_file_failed=Echec_du_déplacement_du_fichier Could_not_move_file_'%0'.=Le_fichier_'%0'_n'a_pas_pu_être_déplacé. diff --git a/src/main/resources/l10n/JabRef_ja.properties b/src/main/resources/l10n/JabRef_ja.properties index e6dbe9539b2..d76560fd93e 100644 --- a/src/main/resources/l10n/JabRef_ja.properties +++ b/src/main/resources/l10n/JabRef_ja.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:=以下の取得子が使用できます\: Could_not_find_fetcher_'%0'=取得子「%0」を見つけられませんでした Running_query_'%0'_with_fetcher_'%1'.=取得子「%1」を使用して、クエリ「%0」を実行しています。 Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=取得子「%1」を使用したクエリ「%0」は、結果を何も返しませんでした。 -Move/Rename_file=ファイルの移動・改名 + +Move_file= +Rename_file= + File_moved=ファイルを移動しました Move_file_failed=ファイルの移動に失敗 Could_not_move_file_'%0'.=ファイルを%0移動できませんでした diff --git a/src/main/resources/l10n/JabRef_nl.properties b/src/main/resources/l10n/JabRef_nl.properties index 8760f9b9133..84ab6848b14 100644 --- a/src/main/resources/l10n/JabRef_nl.properties +++ b/src/main/resources/l10n/JabRef_nl.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:= Could_not_find_fetcher_'%0'= Running_query_'%0'_with_fetcher_'%1'.= Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= -Move/Rename_file= + +Move_file= +Rename_file= + File_moved= Move_file_failed= Could_not_move_file_'%0'.= diff --git a/src/main/resources/l10n/JabRef_sv.properties b/src/main/resources/l10n/JabRef_sv.properties index dabffcc623e..04193951d10 100644 --- a/src/main/resources/l10n/JabRef_sv.properties +++ b/src/main/resources/l10n/JabRef_sv.properties @@ -1381,7 +1381,10 @@ The_following_fetchers_are_available\:= Could_not_find_fetcher_'%0'=Kunde_inte_hitta_hämtaren_'%0' Running_query_'%0'_with_fetcher_'%1'.= Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= -Move/Rename_file=Flytta/Döp om fil + +Move_file=Flytta_fil +Rename_file=Döp_om_fil + File_moved=Filen_flyttad Move_file_failed=Gick_inte_att_flytta_fil Could_not_move_file_'%0'.=Kunde_inte_flytta_filen_'%0' From 6f48c8c62e1f24f321286efc2c8c1914ee5fc623 Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Sat, 18 Feb 2017 23:13:47 +0100 Subject: [PATCH 24/27] Add dialog and cahnge localization --- .../org/jabref/gui/externalfiles/MoveFileAction.java | 10 ++++++---- .../org/jabref/gui/externalfiles/RenameFileAction.java | 10 +++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 194aaf53163..ffb4a024eaf 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -40,7 +40,6 @@ public class MoveFileAction extends AbstractAction { private final FileListEditor editor; private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); - public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; this.eEditor = eEditor; @@ -94,11 +93,14 @@ public void actionPerformed(ActionEvent event) { String[] options = {Localization.lang("Move file"), Localization.lang("Cancel")}; - JOptionPane.showOptionDialog(frame, "Move file to " + " ", "Move", + int dialogResult = JOptionPane.showOptionDialog(frame, "Move file to file directory" + fileDir.get(), + "Move", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); - List fieldChanges = moveFiles.cleanup((eEditor.getEntry())); - fieldChanges.stream().findFirst().ifPresent(x -> System.out.println(x.getNewValue())); + if (dialogResult == JOptionPane.YES_OPTION) { + List fieldChanges = moveFiles.cleanup((eEditor.getEntry())); + fieldChanges.stream().findFirst().ifPresent(x -> System.out.println(x.getNewValue())); + } //myCleanUp.cleanup(); /* File newFile = null; diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index 7e4a89164f8..8a7b8936fd3 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -85,11 +85,15 @@ public void actionPerformed(ActionEvent e) { String[] options = {Localization.lang("Rename file"), Localization.lang("Cancel")}; - JOptionPane.showOptionDialog(frame, "Rename file to " + targetFileName, "Rename", + int dialogResult = JOptionPane.showOptionDialog(frame, "Rename file to " + targetFileName, "Rename", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); - List fieldChanges = pdfCleanup.cleanup(eEditor.getEntry()); - fieldChanges.stream().findFirst().ifPresent(System.out::println); + //indicates Rename pressed + if (dialogResult == JOptionPane.YES_OPTION) { + List fieldChanges = pdfCleanup.cleanup(eEditor.getEntry()); + fieldChanges.stream().findFirst().ifPresent(System.out::println); + } + } } From 76884c2c0bd246def8c0f83df5e77702375e3d8d Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Thu, 23 Feb 2017 17:38:24 +0100 Subject: [PATCH 25/27] Finalize code, fix Localization, do some renames Add changelog enty and missing dots in previous entries --- CHANGELOG.md | 13 +- .../gui/externalfiles/MoveFileAction.java | 118 +----------------- .../gui/externalfiles/RenameFileAction.java | 15 +-- .../logic/cleanup/MoveFilesCleanup.java | 12 +- .../logic/cleanup/RenamePdfCleanup.java | 3 - src/main/resources/l10n/JabRef_da.properties | 2 - src/main/resources/l10n/JabRef_de.properties | 2 - src/main/resources/l10n/JabRef_en.properties | 2 - src/main/resources/l10n/JabRef_es.properties | 2 - src/main/resources/l10n/JabRef_fa.properties | 2 - src/main/resources/l10n/JabRef_fr.properties | 2 - src/main/resources/l10n/JabRef_in.properties | 2 - src/main/resources/l10n/JabRef_it.properties | 2 - src/main/resources/l10n/JabRef_ja.properties | 2 - src/main/resources/l10n/JabRef_nl.properties | 2 - src/main/resources/l10n/JabRef_no.properties | 2 - .../resources/l10n/JabRef_pt_BR.properties | 2 - src/main/resources/l10n/JabRef_ru.properties | 2 - src/main/resources/l10n/JabRef_sv.properties | 2 - src/main/resources/l10n/JabRef_tr.properties | 2 - src/main/resources/l10n/JabRef_vi.properties | 2 - src/main/resources/l10n/JabRef_zh.properties | 2 - 22 files changed, 24 insertions(+), 171 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed83bb94f8d..d12bc7b4c9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We integrated support for the [paper recommender system Mr.DLib](http://help.jabref.org/en/EntryEditor#related-articles-tab) in a new tab in the entry editor. - We renamed "database" to "library" to have a real distinction to SQL and NoSQL databases. [#2095](https://github.com/JabRef/jabref/issues/2095) - Removed the apache.commons.collections library +- The `Move linked files to default file directory`-Cleanup operation respects the `File directory pattern` setting +- We separated the `Move file` and `Rename Pdfs` logic and context menu entries in the `General`-Tab for the Field `file` to improve the semantics ### Fixed - We fixed an issue where authors with multiple surnames were not presented correctly in the main table. [#2534](https://github.com/JabRef/jabref/issues/2534) @@ -43,11 +45,12 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - The field `issue` is now always exported to the corresponding `issue` field in MS-Office XML. - We fixed an issue with repeated escaping of the %-sign when running the LaTeXCleanup more than once. [#2451](https://github.com/JabRef/jabref/issues/2451) - We fixed the import of MS-Office XML files, when the `month` field contained an invalid value. - - ArXiV fetcher now checks similarity of entry when using DOI retrieval to avoid false positives [#2575](https://github.com/JabRef/jabref/issues/2575) - - Sciencedirect/Elsevier fetcher is now able to scrape new HTML structure [#2576](https://github.com/JabRef/jabref/issues/2576) - - Fixed the synchronization logic of keywords and special fields and vice versa [#2580](https://github.com/JabRef/jabref/issues/2580) - - + - ArXiV fetcher now checks similarity of entry when using DOI retrieval to avoid false positives. [#2575](https://github.com/JabRef/jabref/issues/2575) + - Sciencedirect/Elsevier fetcher is now able to scrape new HTML structure. [#2576](https://github.com/JabRef/jabref/issues/2576) + - Fixed the synchronization logic of keywords and special fields and vice versa. [#2580](https://github.com/JabRef/jabref/issues/2580) + - We fixed an issue introduced with Version 3.8.2 where executing the `Rename PDFs`-Cleanup operation moved the files to the file directory. [#2526](https://github.com/JabRef/jabref/issues/2526) + - We fixed an issue where the `Move linked files to default file directory`-Cleanup operation did not move the files to the location of the bib-file. [#2454](https://github.com/JabRef/jabref/issues/2454) + - We fixed an issue where executeing `Move file` on a selected file in the `General`-Tab could overwrite an existing file. [#2385](https://github.com/JabRef/jabref/issues/2358) ### Removed diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index ffb4a024eaf..0c39d40cb13 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -22,19 +22,13 @@ import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; -import org.jabref.model.FieldChange; import org.jabref.model.entry.ParsedFileField; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * Action for moving a file that is linked from an entry in JabRef. */ public class MoveFileAction extends AbstractAction { - private static final Log LOGGER = LogFactory.getLog(MoveFileAction.class); - private final JabRefFrame frame; private final EntryEditor eEditor; private final FileListEditor editor; @@ -56,7 +50,6 @@ public void actionPerformed(ActionEvent event) { } FileListEntry entry = editor.getTableModel().getEntry(selected); - // Check if the current file exists: String ln = entry.link; ParsedFileField field = entry.toParsedFileField(); @@ -66,14 +59,13 @@ public void actionPerformed(ActionEvent event) { // TODO: notify that this operation cannot be done on remote links return; } - System.out.println("Parsed file Field " + field); // Get an absolute path representation: List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() .getFileDirectories(prefs.getFileDirectoryPreferences()); Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { - JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), + JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Move file"), JOptionPane.ERROR_MESSAGE); return; } @@ -83,122 +75,22 @@ public void actionPerformed(ActionEvent event) { } if ((file != null) && Files.exists(file)) { - // Ok, we found the file. Now get a new name: - System.out.println("Cleanup of file " + file); - //Problem: All listed files are cleaned up MoveFilesCleanup moveFiles = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), prefs.getLayoutFormatterPreferences(), field); String[] options = {Localization.lang("Move file"), Localization.lang("Cancel")}; - int dialogResult = JOptionPane.showOptionDialog(frame, "Move file to file directory" + fileDir.get(), - "Move", + int dialogResult = JOptionPane.showOptionDialog(frame, + Localization.lang("Move file to file directory?") + " " + fileDir.get(), + Localization.lang("Move file"), JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); if (dialogResult == JOptionPane.YES_OPTION) { - List fieldChanges = moveFiles.cleanup((eEditor.getEntry())); - fieldChanges.stream().findFirst().ifPresent(x -> System.out.println(x.getNewValue())); - } - - //myCleanUp.cleanup(); - /* File newFile = null; - boolean repeat = true; - while (repeat) { - repeat = false; - String chosenFile; - if (toFileDir) { - // Determine which name to suggest: - String suggName = FileUtil - .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(), - Globals.prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN), - Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader)) - .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : ""); - CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"), - Localization.lang("Rename to '%0'", suggName), - Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR)); - int answer; - // Only ask about renaming file if the file doesn't have the proper name already: - if (suggName.equals(file.getName())) { - answer = JOptionPane.showConfirmDialog(frame, Localization.lang("Move file to file directory?"), - MOVE_RENAME, JOptionPane.YES_NO_OPTION); - } else { - answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION); - } - if (answer != JOptionPane.YES_OPTION) { - return; - } - Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected()); - StringBuilder sb = new StringBuilder(dirs.get(found)); - if (!dirs.get(found).endsWith(File.separator)) { - sb.append(File.separator); - } - if (cbm.isSelected()) { - // Rename: - sb.append(suggName); - } else { - // Do not rename: - sb.append(file.getName()); - } - chosenFile = sb.toString(); - } else { - Optional path = new FileDialog(frame, file.getPath()).saveNewFile(); - if (path.isPresent()) { - chosenFile = path.get().toString(); - } else { - return; - } - } - newFile = new File(chosenFile); - + moveFiles.cleanup((eEditor.getEntry())); } - if ((newFile != null) && !newFile.equals(file)) { - try { - boolean success = file.renameTo(newFile); - if (!success) { - success = FileUtil.copyFile(file.toPath(), newFile.toPath(), true); - } - if (success) { - // Remove the original file: - Files.deleteIfExists(file.toPath()); - - // Relativise path, if possible. - String canPath = new File(dirs.get(found)).getCanonicalPath(); - if (newFile.getCanonicalPath().startsWith(canPath)) { - if ((newFile.getCanonicalPath().length() > canPath.length()) - && (newFile.getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) { - - String newLink = newFile.getCanonicalPath().substring(1 + canPath.length()); - editor.getTableModel().setEntry(selected, - new FileListEntry(entry.description, newLink, entry.type)); - } else { - String newLink = newFile.getCanonicalPath().substring(canPath.length()); - editor.getTableModel().setEntry(selected, - new FileListEntry(entry.description, newLink, entry.type)); - } - - } else { - String newLink = newFile.getCanonicalPath(); - editor.getTableModel().setEntry(selected, - new FileListEntry(entry.description, newLink, entry.type)); - } - eEditor.updateField(editor); - frame.output(Localization.lang("File moved")); - } else { - JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME, - JOptionPane.ERROR_MESSAGE); - } - - } catch (SecurityException | IOException ex) { - LOGGER.warn("Could not move file", ex); - JOptionPane.showMessageDialog(frame, - Localization.lang("Could not move file '%0'.", file.getAbsolutePath()) + ex.getMessage(), - MOVE_RENAME, JOptionPane.ERROR_MESSAGE); - } - - }*/ } else { // File doesn't exist, so we can't move it. JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link), diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index 8a7b8936fd3..dee2f891080 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -22,7 +22,6 @@ import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; -import org.jabref.model.FieldChange; import org.jabref.model.entry.ParsedFileField; public class RenameFileAction extends AbstractAction { @@ -48,9 +47,7 @@ public void actionPerformed(ActionEvent e) { } FileListEntry entry = editor.getTableModel().getEntry(selected); - ParsedFileField field = entry.toParsedFileField(); - System.out.println("Parsed file Field " + field); // Check if the current file exists: String ln = entry.link; boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); @@ -63,7 +60,7 @@ public void actionPerformed(ActionEvent e) { Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { - JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), + JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Rename file"), JOptionPane.ERROR_MESSAGE); return; } @@ -73,7 +70,6 @@ public void actionPerformed(ActionEvent e) { } if ((file != null) && Files.exists(file)) { - System.out.println("Cleanup Rename of file " + file); RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), @@ -81,17 +77,16 @@ public void actionPerformed(ActionEvent e) { prefs.getFileDirectoryPreferences(), field); String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry()); - System.out.println("TargetFileName " + targetFileName); String[] options = {Localization.lang("Rename file"), Localization.lang("Cancel")}; - - int dialogResult = JOptionPane.showOptionDialog(frame, "Rename file to " + targetFileName, "Rename", + int dialogResult = JOptionPane.showOptionDialog(frame, + Localization.lang("Rename file to") + " " + targetFileName, + Localization.lang("Rename file"), JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]); //indicates Rename pressed if (dialogResult == JOptionPane.YES_OPTION) { - List fieldChanges = pdfCleanup.cleanup(eEditor.getEntry()); - fieldChanges.stream().findFirst().ifPresent(System.out::println); + pdfCleanup.cleanup(eEditor.getEntry()); } } diff --git a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java index 5649cd3582c..c5a0e1b9ec2 100644 --- a/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/MoveFilesCleanup.java @@ -35,7 +35,7 @@ public class MoveFilesCleanup implements CleanupJob { private final String fileDirPattern; private static final Log LOGGER = LogFactory.getLog(MoveFilesCleanup.class); - private ParsedFileField singleFieldCleanup; + private ParsedFileField singleFileFieldCleanup; public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPattern, FileDirectoryPreferences fileDirectoryPreferences, LayoutFormatterPreferences layoutPrefs) { @@ -50,7 +50,7 @@ public MoveFilesCleanup(BibDatabaseContext databaseContext, String fileDirPatter ParsedFileField field) { this(databaseContext, fileDirPattern, fileDirectoryPreferences, prefs); - this.singleFieldCleanup = field; + this.singleFileFieldCleanup = field; } @Override @@ -73,10 +73,10 @@ public List cleanup(BibEntry entry) { List fileList; List newFileList; - if (singleFieldCleanup != null) { - fileList = Arrays.asList(singleFieldCleanup); - - newFileList = typedEntry.getFiles().stream().filter(x -> !x.equals(singleFieldCleanup)) + if (singleFileFieldCleanup != null) { + fileList = Arrays.asList(singleFileFieldCleanup); + //Add all other except the current selected file + newFileList = typedEntry.getFiles().stream().filter(name -> !name.equals(singleFileFieldCleanup)) .collect(Collectors.toList()); } else { newFileList = new ArrayList<>(); diff --git a/src/main/java/org/jabref/logic/cleanup/RenamePdfCleanup.java b/src/main/java/org/jabref/logic/cleanup/RenamePdfCleanup.java index 70d3b093b51..705bc4419ef 100644 --- a/src/main/java/org/jabref/logic/cleanup/RenamePdfCleanup.java +++ b/src/main/java/org/jabref/logic/cleanup/RenamePdfCleanup.java @@ -163,12 +163,9 @@ public String getTargetFileName(ParsedFileField flEntry, BibEntry entry) { StringBuilder targetFileName = new StringBuilder(FileUtil .createFileNameFromPattern(databaseContext.getDatabase(), entry, fileNamePattern, layoutPrefs) .trim()); - //Add extension to newFilename targetFileName.append('.').append(FileUtil.getFileExtension(realOldFilename).orElse("pdf")); - return targetFileName.toString(); - } public int getUnsuccessfulRenames() { diff --git a/src/main/resources/l10n/JabRef_da.properties b/src/main/resources/l10n/JabRef_da.properties index ce786f81193..97788a7d8d2 100644 --- a/src/main/resources/l10n/JabRef_da.properties +++ b/src/main/resources/l10n/JabRef_da.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Forespørgsel_'%0'_med_ Move_file=Flyt_fil Rename_file=omdøb_fil -File_moved=Fil_flyttet Move_file_failed=Flytning_af_fil_mislykkedes Could_not_move_file_'%0'.=Kunne_ikke_flytte_fil_'%0'. Could_not_find_file_'%0'.=Kunne_ikke_finde_filen_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Vis_søgeresultater_i_et_vindue Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=Flyt_fil_til_filbibliotek? -Rename_to_'%0'=Omdøb_til_'%0' You_have_changed_the_menu_and_label_font_size.=Du_har_ændret_menu-_og_tekst-skriftstørrelsen. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Libraryn_er_beskyttet._Kan_ikke_gemme_før_eksterne_ændringer_er_gennemset. diff --git a/src/main/resources/l10n/JabRef_de.properties b/src/main/resources/l10n/JabRef_de.properties index f0546ff8a9d..0d0eb9e684d 100644 --- a/src/main/resources/l10n/JabRef_de.properties +++ b/src/main/resources/l10n/JabRef_de.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Die_Abfrage_'%0'_mit_de Move_file=Datei_verschoben Rename_file=Datei_umbenennen -File_moved=Datei_verschoben Move_file_failed=Fehler_beim_Verschieben_der_Datei Could_not_move_file_'%0'.=Datei_'%0'_konnte_nicht_verschoben_werden. Could_not_find_file_'%0'.=Datei_'%0'_nicht_gefunden. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Suchergebnisse_in_einem_Fenster_anzeigen Show_global_search_results_in_a_window=Globale_Suchergebnisse_in_einem_Fenster_anzeigen Search_in_all_open_libraries=Suche_in_allen_offenen_Datenbanken Move_file_to_file_directory?=Datei_in_Dateiverzeichnis_verschieben? -Rename_to_'%0'=Umbenennen_in_'%0' You_have_changed_the_menu_and_label_font_size.=Sie_haben_die_Schriftgröße_für_Menüs_und_Label_geändert. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Die_Datenbank_ist_geschützt._Speichern_nicht_möglich,_bis_externe_Änderungen_geprüft_wurden. diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 98980086948..046c754df0d 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Query_'%0'_with_fetcher Move_file=Move_file Rename_file=Rename_file -File_moved=File_moved Move_file_failed=Move_file_failed Could_not_move_file_'%0'.=Could_not_move_file_'%0'. Could_not_find_file_'%0'.=Could_not_find_file_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Show_search_results_in_a_window Show_global_search_results_in_a_window=Show_global_search_results_in_a_window Search_in_all_open_libraries=Search_in_all_open_libraries Move_file_to_file_directory?=Move_file_to_file_directory? -Rename_to_'%0'=Rename_to_'%0' You_have_changed_the_menu_and_label_font_size.=You_have_changed_the_menu_and_label_font_size. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed. diff --git a/src/main/resources/l10n/JabRef_es.properties b/src/main/resources/l10n/JabRef_es.properties index 0bdd33f7938..15bc0dd8bb1 100644 --- a/src/main/resources/l10n/JabRef_es.properties +++ b/src/main/resources/l10n/JabRef_es.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=La_consulta_'%0'_con_el Move_file=Mover_archivo Rename_file=renombrar_archivo -File_moved=Archivo_movido Move_file_failed=Error_al_mover_de_archivos Could_not_move_file_'%0'.=No_se_puede_mover_el_archivo_'%0'. Could_not_find_file_'%0'.=No_se_encuentra_el_archivo_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Mostrar_los_resultados_de_la_búsqueda_en_una_ve Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=¿Mover_archivo_a_la_carpeta_de_archivos? -Rename_to_'%0'=Renombrar_a_'%0' You_have_changed_the_menu_and_label_font_size.=Ha_cambiado_el_tamaño_de_tipo_de_letra_para_el_menu_y_etiqueta. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=La_base_de_datos_está_protegida._No_se_puede_guardar_hasta_que_los_cambios_externos_hayan_sido_revisados. diff --git a/src/main/resources/l10n/JabRef_fa.properties b/src/main/resources/l10n/JabRef_fa.properties index bb9efdcb0ff..b08808a0b2c 100644 --- a/src/main/resources/l10n/JabRef_fa.properties +++ b/src/main/resources/l10n/JabRef_fa.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= Move_file= Rename_file= -File_moved= Move_file_failed= Could_not_move_file_'%0'.= Could_not_find_file_'%0'.= @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window= Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?= -Rename_to_'%0'= You_have_changed_the_menu_and_label_font_size.= Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.= diff --git a/src/main/resources/l10n/JabRef_fr.properties b/src/main/resources/l10n/JabRef_fr.properties index af711cc1c86..496b427a65f 100644 --- a/src/main/resources/l10n/JabRef_fr.properties +++ b/src/main/resources/l10n/JabRef_fr.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Le_requête_'%0'_pour_l Move_file=Déplacer_fichier Rename_file=Renommer_le_fichier -File_moved=Fichier_déplacé Move_file_failed=Echec_du_déplacement_du_fichier Could_not_move_file_'%0'.=Le_fichier_'%0'_n'a_pas_pu_être_déplacé. Could_not_find_file_'%0'.=Le_fichier_'%0'_n'a_pas_pu_être_trouvé. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Afficher_les_résultats_de_recherche_dans_une_fe Show_global_search_results_in_a_window=Afficher_les_résultats_de_recherche_globale_dans_une_fenêtre Search_in_all_open_libraries=Rechercher_sur_tous_les_fichierss_ouverts Move_file_to_file_directory?=Déplacer_le_fichier_vers_le_répertoire_de_fichiers_? -Rename_to_'%0'=Renommer_vers_'%0' You_have_changed_the_menu_and_label_font_size.=Vous_avez_modifié_la_taille_de_police_des_menus_et_des_étiquettes. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Le_fichier_est_protégée._L'enregistrement_ne_peut_être_effectué_tant_que_les_changements_externes_n'auront_pas_été_vérifiés. diff --git a/src/main/resources/l10n/JabRef_in.properties b/src/main/resources/l10n/JabRef_in.properties index b313191f909..3f942296095 100644 --- a/src/main/resources/l10n/JabRef_in.properties +++ b/src/main/resources/l10n/JabRef_in.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Kueri_'%0'_dengan_penga Move_file=Memindah_berkas Rename_file=Menamai_berkas -File_moved=Berkas_dipindah Move_file_failed=Gagal_memindah_berkas Could_not_move_file_'%0'.=Tidak_bisa_meindah_berkas_'%0'. Could_not_find_file_'%0'.=Tidak_bisa_menemukan_berkas_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Tampilkan_hasil_pencarian_di_jendela Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=Pindah_berkas_ke_direktori_berkas? -Rename_to_'%0'=Ganti_nama_menjadi_'%0' You_have_changed_the_menu_and_label_font_size.=Ukuran_huruf_menu_dan_label_sudah_anda_ubah. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Basisdata_dilindungi._Tidak_bisa_disimpan_sebelum_perubahan_eksternal_diperiksa. diff --git a/src/main/resources/l10n/JabRef_it.properties b/src/main/resources/l10n/JabRef_it.properties index 984abd8d60f..bea98d15a6b 100644 --- a/src/main/resources/l10n/JabRef_it.properties +++ b/src/main/resources/l10n/JabRef_it.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=La_query_'%0'_con_l'uti Move_file=Sposta_file Rename_file=Rinomina_il_file -File_moved=File_spostato Move_file_failed=Spostamento_del_file_fallito Could_not_move_file_'%0'.=Impossibile_spostare_il_file_'%0'. Could_not_find_file_'%0'.=Impossibile_trovare_il_file_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Mostra_i_risultati_della_ricerca_in_una_finestra Show_global_search_results_in_a_window=Mostra_i_risultati_della_ricerca_globale_in_una_finestra Search_in_all_open_libraries=Cerca_in_tutti_i_library_aperti Move_file_to_file_directory?=Spostare_i_file_nella_cartella_dei_file_principale? -Rename_to_'%0'=Rinomina_in_'%0' You_have_changed_the_menu_and_label_font_size.=Sono_state_modificate_le_dimensioni_del_carattere_di_menu_ed_etichette. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Il_library_è_protetto._Le_modifiche_esterne_devono_evvere_state_riviste_prima_di_poter_salvare. diff --git a/src/main/resources/l10n/JabRef_ja.properties b/src/main/resources/l10n/JabRef_ja.properties index ecc54182119..d4e2b913fb2 100644 --- a/src/main/resources/l10n/JabRef_ja.properties +++ b/src/main/resources/l10n/JabRef_ja.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=取得子「%1」を使 Move_file= Rename_file= -File_moved=ファイルを移動しました Move_file_failed=ファイルの移動に失敗 Could_not_move_file_'%0'.=ファイルを%0移動できませんでした Could_not_find_file_'%0'.=ファイル「%0」を見つけられませんでした。 @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=検索結果をウィンドウに表示 Show_global_search_results_in_a_window=大域検索の結果をウィンドウに表示 Search_in_all_open_libraries=全データベースを検索 Move_file_to_file_directory?=ファイルをファイルディレクトリに移動しますか? -Rename_to_'%0'=「%0」に改名 You_have_changed_the_menu_and_label_font_size.=メニュートラベルのフォント寸法が変更されました。 Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=データベースは保護されています。外部からの変更を検査しない限り、保存することができません。 diff --git a/src/main/resources/l10n/JabRef_nl.properties b/src/main/resources/l10n/JabRef_nl.properties index 6f6d5335518..28d18f985fc 100644 --- a/src/main/resources/l10n/JabRef_nl.properties +++ b/src/main/resources/l10n/JabRef_nl.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= Move_file= Rename_file= -File_moved= Move_file_failed= Could_not_move_file_'%0'.= Could_not_find_file_'%0'.= @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window= Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?= -Rename_to_'%0'= You_have_changed_the_menu_and_label_font_size.= Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.= diff --git a/src/main/resources/l10n/JabRef_no.properties b/src/main/resources/l10n/JabRef_no.properties index c9532d037d2..6829796cfa4 100644 --- a/src/main/resources/l10n/JabRef_no.properties +++ b/src/main/resources/l10n/JabRef_no.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=S\u00f8ket_'%0'_med_ned Move_file=Flytt_fil Rename_file=endre_navn_p\u00e5_fil -File_moved=Flyttet_fil Move_file_failed=Flytting_av_fil_mislyktes Could_not_move_file_'%0'.=Kunne_ikke_flytte_filen_'%0'. Could_not_find_file_'%0'.=Kunne_ikke_finne_filen_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Vis_s\u00f8keresultatene_i_et_vundu Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=Flytt_filen_til_hovedkatalogen_for_filer? -Rename_to_'%0'=Endre_navn_til_'%0' You_have_changed_the_menu_and_label_font_size.=Du_har_endret_skriftst\u00f8rrelser. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Libraryn_er_beskyttet._Kan_ikke_lagre_f\u00f8r_eksterne_endringer_har_blitt_gjennomg\u00e5tt. diff --git a/src/main/resources/l10n/JabRef_pt_BR.properties b/src/main/resources/l10n/JabRef_pt_BR.properties index d57bc18f308..57f3bdb90e8 100644 --- a/src/main/resources/l10n/JabRef_pt_BR.properties +++ b/src/main/resources/l10n/JabRef_pt_BR.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Consulta_'%0'_com_ferra Move_file=Mover_arquivo Rename_file=Renomear_arquivo -File_moved=Arquivo_movido Move_file_failed=Movimentação_do_arquivo_falhou Could_not_move_file_'%0'.=Não_foi_possível_mover_o_arquivo_'%0'. Could_not_find_file_'%0'.=Não_foi_possível_encontrar_o_arquivo_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Exibir_resultados_de_busca_em_uma_janela Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=Mover_arquivo_para_o_diretório_de_arquivos? -Rename_to_'%0'=Renomear_para_'%0' You_have_changed_the_menu_and_label_font_size.=Você_alterou_o_menu_e_tamanho_de_fonte_dos_rótulos. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=A_base_de_dados_está_protegida._Não_é_possível_salvar_antes_que_mudanças_externas_sejam_revisadas. diff --git a/src/main/resources/l10n/JabRef_ru.properties b/src/main/resources/l10n/JabRef_ru.properties index 5cc2134b4d0..4821b1b4342 100644 --- a/src/main/resources/l10n/JabRef_ru.properties +++ b/src/main/resources/l10n/JabRef_ru.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Не_найдено_р Move_file=Переместить_файл Rename_file=Ппереименовать_файл -File_moved=Файл_перемещен Move_file_failed=Ошибка_перемещения_файла Could_not_move_file_'%0'.=Не_удалось_переместить_файл_'%0'. Could_not_find_file_'%0'.=Не_удалось_найти_файл_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Показать_результаты_в_окн Show_global_search_results_in_a_window= Search_in_all_open_libraries=Поиск_во_всех_открытых_БД Move_file_to_file_directory?=Файл_будет_перемещен_в_каталог_файлов._Продолжить? -Rename_to_'%0'=Переименовать_в_'%0' You_have_changed_the_menu_and_label_font_size.=Кегль_меню_и_надписи_изменен_пользователем. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Защищенная_БД._Невозможно_сохранить_без_просмотра_внешних_изменений. diff --git a/src/main/resources/l10n/JabRef_sv.properties b/src/main/resources/l10n/JabRef_sv.properties index e92886730e3..0b32d130b65 100644 --- a/src/main/resources/l10n/JabRef_sv.properties +++ b/src/main/resources/l10n/JabRef_sv.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.= Move_file=Flytta_fil Rename_file=Döp_om_fil -File_moved=Filen_flyttad Move_file_failed=Gick_inte_att_flytta_fil Could_not_move_file_'%0'.=Kunde_inte_flytta_filen_'%0' Could_not_find_file_'%0'.=Kunde_inte_hitta_filen_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Visa_sökresultaten_i_ett_fönster Show_global_search_results_in_a_window= Search_in_all_open_libraries= Move_file_to_file_directory?=Flytta_fil_till_filmapp? -Rename_to_'%0'=Byt_namn_till_'%0' You_have_changed_the_menu_and_label_font_size.= Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Libraryn_är_skyddad._Kan_inte_spara_innan_externa_ändringar_är_kontrollerade. diff --git a/src/main/resources/l10n/JabRef_tr.properties b/src/main/resources/l10n/JabRef_tr.properties index 1d412ec0f0e..13e091f4374 100644 --- a/src/main/resources/l10n/JabRef_tr.properties +++ b/src/main/resources/l10n/JabRef_tr.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.='%1'_getiricisiyle_'%0' Move_file=Dosya_Taşı_adlandır Rename_file=Yeniden_adlandır -File_moved=Dosya_taşındı Move_file_failed=Dosya_taşıma_başarısız Could_not_move_file_'%0'.='%0'_dosya_taşınamıyor. Could_not_find_file_'%0'.='%0'_dosyası_bulunamadı. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Arama_sonuçlarını_bir_pencerede_göster Show_global_search_results_in_a_window= Search_in_all_open_libraries=Tüm_açık_veri_tabanlarında_ara Move_file_to_file_directory?=Dosya,_dosya_dizinine_taşınsın_mı? -Rename_to_'%0'='%0'_olarak_yeniden_adlandır You_have_changed_the_menu_and_label_font_size.=Menü_ve_etiket_yazıtipi_boyutunu_değiştirdiniz. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=Veritabanı_korunuyor._Harici_değişiklikler_gözden_geçirilene_dek_kaydedemezsiniz. diff --git a/src/main/resources/l10n/JabRef_vi.properties b/src/main/resources/l10n/JabRef_vi.properties index 3c19c0a9894..9203cb74275 100644 --- a/src/main/resources/l10n/JabRef_vi.properties +++ b/src/main/resources/l10n/JabRef_vi.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=Phép_truy_vấn_'%0'_b Move_file=Chuyển_tin Rename_file=Đặt_lại_tên_tập_tin -File_moved=Tập_tin_bị_di_chuyển Move_file_failed=Việc_chuyển_tập_tin_thất_bại Could_not_move_file_'%0'.=Không_thể_chuyển_tập_tin_'%0'. Could_not_find_file_'%0'.=Không_tìm_thấy_tập_tin_'%0'. @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=Hiển_thị_kết_quả_tìm_trong_một_cửa_ Show_global_search_results_in_a_window= Search_in_all_open_libraries=Tìm_kiếm_trong_tất_cả_CSDL_đang_mở Move_file_to_file_directory?=Di_chuyển_tập_tin_vào_thư_mục_tập_tin? -Rename_to_'%0'=Đổi_tên_thành_'%0' You_have_changed_the_menu_and_label_font_size.=Bạn_đã_thay_đổi_menu_và_cỡ_phông_nhãn. Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=CSDL_được_bảo_vệ._Không_thể_lưu_cho_đến_khi_những_thay_đổi_ngoài_được_xem_xét. diff --git a/src/main/resources/l10n/JabRef_zh.properties b/src/main/resources/l10n/JabRef_zh.properties index fb3e3810fbf..99b8db5b7b9 100644 --- a/src/main/resources/l10n/JabRef_zh.properties +++ b/src/main/resources/l10n/JabRef_zh.properties @@ -1386,7 +1386,6 @@ Query_'%0'_with_fetcher_'%1'_did_not_return_any_results.=使用抓取器'%1'请 Move_file=移动_文件 Rename_file=重命名_文件 -File_moved=文件移动完成 Move_file_failed=移动文件失败 Could_not_move_file_'%0'.=无法移动文件_'%0' Could_not_find_file_'%0'.=无法找到文件_'%0'。 @@ -1400,7 +1399,6 @@ Show_search_results_in_a_window=在新窗口中显示查询结果 Show_global_search_results_in_a_window=在窗口中显示全局搜索结果 Search_in_all_open_libraries=在所有打开的数据库中搜索 Move_file_to_file_directory?=移动文件到文件目录? -Rename_to_'%0'=重命名为_'%0' You_have_changed_the_menu_and_label_font_size.=您已经修改了菜单和标签的字号。 Library_is_protected._Cannot_save_until_external_changes_have_been_reviewed.=数据库受保护中,在外部修改未被复查前无法执行保存操作。 From e692aa423ebd6fee599e7ed3a3c822709235a71e Mon Sep 17 00:00:00 2001 From: Siedlerchr Date: Thu, 2 Mar 2017 22:10:27 +0100 Subject: [PATCH 26/27] Fix passing of preferences --- .../jabref/gui/externalfiles/MoveFileAction.java | 12 +++++------- .../jabref/gui/externalfiles/RenameFileAction.java | 14 ++++++-------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 0c39d40cb13..771eed39809 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -17,9 +17,7 @@ import org.jabref.gui.entryeditor.EntryEditor; import org.jabref.gui.fieldeditors.FileListEditor; import org.jabref.gui.filelist.FileListEntry; -import org.jabref.logic.cleanup.CleanupPreferences; import org.jabref.logic.cleanup.MoveFilesCleanup; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.ParsedFileField; @@ -32,7 +30,6 @@ public class MoveFileAction extends AbstractAction { private final JabRefFrame frame; private final EntryEditor eEditor; private final FileListEditor editor; - private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); public MoveFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; @@ -61,9 +58,9 @@ public void actionPerformed(ActionEvent event) { } // Get an absolute path representation: List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFileDirectories(prefs.getFileDirectoryPreferences()); + .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); + .getFirstExistingFileDir(Globals.prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Move file"), JOptionPane.ERROR_MESSAGE); @@ -77,8 +74,9 @@ public void actionPerformed(ActionEvent event) { if ((file != null) && Files.exists(file)) { MoveFilesCleanup moveFiles = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), - prefs.getFileDirPattern(), prefs.getFileDirectoryPreferences(), - prefs.getLayoutFormatterPreferences(), field); + Globals.prefs.getCleanupPreferences(Globals.journalAbbreviationLoader).getFileDirPattern(), + Globals.prefs.getFileDirectoryPreferences(), + Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader), field); String[] options = {Localization.lang("Move file"), Localization.lang("Cancel")}; diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index dee2f891080..5d3ead4d308 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -17,9 +17,7 @@ import org.jabref.gui.entryeditor.EntryEditor; import org.jabref.gui.fieldeditors.FileListEditor; import org.jabref.gui.filelist.FileListEntry; -import org.jabref.logic.cleanup.CleanupPreferences; import org.jabref.logic.cleanup.RenamePdfCleanup; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.ParsedFileField; @@ -29,7 +27,6 @@ public class RenameFileAction extends AbstractAction { private final JabRefFrame frame; private final EntryEditor eEditor; private final FileListEditor editor; - private final CleanupPreferences prefs = Globals.prefs.getCleanupPreferences(new JournalAbbreviationLoader()); public RenameFileAction(JabRefFrame frame, EntryEditor eEditor, FileListEditor editor) { this.frame = frame; @@ -56,9 +53,9 @@ public void actionPerformed(ActionEvent e) { return; } List dirs = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFileDirectories(prefs.getFileDirectoryPreferences()); + .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); Optional fileDir = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFirstExistingFileDir(prefs.getFileDirectoryPreferences()); + .getFirstExistingFileDir(Globals.prefs.getFileDirectoryPreferences()); if (!fileDir.isPresent()) { JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Rename file"), JOptionPane.ERROR_MESSAGE); @@ -72,9 +69,10 @@ public void actionPerformed(ActionEvent e) { if ((file != null) && Files.exists(file)) { RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, - frame.getCurrentBasePanel().getBibDatabaseContext(), prefs.getFileNamePattern(), - prefs.getLayoutFormatterPreferences(), - prefs.getFileDirectoryPreferences(), field); + frame.getCurrentBasePanel().getBibDatabaseContext(), + Globals.prefs.getCleanupPreferences(Globals.journalAbbreviationLoader).getFileDirPattern(), + Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader), + Globals.prefs.getFileDirectoryPreferences(), field); String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry()); From a906a5cbb2d575271b96b64726ddb0a0b84ef874 Mon Sep 17 00:00:00 2001 From: Joerg Lenhard Date: Fri, 3 Mar 2017 16:11:26 +0100 Subject: [PATCH 27/27] Fix changelog and add getters/setters for FileListEntry --- CHANGELOG.md | 4 +- src/main/java/org/jabref/gui/BasePanel.java | 12 ++--- .../org/jabref/gui/desktop/JabRefDesktop.java | 4 +- .../gui/externalfiles/AutoSetLinks.java | 2 +- .../externalfiles/DownloadExternalFile.java | 14 ++--- .../gui/externalfiles/DroppedFileHandler.java | 6 +-- .../gui/externalfiles/MoveFileAction.java | 4 +- .../gui/externalfiles/RenameFileAction.java | 2 +- .../externalfiles/SynchronizeFileField.java | 16 +++--- .../TransferableFileLinkSelection.java | 2 +- .../gui/externalfiles/WriteXMPAction.java | 4 +- .../WriteXMPEntryEditorAction.java | 4 +- .../gui/fieldeditors/FileListEditor.java | 16 +++--- .../jabref/gui/filelist/FileListEntry.java | 52 ++++++++++++++----- .../gui/filelist/FileListEntryEditor.java | 16 +++--- .../gui/filelist/FileListTableModel.java | 12 ++--- .../gui/importer/ImportInspectionDialog.java | 16 +++--- .../maintable/MainTableSelectionListener.java | 18 +++---- .../SpecialMainTableColumnsBuilder.java | 8 +-- .../jabref/gui/search/SearchResultFrame.java | 16 +++--- 20 files changed, 127 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d23eba0e1a..5086f8a23ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,8 +52,8 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - We fixed an issue where the "find unlinked files" functionality threw an error when only one PDF was imported but not assigned to an entry [#2577](https://github.com/JabRef/jabref/issues/2577) - We fixed issue where escaped braces were incorrectly counted when calculating brace balance in a field [#2561](https://github.com/JabRef/jabref/issues/2561) - We fixed an issue introduced with Version 3.8.2 where executing the `Rename PDFs`-cleanup operation moved the files to the file directory. [#2526](https://github.com/JabRef/jabref/issues/2526) - - We fixed an issue where the `Move linked files to default file directory`- leanup operation did not move the files to the location of the bib-file. [#2454](https://github.com/JabRef/jabref/issues/2454) - - We fixed an issue where executeing `Move file` on a selected file in the `general`-tab could overwrite an existing file. [#2385](https://github.com/JabRef/jabref/issues/2358) + - We fixed an issue where the `Move linked files to default file directory`- cleanup operation did not move the files to the location of the bib-file. [#2454](https://github.com/JabRef/jabref/issues/2454) + - We fixed an issue where executing `Move file` on a selected file in the `general`-tab could overwrite an existing file. [#2385](https://github.com/JabRef/jabref/issues/2358) ======= ### Removed diff --git a/src/main/java/org/jabref/gui/BasePanel.java b/src/main/java/org/jabref/gui/BasePanel.java index a163d9c6db1..98af5454904 100644 --- a/src/main/java/org/jabref/gui/BasePanel.java +++ b/src/main/java/org/jabref/gui/BasePanel.java @@ -931,8 +931,8 @@ private void openExternalFile() { return; } FileListEntry flEntry = fileListTableModel.getEntry(0); - ExternalFileMenuItem item = new ExternalFileMenuItem(frame(), entry, "", flEntry.link, - flEntry.type.get().getIcon(), bibDatabaseContext, flEntry.type); + ExternalFileMenuItem item = new ExternalFileMenuItem(frame(), entry, "", flEntry.getLink(), + flEntry.getType().get().getIcon(), bibDatabaseContext, flEntry.getType()); item.openLink(); }); } @@ -2304,9 +2304,9 @@ public void action() { bes.get(0).getField(FieldName.FILE).ifPresent(tm::setContent); for (int i = 0; i < tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); - if (FieldName.URL.equalsIgnoreCase(flEntry.type.get().getName()) - || FieldName.PS.equalsIgnoreCase(flEntry.type.get().getName()) - || FieldName.PDF.equalsIgnoreCase(flEntry.type.get().getName())) { + if (FieldName.URL.equalsIgnoreCase(flEntry.getType().get().getName()) + || FieldName.PS.equalsIgnoreCase(flEntry.getType().get().getName()) + || FieldName.PDF.equalsIgnoreCase(flEntry.getType().get().getName())) { entry = flEntry; break; } @@ -2315,7 +2315,7 @@ public void action() { output(Localization.lang("No URL defined") + '.'); } else { try { - JabRefDesktop.openExternalFileAnyFormat(bibDatabaseContext, entry.link, entry.type); + JabRefDesktop.openExternalFileAnyFormat(bibDatabaseContext, entry.getLink(), entry.getType()); output(Localization.lang("External viewer called") + '.'); } catch (IOException e) { output(Localization.lang("Could not open link")); diff --git a/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java b/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java index ec72db7efd2..c294e4ec23d 100644 --- a/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java +++ b/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java @@ -221,7 +221,7 @@ public static boolean openExternalFileUnknown(JabRefFrame frame, BibEntry entry, // Then find which one we are looking at: for (int i = 0; i < tModel.getRowCount(); i++) { FileListEntry iEntry = tModel.getEntry(i); - if (iEntry.link.equals(link)) { + if (iEntry.getLink().equals(link)) { flEntry = iEntry; break; } @@ -242,7 +242,7 @@ public static boolean openExternalFileUnknown(JabRefFrame frame, BibEntry entry, frame.getCurrentBasePanel().getUndoManager().addEdit(ce); frame.getCurrentBasePanel().markBaseChanged(); // Finally, open the link: - return openExternalFileAnyFormat(databaseContext, flEntry.link, flEntry.type); + return openExternalFileAnyFormat(databaseContext, flEntry.getLink(), flEntry.getType()); } else { // Canceled: frame.output(cancelMessage); diff --git a/src/main/java/org/jabref/gui/externalfiles/AutoSetLinks.java b/src/main/java/org/jabref/gui/externalfiles/AutoSetLinks.java index b6be412860c..a9a003270d7 100644 --- a/src/main/java/org/jabref/gui/externalfiles/AutoSetLinks.java +++ b/src/main/java/org/jabref/gui/externalfiles/AutoSetLinks.java @@ -137,7 +137,7 @@ public void run() { for (int j = 0; j < tableModel.getRowCount(); j++) { FileListEntry existingEntry = tableModel.getEntry(j); //System.out.println("Comp: "+existingEntry.getLink()); - if (new File(existingEntry.link).equals(f)) { + if (new File(existingEntry.getLink()).equals(f)) { alreadyHas = true; foundAny = true; break; diff --git a/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java b/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java index ea2b6ff4d1f..4538636d194 100644 --- a/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java +++ b/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java @@ -164,7 +164,7 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio editor.getProgressBar().setIndeterminate(true); editor.setOkEnabled(false); editor.setExternalConfirm(closeEntry -> { - File f = directory == null ? new File(closeEntry.link) : expandFilename(directory, closeEntry.link); + File f = directory == null ? new File(closeEntry.getLink()) : expandFilename(directory, closeEntry.getLink()); if (f.isDirectory()) { JOptionPane.showMessageDialog(frame, Localization.lang("Target file cannot be a directory."), Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE); @@ -185,8 +185,8 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio } // Editor closed. Go on: if (editor.okPressed()) { - File toFile = directory == null ? new File(fileListEntry.link) : expandFilename(directory, - fileListEntry.link); + File toFile = directory == null ? new File(fileListEntry.getLink()) : expandFilename(directory, + fileListEntry.getLink()); String dirPrefix; if (directory == null) { dirPrefix = null; @@ -206,10 +206,10 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio // If the local file is in or below the main file directory, change the // path to relative: - if ((dirPrefix != null) && fileListEntry.link.startsWith(directory) - && (fileListEntry.link.length() > dirPrefix.length())) { - fileListEntry = new FileListEntry(fileListEntry.description, - fileListEntry.link.substring(dirPrefix.length()), fileListEntry.type); + if ((dirPrefix != null) && fileListEntry.getLink().startsWith(directory) + && (fileListEntry.getLink().length() > dirPrefix.length())) { + fileListEntry = new FileListEntry(fileListEntry.getDescription(), + fileListEntry.getLink().substring(dirPrefix.length()), fileListEntry.getType()); } callback.downloadComplete(fileListEntry); diff --git a/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java b/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java index 55955cb21ed..7f483ab490a 100644 --- a/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java +++ b/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java @@ -436,10 +436,10 @@ private void doLink(BibEntry entry, ExternalFileType fileType, String filename, FileListEntry flEntry = tm.getEntry(i); // Find the absolute filename for this existing link: String absName; - if (new File(flEntry.link).isAbsolute() || dirs.isEmpty()) { - absName = flEntry.link; + if (new File(flEntry.getLink()).isAbsolute() || dirs.isEmpty()) { + absName = flEntry.getLink(); } else { - Optional file = FileUtil.expandFilename(flEntry.link, dirs); + Optional file = FileUtil.expandFilename(flEntry.getLink(), dirs); if (file.isPresent()) { absName = file.get().getAbsolutePath(); } else { diff --git a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java index 771eed39809..57664f23b13 100644 --- a/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/MoveFileAction.java @@ -48,7 +48,7 @@ public void actionPerformed(ActionEvent event) { FileListEntry entry = editor.getTableModel().getEntry(selected); // Check if the current file exists: - String ln = entry.link; + String ln = entry.getLink(); ParsedFileField field = entry.toParsedFileField(); boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); @@ -91,7 +91,7 @@ public void actionPerformed(ActionEvent event) { } else { // File doesn't exist, so we can't move it. - JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link), + JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.getLink()), Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE); } diff --git a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java index 5d3ead4d308..42433dd6723 100644 --- a/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/RenameFileAction.java @@ -46,7 +46,7 @@ public void actionPerformed(ActionEvent e) { FileListEntry entry = editor.getTableModel().getEntry(selected); ParsedFileField field = entry.toParsedFileField(); // Check if the current file exists: - String ln = entry.link; + String ln = entry.getLink(); boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); if (httpLink) { // TODO: notify that this operation cannot be done on remote links diff --git a/src/main/java/org/jabref/gui/externalfiles/SynchronizeFileField.java b/src/main/java/org/jabref/gui/externalfiles/SynchronizeFileField.java index 35c477df91d..95873a491aa 100644 --- a/src/main/java/org/jabref/gui/externalfiles/SynchronizeFileField.java +++ b/src/main/java/org/jabref/gui/externalfiles/SynchronizeFileField.java @@ -150,7 +150,7 @@ public void run() { for (int j = 0; j < tableModel.getRowCount(); j++) { FileListEntry flEntry = tableModel.getEntry(j); // See if the link looks like an URL: - boolean httpLink = flEntry.link.toLowerCase(Locale.ENGLISH).startsWith("http"); + boolean httpLink = flEntry.getLink().toLowerCase(Locale.ENGLISH).startsWith("http"); if (httpLink) { continue; // Don't check the remote file. // TODO: should there be an option to check remote links? @@ -160,7 +160,7 @@ public void run() { boolean deleted = false; // Get an absolute path representation: - Optional file = FileUtil.expandFilename(flEntry.link, dirsS); + Optional file = FileUtil.expandFilename(flEntry.getLink(), dirsS); if ((!file.isPresent()) || !file.get().exists()) { int answer; if (removeAllBroken) { @@ -168,7 +168,7 @@ public void run() { } else { answer = JOptionPane.showOptionDialog(panel.frame(), Localization.lang("Could not find file '%0'
linked from entry '%1'", - flEntry.link, + flEntry.getLink(), aSel.getCiteKeyOptional().orElse(Localization.lang("undefined"))), Localization.lang("Broken link"), JOptionPane.YES_NO_CANCEL_OPTION, @@ -202,15 +202,15 @@ public void run() { } // Unless we deleted this link, see if its file type is recognized: - if (!deleted && flEntry.type.isPresent() - && (flEntry.type.get() instanceof UnknownExternalFileType)) { + if (!deleted && flEntry.getType().isPresent() + && (flEntry.getType().get() instanceof UnknownExternalFileType)) { String[] options = new String[] { - Localization.lang("Define '%0'", flEntry.type.get().getName()), + Localization.lang("Define '%0'", flEntry.getType().get().getName()), Localization.lang("Change file type"), Localization.lang("Cancel")}; String defOption = options[0]; int answer = JOptionPane.showOptionDialog(panel.frame(), Localization.lang("One or more file links are of the type '%0', which is undefined. What do you want to do?", - flEntry.type.get().getName()), + flEntry.getType().get().getName()), Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, defOption ); @@ -218,7 +218,7 @@ public void run() { // User doesn't want to handle this unknown link type. } else if (answer == JOptionPane.YES_OPTION) { // User wants to define the new file type. Show the dialog: - ExternalFileType newType = new ExternalFileType(flEntry.type.get().getName(), "", "", + ExternalFileType newType = new ExternalFileType(flEntry.getType().get().getName(), "", "", "", "new", IconTheme.JabRefIcon.FILE.getSmallIcon()); ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(panel.frame(), newType); editor.setVisible(true); diff --git a/src/main/java/org/jabref/gui/externalfiles/TransferableFileLinkSelection.java b/src/main/java/org/jabref/gui/externalfiles/TransferableFileLinkSelection.java index a36df2723e4..94d05ccb771 100644 --- a/src/main/java/org/jabref/gui/externalfiles/TransferableFileLinkSelection.java +++ b/src/main/java/org/jabref/gui/externalfiles/TransferableFileLinkSelection.java @@ -35,7 +35,7 @@ public TransferableFileLinkSelection(BasePanel panel, List selection) // Find the default directory for this field type, if any: List dirs = panel.getBibDatabaseContext() .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); - FileUtil.expandFilename(tm.getEntry(0).link, dirs).ifPresent(fileList::add); + FileUtil.expandFilename(tm.getEntry(0).getLink(), dirs).ifPresent(fileList::add); } } diff --git a/src/main/java/org/jabref/gui/externalfiles/WriteXMPAction.java b/src/main/java/org/jabref/gui/externalfiles/WriteXMPAction.java index b592af9e9f5..41c8559fcf7 100644 --- a/src/main/java/org/jabref/gui/externalfiles/WriteXMPAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/WriteXMPAction.java @@ -135,8 +135,8 @@ public void run() { entry.getField(FieldName.FILE).ifPresent(tm::setContent); for (int j = 0; j < tm.getRowCount(); j++) { FileListEntry flEntry = tm.getEntry(j); - if ((flEntry.type.isPresent()) && "pdf".equalsIgnoreCase(flEntry.type.get().getName())) { - FileUtil.expandFilename(flEntry.link, dirs).ifPresent(files::add); + if ((flEntry.getType().isPresent()) && "pdf".equalsIgnoreCase(flEntry.getType().get().getName())) { + FileUtil.expandFilename(flEntry.getLink(), dirs).ifPresent(files::add); } } } diff --git a/src/main/java/org/jabref/gui/externalfiles/WriteXMPEntryEditorAction.java b/src/main/java/org/jabref/gui/externalfiles/WriteXMPEntryEditorAction.java index d26fce262c1..c17400a5519 100644 --- a/src/main/java/org/jabref/gui/externalfiles/WriteXMPEntryEditorAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/WriteXMPEntryEditorAction.java @@ -66,8 +66,8 @@ public void actionPerformed(ActionEvent actionEvent) { entry.getField(FieldName.FILE).ifPresent(tm::setContent); for (int j = 0; j < tm.getRowCount(); j++) { FileListEntry flEntry = tm.getEntry(j); - if ((flEntry.type.isPresent()) && "pdf".equalsIgnoreCase(flEntry.type.get().getName())) { - FileUtil.expandFilename(flEntry.link, dirs).ifPresent(files::add); + if ((flEntry.getType().isPresent()) && "pdf".equalsIgnoreCase(flEntry.getType().get().getName())) { + FileUtil.expandFilename(flEntry.getLink(), dirs).ifPresent(files::add); } } } diff --git a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java index a8f61ac375e..e3317403d19 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java +++ b/src/main/java/org/jabref/gui/fieldeditors/FileListEditor.java @@ -184,13 +184,13 @@ public void actionPerformed(ActionEvent actionEvent) { try { String path = ""; // absolute path - if (Paths.get(entry.link).isAbsolute()) { - path = Paths.get(entry.link).toString(); + if (Paths.get(entry.getLink()).isAbsolute()) { + path = Paths.get(entry.getLink()).toString(); } else { // relative to file folder for (String folder : databaseContext .getFileDirectories(Globals.prefs.getFileDirectoryPreferences())) { - Path file = Paths.get(folder, entry.link); + Path file = Paths.get(folder, entry.getLink()); if (Files.exists(file)) { path = file.toString(); break; @@ -230,7 +230,7 @@ public void actionPerformed(ActionEvent actionEvent) { } FileListEntry entry = tableModel.getEntry(row); - Optional file = FileUtil.expandFilename(databaseContext, entry.link, + Optional file = FileUtil.expandFilename(databaseContext, entry.getLink(), Globals.prefs.getFileDirectoryPreferences()); if (file.isPresent()) { @@ -251,7 +251,7 @@ public void actionPerformed(ActionEvent actionEvent) { } catch (IOException ex) { JOptionPane.showMessageDialog(frame, Localization.lang("File permission error"), Localization.lang("Cannot delete file"), JOptionPane.ERROR_MESSAGE); - LOGGER.warn("File permission error while deleting: " + entry.link, ex); + LOGGER.warn("File permission error while deleting: " + entry.getLink(), ex); } } } else { @@ -280,9 +280,9 @@ private void openSelectedFile() { FileListEntry entry = tableModel.getEntry(row); try { Optional type = ExternalFileTypes.getInstance() - .getExternalFileTypeByName(entry.type.get().getName()); - JabRefDesktop.openExternalFileAnyFormat(databaseContext, entry.link, - type.isPresent() ? type : entry.type); + .getExternalFileTypeByName(entry.getType().get().getName()); + JabRefDesktop.openExternalFileAnyFormat(databaseContext, entry.getLink(), + type.isPresent() ? type : entry.getType()); } catch (IOException e) { LOGGER.warn("Cannot open selected file.", e); } diff --git a/src/main/java/org/jabref/gui/filelist/FileListEntry.java b/src/main/java/org/jabref/gui/filelist/FileListEntry.java index a470bbda512..0e3a84a534e 100644 --- a/src/main/java/org/jabref/gui/filelist/FileListEntry.java +++ b/src/main/java/org/jabref/gui/filelist/FileListEntry.java @@ -10,40 +10,66 @@ */ public class FileListEntry { - public String description; - public String link; - public Optional type; + 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.description = Objects.requireNonNull(description); - this.link = Objects.requireNonNull(link); - this.type = Optional.of(Objects.requireNonNull(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.description = Objects.requireNonNull(description); - this.link = Objects.requireNonNull(link); - this.type = Objects.requireNonNull(type); + this.setDescription(Objects.requireNonNull(description)); + this.setLink(Objects.requireNonNull(link)); + this.setType(Objects.requireNonNull(type)); } public String[] getStringArrayRepresentation() { - return new String[] {description, link, getTypeName()}; + return new String[] {getDescription(), getLink(), getTypeName()}; } private String getTypeName() { - return this.type.isPresent() ? this.type.get().getName() : ""; + return this.getType().isPresent() ? this.getType().get().getName() : ""; } @Override public String toString() { - return description + " : " + link + " : " + type.orElse(null); + return getDescription() + " : " + getLink() + " : " + getType().orElse(null); } public ParsedFileField toParsedFileField() { - return new ParsedFileField(description, link, type.isPresent() ? type.get().getName() : ""); + return new ParsedFileField(getDescription(), 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/FileListEntryEditor.java b/src/main/java/org/jabref/gui/filelist/FileListEntryEditor.java index 667a3dd3d89..9062a1b12de 100644 --- a/src/main/java/org/jabref/gui/filelist/FileListEntryEditor.java +++ b/src/main/java/org/jabref/gui/filelist/FileListEntryEditor.java @@ -277,17 +277,17 @@ public boolean isVisible() { } private void setValues(FileListEntry entry) { - description.setText(entry.description); - link.setText(entry.link); + description.setText(entry.getDescription()); + link.setText(entry.getLink()); Collection list = ExternalFileTypes.getInstance().getExternalFileTypeSelection(); types.setModel(new DefaultComboBoxModel<>(list.toArray(new ExternalFileType[list.size()]))); types.setSelectedIndex(-1); // See what is a reasonable selection for the type combobox: - if ((entry.type.isPresent()) && !(entry.type.get() instanceof UnknownExternalFileType)) { - types.setSelectedItem(entry.type.get()); - } else if ((entry.link != null) && (!entry.link.isEmpty())) { + if ((entry.getType().isPresent()) && !(entry.getType().get() instanceof UnknownExternalFileType)) { + types.setSelectedItem(entry.getType().get()); + } else if ((entry.getLink() != null) && (!entry.getLink().isEmpty())) { checkExtension(); } } @@ -325,9 +325,9 @@ private void storeSettings(FileListEntry listEntry) { ExternalFileType type = (ExternalFileType) types.getSelectedItem(); - listEntry.description = descriptionText; - listEntry.type = Optional.ofNullable(type); - listEntry.link = fileLink; + listEntry.setDescription(descriptionText); + listEntry.setType(Optional.ofNullable(type)); + listEntry.setLink(fileLink); } public boolean okPressed() { diff --git a/src/main/java/org/jabref/gui/filelist/FileListTableModel.java b/src/main/java/org/jabref/gui/filelist/FileListTableModel.java index 05ac1d5c5f6..0941da690c0 100644 --- a/src/main/java/org/jabref/gui/filelist/FileListTableModel.java +++ b/src/main/java/org/jabref/gui/filelist/FileListTableModel.java @@ -48,11 +48,11 @@ public Object getValueAt(int rowIndex, int columnIndex) { FileListEntry entry = list.get(rowIndex); switch (columnIndex) { case 0: - return entry.description; + return entry.getDescription(); case 1: - return entry.link; + return entry.getLink(); default: - return entry.type.isPresent() ? entry.type.get().getName() : ""; + return entry.getType().isPresent() ? entry.getType().get().getName() : ""; } } } @@ -155,10 +155,10 @@ private FileListEntry setContent(String val, boolean firstOnly, boolean deduceUn public static JLabel getFirstLabel(String content) { FileListTableModel tm = new FileListTableModel(); FileListEntry entry = tm.setContent(content, true, true); - if ((entry == null) || (!entry.type.isPresent())) { + if ((entry == null) || (!entry.getType().isPresent())) { return null; } - return entry.type.get().getIconLabel(); + return entry.getType().get().getIconLabel(); } private FileListEntry decodeEntry(ParsedFileField entry, boolean deduceUnknownType) { @@ -212,7 +212,7 @@ public String getToolTipHTMLRepresentation() { synchronized (list) { for (FileListEntry entry : list) { - sb.add(String.format("%s (%s)", entry.description, entry.link)); + sb.add(String.format("%s (%s)", entry.getDescription(), entry.getLink())); } } diff --git a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java index 093d433730c..0df6c28c95f 100644 --- a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java +++ b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java @@ -908,8 +908,8 @@ public void mouseClicked(MouseEvent e) { return; } FileListEntry fl = tableModel.getEntry(0); - (new ExternalFileMenuItem(frame, entry, "", fl.link, null, panel.getBibDatabaseContext(), - fl.type)).actionPerformed(null); + (new ExternalFileMenuItem(frame, entry, "", fl.getLink(), null, panel.getBibDatabaseContext(), + fl.getType())).actionPerformed(null); } } else { // Must be URL_COL openExternalLink(FieldName.URL, e); @@ -962,12 +962,12 @@ private void showFileFieldMenu(MouseEvent e) { // If there are one or more links, open the first one: for (int i = 0; i < fileList.getRowCount(); i++) { FileListEntry flEntry = fileList.getEntry(i); - String description = flEntry.description; + String description = flEntry.getDescription(); if ((description == null) || (description.trim().isEmpty())) { - description = flEntry.link; + description = flEntry.getLink(); } - menu.add(new ExternalFileMenuItem(panel.frame(), entry, description, flEntry.link, - flEntry.type.get().getIcon(), panel.getBibDatabaseContext(), flEntry.type)); + menu.add(new ExternalFileMenuItem(panel.frame(), entry, description, flEntry.getLink(), + flEntry.getType().get().getIcon(), panel.getBibDatabaseContext(), flEntry.getType())); count++; } if (count == 0) { @@ -1421,8 +1421,8 @@ public Object getColumnValue(BibEntry entry, int i) { FileListTableModel model = new FileListTableModel(); entry.getField(FieldName.FILE).ifPresent(model::setContent); fileLabel.setToolTipText(model.getToolTipHTMLRepresentation()); - if ((model.getRowCount() > 0) && model.getEntry(0).type.isPresent()) { - fileLabel.setIcon(model.getEntry(0).type.get().getIcon()); + if ((model.getRowCount() > 0) && model.getEntry(0).getType().isPresent()) { + fileLabel.setIcon(model.getEntry(0).getType().get().getIcon()); } return fileLabel; } else { diff --git a/src/main/java/org/jabref/gui/maintable/MainTableSelectionListener.java b/src/main/java/org/jabref/gui/maintable/MainTableSelectionListener.java index 19fcac5c5fa..9f98cff3d99 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableSelectionListener.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableSelectionListener.java @@ -280,7 +280,7 @@ public void mouseClicked(MouseEvent e) { // If there are one or more links of the correct type, open the first one: if (modelColumn.isFileFilter()) { for (int i = 0; i < fileList.getRowCount(); i++) { - if (fileList.getEntry(i).type.toString().equals(modelColumn.getColumnName())) { + if (fileList.getEntry(i).getType().toString().equals(modelColumn.getColumnName())) { flEntry = fileList.getEntry(i); break; } @@ -291,8 +291,8 @@ public void mouseClicked(MouseEvent e) { } if (flEntry != null) { ExternalFileMenuItem item = new ExternalFileMenuItem(panel.frame(), entry, "", - flEntry.link, flEntry.type.map(ExternalFileType::getIcon).orElse(null), - panel.getBibDatabaseContext(), flEntry.type); + flEntry.getLink(), flEntry.getType().map(ExternalFileType::getIcon).orElse(null), + panel.getBibDatabaseContext(), flEntry.getType()); boolean success = item.openLink(); if (!success) { panel.output(Localization.lang("Unable to open link.")); @@ -382,16 +382,16 @@ private void showIconRightClickMenu(MouseEvent e, int row, MainTableColumn colum for (int i = 0; i < fileList.getRowCount(); i++) { FileListEntry flEntry = fileList.getEntry(i); if (column.isFileFilter() - && (!flEntry.type.get().getName().equalsIgnoreCase(column.getColumnName()))) { + && (!flEntry.getType().get().getName().equalsIgnoreCase(column.getColumnName()))) { continue; } - String description = flEntry.description; + String description = flEntry.getDescription(); if ((description == null) || (description.trim().isEmpty())) { - description = flEntry.link; + description = flEntry.getLink(); } - menu.add(new ExternalFileMenuItem(panel.frame(), entry, description, flEntry.link, - flEntry.type.get().getIcon(), panel.getBibDatabaseContext(), - flEntry.type)); + menu.add(new ExternalFileMenuItem(panel.frame(), entry, description, flEntry.getLink(), + flEntry.getType().get().getIcon(), panel.getBibDatabaseContext(), + flEntry.getType())); showDefaultPopup = false; } } else { diff --git a/src/main/java/org/jabref/gui/maintable/SpecialMainTableColumnsBuilder.java b/src/main/java/org/jabref/gui/maintable/SpecialMainTableColumnsBuilder.java index f2d7a24a245..89759212c12 100644 --- a/src/main/java/org/jabref/gui/maintable/SpecialMainTableColumnsBuilder.java +++ b/src/main/java/org/jabref/gui/maintable/SpecialMainTableColumnsBuilder.java @@ -110,7 +110,7 @@ public Object getColumnValue(BibEntry entry) { if (fileList.getRowCount() > 1) { return new JLabel(IconTheme.JabRefIcon.FILE_MULTIPLE.getSmallIcon()); } else if (fileList.getRowCount() == 1) { - Optional type = fileList.getEntry(0).type; + Optional type = fileList.getEntry(0).getType(); if (type.isPresent()) { return type.get().getIconLabel(); } else { @@ -186,13 +186,13 @@ public Object getColumnValue(BibEntry entry) { FileListTableModel fileList = new FileListTableModel(); entry.getField(FieldName.FILE).ifPresent(fileList::setContent); for (int i = 0; i < fileList.getRowCount(); i++) { - if ((fileList.getEntry(i).type.isPresent()) - && externalFileTypeName.equalsIgnoreCase(fileList.getEntry(i).type.get().getName())) { + if ((fileList.getEntry(i).getType().isPresent()) + && externalFileTypeName.equalsIgnoreCase(fileList.getEntry(i).getType().get().getName())) { if (iconFound) { // already found another file of the desired type - show FILE_MULTIPLE Icon return new JLabel(IconTheme.JabRefIcon.FILE_MULTIPLE.getSmallIcon()); } else { - iconLabel = fileList.getEntry(i).type.get().getIconLabel(); + iconLabel = fileList.getEntry(i).getType().get().getIconLabel(); iconFound = true; } } diff --git a/src/main/java/org/jabref/gui/search/SearchResultFrame.java b/src/main/java/org/jabref/gui/search/SearchResultFrame.java index 5ba5e46b038..cd293d9052c 100644 --- a/src/main/java/org/jabref/gui/search/SearchResultFrame.java +++ b/src/main/java/org/jabref/gui/search/SearchResultFrame.java @@ -472,8 +472,8 @@ public void mouseClicked(MouseEvent e) { return; } FileListEntry fl = tableModel.getEntry(0); - (new ExternalFileMenuItem(frame, entry, "", fl.link, null, - p.getBibDatabaseContext(), fl.type)).actionPerformed(null); + (new ExternalFileMenuItem(frame, entry, "", fl.getLink(), null, + p.getBibDatabaseContext(), fl.getType())).actionPerformed(null); } break; case URL_COL: @@ -511,12 +511,12 @@ public void processPopupTrigger(MouseEvent e) { // If there are one or more links, open the first one: for (int i = 0; i < fileList.getRowCount(); i++) { FileListEntry flEntry = fileList.getEntry(i); - String description = flEntry.description; + String description = flEntry.getDescription(); if ((description == null) || (description.trim().isEmpty())) { - description = flEntry.link; + description = flEntry.getLink(); } - menu.add(new ExternalFileMenuItem(p.frame(), entry, description, flEntry.link, - flEntry.type.get().getIcon(), p.getBibDatabaseContext(), flEntry.type)); + menu.add(new ExternalFileMenuItem(p.frame(), entry, description, flEntry.getLink(), + flEntry.getType().get().getIcon(), p.getBibDatabaseContext(), flEntry.getType())); count++; } @@ -586,8 +586,8 @@ public Object getColumnValue(BibEntry entry, int column) { entry.getField(FieldName.FILE).ifPresent(tmpModel::setContent); fileLabel.setToolTipText(tmpModel.getToolTipHTMLRepresentation()); if (tmpModel.getRowCount() > 0) { - if (tmpModel.getEntry(0).type.isPresent()) { - fileLabel.setIcon(tmpModel.getEntry(0).type.get().getIcon()); + if (tmpModel.getEntry(0).getType().isPresent()) { + fileLabel.setIcon(tmpModel.getEntry(0).getType().get().getIcon()); } else { fileLabel.setIcon(IconTheme.JabRefIcon.FILE.getSmallIcon()); }