diff --git a/CHANGELOG.md b/CHANGELOG.md index ba2ce6c48f7a..84775e2390c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,9 +38,15 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `# - Fixed [#1321](https://github.com/JabRef/jabref/issues/1321): LaTeX commands in fields not displayed in the list of references - Fixed [#1639](https://github.com/JabRef/jabref/issues/1639): Google Scholar fetching works again. - Date fields in the BibLatex standard are now always formatted in the correct way, independent of the preferences +- Fixed [#1554](https://github.com/JabRef/jabref/issues/1554): Import dialog is no longer hidden behind main window +- Fixed [#1643](https://github.com/JabRef/jabref/issues/1643): Searching with double quotes in a specific field ignores the last character +- Fixed [#1288](https://github.com/JabRef/jabref/issues/1288): Newly opened bib-file is not focused +- Fixed [#1669](https://github.com/JabRef/jabref/issues/1669): Dialog for manual connection to OpenOffice/LibreOffice works again on Linux + ### Removed - It is not longer possible to choose to convert HTML sub- and superscripts to equations +- [#1610](https://github.com/JabRef/jabref/issues/1610) Removed the possibility to auto show or hide the groups interface @@ -489,4 +495,4 @@ The changelog of 2.11 and versions before is maintained as [text file](https://g [3.1]: https://github.com/JabRef/jabref/compare/v3.0...v3.1 [3.0]: https://github.com/JabRef/jabref/compare/v2.11.1...v3.0 [dev_2.11]: https://github.com/JabRef/jabref/compare/v2.11.1...dev_2.11 -[2.11.1]: https://github.com/JabRef/jabref/compare/v2.11...v2.11.1 \ No newline at end of file +[2.11.1]: https://github.com/JabRef/jabref/compare/v2.11...v2.11.1 diff --git a/build.gradle b/build.gradle index f01b37063531..1f573ff628c4 100644 --- a/build.gradle +++ b/build.gradle @@ -47,7 +47,7 @@ install4j { } task wrapper(type: Wrapper) { - gradleVersion = '2.14' + gradleVersion = '2.14.1' } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 2c6137b87896..d3b83982b9b1 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 21c4484a7c02..f091de1b5c6d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Jun 27 17:21:50 CEST 2016 +#Wed Aug 03 11:49:15 CEST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip diff --git a/gradlew b/gradlew index 9d82f7891513..27309d92314c 100755 --- a/gradlew +++ b/gradlew @@ -6,12 +6,30 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -30,6 +48,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,26 +59,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -85,7 +89,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then diff --git a/gradlew.bat b/gradlew.bat index 5f192121eb4f..832fdb6079b4 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -8,14 +8,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome diff --git a/src/jmh/java/net/sf/jabref/benchmarks/Benchmarks.java b/src/jmh/java/net/sf/jabref/benchmarks/Benchmarks.java index 59bf3e6758d4..2748fe43169d 100644 --- a/src/jmh/java/net/sf/jabref/benchmarks/Benchmarks.java +++ b/src/jmh/java/net/sf/jabref/benchmarks/Benchmarks.java @@ -127,7 +127,7 @@ public boolean keywordGroupContains() throws ParseException { } @Benchmark - public boolean keywordGroupContainsWord() throws ParseException { + public boolean keywordGroupContainsWord() { return KeywordGroup.containsWord("testWord", "Some longer test string containing testWord the test word"); } diff --git a/src/main/java/net/sf/jabref/JabRefGUI.java b/src/main/java/net/sf/jabref/JabRefGUI.java index 49b662487c9e..6a30a5745a1a 100644 --- a/src/main/java/net/sf/jabref/JabRefGUI.java +++ b/src/main/java/net/sf/jabref/JabRefGUI.java @@ -41,7 +41,6 @@ import net.sf.jabref.importer.OpenDatabaseAction; import net.sf.jabref.importer.ParserResult; import net.sf.jabref.logic.l10n.Localization; -import net.sf.jabref.logic.preferences.LastFocusedTabPreferences; import net.sf.jabref.logic.util.OS; import net.sf.jabref.logic.util.Version; import net.sf.jabref.logic.util.VersionPreferences; @@ -58,16 +57,25 @@ public class JabRefGUI { private static JabRefFrame mainFrame; - private final List loaded; + private final List bibDatabases; private final boolean isBlank; - private final List postponed = new ArrayList<>(); private final List failed = new ArrayList<>(); private final List toOpenTab = new ArrayList<>(); - public JabRefGUI(List loaded, boolean isBlank) { - this.loaded = loaded; + private String focusedFile; + + public JabRefGUI(List argsDatabases, boolean isBlank) { + this.bibDatabases = argsDatabases; this.isBlank = isBlank; + + // passed file (we take the first one) should be focused + if (!argsDatabases.isEmpty()) { + focusedFile = argsDatabases.get(0).getFile().getAbsolutePath(); + } else { + focusedFile = Globals.prefs.get(JabRefPreferences.LAST_FOCUSED); + } + openWindow(); JabRefGUI.checkForNewVersion(false); } @@ -102,9 +110,8 @@ private void openWindow() { setLookAndFeel(); // If the option is enabled, open the last edited databases, if any. - if (!isBlank && Globals.prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED) - && (Globals.prefs.get(JabRefPreferences.LAST_EDITED) != null)) { - openLastEditedDatabase(); + if (!isBlank && Globals.prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) { + openLastEditedDatabases(); } GUIGlobals.init(); @@ -114,19 +121,20 @@ private void openWindow() { LOGGER.debug("Initializing frame"); JabRefGUI.mainFrame = new JabRefFrame(); - // Add all loaded databases to the frame: - boolean first = true; - if (!loaded.isEmpty()) { - for (Iterator i = loaded.iterator(); i.hasNext();) { - ParserResult pr = i.next(); + // Add all bibDatabases databases to the frame: + boolean first = false; + if (!bibDatabases.isEmpty()) { + for (Iterator parserResultIterator = bibDatabases.iterator(); parserResultIterator.hasNext();) { + ParserResult pr = parserResultIterator.next(); - if (new LastFocusedTabPreferences(Globals.prefs).hadLastFocus(pr.getFile())) { + // Define focused tab + if (focusedFile != null && pr.getFile().getAbsolutePath().equals(focusedFile)) { first = true; } if (pr.isInvalid()) { failed.add(pr); - i.remove(); + parserResultIterator.remove(); } else if (!pr.isPostponedAutosaveFound()) { if (pr.toOpenTab()) { // things to be appended to an opened tab should be done after opening all tabs @@ -137,7 +145,7 @@ private void openWindow() { first = false; } } else { - i.remove(); + parserResultIterator.remove(); postponed.add(pr.getFile()); } } @@ -177,7 +185,7 @@ private void openWindow() { if (Globals.prefs.getBoolean(JabRefPreferences.DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP)) { int i = 0; - for (ParserResult pr : loaded) { + for (ParserResult pr : bibDatabases) { ParserResultWarningDialog.showParserResultWarningDialog(pr, JabRefGUI.getMainFrame(), i++); } } @@ -189,10 +197,10 @@ private void openWindow() { // in this version of JabRef. // Note that we have to check whether i does not go over getBasePanelCount(). // This is because importToOpen might have been used, which adds to - // loaded, but not to getBasePanelCount() + // loadedDatabases, but not to getBasePanelCount() - for (int i = 0; (i < loaded.size()) && (i < JabRefGUI.getMainFrame().getBasePanelCount()); i++) { - ParserResult pr = loaded.get(i); + for (int i = 0; (i < bibDatabases.size()) && (i < JabRefGUI.getMainFrame().getBasePanelCount()); i++) { + ParserResult pr = bibDatabases.get(i); BasePanel panel = JabRefGUI.getMainFrame().getBasePanelAt(i); OpenDatabaseAction.performPostOpenActions(panel, pr, true); } @@ -206,33 +214,43 @@ private void openWindow() { SwingUtilities.invokeLater(asp); } - if (!loaded.isEmpty()) { + if (!bibDatabases.isEmpty()) { new FocusRequester(JabRefGUI.getMainFrame().getCurrentBasePanel().getMainTable()); } } - private void openLastEditedDatabase() { - // How to handle errors in the databases to open? - List names = Globals.prefs.getStringList(JabRefPreferences.LAST_EDITED); - lastEdLoop: for (String name : names) { - File fileToOpen = new File(name); + private void openLastEditedDatabases() { + if (Globals.prefs.get(JabRefPreferences.LAST_EDITED) == null) { + return; + } + + List lastFiles = Globals.prefs.getStringList(JabRefPreferences.LAST_EDITED); - for (ParserResult pr : loaded) { - if ((pr.getFile() != null) && pr.getFile().equals(fileToOpen)) { - continue lastEdLoop; - } + for (String fileName : lastFiles) { + File dbFile = new File(fileName); + + // Already parsed via command line parameter, e.g., "jabref.jar somefile.bib" + if (isLoaded(dbFile) || !dbFile.exists()) { + continue; } - if (fileToOpen.exists()) { - ParserResult pr = OpenDatabaseAction.loadDatabaseOrAutoSave(name, false); + ParserResult parsedDatabase = OpenDatabaseAction.loadDatabaseOrAutoSave(fileName, false); - if (pr.isNullResult()) { - LOGGER.error(Localization.lang("Error opening file") + " '" + fileToOpen.getPath() + "'"); - } else { - loaded.add(pr); - } + if (parsedDatabase.isNullResult()) { + LOGGER.error(Localization.lang("Error opening file") + " '" + dbFile.getPath() + "'"); + } else { + bibDatabases.add(parsedDatabase); + } + } + } + + private boolean isLoaded(File fileToOpen) { + for (ParserResult pr : bibDatabases) { + if (pr.getFile() != null && pr.getFile().equals(fileToOpen)) { + return true; } } + return false; } private void setLookAndFeel() { diff --git a/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java b/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java index 01fbffd52abb..9549565476a0 100644 --- a/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java +++ b/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java @@ -51,15 +51,13 @@ import org.apache.commons.logging.LogFactory; public class ArgumentProcessor { + private static final Log LOGGER = LogFactory.getLog(ArgumentProcessor.class); public enum Mode { INITIAL_START, REMOTE_START } - - private static final Log LOGGER = LogFactory.getLog(ArgumentProcessor.class); - private final JabRefCLI cli; private final List parserResults; @@ -230,7 +228,7 @@ private void doAuxImport(List loaded) { private List importAndOpenFiles() { List loaded = new ArrayList<>(); List toImport = new ArrayList<>(); - if (!cli.isBlank() && (cli.getLeftOver().length > 0)) { + if (!cli.isBlank() && (!cli.getLeftOver().isEmpty())) { for (String aLeftOver : cli.getLeftOver()) { // Leftover arguments that have a "bib" extension are interpreted as // BIB files to open. Other files, and files that could not be opened diff --git a/src/main/java/net/sf/jabref/cli/JabRefCLI.java b/src/main/java/net/sf/jabref/cli/JabRefCLI.java index ab5a8561d11c..0e21435f835d 100644 --- a/src/main/java/net/sf/jabref/cli/JabRefCLI.java +++ b/src/main/java/net/sf/jabref/cli/JabRefCLI.java @@ -15,6 +15,9 @@ */ package net.sf.jabref.cli; +import java.util.Arrays; +import java.util.List; + import net.sf.jabref.Globals; import net.sf.jabref.logic.exporter.ExportFormats; import net.sf.jabref.logic.l10n.Localization; @@ -32,7 +35,7 @@ public class JabRefCLI { private static final Log LOGGER = LogFactory.getLog(JabRefCLI.class); - private String[] leftOver; + private List leftOver; private final CommandLine cl; @@ -42,7 +45,7 @@ public JabRefCLI(String[] args) { try { this.cl = new DefaultParser().parse(options, args); - this.leftOver = cl.getArgs(); + this.leftOver = Arrays.asList(cl.getArgs()); } catch (ParseException e) { LOGGER.warn("Problem parsing arguments", e); @@ -262,7 +265,7 @@ private String getVersionInfo() { return String.format("JabRef %s", Globals.BUILD_INFO.getVersion()); } - public String[] getLeftOver() { + public List getLeftOver() { return leftOver; } diff --git a/src/main/java/net/sf/jabref/cli/XMPUtilMain.java b/src/main/java/net/sf/jabref/cli/XMPUtilMain.java new file mode 100644 index 000000000000..41520966945d --- /dev/null +++ b/src/main/java/net/sf/jabref/cli/XMPUtilMain.java @@ -0,0 +1,175 @@ +package net.sf.jabref.cli; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import javax.xml.transform.TransformerException; + +import net.sf.jabref.Globals; +import net.sf.jabref.importer.ParserResult; +import net.sf.jabref.importer.fileformat.BibtexParser; +import net.sf.jabref.logic.bibtex.BibEntryWriter; +import net.sf.jabref.logic.bibtex.LatexFieldFormatter; +import net.sf.jabref.logic.bibtex.LatexFieldFormatterPreferences; +import net.sf.jabref.logic.xmp.XMPPreferences; +import net.sf.jabref.logic.xmp.XMPUtil; +import net.sf.jabref.model.database.BibDatabaseMode; +import net.sf.jabref.model.entry.BibEntry; +import net.sf.jabref.preferences.JabRefPreferences; + +import org.apache.jempbox.impl.XMLUtil; +import org.apache.jempbox.xmp.XMPMetadata; + +public class XMPUtilMain { + + /** + * Command-line tool for working with XMP-data. + * + * Read or write XMP-metadata from or to pdf file. + * + * Usage: + *
+ *
Read from PDF and print as bibtex:
+ *
xmpUtil PDF
+ *
Read from PDF and print raw XMP:
+ *
xmpUtil -x PDF
+ *
Write the entry in BIB given by KEY to the PDF:
+ *
xmpUtil KEY BIB PDF
+ *
Write all entries in BIB to the PDF:
+ *
xmpUtil BIB PDF
+ *
+ * + * @param args + * Command line strings passed to utility. + * @throws IOException + * If any of the given files could not be read or written. + * @throws TransformerException + * If the given BibEntry is malformed. + */ + public static void main(String[] args) throws IOException, TransformerException { + + // Don't forget to initialize the preferences + if (Globals.prefs == null) { + Globals.prefs = JabRefPreferences.getInstance(); + } + + XMPPreferences xmpPreferences = XMPPreferences.fromPreferences(Globals.prefs); + + switch (args.length) { + case 0: + usage(); + break; + case 1: + + if (args[0].endsWith(".pdf")) { + // Read from pdf and write as BibTex + List l = XMPUtil.readXMP(new File(args[0]), xmpPreferences); + + BibEntryWriter bibtexEntryWriter = new BibEntryWriter( + new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)), false); + + for (BibEntry entry : l) { + StringWriter sw = new StringWriter(); + bibtexEntryWriter.write(entry, sw, BibDatabaseMode.BIBTEX); + System.out.println(sw.getBuffer()); + } + + } 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); + Collection entries = result.getDatabase().getEntries(); + + if (entries.isEmpty()) { + System.err.println("Could not find BibEntry in " + args[0]); + } else { + System.out.println(XMPUtil.toXMP(entries, result.getDatabase(), xmpPreferences)); + } + } + } else { + usage(); + } + break; + case 2: + if ("-x".equals(args[0]) && args[1].endsWith(".pdf")) { + // Read from pdf and write as BibTex + Optional meta = XMPUtil.readRawXMP(new File(args[1])); + + if (meta.isPresent()) { + XMLUtil.save(meta.get().getXMPDocument(), System.out, StandardCharsets.UTF_8.name()); + } else { + System.err.println("The given pdf does not contain any XMP-metadata."); + } + break; + } + + if (args[0].endsWith(".bib") && args[1].endsWith(".pdf")) { + ParserResult result = BibtexParser.parse(new FileReader(args[0])); + + Collection entries = result.getDatabase().getEntries(); + + if (entries.isEmpty()) { + System.err.println("Could not find BibEntry in " + args[0]); + } else { + XMPUtil.writeXMP(new File(args[1]), entries, result.getDatabase(), false, xmpPreferences); + System.out.println("XMP written."); + } + break; + } + + usage(); + break; + case 3: + if (!args[1].endsWith(".bib") && !args[2].endsWith(".pdf")) { + usage(); + break; + } + + ParserResult result = BibtexParser.parse(new FileReader(args[1])); + + Optional bibEntry = result.getDatabase().getEntryByKey(args[0]); + + if (bibEntry.isPresent()) { + XMPUtil.writeXMP(new File(args[2]), bibEntry.get(), result.getDatabase(), xmpPreferences); + + System.out.println("XMP written."); + } else { + System.err.println("Could not find BibEntry " + args[0] + " in " + args[0]); + } + break; + + default: + usage(); + } + } + + /** + * Print usage information for the command line tool xmpUtil. + * + * @see XMPUtil#main(String[]) + */ + private static void usage() { + System.out.println("Read or write XMP-metadata from or to pdf file."); + System.out.println(""); + System.out.println("Usage:"); + System.out.println("Read from PDF and print as bibtex:"); + System.out.println(" xmpUtil "); + System.out.println("Read from PDF and print raw XMP:"); + System.out.println(" xmpUtil -x "); + System.out + .println("Write the entry in given by to the PDF:"); + System.out.println(" xmpUtil "); + System.out.println("Write all entries in to the PDF:"); + System.out.println(" xmpUtil "); + System.out.println(""); + System.out + .println("To report bugs visit http://jabref.sourceforge.net"); + } + +} diff --git a/src/main/java/net/sf/jabref/collab/FileUpdateMonitor.java b/src/main/java/net/sf/jabref/collab/FileUpdateMonitor.java index 2a6483711929..d5cce41b8c62 100644 --- a/src/main/java/net/sf/jabref/collab/FileUpdateMonitor.java +++ b/src/main/java/net/sf/jabref/collab/FileUpdateMonitor.java @@ -85,12 +85,12 @@ public String addUpdateListener(FileUpdateListener ul, File file) throws IOExcep * force a report to all listeners before the next routine check. */ public boolean hasBeenModified(String handle) { - Object o = entries.get(handle); - if (o == null) { + Entry entry = entries.get(handle); + if (entry == null) { return false; } try { - return ((Entry) o).hasBeenUpdated(); + return entry.hasBeenUpdated(); } catch (IOException ex) { // Thrown if file has been removed. We return false. return false; @@ -105,11 +105,10 @@ public boolean hasBeenModified(String handle) { * @param handle the handle to the correct file. */ public void perturbTimestamp(String handle) { - Object o = entries.get(handle); - if (o == null) { - return; + Entry entry = entries.get(handle); + if (entry != null) { + entry.decreaseTimeStamp(); } - ((Entry) o).decreaseTimeStamp(); } /** @@ -121,9 +120,8 @@ public void removeUpdateListener(String handle) { } public void updateTimeStamp(String key) { - Object o = entries.get(key); - if (o != null) { - Entry entry = (Entry) o; + Entry entry = entries.get(key); + if (entry != null) { entry.updateTimeStamp(); } } @@ -136,11 +134,11 @@ public void updateTimeStamp(String key) { * @return File The temporary file. */ public Path getTempFile(String key) throws IllegalArgumentException { - Object o = entries.get(key); - if (o == null) { + Entry entry = entries.get(key); + if (entry == null) { throw new IllegalArgumentException("Entry not found"); } - return ((Entry) o).getTmpFile(); + return entry.getTmpFile(); } diff --git a/src/main/java/net/sf/jabref/external/DroppedFileHandler.java b/src/main/java/net/sf/jabref/external/DroppedFileHandler.java index b125d4c173ca..0f7061117607 100644 --- a/src/main/java/net/sf/jabref/external/DroppedFileHandler.java +++ b/src/main/java/net/sf/jabref/external/DroppedFileHandler.java @@ -42,6 +42,7 @@ import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.OS; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; @@ -235,7 +236,7 @@ private boolean tryXmpImport(String fileName, ExternalFileType fileType, NamedCo List xmpEntriesInFile; try { - xmpEntriesInFile = XMPUtil.readXMP(fileName, Globals.prefs); + xmpEntriesInFile = XMPUtil.readXMP(fileName, XMPPreferences.fromPreferences(Globals.prefs)); } catch (IOException e) { LOGGER.warn("Problem reading XMP", e); return false; diff --git a/src/main/java/net/sf/jabref/external/ExternalFileTypes.java b/src/main/java/net/sf/jabref/external/ExternalFileTypes.java index 7b2cdb82c1cc..76ec7f5d1d0c 100644 --- a/src/main/java/net/sf/jabref/external/ExternalFileTypes.java +++ b/src/main/java/net/sf/jabref/external/ExternalFileTypes.java @@ -262,7 +262,7 @@ public void setExternalFileTypes(List types) { array[i] = new String[] {type.getName(), FILE_TYPE_REMOVED_FLAG}; i++; } - Globals.prefs.put("externalFileTypes", FileField.encodeStringArray(array)); + Globals.prefs.put(JabRefPreferences.EXTERNAL_FILE_TYPES, FileField.encodeStringArray(array)); } /** diff --git a/src/main/java/net/sf/jabref/external/RegExpFileSearch.java b/src/main/java/net/sf/jabref/external/RegExpFileSearch.java index 37881a8bfe26..2cdfc35a36cd 100644 --- a/src/main/java/net/sf/jabref/external/RegExpFileSearch.java +++ b/src/main/java/net/sf/jabref/external/RegExpFileSearch.java @@ -329,12 +329,9 @@ public static String getFieldAndFormat(String fieldAndFormat, BibEntry entry, Bi return ""; } - String fieldValue = BibDatabase.getResolvedField(beforeColon, entry, database); - // If no field value was found, try to interpret it as a key generator field marker: - if (fieldValue == null) { - fieldValue = LabelPatternUtil.makeLabel(entry, beforeColon); - } + String fieldValue = BibDatabase.getResolvedField(beforeColon, entry, database) + .orElse(LabelPatternUtil.makeLabel(entry, beforeColon)); if (fieldValue == null) { return ""; diff --git a/src/main/java/net/sf/jabref/external/WriteXMPAction.java b/src/main/java/net/sf/jabref/external/WriteXMPAction.java index 87b2692a62db..2e79ea0a84f7 100644 --- a/src/main/java/net/sf/jabref/external/WriteXMPAction.java +++ b/src/main/java/net/sf/jabref/external/WriteXMPAction.java @@ -46,6 +46,7 @@ import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; @@ -159,7 +160,7 @@ public void run() { for (File file : files) { if (file.exists()) { try { - XMPUtil.writeXMP(file, entry, database); + XMPUtil.writeXMP(file, entry, database, XMPPreferences.fromPreferences(Globals.prefs)); optDiag.getProgressArea().append(" " + Localization.lang("OK") + ".\n"); entriesChanged++; } catch (Exception e) { diff --git a/src/main/java/net/sf/jabref/external/WriteXMPEntryEditorAction.java b/src/main/java/net/sf/jabref/external/WriteXMPEntryEditorAction.java index bdb4f8867635..ab55d24f4779 100644 --- a/src/main/java/net/sf/jabref/external/WriteXMPEntryEditorAction.java +++ b/src/main/java/net/sf/jabref/external/WriteXMPEntryEditorAction.java @@ -25,6 +25,7 @@ import javax.swing.Action; import javax.xml.transform.TransformerException; +import net.sf.jabref.Globals; import net.sf.jabref.gui.BasePanel; import net.sf.jabref.gui.FileListEntry; import net.sf.jabref.gui.FileListTableModel; @@ -33,6 +34,7 @@ import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.FieldName; @@ -126,7 +128,8 @@ public void run() { } else { try { - XMPUtil.writeXMP(file, entry, panel.getDatabase()); + XMPUtil.writeXMP(file, entry, panel.getDatabase(), + XMPPreferences.fromPreferences(Globals.prefs)); if (files.size() == 1) { message = Localization.lang("Wrote XMP-metadata"); } diff --git a/src/main/java/net/sf/jabref/gui/DuplicateSearch.java b/src/main/java/net/sf/jabref/gui/DuplicateSearch.java index 7719464e1f74..31204d96a01a 100644 --- a/src/main/java/net/sf/jabref/gui/DuplicateSearch.java +++ b/src/main/java/net/sf/jabref/gui/DuplicateSearch.java @@ -22,6 +22,7 @@ package net.sf.jabref.gui; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.swing.SwingUtilities; @@ -44,7 +45,7 @@ public class DuplicateSearch implements Runnable { private final BasePanel panel; private List bes; - private final List duplicates = new ArrayList<>(); + private final List> duplicates = new ArrayList<>(); public DuplicateSearch(BasePanel bp) { @@ -85,21 +86,21 @@ public void run() { } } else { // duplicates found - BibEntry[] be = duplicates.get(current); + List be = duplicates.get(current); current++; - if (!toRemove.contains(be[0]) && !toRemove.contains(be[1])) { + if (!toRemove.contains(be.get(0)) && !toRemove.contains(be.get(1))) { // Check if they are exact duplicates: boolean askAboutExact = false; - if (DuplicateCheck.compareEntriesStrictly(be[0], be[1]) > 1) { + if (DuplicateCheck.compareEntriesStrictly(be.get(0), be.get(1)) > 1) { if (autoRemoveExactDuplicates) { - toRemove.add(be[1]); + toRemove.add(be.get(1)); duplicateCounter++; continue; } askAboutExact = true; } - DuplicateCallBack cb = new DuplicateCallBack(JabRefGUI.getMainFrame(), be[0], be[1], + DuplicateCallBack cb = new DuplicateCallBack(JabRefGUI.getMainFrame(), be.get(0), be.get(1), askAboutExact ? DuplicateResolverType.DUPLICATE_SEARCH_WITH_EXACT : DuplicateResolverType.DUPLICATE_SEARCH); ((CallBack) Spin.over(cb)).update(); @@ -107,19 +108,18 @@ public void run() { DuplicateResolverResult answer = cb.getSelected(); if ((answer == DuplicateResolverResult.KEEP_LEFT) || (answer == DuplicateResolverResult.AUTOREMOVE_EXACT)) { - toRemove.add(be[1]); + toRemove.add(be.get(1)); if (answer == DuplicateResolverResult.AUTOREMOVE_EXACT) { autoRemoveExactDuplicates = true; // Remember choice } } else if (answer == DuplicateResolverResult.KEEP_RIGHT) { - toRemove.add(be[0]); + toRemove.add(be.get(0)); } else if (answer == DuplicateResolverResult.BREAK) { st.setFinished(); // thread killing current = Integer.MAX_VALUE; duplicateCounter--; // correct counter } else if (answer == DuplicateResolverResult.KEEP_MERGE) { - toRemove.add(be[0]); - toRemove.add(be[1]); + toRemove.addAll(be); toAdd.add(cb.getMergedEntry()); } } @@ -180,7 +180,7 @@ public void run() { // If (suspected) duplicates, add them to the duplicates vector. if (eq) { synchronized (duplicates) { - duplicates.add(new BibEntry[]{first, second}); + duplicates.add(Arrays.asList(first, second)); duplicates.notifyAll(); // send wake up all } } diff --git a/src/main/java/net/sf/jabref/gui/FieldSetComponent.java b/src/main/java/net/sf/jabref/gui/FieldSetComponent.java index d48a565b9694..1586d19dd650 100644 --- a/src/main/java/net/sf/jabref/gui/FieldSetComponent.java +++ b/src/main/java/net/sf/jabref/gui/FieldSetComponent.java @@ -203,11 +203,7 @@ public void selectField(String fieldName) { } public String getFirstSelected() { - Object o = list.getSelectedValue(); - if (o == null) { - return null; - } - return (String) o; + return list.getSelectedValue(); } @Override @@ -375,7 +371,7 @@ public void actionPerformed(ActionEvent e) { */ protected class FieldListFocusListener implements FocusListener { - private JList list; + private final JList list; public FieldListFocusListener(JList list) { this.list = list; diff --git a/src/main/java/net/sf/jabref/gui/GUIGlobals.java b/src/main/java/net/sf/jabref/gui/GUIGlobals.java index 1266eef414f5..de09b5ffd6d7 100644 --- a/src/main/java/net/sf/jabref/gui/GUIGlobals.java +++ b/src/main/java/net/sf/jabref/gui/GUIGlobals.java @@ -72,12 +72,12 @@ public class GUIGlobals { } public static JLabel getTableIcon(String fieldType) { - Object o = GUIGlobals.TABLE_ICONS.get(fieldType); - if (o == null) { + JLabel label = GUIGlobals.TABLE_ICONS.get(fieldType); + if (label == null) { LOGGER.info("Error: no table icon defined for type '" + fieldType + "'."); return null; } else { - return (JLabel) o; + return label; } } diff --git a/src/main/java/net/sf/jabref/gui/ImportInspectionDialog.java b/src/main/java/net/sf/jabref/gui/ImportInspectionDialog.java index bf08306974d4..aefb9a7a3d4e 100644 --- a/src/main/java/net/sf/jabref/gui/ImportInspectionDialog.java +++ b/src/main/java/net/sf/jabref/gui/ImportInspectionDialog.java @@ -196,6 +196,7 @@ public class ImportInspectionDialog extends JDialog implements ImportInspector, * @param panel */ public ImportInspectionDialog(JabRefFrame frame, BasePanel panel, String undoName, boolean newDatabase) { + super(frame); this.frame = frame; this.panel = panel; this.bibDatabaseContext = (panel == null) ? null : panel.getBibDatabaseContext(); @@ -841,13 +842,13 @@ public void actionPerformed(ActionEvent event) { */ private void removeSelectedEntries() { int row = glTable.getSelectedRow(); - List toRemove = new ArrayList<>(); + List toRemove = new ArrayList<>(); toRemove.addAll(selectionModel.getSelected()); entries.getReadWriteLock().writeLock().lock(); try { - for (Object o : toRemove) { - entries.remove(o); + for (BibEntry entry : toRemove) { + entries.remove(entry); } } finally { entries.getReadWriteLock().writeLock().unlock(); diff --git a/src/main/java/net/sf/jabref/gui/JabRefFrame.java b/src/main/java/net/sf/jabref/gui/JabRefFrame.java index 358d0a04a7bb..44e253fc39e2 100644 --- a/src/main/java/net/sf/jabref/gui/JabRefFrame.java +++ b/src/main/java/net/sf/jabref/gui/JabRefFrame.java @@ -37,6 +37,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Objects; +import java.util.Optional; import javax.swing.AbstractAction; import javax.swing.Action; @@ -73,8 +74,6 @@ import net.sf.jabref.Globals; import net.sf.jabref.JabRefExecutorService; import net.sf.jabref.external.ExternalFileTypeEditor; -import net.sf.jabref.external.push.PushToApplicationButton; -import net.sf.jabref.external.push.PushToApplications; import net.sf.jabref.gui.actions.Actions; import net.sf.jabref.gui.actions.AutoLinkFilesAction; import net.sf.jabref.gui.actions.ErrorConsoleAction; @@ -108,6 +107,8 @@ import net.sf.jabref.gui.menus.RightClickMenu; import net.sf.jabref.gui.openoffice.OpenOfficePanel; import net.sf.jabref.gui.preftabs.PreferencesDialog; +import net.sf.jabref.gui.push.PushToApplicationButton; +import net.sf.jabref.gui.push.PushToApplications; import net.sf.jabref.gui.util.FocusRequester; import net.sf.jabref.gui.util.PositionWindow; import net.sf.jabref.gui.worker.MarkEntriesAction; @@ -149,11 +150,10 @@ * The main window of the application. */ public class JabRefFrame extends JFrame implements OutputPrinter { + private static final Log LOGGER = LogFactory.getLog(JabRefFrame.class); // Frame titles. private static final String FRAME_TITLE = "JabRef"; - - private static final Log LOGGER = LogFactory.getLog(JabRefFrame.class); private static final String ELLIPSES = "..."; private final JSplitPane splitPane = new JSplitPane(); @@ -463,6 +463,7 @@ public void actionPerformed(ActionEvent e) { private final AutoLinkFilesAction autoLinkFile = new AutoLinkFilesAction(); private PushToApplicationButton pushExternalButton; + private PushToApplications pushApplications; private GeneralFetcher generalFetcher; @@ -879,7 +880,8 @@ private void initLayout() { setProgressBarVisible(false); - pushExternalButton = new PushToApplicationButton(this, PushToApplications.getApplications()); + pushApplications = new PushToApplications(); + pushExternalButton = new PushToApplicationButton(this, pushApplications.getApplications()); fillMenu(); createToolBar(); getContentPane().setLayout(gbl); @@ -1377,19 +1379,26 @@ public static JMenu subMenu(String name) { return res; } - public void addParserResult(ParserResult pr, boolean raisePanel) { + public void addParserResult(ParserResult pr, boolean focusPanel) { if (pr.toOpenTab()) { // Add the entries to the open tab. BasePanel panel = getCurrentBasePanel(); if (panel == null) { // There is no open tab to add to, so we create a new tab: - addTab(pr.getDatabaseContext(), raisePanel); + addTab(pr.getDatabaseContext(), focusPanel); } else { List entries = new ArrayList<>(pr.getDatabase().getEntries()); addImportedEntries(panel, entries, false); } } else { - addTab(pr.getDatabaseContext(), raisePanel); + // only add tab if DB is not already open + Optional panel = getBasePanelList().stream().filter(p -> p.getBibDatabaseContext().getDatabaseFile().equals(pr.getFile())).findFirst(); + + if (panel.isPresent()) { + tabbedPane.setSelectedComponent(panel.get()); + } else { + addTab(pr.getDatabaseContext(), focusPanel); + } } } @@ -1642,6 +1651,7 @@ public void addTab(BasePanel bp, boolean raisePanel) { public BasePanel addTab(BibDatabaseContext databaseContext, boolean raisePanel) { Objects.requireNonNull(databaseContext); + BasePanel bp = new BasePanel(JabRefFrame.this, databaseContext); addTab(bp, raisePanel); return bp; @@ -2247,4 +2257,8 @@ public void setFetcherToggle(boolean enabled) { public void setPreviewToggle(boolean enabled) { previewToggle.setSelected(enabled); } + + public PushToApplications getPushApplications() { + return pushApplications; + } } diff --git a/src/main/java/net/sf/jabref/gui/SidePaneManager.java b/src/main/java/net/sf/jabref/gui/SidePaneManager.java index 231fc6cc2357..9336a241c5e5 100644 --- a/src/main/java/net/sf/jabref/gui/SidePaneManager.java +++ b/src/main/java/net/sf/jabref/gui/SidePaneManager.java @@ -73,11 +73,11 @@ public synchronized boolean hasComponent(String name) { } public synchronized boolean isComponentVisible(String name) { - Object o = components.get(name); - if (o == null) { + SidePaneComponent sidePaneComponent = components.get(name); + if (sidePaneComponent == null) { return false; } else { - return visible.contains(o); + return visible.contains(sidePaneComponent); } } @@ -90,20 +90,20 @@ public synchronized void toggle(String name) { } public synchronized void show(String name) { - Object o = components.get(name); - if (o == null) { + SidePaneComponent sidePaneComponent = components.get(name); + if (sidePaneComponent == null) { LOGGER.warn("Side pane component '" + name + "' unknown."); } else { - show((SidePaneComponent) o); + show(sidePaneComponent); } } public synchronized void hide(String name) { - Object o = components.get(name); - if (o == null) { + SidePaneComponent sidePaneComponent = components.get(name); + if (sidePaneComponent == null) { LOGGER.warn("Side pane component '" + name + "' unknown."); } else { - hideComponent((SidePaneComponent) o); + hideComponent(sidePaneComponent); } } diff --git a/src/main/java/net/sf/jabref/gui/entryeditor/EntryEditor.java b/src/main/java/net/sf/jabref/gui/entryeditor/EntryEditor.java index 066639c70952..8aa1cd5c2b0a 100644 --- a/src/main/java/net/sf/jabref/gui/entryeditor/EntryEditor.java +++ b/src/main/java/net/sf/jabref/gui/entryeditor/EntryEditor.java @@ -440,7 +440,7 @@ private void setupToolBar() { leftPan.add(closeBut, BorderLayout.NORTH); // Create type-label - TypedBibEntry typedEntry = new TypedBibEntry(entry, Optional.empty(), panel.getBibDatabaseContext().getMode()); + TypedBibEntry typedEntry = new TypedBibEntry(entry, panel.getBibDatabaseContext().getMode()); leftPan.add(new TypeLabel(typedEntry.getTypeForDisplay()), BorderLayout.CENTER); TypeButton typeButton = new TypeButton(); @@ -1355,7 +1355,7 @@ public void actionPerformed(ActionEvent e) { // this updates the table automatically, on close, but not // within the tab - Object oldValue = entry.getCiteKey(); + String oldValue = entry.getCiteKey(); if (oldValue != null) { if (Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) { @@ -1380,7 +1380,7 @@ public void actionPerformed(ActionEvent e) { LabelPatternPreferences.fromPreferences(Globals.prefs)); // Store undo information: - panel.getUndoManager().addEdit(new UndoableKeyChange(panel.getDatabase(), entry, (String) oldValue, entry.getCiteKey())); + panel.getUndoManager().addEdit(new UndoableKeyChange(panel.getDatabase(), entry, oldValue, entry.getCiteKey())); // here we update the field String bibtexKeyData = entry.getCiteKey(); diff --git a/src/main/java/net/sf/jabref/gui/groups/EntryTableTransferHandler.java b/src/main/java/net/sf/jabref/gui/groups/EntryTableTransferHandler.java index 2cb38bfd2606..c8d3d1edf092 100644 --- a/src/main/java/net/sf/jabref/gui/groups/EntryTableTransferHandler.java +++ b/src/main/java/net/sf/jabref/gui/groups/EntryTableTransferHandler.java @@ -315,11 +315,9 @@ private boolean handleDraggedFilenames(String s, final int dropRow) { * @return success status for the operation */ private boolean handleDraggedFiles(List files, final int dropRow) { - final String[] fileNames = new String[files.size()]; - int i = 0; + final List fileNames = new ArrayList<>(); for (File file : files) { - fileNames[i] = file.getAbsolutePath(); - i++; + fileNames.add(file.getAbsolutePath()); } // Try to load BIB files normally, and import the rest into the current // database. diff --git a/src/main/java/net/sf/jabref/gui/groups/GroupSelector.java b/src/main/java/net/sf/jabref/gui/groups/GroupSelector.java index 289a5ae0a946..db25ab211bdf 100644 --- a/src/main/java/net/sf/jabref/gui/groups/GroupSelector.java +++ b/src/main/java/net/sf/jabref/gui/groups/GroupSelector.java @@ -1224,15 +1224,6 @@ public void setActiveBasePanel(BasePanel panel) { setGroups(metaData.getGroups()); } - // auto show/hide groups interface - if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_AUTO_SHOW) && !groupsRoot.isLeaf()) { // groups were defined - frame.getSidePaneManager().show("groups"); - frame.groupToggle.setSelected(true); - } else if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_AUTO_HIDE) && groupsRoot.isLeaf()) { // groups were not defined - frame.getSidePaneManager().hide("groups"); - frame.groupToggle.setSelected(false); - } - synchronized (getTreeLock()) { validateTree(); } diff --git a/src/main/java/net/sf/jabref/gui/help/HelpAction.java b/src/main/java/net/sf/jabref/gui/help/HelpAction.java index 68e3f66e4cab..2e8854e723ca 100644 --- a/src/main/java/net/sf/jabref/gui/help/HelpAction.java +++ b/src/main/java/net/sf/jabref/gui/help/HelpAction.java @@ -31,16 +31,12 @@ import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.preferences.JabRefPreferences; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * This Action keeps a reference to a URL. When activated, it shows the help * Dialog unless it is already visible, and shows the URL in it. */ public class HelpAction extends MnemonicAwareAction { - private static final Log LOGGER = LogFactory.getLog(HelpAction.class); private HelpFile helpPage; diff --git a/src/main/java/net/sf/jabref/gui/maintable/MainTable.java b/src/main/java/net/sf/jabref/gui/maintable/MainTable.java index 98dba92fda21..668ae2619527 100644 --- a/src/main/java/net/sf/jabref/gui/maintable/MainTable.java +++ b/src/main/java/net/sf/jabref/gui/maintable/MainTable.java @@ -510,7 +510,7 @@ private boolean matches(int row, Matcher m) { private boolean isComplete(int row) { try { BibEntry entry = getBibEntry(row); - TypedBibEntry typedEntry = new TypedBibEntry(entry, Optional.of(panel.getDatabase()), panel.getBibDatabaseContext().getMode()); + TypedBibEntry typedEntry = new TypedBibEntry(entry, panel.getBibDatabaseContext()); return typedEntry.hasAllRequiredFields(); } catch (NullPointerException ex) { return true; diff --git a/src/main/java/net/sf/jabref/gui/maintable/MainTableSelectionListener.java b/src/main/java/net/sf/jabref/gui/maintable/MainTableSelectionListener.java index b19f4efc6705..32a1e494b735 100644 --- a/src/main/java/net/sf/jabref/gui/maintable/MainTableSelectionListener.java +++ b/src/main/java/net/sf/jabref/gui/maintable/MainTableSelectionListener.java @@ -121,7 +121,7 @@ public void listChanged(ListEvent e) { return; } EventList selected = e.getSourceList(); - Object newSelected = null; + BibEntry newSelected = null; while (e.next()) { if (e.getType() == ListEvent.INSERT) { if (newSelected == null) { @@ -137,7 +137,7 @@ public void listChanged(ListEvent e) { if (newSelected != null) { // Ok, we have a single new entry that has been selected. Now decide what to do with it: - final BibEntry toShow = (BibEntry) newSelected; + final BibEntry toShow = newSelected; final BasePanelMode mode = panel.getMode(); // What is the panel already showing? if ((mode == BasePanelMode.WILL_SHOW_EDITOR) || (mode == BasePanelMode.SHOWING_EDITOR)) { // An entry is currently being edited. diff --git a/src/main/java/net/sf/jabref/gui/openoffice/OOBibBase.java b/src/main/java/net/sf/jabref/gui/openoffice/OOBibBase.java index 781a16a4cf59..3bed37b5f702 100644 --- a/src/main/java/net/sf/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/net/sf/jabref/gui/openoffice/OOBibBase.java @@ -54,6 +54,7 @@ import net.sf.jabref.logic.openoffice.OOBibStyle; import net.sf.jabref.logic.openoffice.OOPreFormatter; import net.sf.jabref.logic.openoffice.OOUtil; +import net.sf.jabref.logic.openoffice.UndefinedBibtexEntry; import net.sf.jabref.logic.openoffice.UndefinedParagraphFormatException; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; @@ -191,17 +192,17 @@ public Optional getCurrentDocumentTitle() { public void selectDocument() throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException, NoSuchElementException, NoDocumentException { - List ls = getTextDocuments(); + List textDocumentList = getTextDocuments(); XTextDocument selected; - if (ls.isEmpty()) { + if (textDocumentList.isEmpty()) { // No text documents found. throw new NoDocumentException("No Writer documents found"); - } else if (ls.size() == 1) { + } else if (textDocumentList.size() == 1) { // Get the only one - selected = ls.get(0); + selected = textDocumentList.get(0); } else { // Bring up a dialog - selected = selectComponent(ls); + selected = selectComponent(textDocumentList); } if (selected == null) { @@ -229,8 +230,8 @@ public void selectDocument() throws UnknownPropertyException, WrappedTargetExcep } private XDesktop simpleBootstrap(String pathToExecutable) - throws IOException, IllegalAccessException, InvocationTargetException, BootstrapException, - CreationException { + throws IllegalAccessException, InvocationTargetException, BootstrapException, + CreationException, IOException { ClassLoader loader = ClassLoader.getSystemClassLoader(); if (loader instanceof URLClassLoader) { @@ -262,29 +263,29 @@ private XDesktop simpleBootstrap(String pathToExecutable) } catch (Exception e) { throw new CreationException(e.getMessage()); } - XDesktop xD = UnoRuntime.queryInterface(XDesktop.class, desktop); + XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); UnoRuntime.queryInterface(XComponentLoader.class, desktop); - return xD; + return xDesktop; } private List getTextDocuments() throws NoSuchElementException, WrappedTargetException { - List res = new ArrayList<>(); - XEnumerationAccess enumA = xDesktop.getComponents(); - XEnumeration e = enumA.createEnumeration(); + List result = new ArrayList<>(); + XEnumerationAccess enumAccess = xDesktop.getComponents(); + XEnumeration componentEnumeration = enumAccess.createEnumeration(); // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies - while (e.hasMoreElements()) { - Object o = e.nextElement(); - XComponent comp = UnoRuntime.queryInterface(XComponent.class, o); - XTextDocument doc = UnoRuntime.queryInterface(XTextDocument.class, comp); - if (doc != null) { - res.add(doc); + while (componentEnumeration.hasMoreElements()) { + Object nextElement = componentEnumeration.nextElement(); + XComponent component = UnoRuntime.queryInterface(XComponent.class, nextElement); + XTextDocument document = UnoRuntime.queryInterface(XTextDocument.class, component); + if (document != null) { + result.add(document); } } - return res; + return result; } public void setCustomProperty(String property, String value) throws UnknownPropertyException, @@ -306,9 +307,7 @@ public Optional getCustomProperty(String property) throws UnknownPropert } public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException { - XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - XNameAccess nameAccess = supplier.getReferenceMarks(); - sortedReferenceMarks = getSortedReferenceMarks(nameAccess); + sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } /** @@ -444,35 +443,31 @@ public List refreshCiteMarkers(List databases, OOBibStyle s } } - public XNameAccess getReferenceMarks() { - XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - return supplier.getReferenceMarks(); - } public List getJabRefReferenceMarks(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); // Remove all reference marks that don't look like JabRef citations: - List res = new ArrayList<>(); + List result = new ArrayList<>(); if (names != null) { for (String name : names) { if (CITE_PATTERN.matcher(name).find()) { - res.add(name); + result.add(name); } } } - return res; + return result; } private List refreshCiteMarkersInternal(List databases, OOBibStyle style) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, BibEntryNotFoundException { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); Map entries = findCitedEntries(databases, cited, linkSourceBase); - XNameAccess nameAccess = getReferenceMarks(); + XNameAccess xReferenceMarks = getReferenceMarks(); List names; if (style.isSortByPosition()) { @@ -491,7 +486,7 @@ private List refreshCiteMarkersInternal(List databases, OOB for (BibEntry entry : entries.keySet()) { cited.add(entry.getCiteKey()); } - names = Arrays.asList(nameAccess.getElementNames()); + names = Arrays.asList(xReferenceMarks.getElementNames()); } else { names = sortedReferenceMarks; } @@ -516,12 +511,12 @@ private List refreshCiteMarkersInternal(List databases, OOB int[] types = new int[names.size()]; for (int i = 0; i < names.size(); i++) { - Matcher m = CITE_PATTERN.matcher(names.get(i)); - if (m.find()) { - String typeStr = m.group(1); + Matcher citeMatcher = CITE_PATTERN.matcher(names.get(i)); + if (citeMatcher.find()) { + String typeStr = citeMatcher.group(1); int type = Integer.parseInt(typeStr); types[i] = type; // Remember the type in case we need to uniquefy. - String[] keys = m.group(2).split(","); + String[] keys = citeMatcher.group(2).split(","); bibtexKeys[i] = keys; BibEntry[] cEntries = new BibEntry[keys.length]; for (int j = 0; j < cEntries.length; j++) { @@ -722,10 +717,10 @@ private List refreshCiteMarkersInternal(List databases, OOB // Check if we are supposed to set a character format for citations: boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < names.size(); i++) { - Object o = nameAccess.getByName(names.get(i)); - XTextContent bm = UnoRuntime.queryInterface(XTextContent.class, o); + Object referenceMark = xReferenceMarks.getByName(names.get(i)); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); - XTextCursor cursor = bm.getAnchor().getText().createTextCursorByRange(bm.getAnchor()); + XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); if (mustTestCharFormat) { // If we are supposed to set character format for citations, must run a test before we @@ -743,7 +738,7 @@ private List refreshCiteMarkersInternal(List databases, OOB } } - text.removeTextContent(bm); + text.removeTextContent(bookmark); insertReferenceMark(names.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, style); if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { @@ -769,25 +764,25 @@ private List refreshCiteMarkersInternal(List databases, OOB private List getSortedReferenceMarks(final XNameAccess nameAccess) throws WrappedTargetException, NoSuchElementException { - XTextViewCursorSupplier css = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, + XTextViewCursorSupplier cursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, mxDoc.getCurrentController()); - XTextViewCursor tvc = css.getViewCursor(); - XTextRange initialPos = tvc.getStart(); + XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); + XTextRange initialPos = viewCursor.getStart(); List names = Arrays.asList(nameAccess.getElementNames()); List positions = new ArrayList<>(names.size()); for (String name : names) { - XTextContent tc = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(name)); - XTextRange r = tc.getAnchor(); + XTextContent textContent = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(name)); + XTextRange range = textContent.getAnchor(); // Check if we are inside a footnote: - if (UnoRuntime.queryInterface(XFootnote.class, r.getText()) != null) { + if (UnoRuntime.queryInterface(XFootnote.class, range.getText()) != null) { // Find the linking footnote marker: - XFootnote footer = UnoRuntime.queryInterface(XFootnote.class, r.getText()); + XFootnote footer = UnoRuntime.queryInterface(XFootnote.class, range.getText()); // The footnote's anchor gives the correct position in the text: - r = footer.getAnchor(); + range = footer.getAnchor(); } - positions.add(findPosition(tvc, r)); + positions.add(findPosition(viewCursor, range)); } Set set = new TreeSet<>(); for (int i = 0; i < positions.size(); i++) { @@ -798,13 +793,13 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) for (ComparableMark mark : set) { result.add(mark.getName()); } - tvc.gotoRange(initialPos, false); + viewCursor.gotoRange(initialPos, false); return result; } public void rebuildBibTextSection(List databases, OOBibStyle style) - throws IOException, NoSuchElementException, WrappedTargetException, IllegalArgumentException, + throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, CreationException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); @@ -827,9 +822,13 @@ public void rebuildBibTextSection(List databases, OOBibStyle style) populateBibTextSection(entries, style); } - private String getUniqueReferenceMarkName(String bibtexKey, int type) { + public XNameAccess getReferenceMarks() { XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - XNameAccess xNamedRefMarks = supplier.getReferenceMarks(); + return supplier.getReferenceMarks(); + } + + private String getUniqueReferenceMarkName(String bibtexKey, int type) { + XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; String name = OOBibBase.BIB_CITATION + '_' + type + '_' + bibtexKey; while (xNamedRefMarks.hasByName(name)) { @@ -862,9 +861,7 @@ private Map findCitedEntries(List databases, } private List findCitedKeys() throws NoSuchElementException, WrappedTargetException { - - XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - XNameAccess xNamedMarks = supplier.getReferenceMarks(); + XNameAccess xNamedMarks = getReferenceMarks(); String[] names = xNamedMarks.getElementNames(); List keys = new ArrayList<>(); for (String name1 : names) { @@ -887,9 +884,9 @@ private Map getSortedEntriesFromSortedRefMarks(List newList = new LinkedHashMap<>(); for (String name : names) { - Matcher m = CITE_PATTERN.matcher(name); - if (m.find()) { - String[] keys = m.group(2).split(","); + Matcher citeMatcher = CITE_PATTERN.matcher(name); + if (citeMatcher.find()) { + String[] keys = citeMatcher.group(2).split(","); for (String key : keys) { BibDatabase database = linkSourceBase.get(key); Optional origEntry = Optional.empty(); @@ -924,9 +921,9 @@ private Point findPosition(XTextViewCursor cursor, XTextRange range) { */ public List parseRefMarkName(String name) { List keys = new ArrayList<>(); - Matcher m = CITE_PATTERN.matcher(name); - if (m.find()) { - String[] keystring = m.group(2).split(","); + Matcher citeMatcher = CITE_PATTERN.matcher(name); + if (citeMatcher.find()) { + String[] keystring = citeMatcher.group(2).split(","); for (String aKeystring : keystring) { if (!keys.contains(aKeystring)) { keys.add(aKeystring); @@ -946,15 +943,15 @@ public List parseRefMarkName(String name) { */ private List findCitedEntryIndex(String citRefName, List keys) { - Matcher m = CITE_PATTERN.matcher(citRefName); - if (m.find()) { - List keyStrings = Arrays.asList(m.group(2).split(",")); - List res = new ArrayList<>(keyStrings.size()); + Matcher citeMatcher = CITE_PATTERN.matcher(citRefName); + if (citeMatcher.find()) { + List keyStrings = Arrays.asList(citeMatcher.group(2).split(",")); + List result = new ArrayList<>(keyStrings.size()); for (String key : keyStrings) { int ind = keys.indexOf(key); - res.add(ind == -1 ? -1 : 1 + ind); + result.add(ind == -1 ? -1 : 1 + ind); } - return res; + return result; } else { return Collections.emptyList(); } @@ -962,10 +959,10 @@ private List findCitedEntryIndex(String citRefName, List keys) public String getCitationContext(XNameAccess nameAccess, String refMarkName, int charBefore, int charAfter, boolean htmlMarkup) throws NoSuchElementException, WrappedTargetException { - Object o = nameAccess.getByName(refMarkName); - XTextContent bm = UnoRuntime.queryInterface(XTextContent.class, o); + Object referenceMark = nameAccess.getByName(refMarkName); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); - XTextCursor cursor = bm.getAnchor().getText().createTextCursorByRange(bm.getAnchor()); + XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); String citPart = cursor.getString(); int flex = 8; for (int i = 0; i < charBefore; i++) { @@ -1037,7 +1034,7 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style) - throws IOException, NoSuchElementException, WrappedTargetException, PropertyVetoException, + throws NoSuchElementException, WrappedTargetException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { - XTextSectionsSupplier supp = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc); - XTextSection section = (XTextSection) ((Any) supp.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) + XTextSectionsSupplier supplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc); + XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) .getObject(); XTextCursor cursor = text.createTextCursorByRange(section.getAnchor()); OOUtil.insertTextAtCurrentLocation(text, cursor, (String) style.getProperty(OOBibStyle.TITLE), @@ -1112,7 +1109,7 @@ private XTextContent insertBookMark(String name, XTextCursor position) } private void insertReferenceMark(String name, String citationText, XTextCursor position, boolean withText, - OOBibStyle style) throws IOException, UnknownPropertyException, WrappedTargetException, + OOBibStyle style) throws UnknownPropertyException, WrappedTargetException, PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException { // Check if there is "page info" stored for this citation. If so, insert it into @@ -1175,8 +1172,8 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { - XTextRange rng = position.getStart(); - XTextCursor cursor = position.getText().createTextCursorByRange(rng); + XTextRange range = position.getStart(); + XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); XPropertySet xcp = UnoRuntime.queryInterface(XPropertySet.class, cursor); @@ -1188,11 +1185,11 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, } private void removeReferenceMark(String name) throws NoSuchElementException, WrappedTargetException { - XReferenceMarksSupplier xSupplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - if (xSupplier.getReferenceMarks().hasByName(name)) { - Object o = xSupplier.getReferenceMarks().getByName(name); - XTextContent bm = UnoRuntime.queryInterface(XTextContent.class, o); - text.removeTextContent(bm); + XNameAccess xReferenceMarks = getReferenceMarks(); + if (xReferenceMarks.hasByName(name)) { + Object referenceMark = xReferenceMarks.getByName(name); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + text.removeTextContent(bookmark); } } @@ -1204,9 +1201,7 @@ private void removeReferenceMark(String name) throws NoSuchElementException, Wra * @throws NoSuchElementException */ private XTextRange getBookmarkRange(String name) throws NoSuchElementException, WrappedTargetException { - // query XBookmarksSupplier from document model and get bookmarks collection - XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xCurrentComponent); - XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + XNameAccess xNamedBookmarks = getBookmarks(); // retrieve bookmark by name if (!xNamedBookmarks.hasByName(name)) { @@ -1217,12 +1212,18 @@ private XTextRange getBookmarkRange(String name) throws NoSuchElementException, return xFoundBookmark.getAnchor(); } + private XNameAccess getBookmarks() { + // query XBookmarksSupplier from document model and get bookmarks collection + XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xCurrentComponent); + XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + return xNamedBookmarks; + } + public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, BibEntryNotFoundException { - XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); - XNameAccess nameAccess = supplier.getReferenceMarks(); + XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); @@ -1231,19 +1232,18 @@ public void combineCiteMarkers(List databases, OOBibStyle style) int piv = 0; boolean madeModifications = false; while (piv < (names.size() - 1)) { - XTextRange r1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) - .getAnchor() - .getEnd(); - XTextRange r2 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) + XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) + .getAnchor().getEnd(); + XTextRange range2 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) .getAnchor().getStart(); - if (r1.getText() != r2.getText()) { + if (range1.getText() != range2.getText()) { piv++; continue; } - XTextCursor mxDocCursor = r1.getText().createTextCursorByRange(r1); + XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); mxDocCursor.goRight((short) 1, true); boolean couldExpand = true; - while (couldExpand && (compare.compareRegionEnds(mxDocCursor, r2) > 0)) { + while (couldExpand && (compare.compareRegionEnds(mxDocCursor, range2) > 0)) { couldExpand = mxDocCursor.goRight((short) 1, true); } String cursorText = mxDocCursor.getString(); diff --git a/src/main/java/net/sf/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/net/sf/jabref/gui/openoffice/OpenOfficePanel.java index d56a426aacaa..4fd6a89fc806 100644 --- a/src/main/java/net/sf/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/net/sf/jabref/gui/openoffice/OpenOfficePanel.java @@ -16,6 +16,7 @@ package net.sf.jabref.gui.openoffice; import java.awt.BorderLayout; +import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -106,7 +107,7 @@ public class OpenOfficePanel extends AbstractWorker { private final JButton update; private final JButton merge = new JButton(Localization.lang("Merge citations")); private final JButton manageCitations = new JButton(Localization.lang("Manage citations")); - private final JButton exportCitations = new JButton(Localization.lang("Generate new BIB database")); + private final JButton exportCitations = new JButton(Localization.lang("Export cited")); private final JButton settingsB = new JButton(Localization.lang("Settings")); private final JButton help = new HelpAction(Localization.lang("OpenOffice/LibreOffice integration"), HelpFile.OPENOFFICE_LIBREOFFICE).getHelpButton(); @@ -132,10 +133,15 @@ private OpenOfficePanel() { manualConnect = new JButton(connectImage); connect.setToolTipText(Localization.lang("Connect")); manualConnect.setToolTipText(Localization.lang("Manual connect")); + connect.setPreferredSize(new Dimension(24, 24)); + manualConnect.setPreferredSize(new Dimension(24, 24)); + selectDocument = new JButton(IconTheme.JabRefIcon.OPEN.getSmallIcon()); selectDocument.setToolTipText(Localization.lang("Select Writer document")); + selectDocument.setPreferredSize(new Dimension(24, 24)); update = new JButton(IconTheme.JabRefIcon.REFRESH.getSmallIcon()); update.setToolTipText(Localization.lang("Sync OpenOffice/LibreOffice bibliography")); + update.setPreferredSize(new Dimension(24, 24)); preferences = new OpenOfficePreferences(Globals.prefs); loader = new StyleLoader(preferences, LayoutFormatterPreferences.fromPreferences(Globals.prefs, Globals.journalAbbreviationLoader), @@ -311,8 +317,9 @@ public void actionPerformed(ActionEvent e) { .layout(new FormLayout("fill:pref:grow", "p,p,p,p,p,p,p,p,p,p,p")); FormBuilder topRowBuilder = FormBuilder.create() - .layout(new FormLayout("fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref:grow, " - + "1dlu, fill:pref:grow, 1dlu, fill:pref:grow", "pref")); + .layout(new FormLayout( + "fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref", + "pref")); topRowBuilder.add(connect).xy(1, 1); topRowBuilder.add(manualConnect).xy(3, 1); topRowBuilder.add(selectDocument).xy(5, 1); @@ -403,11 +410,11 @@ private void connect(boolean auto) { autoDetected = true; dialogOkPressed = true; diag.dispose(); - } else if (!adp.canceled()) { + } else if (adp.canceled()) { + frame.setStatus(Localization.lang("Operation canceled.")); + } else { JOptionPane.showMessageDialog(diag, Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), JOptionPane.ERROR_MESSAGE); - } else { - frame.setStatus(Localization.lang("Operation canceled.")); } if (!autoDetected) { return; @@ -564,7 +571,7 @@ private void showConnectDialog() { builder.add(ooExec).xy(3, 1); builder.add(browseOOExec).xy(5, 1); - builder.appendColumns("4dlu, pref"); + builder.appendRows("4dlu, pref"); builder.add(Localization.lang("Path to OpenOffice/LibreOffice library dir")).xy(1, 3); builder.add(ooJars).xy(3, 3); builder.add(browseOOJars).xy(5, 3); diff --git a/src/main/java/net/sf/jabref/gui/preftabs/ExternalTab.java b/src/main/java/net/sf/jabref/gui/preftabs/ExternalTab.java index f3af975ad094..bb5c0d30cfb7 100644 --- a/src/main/java/net/sf/jabref/gui/preftabs/ExternalTab.java +++ b/src/main/java/net/sf/jabref/gui/preftabs/ExternalTab.java @@ -33,10 +33,9 @@ import net.sf.jabref.Globals; import net.sf.jabref.external.ExternalFileTypeEditor; -import net.sf.jabref.external.push.PushToApplication; -import net.sf.jabref.external.push.PushToApplicationButton; -import net.sf.jabref.external.push.PushToApplications; import net.sf.jabref.gui.JabRefFrame; +import net.sf.jabref.gui.push.PushToApplication; +import net.sf.jabref.gui.push.PushToApplicationButton; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.preferences.JabRefPreferences; @@ -130,7 +129,7 @@ public ExternalTab(JabRefFrame frame, PreferencesDialog prefsDiag, JabRefPrefere JPanel butpan = new JPanel(); butpan.setLayout(new GridLayout(3, 3)); - for(PushToApplication pushToApplication : PushToApplications.getApplications()) { + for (PushToApplication pushToApplication : frame.getPushApplications().getApplications()) { addSettingsButton(pushToApplication, butpan); } builder.append(new JPanel()); diff --git a/src/main/java/net/sf/jabref/gui/preftabs/GroupsPrefsTab.java b/src/main/java/net/sf/jabref/gui/preftabs/GroupsPrefsTab.java index 8331d5c95b8c..a8375a14008b 100644 --- a/src/main/java/net/sf/jabref/gui/preftabs/GroupsPrefsTab.java +++ b/src/main/java/net/sf/jabref/gui/preftabs/GroupsPrefsTab.java @@ -38,10 +38,6 @@ class GroupsPrefsTab extends JPanel implements PrefsTab { "" + Localization.lang("Show dynamic groups in italics") + ""); private final JCheckBox expandTree = new JCheckBox( Localization.lang("Initially show groups tree expanded")); - private final JCheckBox autoShow = new JCheckBox( - Localization.lang("Automatically show groups interface when switching to a database that contains groups")); - private final JCheckBox autoHide = new JCheckBox( - Localization.lang("Automatically hide groups interface when switching to a database that contains no groups")); private final JCheckBox autoAssignGroup = new JCheckBox( Localization.lang("Automatically assign new entry to selected groups")); private final JTextField groupingField = new JTextField(20); @@ -86,14 +82,6 @@ public void focusLost(FocusEvent e) { builder.nextLine(); builder.nextLine(); builder.nextColumn(); - builder.append(autoShow); - builder.nextLine(); - builder.nextLine(); - builder.nextColumn(); - builder.append(autoHide); - builder.nextLine(); - builder.nextLine(); - builder.nextColumn(); builder.append(autoAssignGroup); builder.nextLine(); builder.nextLine(); @@ -125,8 +113,6 @@ public void setValues() { showDynamic.setSelected(prefs.getBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC)); expandTree.setSelected(prefs.getBoolean(JabRefPreferences.GROUP_EXPAND_TREE)); groupingField.setText(prefs.get(JabRefPreferences.GROUPS_DEFAULT_FIELD)); - autoShow.setSelected(prefs.getBoolean(JabRefPreferences.GROUP_AUTO_SHOW)); - autoHide.setSelected(prefs.getBoolean(JabRefPreferences.GROUP_AUTO_HIDE)); keywordSeparator.setText(prefs.get(JabRefPreferences.KEYWORD_SEPARATOR)); autoAssignGroup.setSelected(prefs.getBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP)); } @@ -137,8 +123,6 @@ public void storeSettings() { prefs.putBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC, showDynamic.isSelected()); prefs.putBoolean(JabRefPreferences.GROUP_EXPAND_TREE, expandTree.isSelected()); prefs.put(JabRefPreferences.GROUPS_DEFAULT_FIELD, groupingField.getText().trim()); - prefs.putBoolean(JabRefPreferences.GROUP_AUTO_SHOW, autoShow.isSelected()); - prefs.putBoolean(JabRefPreferences.GROUP_AUTO_HIDE, autoHide.isSelected()); prefs.putBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP, autoAssignGroup.isSelected()); prefs.put(JabRefPreferences.KEYWORD_SEPARATOR, keywordSeparator.getText()); } diff --git a/src/main/java/net/sf/jabref/gui/preftabs/TableColumnsTab.java b/src/main/java/net/sf/jabref/gui/preftabs/TableColumnsTab.java index 61db7cdde587..809bf09b394c 100644 --- a/src/main/java/net/sf/jabref/gui/preftabs/TableColumnsTab.java +++ b/src/main/java/net/sf/jabref/gui/preftabs/TableColumnsTab.java @@ -181,16 +181,15 @@ public Object getValueAt(int row, int column) { if (internalRow >= tableRows.size()) { return ""; } - Object rowContent = tableRows.get(internalRow); + TableRow rowContent = tableRows.get(internalRow); if (rowContent == null) { return ""; } - TableRow tr = (TableRow) rowContent; // Only two columns if (column == 0) { - return tr.getName(); + return rowContent.getName(); } else { - return tr.getLength() > 0 ? Integer.toString(tr.getLength()) : ""; + return rowContent.getLength() > 0 ? Integer.toString(rowContent.getLength()) : ""; } } diff --git a/src/main/java/net/sf/jabref/external/push/AbstractPushToApplication.java b/src/main/java/net/sf/jabref/gui/push/AbstractPushToApplication.java similarity index 99% rename from src/main/java/net/sf/jabref/external/push/AbstractPushToApplication.java rename to src/main/java/net/sf/jabref/gui/push/AbstractPushToApplication.java index 5691e69d5016..633b4a8efa30 100644 --- a/src/main/java/net/sf/jabref/external/push/AbstractPushToApplication.java +++ b/src/main/java/net/sf/jabref/gui/push/AbstractPushToApplication.java @@ -14,7 +14,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.io.IOException; import java.util.List; diff --git a/src/main/java/net/sf/jabref/external/push/PushToApplication.java b/src/main/java/net/sf/jabref/gui/push/PushToApplication.java similarity index 98% rename from src/main/java/net/sf/jabref/external/push/PushToApplication.java rename to src/main/java/net/sf/jabref/gui/push/PushToApplication.java index 7dc20eec0345..5b7d90af2ab9 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToApplication.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToApplication.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.util.List; diff --git a/src/main/java/net/sf/jabref/external/push/PushToApplicationAction.java b/src/main/java/net/sf/jabref/gui/push/PushToApplicationAction.java similarity index 99% rename from src/main/java/net/sf/jabref/external/push/PushToApplicationAction.java rename to src/main/java/net/sf/jabref/gui/push/PushToApplicationAction.java index 9fdd1e247a62..bf82dfb5b2e7 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToApplicationAction.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToApplicationAction.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.awt.event.ActionEvent; import java.util.List; diff --git a/src/main/java/net/sf/jabref/external/push/PushToApplicationButton.java b/src/main/java/net/sf/jabref/gui/push/PushToApplicationButton.java similarity index 92% rename from src/main/java/net/sf/jabref/external/push/PushToApplicationButton.java rename to src/main/java/net/sf/jabref/gui/push/PushToApplicationButton.java index 59dc83d9b5c1..391d2c70c596 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToApplicationButton.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToApplicationButton.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.awt.BorderLayout; import java.awt.Component; @@ -63,7 +63,7 @@ public class PushToApplicationButton implements ActionListener { private final List pushActions; private JPanel comp; private JButton pushButton; - private int selected; + private PushToApplication toApp; private JPopupMenu popup; private final Map actions = new HashMap<>(); private final Dimension buttonDim = new Dimension(23, 23); @@ -104,14 +104,19 @@ private void init() { // Set the last used external application String appSelected = Globals.prefs.get(JabRefPreferences.PUSH_TO_APPLICATION); - for (int i = 0; i < pushActions.size(); i++) { - if (pushActions.get(i).getApplicationName().equals(appSelected)) { - selected = i; + for (PushToApplication application : pushActions) { + if (application.getApplicationName().equals(appSelected)) { + toApp = application; break; } } - setSelected(selected); + if (toApp == null) { + // Nothing found, pick first + toApp = pushActions.get(0); + } + + setSelected(); pushButton.addActionListener(this); pushButton.addMouseListener(new PushButtonMouseListener()); pushButton.setOpaque(false); @@ -123,7 +128,6 @@ private void init() { optPopup.add(settings); settings.addActionListener(event -> { - PushToApplication toApp = pushActions.get(selected); JPanel options = toApp.getSettingsPanel(); if (options != null) { PushToApplicationButton.showSettingsDialog(frame, toApp, options); @@ -138,13 +142,11 @@ private void init() { */ private void buildPopupMenu() { popup = new JPopupMenu(); - int j = 0; for (PushToApplication application : pushActions) { JMenuItem item = new JMenuItem(application.getApplicationName(), application.getIcon()); item.setToolTipText(application.getTooltip()); - item.addActionListener(new PopupItemActionListener(j)); + item.addActionListener(new PopupItemActionListener(application)); popup.add(item); - j++; } } @@ -153,9 +155,12 @@ private void buildPopupMenu() { * * @param i The List index of the application to default to. */ - private void setSelected(int i) { - selected = i; - PushToApplication toApp = pushActions.get(i); + private void setSelected(PushToApplication newApplication) { + toApp = newApplication; + setSelected(); + } + + private void setSelected() { pushButton.setIcon(toApp.getIcon()); pushButton.setToolTipText(toApp.getTooltip()); pushButton.setPreferredSize(buttonDim); @@ -182,8 +187,6 @@ public Action getMenuAction() { @Override public void actionPerformed(ActionEvent e) { - PushToApplication toApp = pushActions.get(selected); - // Lazy initialization of the push action: PushToApplicationAction action = actions.get(toApp); if (action == null) { @@ -252,17 +255,17 @@ public void actionPerformed(ActionEvent e) { class PopupItemActionListener implements ActionListener { - private final int index; + private final PushToApplication application; - public PopupItemActionListener(int index) { - this.index = index; + public PopupItemActionListener(PushToApplication application) { + this.application = application; } @Override public void actionPerformed(ActionEvent e) { // Change the selection: - setSelected(index); + setSelected(application); // Invoke the selected operation (is that expected behaviour?): //PushToApplicationButton.this.actionPerformed(null); // It makes sense to transfer focus to the push button after the @@ -317,7 +320,6 @@ public void mouseReleased(MouseEvent event) { private void processPopupTrigger(MouseEvent e) { // We only want to show the popup if a settings panel exists for the selected // item: - PushToApplication toApp = pushActions.get(selected); if (toApp.getSettingsPanel() != null) { optPopup.show(pushButton, e.getX(), e.getY()); } diff --git a/src/main/java/net/sf/jabref/external/push/PushToApplications.java b/src/main/java/net/sf/jabref/gui/push/PushToApplications.java similarity index 57% rename from src/main/java/net/sf/jabref/external/push/PushToApplications.java rename to src/main/java/net/sf/jabref/gui/push/PushToApplications.java index c531df9e9214..c5e0195b81cb 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToApplications.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToApplications.java @@ -14,30 +14,33 @@ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.util.ArrayList; import java.util.List; public class PushToApplications { - private static final List APPLICATIONS; + private final List applications; + + + public PushToApplications() { /** * Set up the current available choices: */ - static { - APPLICATIONS = new ArrayList<>(); - - PushToApplications.APPLICATIONS.add(new PushToEmacs()); - PushToApplications.APPLICATIONS.add(new PushToLatexEditor()); - PushToApplications.APPLICATIONS.add(new PushToLyx()); - PushToApplications.APPLICATIONS.add(new PushToTexmaker()); - PushToApplications.APPLICATIONS.add(new PushToTeXstudio()); - PushToApplications.APPLICATIONS.add(new PushToVim()); - PushToApplications.APPLICATIONS.add(new PushToWinEdt()); + + applications = new ArrayList<>(); + + applications.add(new PushToEmacs()); + applications.add(new PushToLatexEditor()); + applications.add(new PushToLyx()); + applications.add(new PushToTexmaker()); + applications.add(new PushToTeXstudio()); + applications.add(new PushToVim()); + applications.add(new PushToWinEdt()); } - public static List getApplications() { - return APPLICATIONS; + public List getApplications() { + return applications; } } diff --git a/src/main/java/net/sf/jabref/external/push/PushToEmacs.java b/src/main/java/net/sf/jabref/gui/push/PushToEmacs.java similarity index 99% rename from src/main/java/net/sf/jabref/external/push/PushToEmacs.java rename to src/main/java/net/sf/jabref/gui/push/PushToEmacs.java index 8c7af57028fc..14130fa23735 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToEmacs.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToEmacs.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/net/sf/jabref/external/push/PushToLatexEditor.java b/src/main/java/net/sf/jabref/gui/push/PushToLatexEditor.java similarity index 97% rename from src/main/java/net/sf/jabref/external/push/PushToLatexEditor.java rename to src/main/java/net/sf/jabref/gui/push/PushToLatexEditor.java index b81d1ccb034d..3c5c2995b9bc 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToLatexEditor.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToLatexEditor.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import javax.swing.Icon; diff --git a/src/main/java/net/sf/jabref/external/push/PushToLyx.java b/src/main/java/net/sf/jabref/gui/push/PushToLyx.java similarity index 99% rename from src/main/java/net/sf/jabref/external/push/PushToLyx.java rename to src/main/java/net/sf/jabref/gui/push/PushToLyx.java index 96bcfc5d3404..218287121a1c 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToLyx.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToLyx.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.io.BufferedWriter; import java.io.File; diff --git a/src/main/java/net/sf/jabref/external/push/PushToTeXstudio.java b/src/main/java/net/sf/jabref/gui/push/PushToTeXstudio.java similarity index 97% rename from src/main/java/net/sf/jabref/external/push/PushToTeXstudio.java rename to src/main/java/net/sf/jabref/gui/push/PushToTeXstudio.java index 96b16d7aa7e9..572b0268c3a0 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToTeXstudio.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToTeXstudio.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import javax.swing.Icon; diff --git a/src/main/java/net/sf/jabref/external/push/PushToTexmaker.java b/src/main/java/net/sf/jabref/gui/push/PushToTexmaker.java similarity index 97% rename from src/main/java/net/sf/jabref/external/push/PushToTexmaker.java rename to src/main/java/net/sf/jabref/gui/push/PushToTexmaker.java index 5caaead3108d..a689c085d8c9 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToTexmaker.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToTexmaker.java @@ -14,7 +14,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import javax.swing.Icon; diff --git a/src/main/java/net/sf/jabref/external/push/PushToVim.java b/src/main/java/net/sf/jabref/gui/push/PushToVim.java similarity index 99% rename from src/main/java/net/sf/jabref/external/push/PushToVim.java rename to src/main/java/net/sf/jabref/gui/push/PushToVim.java index 805dd56b913c..994a9cb2bd58 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToVim.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToVim.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/net/sf/jabref/external/push/PushToWinEdt.java b/src/main/java/net/sf/jabref/gui/push/PushToWinEdt.java similarity index 97% rename from src/main/java/net/sf/jabref/external/push/PushToWinEdt.java rename to src/main/java/net/sf/jabref/gui/push/PushToWinEdt.java index dd150b15663d..84a0b254994d 100644 --- a/src/main/java/net/sf/jabref/external/push/PushToWinEdt.java +++ b/src/main/java/net/sf/jabref/gui/push/PushToWinEdt.java @@ -13,7 +13,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.external.push; +package net.sf.jabref.gui.push; import javax.swing.Icon; diff --git a/src/main/java/net/sf/jabref/gui/util/comparator/FirstColumnComparator.java b/src/main/java/net/sf/jabref/gui/util/comparator/FirstColumnComparator.java index 51b724d32db7..322ad21d89aa 100644 --- a/src/main/java/net/sf/jabref/gui/util/comparator/FirstColumnComparator.java +++ b/src/main/java/net/sf/jabref/gui/util/comparator/FirstColumnComparator.java @@ -16,7 +16,6 @@ package net.sf.jabref.gui.util.comparator; import java.util.Comparator; -import java.util.Optional; import net.sf.jabref.BibDatabaseContext; import net.sf.jabref.logic.TypedBibEntry; @@ -35,8 +34,8 @@ public int compare(BibEntry e1, BibEntry e2) { int score1 = 0; int score2 = 0; - TypedBibEntry typedEntry1 = new TypedBibEntry(e1, Optional.of(database.getDatabase()), database.getMode()); - TypedBibEntry typedEntry2 = new TypedBibEntry(e2, Optional.of(database.getDatabase()), database.getMode()); + TypedBibEntry typedEntry1 = new TypedBibEntry(e1, database); + TypedBibEntry typedEntry2 = new TypedBibEntry(e2, database); if (typedEntry1.hasAllRequiredFields()) { score1++; } diff --git a/src/main/java/net/sf/jabref/importer/EntryFromPDFCreator.java b/src/main/java/net/sf/jabref/importer/EntryFromPDFCreator.java index d47c35e31b5b..48c8eff037f8 100644 --- a/src/main/java/net/sf/jabref/importer/EntryFromPDFCreator.java +++ b/src/main/java/net/sf/jabref/importer/EntryFromPDFCreator.java @@ -5,6 +5,7 @@ import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Calendar; +import java.util.Collections; import java.util.List; import java.util.Optional; @@ -13,6 +14,7 @@ import net.sf.jabref.external.ExternalFileType; import net.sf.jabref.external.ExternalFileTypes; import net.sf.jabref.gui.IconTheme; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.pdfimport.PdfImporter; @@ -60,8 +62,7 @@ protected Optional createBibtexEntry(File pdfFile) { } PdfImporter pi = new PdfImporter(JabRefGUI.getMainFrame(), JabRefGUI.getMainFrame().getCurrentBasePanel(), JabRefGUI.getMainFrame().getCurrentBasePanel().getMainTable(), -1); - String[] fileNames = {pdfFile.toString()}; - ImportPdfFilesResult res = pi.importPdfFiles(fileNames); + ImportPdfFilesResult res = pi.importPdfFiles(Collections.singletonList(pdfFile.toString())); if (res.getEntries().size() == 1) { return Optional.of(res.getEntries().get(0)); } else { @@ -122,7 +123,8 @@ private void addEntryDataFromPDDocumentInformation(File pdfFile, BibEntry entry) */ private void addEntryDataFromXMP(File aFile, BibEntry entry) { try { - List entrys = XMPUtil.readXMP(aFile.getAbsoluteFile(), Globals.prefs); + List entrys = XMPUtil.readXMP(aFile.getAbsoluteFile(), + XMPPreferences.fromPreferences(Globals.prefs)); addEntrysToEntry(entry, entrys); } catch (IOException e) { // no canceling here, just no data added. diff --git a/src/main/java/net/sf/jabref/importer/ParserResult.java b/src/main/java/net/sf/jabref/importer/ParserResult.java index 0841a087e5ac..5acd2ce49d57 100644 --- a/src/main/java/net/sf/jabref/importer/ParserResult.java +++ b/src/main/java/net/sf/jabref/importer/ParserResult.java @@ -146,10 +146,10 @@ public boolean hasDuplicateKeys() { /** * Get all duplicated keys found in the database. * - * @return An array containing the duplicated keys. + * @return A list containing the duplicated keys. */ - public String[] getDuplicateKeys() { - return duplicateKeys.toArray(new String[duplicateKeys.size()]); + public List getDuplicateKeys() { + return duplicateKeys; } public boolean isPostponedAutosaveFound() { @@ -181,7 +181,6 @@ public BibDatabaseContext getDatabaseContext() { } public boolean isNullResult() { - // TODO Auto-generated method stub return this == NULL_RESULT; } diff --git a/src/main/java/net/sf/jabref/importer/fileformat/BibtexParser.java b/src/main/java/net/sf/jabref/importer/fileformat/BibtexParser.java index 918212f4d563..172f89f50e54 100644 --- a/src/main/java/net/sf/jabref/importer/fileformat/BibtexParser.java +++ b/src/main/java/net/sf/jabref/importer/fileformat/BibtexParser.java @@ -242,7 +242,7 @@ private void parseAndAddEntry(String type) { } } - private void parseJabRefComment(Map meta) throws IOException { + private void parseJabRefComment(Map meta) { StringBuilder buffer = null; try { buffer = parseBracketedTextExactly(); diff --git a/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java index 2d8881d2fb25..b3a03ccda0af 100644 --- a/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java +++ b/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java @@ -127,6 +127,9 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } } String entry = current.toString(); + if (!checkLineValidity(entry)) { + continue; + } String label = entry.substring(0, entry.indexOf('-')).trim(); String value = entry.substring(entry.indexOf('-') + 1).trim(); @@ -227,13 +230,16 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { // create one here b.setField(fields); bibitems.add(b); - } return new ParserResult(bibitems); } + private boolean checkLineValidity(String line) { + return (line.length() >= 5) && (line.charAt(4) == '-'); + } + private String addSourceType(String value, String type) { String val = value.toLowerCase(Locale.ENGLISH); String theType = type; diff --git a/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java index a3937b48c892..e4f04e567e06 100644 --- a/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java +++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java @@ -26,6 +26,7 @@ import net.sf.jabref.Globals; import net.sf.jabref.importer.ParserResult; import net.sf.jabref.logic.l10n.Localization; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; /** @@ -55,7 +56,7 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { public ParserResult importDatabase(Path filePath, Charset defaultEncoding) { Objects.requireNonNull(filePath); try { - return new ParserResult(XMPUtil.readXMP(filePath, Globals.prefs)); + return new ParserResult(XMPUtil.readXMP(filePath, XMPPreferences.fromPreferences(Globals.prefs))); } catch (IOException exception) { return ParserResult.fromErrorMessage(exception.getLocalizedMessage()); } @@ -76,7 +77,7 @@ protected boolean isRecognizedFormat(BufferedReader reader) throws IOException { @Override public boolean isRecognizedFormat(Path filePath, Charset defaultEncoding) throws IOException { Objects.requireNonNull(filePath); - return XMPUtil.hasMetadata(filePath, Globals.prefs); + return XMPUtil.hasMetadata(filePath, XMPPreferences.fromPreferences(Globals.prefs)); } @Override diff --git a/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java index cd349dbae324..f3521a0062dd 100644 --- a/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java +++ b/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java @@ -182,9 +182,9 @@ public ParserResult importDatabase(BufferedReader reader) throws IOException { } if (isChapter) { - Object titleO = h.get(FieldName.TITLE); + String titleO = h.get(FieldName.TITLE); if (titleO != null) { - String title = ((String) titleO).trim(); + String title = titleO.trim(); int inPos = title.indexOf("\" in "); if (inPos > 1) { h.put(FieldName.TITLE, title.substring(0, inPos)); diff --git a/src/main/java/net/sf/jabref/logic/TypedBibEntry.java b/src/main/java/net/sf/jabref/logic/TypedBibEntry.java index e684e00d8998..bdfe388b6cee 100644 --- a/src/main/java/net/sf/jabref/logic/TypedBibEntry.java +++ b/src/main/java/net/sf/jabref/logic/TypedBibEntry.java @@ -42,18 +42,14 @@ public TypedBibEntry(BibEntry entry, BibDatabaseMode mode) { this(entry, Optional.empty(), mode); } - public TypedBibEntry(BibEntry entry, Optional database, BibDatabaseMode mode) { + private TypedBibEntry(BibEntry entry, Optional database, BibDatabaseMode mode) { this.entry = Objects.requireNonNull(entry); this.database = Objects.requireNonNull(database); this.mode = mode; } public TypedBibEntry(BibEntry entry, BibDatabaseContext databaseContext) { - this(entry, databaseContext.getDatabase(), databaseContext.getMode()); - } - - public TypedBibEntry(BibEntry entry, BibDatabase database, BibDatabaseMode mode) { - this(entry, Optional.of(database), mode); + this(entry, Optional.of(databaseContext.getDatabase()), databaseContext.getMode()); } /** diff --git a/src/main/java/net/sf/jabref/logic/bibtex/BibEntryWriter.java b/src/main/java/net/sf/jabref/logic/bibtex/BibEntryWriter.java index e6db35d23fec..285dd34ecd84 100644 --- a/src/main/java/net/sf/jabref/logic/bibtex/BibEntryWriter.java +++ b/src/main/java/net/sf/jabref/logic/bibtex/BibEntryWriter.java @@ -83,7 +83,7 @@ public void writeWithoutPrependedNewlines(BibEntry entry, Writer out, BibDatabas private void writeRequiredFieldsFirstRemainingFieldsSecond(BibEntry entry, Writer out, BibDatabaseMode bibDatabaseMode) throws IOException { // Write header with type and bibtex-key. - TypedBibEntry typedEntry = new TypedBibEntry(entry, Optional.empty(), bibDatabaseMode); + TypedBibEntry typedEntry = new TypedBibEntry(entry, bibDatabaseMode); out.write('@' + typedEntry.getTypeForDisplay() + '{'); writeKeyField(entry, out); diff --git a/src/main/java/net/sf/jabref/logic/exporter/OpenDocumentRepresentation.java b/src/main/java/net/sf/jabref/logic/exporter/OpenDocumentRepresentation.java index 4f1071522840..f7eabc022322 100644 --- a/src/main/java/net/sf/jabref/logic/exporter/OpenDocumentRepresentation.java +++ b/src/main/java/net/sf/jabref/logic/exporter/OpenDocumentRepresentation.java @@ -214,8 +214,7 @@ public Document getDOMrepresentation() { } private String getField(BibEntry e, String field) { - String s = BibDatabase.getResolvedField(field, e, database); - return s == null ? "" : s; + return BibDatabase.getResolvedField(field, e, database).orElse(""); } private void addTableCell(Document doc, Element parent, String content) { diff --git a/src/main/java/net/sf/jabref/logic/groups/AllEntriesGroup.java b/src/main/java/net/sf/jabref/logic/groups/AllEntriesGroup.java index aaf66b253e8f..00e4173f2492 100644 --- a/src/main/java/net/sf/jabref/logic/groups/AllEntriesGroup.java +++ b/src/main/java/net/sf/jabref/logic/groups/AllEntriesGroup.java @@ -18,7 +18,6 @@ import java.util.List; import java.util.Optional; -import net.sf.jabref.importer.fileformat.ParseException; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.model.entry.BibEntry; @@ -33,7 +32,7 @@ public AllEntriesGroup() { super(Localization.lang("All entries"), GroupHierarchyType.INDEPENDENT); } - public static AbstractGroup fromString(String s) throws ParseException { + public static AbstractGroup fromString(String s) { if (!s.startsWith(AllEntriesGroup.ID)) { throw new IllegalArgumentException("AllEntriesGroup cannot be created from \"" + s + "\"."); } diff --git a/src/main/java/net/sf/jabref/logic/layout/LayoutEntry.java b/src/main/java/net/sf/jabref/logic/layout/LayoutEntry.java index 1a88163807d9..4e01d644567d 100644 --- a/src/main/java/net/sf/jabref/logic/layout/LayoutEntry.java +++ b/src/main/java/net/sf/jabref/logic/layout/LayoutEntry.java @@ -207,11 +207,8 @@ public String doLayout(BibEntry bibtex, BibDatabase database, Optional case LayoutHelper.IS_LAYOUT_TEXT: return text; case LayoutHelper.IS_SIMPLE_FIELD: - String value = BibDatabase.getResolvedField(text, bibtex, database); + String value = BibDatabase.getResolvedField(text, bibtex, database).orElse(""); - if (value == null) { - value = ""; - } // If a post formatter has been set, call it: if (postFormatter != null) { value = postFormatter.format(value); @@ -229,7 +226,7 @@ public String doLayout(BibEntry bibtex, BibDatabase database, Optional // Printing the encoding name is not supported in entry layouts, only // in begin/end layouts. This prevents breakage if some users depend // on a field called "encoding". We simply return this field instead: - return BibDatabase.getResolvedField("encoding", bibtex, database); + return BibDatabase.getResolvedField("encoding", bibtex, database).orElse(null); default: return ""; } @@ -243,14 +240,10 @@ private String handleOptionField(BibEntry bibtex, BibDatabase database) { } else { // changed section begin - arudert // resolve field (recognized by leading backslash) or text - String fieldText = text.startsWith("\\") ? BibDatabase.getResolvedField(text.substring(1), bibtex, - database) : BibDatabase.getText(text, database); + fieldEntry = text.startsWith("\\") ? BibDatabase + .getResolvedField(text.substring(1), bibtex, database) + .orElse("") : BibDatabase.getText(text, database); // changed section end - arudert - if (fieldText == null) { - fieldEntry = ""; - } else { - fieldEntry = fieldText; - } } if (option != null) { @@ -268,38 +261,37 @@ private String handleOptionField(BibEntry bibtex, BibDatabase database) { } private String handleFieldOrGroupStart(BibEntry bibtex, BibDatabase database, Optional highlightPattern) { - String field; + Optional field; if (type == LayoutHelper.IS_GROUP_START) { field = BibDatabase.getResolvedField(text, bibtex, database); } else if (text.matches(".*(;|(\\&+)).*")) { // split the strings along &, && or ; for AND formatter String[] parts = text.split("\\s*(;|(\\&+))\\s*"); - field = null; + field = Optional.empty(); for (String part : parts) { field = BibDatabase.getResolvedField(part, bibtex, database); - if (field == null) { + if (!field.isPresent()) { break; } - } } else { // split the strings along |, || for OR formatter String[] parts = text.split("\\s*(\\|+)\\s*"); - field = null; + field = Optional.empty(); for (String part : parts) { field = BibDatabase.getResolvedField(part, bibtex, database); - if (field != null) { + if (field.isPresent()) { break; } } } - if ((field == null) || ((type == LayoutHelper.IS_GROUP_START) - && field.equalsIgnoreCase(LayoutHelper.getCurrentGroup()))) { + if ((!field.isPresent()) || ((type == LayoutHelper.IS_GROUP_START) + && field.get().equalsIgnoreCase(LayoutHelper.getCurrentGroup()))) { return null; } else { if (type == LayoutHelper.IS_GROUP_START) { - LayoutHelper.setCurrentGroup(field); + LayoutHelper.setCurrentGroup(field.get()); } StringBuilder sb = new StringBuilder(100); String fieldText; diff --git a/src/main/java/net/sf/jabref/logic/layout/format/HTMLChars.java b/src/main/java/net/sf/jabref/logic/layout/format/HTMLChars.java index 460579b9167f..352df7684890 100644 --- a/src/main/java/net/sf/jabref/logic/layout/format/HTMLChars.java +++ b/src/main/java/net/sf/jabref/logic/layout/format/HTMLChars.java @@ -53,11 +53,11 @@ public String format(String inField) { if (incommand) { /* Close Command */ String command = currentCommand.toString(); - Object result = HTML_CHARS.get(command); + String result = HTML_CHARS.get(command); if (result == null) { sb.append(command); } else { - sb.append((String) result); + sb.append(result); } } escaped = true; @@ -163,19 +163,19 @@ public String format(String inField) { // This end brace terminates a command. This can be the case in // constructs like {\aa}. The correct behaviour should be to // substitute the evaluated command and swallow the brace: - Object result = HTML_CHARS.get(command); + String result = HTML_CHARS.get(command); if (result == null) { // If the command is unknown, just print it: sb.append(command); } else { - sb.append((String) result); + sb.append(result); } } else { - Object result = HTML_CHARS.get(command); + String result = HTML_CHARS.get(command); if (result == null) { sb.append(command); } else { - sb.append((String) result); + sb.append(result); } sb.append(' '); } diff --git a/src/main/java/net/sf/jabref/logic/layout/format/LatexToUnicodeFormatter.java b/src/main/java/net/sf/jabref/logic/layout/format/LatexToUnicodeFormatter.java index 7a3b03ebcb5b..76fa6d2358c9 100644 --- a/src/main/java/net/sf/jabref/logic/layout/format/LatexToUnicodeFormatter.java +++ b/src/main/java/net/sf/jabref/logic/layout/format/LatexToUnicodeFormatter.java @@ -69,11 +69,11 @@ public String format(String inField) { if (incommand) { /* Close Command */ String command = currentCommand.toString(); - Object result = LatexToUnicodeFormatter.CHARS.get(command); + String result = LatexToUnicodeFormatter.CHARS.get(command); if (result == null) { sb.append(command); } else { - sb.append((String) result); + sb.append(result); } } @@ -162,7 +162,7 @@ public String format(String inField) { argument = part; if (argument != null) { // handle common case of general latex command - Object result = LatexToUnicodeFormatter.CHARS.get(command + argument); + String result = LatexToUnicodeFormatter.CHARS.get(command + argument); // If found, then use translated version. If not, then keep // the @@ -185,7 +185,7 @@ public String format(String inField) { sb.append(argument); } } else { - sb.append((String) result); + sb.append(result); } } @@ -193,22 +193,22 @@ public String format(String inField) { // This end brace terminates a command. This can be the case in // constructs like {\aa}. The correct behaviour should be to // substitute the evaluated command and swallow the brace: - Object result = LatexToUnicodeFormatter.CHARS.get(command); + String result = LatexToUnicodeFormatter.CHARS.get(command); if (result == null) { // If the command is unknown, just print it: sb.append(command); } else { - sb.append((String) result); + sb.append(result); } } else { - Object result = LatexToUnicodeFormatter.CHARS.get(command); + String result = LatexToUnicodeFormatter.CHARS.get(command); if (result == null) { sb.append(command); } else { - sb.append((String) result); + sb.append(result); } sb.append(' '); } 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 a18054eb421e..002d516fa6f6 100644 --- a/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/net/sf/jabref/logic/openoffice/OOBibStyle.java @@ -31,6 +31,7 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @@ -731,13 +732,13 @@ private String getCitationMarkerField(BibEntry entry, BibDatabase database, Stri String authorField = getStringCitProperty(AUTHOR_FIELD); String[] fields = field.split(FieldName.FIELD_SEPARATOR); for (String s : fields) { - String content = BibDatabase.getResolvedField(s, entry, database); + Optional content = BibDatabase.getResolvedField(s, entry, database); - if ((content != null) && !content.trim().isEmpty()) { - if (field.equals(authorField) && StringUtil.isInCurlyBrackets(content)) { - return "{" + fieldFormatter.format(content) + "}"; + if ((content.isPresent()) && !content.get().trim().isEmpty()) { + if (field.equals(authorField) && StringUtil.isInCurlyBrackets(content.get())) { + return "{" + fieldFormatter.format(content.get()) + "}"; } - return fieldFormatter.format(content); + return fieldFormatter.format(content.get()); } } // No luck? Return an empty string: diff --git a/src/main/java/net/sf/jabref/logic/openoffice/OOPreFormatter.java b/src/main/java/net/sf/jabref/logic/openoffice/OOPreFormatter.java index 14018be0b0ee..bb05f57848a0 100644 --- a/src/main/java/net/sf/jabref/logic/openoffice/OOPreFormatter.java +++ b/src/main/java/net/sf/jabref/logic/openoffice/OOPreFormatter.java @@ -108,7 +108,7 @@ public String format(String field) { // Are we already at the end of the string? if ((i + 1) == finalResult.length()) { String command = currentCommand.toString(); - Object result = OOPreFormatter.CHARS.get(command); + String result = OOPreFormatter.CHARS.get(command); /* If found, then use translated version. If not, * then keep * the text of the parameter intact. @@ -116,7 +116,7 @@ public String format(String field) { if (result == null) { sb.append(command); } else { - sb.append((String) result); + sb.append(result); } } diff --git a/src/main/java/net/sf/jabref/gui/openoffice/UndefinedBibtexEntry.java b/src/main/java/net/sf/jabref/logic/openoffice/UndefinedBibtexEntry.java similarity index 90% rename from src/main/java/net/sf/jabref/gui/openoffice/UndefinedBibtexEntry.java rename to src/main/java/net/sf/jabref/logic/openoffice/UndefinedBibtexEntry.java index fae53bfa2b0e..dbf987e0c22f 100644 --- a/src/main/java/net/sf/jabref/gui/openoffice/UndefinedBibtexEntry.java +++ b/src/main/java/net/sf/jabref/logic/openoffice/UndefinedBibtexEntry.java @@ -13,9 +13,8 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -package net.sf.jabref.gui.openoffice; +package net.sf.jabref.logic.openoffice; -import net.sf.jabref.logic.openoffice.OOBibStyle; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.FieldName; import net.sf.jabref.model.entry.IdGenerator; @@ -24,7 +23,7 @@ * Subclass of BibEntry for representing entries referenced in a document that can't * be found in JabRef's current database. */ -class UndefinedBibtexEntry extends BibEntry { +public class UndefinedBibtexEntry extends BibEntry { private final String key; diff --git a/src/main/java/net/sf/jabref/logic/preferences/LastFocusedTabPreferences.java b/src/main/java/net/sf/jabref/logic/preferences/LastFocusedTabPreferences.java index 7e27f8309272..2eb855e6152a 100644 --- a/src/main/java/net/sf/jabref/logic/preferences/LastFocusedTabPreferences.java +++ b/src/main/java/net/sf/jabref/logic/preferences/LastFocusedTabPreferences.java @@ -31,7 +31,7 @@ public LastFocusedTabPreferences(JabRefPreferences preferences) { public void setLastFocusedTab(File file) { if (file == null) { - return; // no change detected + return; } String filePath = file.getAbsolutePath(); diff --git a/src/main/java/net/sf/jabref/logic/remote/server/RemoteListenerServer.java b/src/main/java/net/sf/jabref/logic/remote/server/RemoteListenerServer.java index efee50b0ee54..f54c61f6296f 100644 --- a/src/main/java/net/sf/jabref/logic/remote/server/RemoteListenerServer.java +++ b/src/main/java/net/sf/jabref/logic/remote/server/RemoteListenerServer.java @@ -27,11 +27,11 @@ import org.apache.commons.logging.LogFactory; public class RemoteListenerServer implements Runnable { + private static final Log LOGGER = LogFactory.getLog(RemoteListenerServer.class); private static final int BACKLOG = 1; - private static final int ONE_SECOND_TIMEOUT = 1000; - private static final Log LOGGER = LogFactory.getLog(RemoteListenerServer.class); + private static final int ONE_SECOND_TIMEOUT = 1000; private final MessageHandler messageHandler; private final ServerSocket serverSocket; diff --git a/src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java b/src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java index d1d7d58dbbbc..0b2c4430cd19 100644 --- a/src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java +++ b/src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java @@ -229,7 +229,7 @@ public Boolean visitComparison(SearchParser.ComparisonContext ctx) { // remove possible enclosing " symbols String right = ctx.right.getText(); if(right.startsWith("\"") && right.endsWith("\"")) { - right = right.substring(1, right.length() - 2); + right = right.substring(1, right.length() - 1); } return comparison(ctx.left.getText(), ComparisonOperator.build(ctx.operator.getText()), right); diff --git a/src/main/java/net/sf/jabref/logic/xmp/XMPPreferences.java b/src/main/java/net/sf/jabref/logic/xmp/XMPPreferences.java new file mode 100644 index 000000000000..96475459c60e --- /dev/null +++ b/src/main/java/net/sf/jabref/logic/xmp/XMPPreferences.java @@ -0,0 +1,37 @@ +package net.sf.jabref.logic.xmp; + +import java.util.List; + +import net.sf.jabref.preferences.JabRefPreferences; + +public class XMPPreferences { + + private final boolean useXMPPrivacyFilter; + private final List xmpPrivacyFilter; + private final String keywordSeparator; + + + public XMPPreferences(boolean useXMPPrivacyFilter, List xmpPrivacyFilter, String keywordSeparator) { + this.useXMPPrivacyFilter = useXMPPrivacyFilter; + this.xmpPrivacyFilter = xmpPrivacyFilter; + this.keywordSeparator = keywordSeparator; + } + + public static XMPPreferences fromPreferences(JabRefPreferences jabrefPreferences) { + return new XMPPreferences(jabrefPreferences.getBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER), + jabrefPreferences.getStringList(JabRefPreferences.XMP_PRIVACY_FILTERS), + jabrefPreferences.get(JabRefPreferences.KEYWORD_SEPARATOR)); + } + + public boolean isUseXMPPrivacyFilter() { + return useXMPPrivacyFilter; + } + + public List getXmpPrivacyFilter() { + return xmpPrivacyFilter; + } + + public String getKeywordSeparator() { + return keywordSeparator; + } +} diff --git a/src/main/java/net/sf/jabref/logic/xmp/XMPSchemaBibtex.java b/src/main/java/net/sf/jabref/logic/xmp/XMPSchemaBibtex.java index 08e081feb486..8e4f9099a71c 100644 --- a/src/main/java/net/sf/jabref/logic/xmp/XMPSchemaBibtex.java +++ b/src/main/java/net/sf/jabref/logic/xmp/XMPSchemaBibtex.java @@ -32,7 +32,6 @@ import net.sf.jabref.model.entry.FieldProperties; import net.sf.jabref.model.entry.IdGenerator; import net.sf.jabref.model.entry.InternalBibtexFields; -import net.sf.jabref.preferences.JabRefPreferences; import org.apache.jempbox.xmp.XMPMetadata; import org.apache.jempbox.xmp.XMPSchema; @@ -276,8 +275,8 @@ public static Map getAllProperties(XMPSchema schema, String name - public void setBibtexEntry(BibEntry entry) { - setBibtexEntry(entry, null); + public void setBibtexEntry(BibEntry entry, XMPPreferences xmpPreferences) { + setBibtexEntry(entry, null, xmpPreferences); } /** @@ -285,21 +284,17 @@ public void setBibtexEntry(BibEntry entry) { * @param entry * @param database maybenull */ - public void setBibtexEntry(BibEntry entry, BibDatabase database) { + public void setBibtexEntry(BibEntry entry, BibDatabase database, XMPPreferences xmpPreferences) { // Set all the values including key and entryType Set fields = entry.getFieldNames(); - JabRefPreferences prefs = JabRefPreferences.getInstance(); - if (prefs.getBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER)) { - Set filters = new TreeSet<>(prefs.getStringList(JabRefPreferences.XMP_PRIVACY_FILTERS)); + if (xmpPreferences != null && xmpPreferences.isUseXMPPrivacyFilter()) { + Set filters = new TreeSet<>(xmpPreferences.getXmpPrivacyFilter()); fields.removeAll(filters); } for (String field : fields) { - String value = BibDatabase.getResolvedField(field, entry, database); - if (value == null) { - value = ""; - } + String value = BibDatabase.getResolvedField(field, entry, database).orElse(""); if (InternalBibtexFields.getFieldExtras(field).contains(FieldProperties.PERSON_NAMES)) { setPersonList(field, value); } else { diff --git a/src/main/java/net/sf/jabref/logic/xmp/XMPUtil.java b/src/main/java/net/sf/jabref/logic/xmp/XMPUtil.java index 751b6e38770f..4de71391a41b 100644 --- a/src/main/java/net/sf/jabref/logic/xmp/XMPUtil.java +++ b/src/main/java/net/sf/jabref/logic/xmp/XMPUtil.java @@ -19,12 +19,9 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; @@ -42,13 +39,7 @@ import javax.xml.transform.TransformerException; -import net.sf.jabref.Globals; -import net.sf.jabref.importer.ParserResult; -import net.sf.jabref.importer.fileformat.BibtexParser; import net.sf.jabref.logic.TypedBibEntry; -import net.sf.jabref.logic.bibtex.BibEntryWriter; -import net.sf.jabref.logic.bibtex.LatexFieldFormatter; -import net.sf.jabref.logic.bibtex.LatexFieldFormatterPreferences; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.database.BibDatabaseMode; import net.sf.jabref.model.entry.Author; @@ -57,7 +48,6 @@ import net.sf.jabref.model.entry.EntryUtil; import net.sf.jabref.model.entry.FieldName; import net.sf.jabref.model.entry.MonthUtil; -import net.sf.jabref.preferences.JabRefPreferences; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -96,8 +86,8 @@ public class XMPUtil { * @return BibtexEntryies found in the PDF or an empty list * @throws IOException */ - public static List readXMP(String filename, JabRefPreferences prefs) throws IOException { - return XMPUtil.readXMP(new File(filename), prefs); + public static List readXMP(String filename, XMPPreferences xmpPreferences) throws IOException { + return XMPUtil.readXMP(new File(filename), xmpPreferences); } /** @@ -126,8 +116,8 @@ public static List readXMP(String filename, JabRefPreferences prefs) t * If the file could not be written to or could not be found. */ public static void writeXMP(String filename, BibEntry entry, - BibDatabase database) throws IOException, TransformerException { - XMPUtil.writeXMP(new File(filename), entry, database); + BibDatabase database, XMPPreferences xmpPreferences) throws IOException, TransformerException { + XMPUtil.writeXMP(new File(filename), entry, database, xmpPreferences); } /** @@ -140,10 +130,10 @@ public static void writeXMP(String filename, BibEntry entry, * Throws an IOException if the file cannot be read, so the user * than remove a lock or cancel the operation. */ - public static List readXMP(File file, JabRefPreferences prefs) throws IOException { + public static List readXMP(File file, XMPPreferences xmpPreferences) throws IOException { List result = Collections.emptyList(); try (FileInputStream inputStream = new FileInputStream(file)) { - result = XMPUtil.readXMP(inputStream, prefs); + result = XMPUtil.readXMP(inputStream, xmpPreferences); } return result; } @@ -181,7 +171,7 @@ public static PDDocument loadWithAutomaticDecryption(InputStream inputStream) th * * @return list of BibEntries retrieved from the stream. May be empty, but never null */ - public static List readXMP(InputStream inputStream, JabRefPreferences prefs) + public static List readXMP(InputStream inputStream, XMPPreferences xmpPreferences) throws IOException { List result = new LinkedList<>(); @@ -209,7 +199,8 @@ public static List readXMP(InputStream inputStream, JabRefPreferences for (XMPSchema schema : schemas) { XMPSchemaDublinCore dc = (XMPSchemaDublinCore) schema; - Optional entry = XMPUtil.getBibtexEntryFromDublinCore(dc, prefs); + Optional entry = XMPUtil.getBibtexEntryFromDublinCore(dc, + xmpPreferences); if (entry.isPresent()) { if (entry.get().getType() == null) { @@ -237,8 +228,8 @@ public static List readXMP(InputStream inputStream, JabRefPreferences return result; } - public static Collection readXMP(Path filePath, JabRefPreferences prefs) throws IOException { - return readXMP(filePath.toFile(), prefs); + public static Collection readXMP(Path filePath, XMPPreferences xmpPreferences) throws IOException { + return readXMP(filePath.toFile(), xmpPreferences); } /** @@ -316,7 +307,7 @@ public static Optional getBibtexEntryFromDocumentInformation( * @return The bibtex entry found in the document information. */ public static Optional getBibtexEntryFromDublinCore(XMPSchemaDublinCore dcSchema, - JabRefPreferences prefs) { + XMPPreferences xmpPreferences) { BibEntry entry = new BibEntry(); @@ -420,7 +411,7 @@ public static Optional getBibtexEntryFromDublinCore(XMPSchemaDublinCor */ List subjects = dcSchema.getSubjects(); if (subjects != null) { - entry.addKeywords(subjects, prefs.get(JabRefPreferences.KEYWORD_SEPARATOR)); + entry.addKeywords(subjects, xmpPreferences.getKeywordSeparator()); } /** @@ -471,10 +462,10 @@ public static Optional getBibtexEntryFromDublinCore(XMPSchemaDublinCor * If the file could not be written to or could not be found. */ public static void writeXMP(File file, BibEntry entry, - BibDatabase database) throws IOException, TransformerException { + BibDatabase database, XMPPreferences xmpPreferences) throws IOException, TransformerException { List l = new LinkedList<>(); l.add(entry); - XMPUtil.writeXMP(file, l, database, true); + XMPUtil.writeXMP(file, l, database, true, xmpPreferences); } /** @@ -497,7 +488,7 @@ public static void writeXMP(File file, BibEntry entry, * resolved. */ private static void toXMP(Collection bibtexEntries, - BibDatabase database, OutputStream outputStream) + BibDatabase database, OutputStream outputStream, XMPPreferences xmpPreferences) throws IOException, TransformerException { Collection resolvedEntries; @@ -512,7 +503,7 @@ private static void toXMP(Collection bibtexEntries, for (BibEntry e : resolvedEntries) { XMPSchemaBibtex schema = new XMPSchemaBibtex(x); x.addSchema(schema); - schema.setBibtexEntry(e); + schema.setBibtexEntry(e, xmpPreferences); } x.save(outputStream); @@ -536,10 +527,10 @@ private static void toXMP(Collection bibtexEntries, * Thrown if the bibtexEntries could not transformed to XMP. */ public static String toXMP(Collection bibtexEntries, - BibDatabase database) throws TransformerException { + BibDatabase database, XMPPreferences xmpPreferences) throws TransformerException { try { ByteArrayOutputStream bs = new ByteArrayOutputStream(); - XMPUtil.toXMP(bibtexEntries, database, bs); + XMPUtil.toXMP(bibtexEntries, database, bs, xmpPreferences); return bs.toString(); } catch (IOException e) { throw new TransformerException(e); @@ -596,7 +587,7 @@ public static Optional readRawXMP(File file) throws IOException { } private static void writeToDCSchema(XMPSchemaDublinCore dcSchema, - BibEntry entry, BibDatabase database) { + BibEntry entry, BibDatabase database, XMPPreferences xmpPreferences) { BibEntry resolvedEntry; if (database == null) { @@ -606,11 +597,9 @@ private static void writeToDCSchema(XMPSchemaDublinCore dcSchema, } // Query privacy filter settings - JabRefPreferences prefs = JabRefPreferences.getInstance(); - boolean useXmpPrivacyFilter = - prefs.getBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER); + boolean useXmpPrivacyFilter = xmpPreferences.isUseXMPPrivacyFilter(); // Fields for which not to write XMP data later on: - Set filters = new TreeSet<>(prefs.getStringList(JabRefPreferences.XMP_PRIVACY_FILTERS)); + Set filters = new TreeSet<>(xmpPreferences.getXmpPrivacyFilter()); // Set all the values including key and entryType @@ -878,7 +867,7 @@ private static void writeToDCSchema(XMPSchemaDublinCore dcSchema, * * Bibtex-Fields used: title */ - TypedBibEntry typedEntry = new TypedBibEntry(entry, Optional.empty(), BibDatabaseMode.BIBTEX); + TypedBibEntry typedEntry = new TypedBibEntry(entry, BibDatabaseMode.BIBTEX); String o = typedEntry.getTypeForDisplay(); if (!o.isEmpty()) { dcSchema.addType(o); @@ -902,12 +891,12 @@ private static void writeToDCSchema(XMPSchemaDublinCore dcSchema, * @throws TransformerException */ public static void writeDublinCore(PDDocument document, BibEntry entry, - BibDatabase database) throws IOException, TransformerException { + BibDatabase database, XMPPreferences xmpPreferences) throws IOException, TransformerException { List entries = new ArrayList<>(); entries.add(entry); - XMPUtil.writeDublinCore(document, entries, database); + XMPUtil.writeDublinCore(document, entries, database, xmpPreferences); } /** @@ -927,7 +916,7 @@ public static void writeDublinCore(PDDocument document, BibEntry entry, * @throws TransformerException */ private static void writeDublinCore(PDDocument document, - Collection entries, BibDatabase database) + Collection entries, BibDatabase database, XMPPreferences xmpPreferences) throws IOException, TransformerException { Collection resolvedEntries; @@ -956,7 +945,7 @@ private static void writeDublinCore(PDDocument document, for (BibEntry entry : resolvedEntries) { XMPSchemaDublinCore dcSchema = new XMPSchemaDublinCore(meta); - XMPUtil.writeToDCSchema(dcSchema, entry, null); + XMPUtil.writeToDCSchema(dcSchema, entry, null, xmpPreferences); meta.addSchema(dcSchema); } @@ -985,7 +974,7 @@ private static void writeDublinCore(PDDocument document, * database is null the strings will not be resolved. */ private static void writeDocumentInformation(PDDocument document, - BibEntry entry, BibDatabase database) { + BibEntry entry, BibDatabase database, XMPPreferences xmpPreferences) { PDDocumentInformation di = document.getDocumentInformation(); @@ -997,11 +986,9 @@ private static void writeDocumentInformation(PDDocument document, } // Query privacy filter settings - JabRefPreferences prefs = JabRefPreferences.getInstance(); - boolean useXmpPrivacyFilter = - prefs.getBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER); + boolean useXmpPrivacyFilter = xmpPreferences.isUseXMPPrivacyFilter(); // Fields for which not to write XMP data later on: - Set filters = new TreeSet<>(prefs.getStringList(JabRefPreferences.XMP_PRIVACY_FILTERS)); + Set filters = new TreeSet<>(xmpPreferences.getXmpPrivacyFilter()); // Set all the values including key and entryType for (Entry field : resolvedEntry.getFieldMap().entrySet()) { @@ -1067,7 +1054,7 @@ private static void writeDocumentInformation(PDDocument document, */ public static void writeXMP(File file, Collection bibtexEntries, BibDatabase database, - boolean writePDFInfo) throws IOException, TransformerException { + boolean writePDFInfo, XMPPreferences xmpPreferences) throws IOException, TransformerException { Collection resolvedEntries; if (database == null) { @@ -1083,8 +1070,8 @@ public static void writeXMP(File file, if (writePDFInfo && (resolvedEntries.size() == 1)) { XMPUtil.writeDocumentInformation(document, resolvedEntries - .iterator().next(), null); - XMPUtil.writeDublinCore(document, resolvedEntries, null); + .iterator().next(), null, xmpPreferences); + XMPUtil.writeDublinCore(document, resolvedEntries, null, xmpPreferences); } PDDocumentCatalog catalog = document.getDocumentCatalog(); @@ -1110,7 +1097,7 @@ public static void writeXMP(File file, for (BibEntry e : resolvedEntries) { XMPSchemaBibtex bibtex = new XMPSchemaBibtex(meta); meta.addSchema(bibtex); - bibtex.setBibtexEntry(e, null); + bibtex.setBibtexEntry(e, xmpPreferences); } // Save to stream and then input that stream to the PDF @@ -1130,159 +1117,12 @@ public static void writeXMP(File file, } } - /** - * Print usage information for the command line tool xmpUtil. - * - * @see XMPUtil#main(String[]) - */ - private static void usage() { - System.out.println("Read or write XMP-metadata from or to pdf file."); - System.out.println(""); - System.out.println("Usage:"); - System.out.println("Read from PDF and print as bibtex:"); - System.out.println(" xmpUtil "); - System.out.println("Read from PDF and print raw XMP:"); - System.out.println(" xmpUtil -x "); - System.out - .println("Write the entry in given by to the PDF:"); - System.out.println(" xmpUtil "); - System.out.println("Write all entries in to the PDF:"); - System.out.println(" xmpUtil "); - System.out.println(""); - System.out - .println("To report bugs visit http://jabref.sourceforge.net"); - } - - /** - * Command-line tool for working with XMP-data. - * - * Read or write XMP-metadata from or to pdf file. - * - * Usage: - *
- *
Read from PDF and print as bibtex:
- *
xmpUtil PDF
- *
Read from PDF and print raw XMP:
- *
xmpUtil -x PDF
- *
Write the entry in BIB given by KEY to the PDF:
- *
xmpUtil KEY BIB PDF
- *
Write all entries in BIB to the PDF:
- *
xmpUtil BIB PDF
- *
- * - * @param args - * Command line strings passed to utility. - * @throws IOException - * If any of the given files could not be read or written. - * @throws TransformerException - * If the given BibEntry is malformed. - */ - public static void main(String[] args) throws IOException, TransformerException { - - // Don't forget to initialize the preferences - if (Globals.prefs == null) { - Globals.prefs = JabRefPreferences.getInstance(); - } - - switch (args.length) { - case 0: - XMPUtil.usage(); - break; - case 1: - - if (args[0].endsWith(".pdf")) { - // Read from pdf and write as BibTex - List l = XMPUtil.readXMP(new File(args[0]), Globals.prefs); - - BibEntryWriter bibtexEntryWriter = new BibEntryWriter( - new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)), false); - - for (BibEntry entry : l) { - StringWriter sw = new StringWriter(); - bibtexEntryWriter.write(entry, sw, BibDatabaseMode.BIBTEX); - System.out.println(sw.getBuffer()); - } - - } 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); - Collection entries = result.getDatabase().getEntries(); - - if (entries.isEmpty()) { - System.err.println("Could not find BibEntry in " + args[0]); - } else { - System.out.println(XMPUtil.toXMP(entries, result.getDatabase())); - } - } - } else { - XMPUtil.usage(); - } - break; - case 2: - if ("-x".equals(args[0]) && args[1].endsWith(".pdf")) { - // Read from pdf and write as BibTex - Optional meta = XMPUtil.readRawXMP(new File(args[1])); - - if (meta.isPresent()) { - XMLUtil.save(meta.get().getXMPDocument(), System.out, StandardCharsets.UTF_8.name()); - } else { - System.err - .println("The given pdf does not contain any XMP-metadata."); - } - break; - } - - if (args[0].endsWith(".bib") && args[1].endsWith(".pdf")) { - ParserResult result = BibtexParser - .parse(new FileReader(args[0])); - - Collection entries = result.getDatabase() - .getEntries(); - - if (entries.isEmpty()) { - System.err.println("Could not find BibEntry in " - + args[0]); - } else { - XMPUtil.writeXMP(new File(args[1]), entries, result - .getDatabase(), false); - System.out.println("XMP written."); - } - break; - } - - XMPUtil.usage(); - break; - case 3: - if (!args[1].endsWith(".bib") && !args[2].endsWith(".pdf")) { - XMPUtil.usage(); - break; - } - - ParserResult result = BibtexParser.parse(new FileReader(args[1])); - - Optional bibEntry = result.getDatabase().getEntryByKey(args[0]); - - if (bibEntry.isPresent()) { - XMPUtil.writeXMP(new File(args[2]), bibEntry.get(), result.getDatabase()); - - System.out.println("XMP written."); - } else { - System.err.println("Could not find BibEntry " + args[0] + " in " + args[0]); - } - break; - - default: - XMPUtil.usage(); - } - } - /** * see XMPUtil.hasMetadata(InputStream) */ - public static boolean hasMetadata(Path path, JabRefPreferences prefs) { + public static boolean hasMetadata(Path path, XMPPreferences xmpPreferences) { try (InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ)) { - return hasMetadata(inputStream, prefs); + return hasMetadata(inputStream, xmpPreferences); } catch (IOException e) { LOGGER.error("XMP reading failed", e); return false; @@ -1300,9 +1140,9 @@ public static boolean hasMetadata(Path path, JabRefPreferences prefs) { * The inputStream to read the PDF from. * @return whether a BibEntry was found in the given PDF. */ - public static boolean hasMetadata(InputStream inputStream, JabRefPreferences prefs) { + public static boolean hasMetadata(InputStream inputStream, XMPPreferences xmpPreferences) { try { - List bibEntries = XMPUtil.readXMP(inputStream, prefs); + List bibEntries = XMPUtil.readXMP(inputStream, xmpPreferences); return !bibEntries.isEmpty(); } catch (EncryptedPdfsNotSupportedException ex) { LOGGER.info("Encryption not supported by XMPUtil"); diff --git a/src/main/java/net/sf/jabref/model/database/BibDatabase.java b/src/main/java/net/sf/jabref/model/database/BibDatabase.java index 0577627e11e6..98a8d257f101 100644 --- a/src/main/java/net/sf/jabref/model/database/BibDatabase.java +++ b/src/main/java/net/sf/jabref/model/database/BibDatabase.java @@ -487,6 +487,8 @@ private String resolveContent(String result, Set usedIds) { return res; } + + /** * Returns the text stored in the given field of the given bibtex entry * which belongs to the given database. @@ -497,15 +499,15 @@ private String resolveContent(String result, Set usedIds) { * unset fields in the entry linked by the "crossref" field, if any. * * @param field The field to return the value of. - * @param entry maybenull - * The bibtex entry which contains the field. + * @param entry The bibtex entry which contains the field. * @param database maybenull * The database of the bibtex entry. * @return The resolved field value or null if not found. */ - public static String getResolvedField(String field, BibEntry entry, BibDatabase database) { + public static Optional getResolvedField(String field, BibEntry entry, BibDatabase database) { + Objects.requireNonNull(entry, "entry cannot be null"); if ("bibtextype".equals(field)) { - return EntryUtil.capitalizeFirst(entry.getType()); + return Optional.of(EntryUtil.capitalizeFirst(entry.getType())); } // TODO: Changed this to also consider alias fields, which is the expected @@ -527,7 +529,7 @@ public static String getResolvedField(String field, BibEntry entry, BibDatabase } } - return BibDatabase.getText(result.orElse(null), database); + return result.map(resultText -> BibDatabase.getText(resultText, database)); } /** diff --git a/src/main/java/net/sf/jabref/model/database/DuplicationChecker.java b/src/main/java/net/sf/jabref/model/database/DuplicationChecker.java index df1cc9a5ed46..b21ebce17421 100644 --- a/src/main/java/net/sf/jabref/model/database/DuplicationChecker.java +++ b/src/main/java/net/sf/jabref/model/database/DuplicationChecker.java @@ -55,11 +55,11 @@ public boolean checkForDuplicateKeyAndAdd(String oldKey, String newKey) { * Returns the number of occurrences of the given key in this database. */ public int getNumberOfKeyOccurrences(String key) { - Object o = allKeys.get(key); - if (o == null) { + Integer numberOfOccurrences = allKeys.get(key); + if (numberOfOccurrences == null) { return 0; } else { - return (Integer) o; + return numberOfOccurrences; } } diff --git a/src/main/java/net/sf/jabref/model/database/EntrySorter.java b/src/main/java/net/sf/jabref/model/database/EntrySorter.java index 1d078cd79f82..e71d9fc9c0e3 100644 --- a/src/main/java/net/sf/jabref/model/database/EntrySorter.java +++ b/src/main/java/net/sf/jabref/model/database/EntrySorter.java @@ -22,13 +22,8 @@ import net.sf.jabref.model.entry.BibEntry; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - public class EntrySorter { - private static final Log LOGGER = LogFactory.getLog(EntrySorter.class); - // guarded by itself private final List entries; diff --git a/src/main/java/net/sf/jabref/model/entry/BibEntry.java b/src/main/java/net/sf/jabref/model/entry/BibEntry.java index 5b3dd644ec9b..bbec8b8b35eb 100644 --- a/src/main/java/net/sf/jabref/model/entry/BibEntry.java +++ b/src/main/java/net/sf/jabref/model/entry/BibEntry.java @@ -421,7 +421,7 @@ public boolean allFieldsPresent(List allFields, BibDatabase database) { return false; } } else { - if (BibDatabase.getResolvedField(fieldName, this, database) == null) { + if (!BibDatabase.getResolvedField(fieldName, this, database).isPresent()) { return false; } } @@ -433,8 +433,8 @@ private boolean atLeastOnePresent(String[] fieldsToCheck, BibDatabase database) for (String field : fieldsToCheck) { String fieldName = toLowerCase(field); - String value = BibDatabase.getResolvedField(fieldName, this, database); - if ((value != null) && !value.isEmpty()) { + Optional value = BibDatabase.getResolvedField(fieldName, this, database); + if ((value.isPresent()) && !value.get().isEmpty()) { return true; } } diff --git a/src/main/java/net/sf/jabref/pdfimport/PdfImporter.java b/src/main/java/net/sf/jabref/pdfimport/PdfImporter.java index 51b3eb4966ae..23b51031bac8 100644 --- a/src/main/java/net/sf/jabref/pdfimport/PdfImporter.java +++ b/src/main/java/net/sf/jabref/pdfimport/PdfImporter.java @@ -19,7 +19,6 @@ 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; @@ -45,6 +44,7 @@ import net.sf.jabref.logic.labelpattern.LabelPatternUtil; import net.sf.jabref.logic.util.UpdateField; import net.sf.jabref.logic.util.io.FileUtil; +import net.sf.jabref.logic.xmp.XMPPreferences; import net.sf.jabref.logic.xmp.XMPUtil; import net.sf.jabref.model.database.KeyCollisionException; import net.sf.jabref.model.entry.BibEntry; @@ -111,11 +111,11 @@ public List getEntries() { * @param fileNames states the names of the files to import * @return list of successful created BibTeX entries and list of non-PDF files */ - public ImportPdfFilesResult importPdfFiles(String[] fileNames) { + public ImportPdfFilesResult importPdfFiles(List fileNames) { // sort fileNames in PDFfiles to import and other files // PDFfiles: variable files // other files: variable noPdfFiles - List files = new ArrayList<>(Arrays.asList(fileNames)); + List files = new ArrayList<>(fileNames); List noPdfFiles = new ArrayList<>(); PdfFileFilter pdfFilter = PdfFileFilter.INSTANCE; for (String file : files) { @@ -127,7 +127,7 @@ public ImportPdfFilesResult importPdfFiles(String[] fileNames) { // files and noPdfFiles correctly sorted // import the files - List entries = importPdfFiles(files); + List entries = importPdfFilesInternal(files); return new ImportPdfFilesResult(noPdfFiles, entries); } @@ -136,7 +136,7 @@ public ImportPdfFilesResult importPdfFiles(String[] fileNames) { * @param fileNames - PDF files to import * @return true if the import succeeded, false otherwise */ - private List importPdfFiles(List fileNames) { + private List importPdfFilesInternal(List fileNames) { if (panel == null) { return Collections.emptyList(); } @@ -151,7 +151,7 @@ private List importPdfFiles(List fileNames) { for (String fileName : fileNames) { if (!neverShow && !doNotShowAgain) { importDialog = new ImportDialog(dropRow >= 0, fileName); - if (!XMPUtil.hasMetadata(Paths.get(fileName), Globals.prefs)) { + if (!XMPUtil.hasMetadata(Paths.get(fileName), XMPPreferences.fromPreferences(Globals.prefs))) { importDialog.disableXMPChoice(); } importDialog.setLocationRelativeTo(frame); diff --git a/src/main/java/net/sf/jabref/preferences/JabRefPreferences.java b/src/main/java/net/sf/jabref/preferences/JabRefPreferences.java index b77717a24158..192b348bd1ca 100644 --- a/src/main/java/net/sf/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/net/sf/jabref/preferences/JabRefPreferences.java @@ -194,8 +194,6 @@ public class JabRefPreferences { public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CA = "editorEMACSkeyBindingsRebindCA"; public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CF = "editorEMACSkeyBindingsRebindCF"; public static final String GROUP_SHOW_NUMBER_OF_ELEMENTS = "groupShowNumberOfElements"; - public static final String GROUP_AUTO_HIDE = "groupAutoHide"; - public static final String GROUP_AUTO_SHOW = "groupAutoShow"; public static final String GROUP_EXPAND_TREE = "groupExpandTree"; public static final String GROUP_SHOW_DYNAMIC = "groupShowDynamic"; public static final String GROUP_SHOW_ICONS = "groupShowIcons"; @@ -617,8 +615,6 @@ private JabRefPreferences() { defaults.put(GROUP_SHOW_ICONS, Boolean.TRUE); defaults.put(GROUP_SHOW_DYNAMIC, Boolean.TRUE); defaults.put(GROUP_EXPAND_TREE, Boolean.TRUE); - defaults.put(GROUP_AUTO_SHOW, Boolean.TRUE); - defaults.put(GROUP_AUTO_HIDE, Boolean.TRUE); defaults.put(GROUP_SHOW_NUMBER_OF_ELEMENTS, Boolean.FALSE); defaults.put(AUTO_ASSIGN_GROUP, Boolean.TRUE); defaults.put(KEYWORD_SEPARATOR, ", "); diff --git a/src/main/resources/l10n/JabRef_da.properties b/src/main/resources/l10n/JabRef_da.properties index 144bf454a830..11c39e370628 100644 --- a/src/main/resources/l10n/JabRef_da.properties +++ b/src/main/resources/l10n/JabRef_da.properties @@ -75,10 +75,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Autolink_kun_filer_med_navn_som_sv Automatically_create_groups=Generer_grupper_automatisk Automatically_create_groups_for_database.=Generer_grupper_for_databasen. Automatically_created_groups=Genererede_grupper_automatisk -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Skjul_automatisk_grupperingspanel_når_du_skifter_til_en_database,_som_ikke_indeholder_grupper - Automatically_remove_exact_duplicates=Fjern_eksakte_dubletter_automatisk -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Vis_automatisk_grupperingspanel_når_du_skifter_til_en_database,_som_indeholder_grupper Allow_overwriting_existing_links.=Tillad_overskrivning_af_eksisterende_links. Do_not_overwrite_existing_links.=Overskriv_ikke_eksisterende_links. AUX_file_import=AUX-fil_import @@ -1715,5 +1712,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_de.properties b/src/main/resources/l10n/JabRef_de.properties index 40828f79217b..65c2a3547e53 100644 --- a/src/main/resources/l10n/JabRef_de.properties +++ b/src/main/resources/l10n/JabRef_de.properties @@ -141,13 +141,8 @@ Automatically_create_groups_for_database.=Automatisch_Gruppen_für_die_Datei_anl Automatically_created_groups=Automatisch_erzeugte_Gruppen -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Gruppenansicht_automatisch_ausblenden,_wenn_zu_einer_Datei_ohne_Gruppen_gewechselt_wird - - Automatically_remove_exact_duplicates=Exakte_Duplikate_automatisch_löschen -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Gruppenansicht_automatisch_einblenden,_wenn_zu_einer_Datei_mit_Gruppen_gewechselt_wird - Allow_overwriting_existing_links.=Vorhandene_Links_überschreiben. @@ -2434,5 +2429,6 @@ Error_occured_while_executing_the_command_\"%0\".=Während_der_Ausführung_des_B Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index abee2e515b31..ac361344f49c 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -135,12 +135,8 @@ Automatically_create_groups_for_database.=Automatically_create_groups_for_databa Automatically_created_groups=Automatically_created_groups -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups - Automatically_remove_exact_duplicates=Automatically_remove_exact_duplicates -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups - Allow_overwriting_existing_links.=Allow_overwriting_existing_links. Do_not_overwrite_existing_links.=Do_not_overwrite_existing_links. @@ -2273,7 +2269,7 @@ Latest_version=Latest_version Online_help_forum=Online_help_forum Custom=Custom -Generate_new_BIB_database=Generate_new_BIB_database +Export_cited=Export_cited Unable_to_generate_new_database=Unable_to_generate_new_database Open_console=Open_console diff --git a/src/main/resources/l10n/JabRef_es.properties b/src/main/resources/l10n/JabRef_es.properties index 30459a6ba858..8d7bed7603e0 100644 --- a/src/main/resources/l10n/JabRef_es.properties +++ b/src/main/resources/l10n/JabRef_es.properties @@ -73,9 +73,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Autoenlazar_sólo_archivos_cuyo_no Automatically_create_groups=Crear_grupos_automáticamente Automatically_create_groups_for_database.=Crear_grupos_para_base_de_datos_automáticamente Automatically_created_groups=Grupos_automáticamente_creados -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Ocultar_automáticamente_el_interfaz_de_grupos_cuando_se_cambie_a_una_base_de_datos_que_no_contenga_grupos Automatically_remove_exact_duplicates=Eliminar_automáticamente_duplicados_exactos -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Mostrar_automáticamente_el_interfaz_de_grupos_cuando_se_cambie_a_una_base_de_datos_que_contenga_grupos Allow_overwriting_existing_links.=Permitir_sobreescribir_enlaces_existentes. Do_not_overwrite_existing_links.=No_sobreescribir_enlaces_existentes. AUX_file_import=Importar_archivo_AUX @@ -1617,5 +1615,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_fa.properties b/src/main/resources/l10n/JabRef_fa.properties index 0ee67fe7b2bd..67f97675c867 100644 --- a/src/main/resources/l10n/JabRef_fa.properties +++ b/src/main/resources/l10n/JabRef_fa.properties @@ -139,16 +139,8 @@ Automatically_create_groups_for_database.= Automatically_created_groups= -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups= - Automatically_remove_exact_duplicates= -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups= - - - - - AUX_file_import= Available_export_formats= @@ -2403,5 +2395,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_fr.properties b/src/main/resources/l10n/JabRef_fr.properties index 77c262e05be1..bd900c9b4682 100644 --- a/src/main/resources/l10n/JabRef_fr.properties +++ b/src/main/resources/l10n/JabRef_fr.properties @@ -44,8 +44,8 @@ All_entries=Toutes_les_entrées All_entries_of_this_type_will_be_declared_typeless._Continue?=Toutes_les_entrées_de_ce_type_seront_déclarées_'sans_type'._Continuer_? All_fields=Tous_les_champs All_subgroups_(recursively)=Tous_les_sous-groupes_(récursivement) -An_exception_occurred_while_accessing_'%0'=Une_Exception_est_survenue_lors_de_l'accès_à_'%0' -A_SAX_exception_occurred_while_parsing_'%0'\:=Une_Exception_SAX_est_survenue_pendant_le_traitement_de_'%0'_\: +An_exception_occurred_while_accessing_'%0'=Une_exception_est_survenue_lors_de_l'accès_à_'%0' +A_SAX_exception_occurred_while_parsing_'%0'\:=Une_exception_SAX_est_survenue_pendant_le_traitement_de_'%0'_\: and=et and_the_class_must_be_available_in_your_classpath_next_time_you_start_JabRef.=et_la_classe_doit_être_disponible_dans_votre_chemin_de_classe_la_prochaine_fois_que_vous_démarrez_JabRef. any_field_that_matches_the_regular_expression_%0=tout_champ_qui_correspond_à_l'expression_régulière_%0 @@ -73,9 +73,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Lier_automatiquement_les_fichiers_ Automatically_create_groups=Créer_automatiquement_des_groupes Automatically_create_groups_for_database.=Créer_automatiquement_des_groupes_pour_la_base. Automatically_created_groups=Groupes_créés_automatiquement -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Masquer_automatiquement_l'interface_des_groupes_lors_de_l'affichage_d'une_base_de_données_qui_ne_contient_pas_de_groupes Automatically_remove_exact_duplicates=Supprimer_automatiquement_les_doublons_identiques -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Afficher_automatiquement_l'interface_des_groupes_lors_de_l'affichage_d'une_base_de_données_qui_contient_des_groupes Allow_overwriting_existing_links.=Ecraser_les_liens_existants. Do_not_overwrite_existing_links.=Ne_pas_écraser_les_liens_existants. AUX_file_import=Importation_de_fichier_AUX @@ -430,7 +428,7 @@ Mark_entries=Etiqueter_ces_entrées Mark_entry=Etiqueter_l'entrée Mark_new_entries_with_addition_date=Enregistrer_la_date_d'ajout_pour_les_nouvelles_entrées Mark_new_entries_with_owner_name=Nouvelles_entrées_attribuées_au_propriétaire -Memory_stick_mode=Mode_Clef_Mémoire +Memory_stick_mode=Mode_clef_mémoire Menu_and_label_font_size=Taille_de_police_pour_les_menus_et_les_champs Merged_external_changes=Fusionner_les_modifications_externes Messages=Messages @@ -676,7 +674,7 @@ Store_journal_abbreviations=Stocker_les_abréviations_de_journaux Stored_entry=Entrée_enregistrée Strings=Chaîne Strings_for_database=Chaînes_pour_la_base -Subdatabase_from_AUX=BibTeX_à_partir_de_LaTex_AUX +Subdatabase_from_AUX=BibTeX_à_partir_de_LaTeX_AUX Switches_between_full_and_abbreviated_journal_name_if_the_journal_name_is_known.=Basculer_entre_les_noms_de_journaux_développés_et_abrégés_si_le_nom_de_journal_est_connu. Synchronize_file_links=Synchroniser_les_liens_vers_les_fichiers Synchronizing_file_links...=Synchronisation_des_liens_fichier... @@ -1227,7 +1225,7 @@ illegal_backslash_expression=Expression_avec_barre_oblique_inversée_(\\)_illég Move_to_group=Déplacer_vers_le_groupe Clear_read_status=Effacer_le_statut_de_lecture -Convert_to_BibLatex_format_(for_example,_move_the_value_of_the_'journal'_field_to_'journaltitle')=Convertir_au_format_BibLatex_(par_exemple,_transformer_la_valeur_du_champ_'journal'_en_'journaltitle') +Convert_to_BibLatex_format_(for_example,_move_the_value_of_the_'journal'_field_to_'journaltitle')=Convertir_au_format_BibLaTeX_(par_exemple,_transformer_la_valeur_du_champ_'journal'_en_'journaltitle') Could_not_apply_changes.=Les_changements_n'ont_pas_pu_être_effectués. Deprecated_fields=Champs_obsolètes Hide/show_toolbar=Masquer/afficher_la_barre_d'outils @@ -1278,7 +1276,7 @@ Cannot_get_info_based_on_given_DOI\:_%0=Aucune_information_disponible_à_partir_ Entry_from_DOI=Entrée_à_partir_du_DOI Fetching_info_based_on_DOI=Recherche_d'informations_à_partir_du_DOI Follow_DOI_or_URL_link_and_try_to_locate_PDF_full_text_document=Suivre_le_DOI_ou_le_lien_URL,_et_essayer_de_trouver_le_document_complet_en_PDF -Get_BibTeX_data_from_DOI=Récupérer_les_données_BibTEX_à_partir_du_DOI +Get_BibTeX_data_from_DOI=Récupérer_les_données_BibTeX_à_partir_du_DOI Left_entry=Entrée_de_gauche Merge_entry_with_DOI_information=Fusionner_l'entrée_sur_la_base_des_informations_du_DOI No_information_added=Aucune_information_ajoutée @@ -1477,7 +1475,7 @@ Usage=Usage Are_you_sure_you_want_to_reset_all_settings_to_default_values?=Etes-vous_sûr_de_vouloir_rétablir_toutes_les_valeurs_par_défaut_du_paramétrage_? Reset_preferences=Rétablir_les_préférences -Ill-formed_entrytype_comment_in_BIB_file=Commentaire_de_type_d'entrées_mal_construit_dans_un_fichier_bib +Ill-formed_entrytype_comment_in_BIB_file=Commentaire_de_type_d'entrées_mal_construit_dans_un_fichier_BIB Clipboard=Presse-papiers Could_not_paste_entry_as_text\:=L'entrée_n'a_pas_pu_être_collée_comme_du_texte_: Do_you_still_want_to_continue?=Voulez-vous_continuer_? @@ -1646,20 +1644,18 @@ Please_open_%0_manually.=Ouvrez_%0_manuellement,_SVP. The_link_has_been_copied_to_the_clipboard.=Le_lien_a_été_copié_dans_le_presse-papiers. -Online_help_forum= +Online_help_forum=Forum_d'aide_en_ligne -Custom= +Custom=Personnalisé -Converts_HTML_code_to_Unicode.= +Converts_HTML_code_to_Unicode.=Convertit_du_code_HTML_en_Unicode. -Open_console= -Use_default_terminal_emulator= -Execute_command= -Note\:_Use_the_placeholder_%0_for_the_location_of_the_opened_database_file.= -Executing_command_\"%0\"...= -Error_occured_while_executing_the_command_\"%0\".= - -Reformat_ISSN= - -Generate_new_BIB_database= -Unable_to_generate_new_database= +Open_console=Ouvrir_la_console +Use_default_terminal_emulator=Utilise_l'émulateur_de_terminal_par_défaut +Execute_command=Lance_une_commande +Note\:_Use_the_placeholder_%0_for_the_location_of_the_opened_database_file.=Note_:_Utiliser_le_paramètre_%0_comme_localisation_du_fichier_de_la_base_de_données_ouverte. +Executing_command_\"%0\"...=Exécution_de_la_commande_\"%0\"... +Error_occured_while_executing_the_command_\"%0\".=Une_erreur_est_survenue_lors_de_l'exécution_de_la_commande_\"%0\". +Reformat_ISSN=Reformater_l'ISSN +Unable_to_generate_new_database=Impossible_de_générer_une_nouvelle_base_de_données +Export_cited= diff --git a/src/main/resources/l10n/JabRef_in.properties b/src/main/resources/l10n/JabRef_in.properties index 4e59d22be41c..96dd54c5b866 100644 --- a/src/main/resources/l10n/JabRef_in.properties +++ b/src/main/resources/l10n/JabRef_in.properties @@ -73,9 +73,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Tautan_otomatis_hanya_pada_berkas_ Automatically_create_groups=Otomatis_membuat_grup Automatically_create_groups_for_database.=Otomatis_membuat_grup_untuk_basisdata. Automatically_created_groups=Grup_yang_dibuat_otomatis -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Otomatis_sembunyikan_antarmuka_grup_ketika_merubah_ke_basisdata_yang_tidak_punya_grup Automatically_remove_exact_duplicates=Otomatis_menghapus_yang_sama -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Otomatis_menampilkan_antarmuka_grup_ketika_merubah_ke_basisdata_yang_mempunyai_grup Allow_overwriting_existing_links.=Mengijinkan_menindih_tautan_yang_ada. Do_not_overwrite_existing_links.=Tidak_boleh_menindih_tautan_yang_ada. AUX_file_import=Impor_berkas_AUX @@ -1636,5 +1634,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_it.properties b/src/main/resources/l10n/JabRef_it.properties index 076102b2c2ab..f3bdb3595e63 100644 --- a/src/main/resources/l10n/JabRef_it.properties +++ b/src/main/resources/l10n/JabRef_it.properties @@ -75,10 +75,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Collegare_automaticamente_solo_i_f Automatically_create_groups=Crea_automaticamente_i_gruppi Automatically_create_groups_for_database.=Crea_automaticamente_i_gruppi_per_il_database Automatically_created_groups=Gruppi_creati_automaticamente -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Nascondi_automaticamente_l'interfaccia_dei_gruppi_nel_passare_ad_un_database_che_non_contiene_gruppi - Automatically_remove_exact_duplicates=Rimuovi_automaticamente_i_duplicati_esatti -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Mostra_automaticamente_l'interfaccia_dei_gruppi_nel_passare_ad_un_database_che_contiene_gruppi Allow_overwriting_existing_links.=Consenti_la_sovrascrittura_dei_collegamenti_esistenti. Do_not_overwrite_existing_links.=Non_consentire_la_sovrascrittura_dei_collegamenti_esistenti. AUX_file_import=Importa_file_AUX @@ -1736,5 +1733,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_ja.properties b/src/main/resources/l10n/JabRef_ja.properties index 8e531d057c91..f0654a9aabd4 100644 --- a/src/main/resources/l10n/JabRef_ja.properties +++ b/src/main/resources/l10n/JabRef_ja.properties @@ -140,15 +140,8 @@ Automatically_create_groups_for_database.=データベースのグループを Automatically_created_groups=グループを自動生成しました -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=グループを含まないデータベースに切り替えた際、グループインタフェースを自動的に非表示 - Automatically_remove_exact_duplicates=完全な重複を自動的に削除する -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=グループを含むデータベースに切り替えた際、グループインタフェースを自動的に表示 - - - - AUX_file_import=AUXファイルの読み込み Available_export_formats=使用できる書き出し書式 @@ -2381,5 +2374,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_nl.properties b/src/main/resources/l10n/JabRef_nl.properties index dc269b04bca2..d9c02876ee68 100644 --- a/src/main/resources/l10n/JabRef_nl.properties +++ b/src/main/resources/l10n/JabRef_nl.properties @@ -141,13 +141,8 @@ Automatically_create_groups_for_database.=Automatisch_groepen_voor_database_aanm Automatically_created_groups=Automatisch_aangemaakte_groepen -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Verberg_automatisch_het_groepenvenster_bij_overgang_naar_een_database_die_geen_groepen_bevat - Automatically_remove_exact_duplicates=Automatisch_exacte_kopie\u00ebn_verwijderen -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Toon_automatisch_het_groepenvenster_bij_overgang_naar_een_database_die_groepen_bevat - - Allow_overwriting_existing_links.=Overschrijven_van_bestaande_snelkoppelingen_toestaan. Do_not_overwrite_existing_links.=Overschrijven_van_bestaande_snelkoppelingen_niet_toestaan. @@ -2412,5 +2407,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_no.properties b/src/main/resources/l10n/JabRef_no.properties index f47172b0f77c..a6a4d4e7d52c 100644 --- a/src/main/resources/l10n/JabRef_no.properties +++ b/src/main/resources/l10n/JabRef_no.properties @@ -153,13 +153,7 @@ Automatically_create_groups_for_database.=Generer_grupper_for_databasen. Automatically_created_groups=Genererte_grupper_automatisk -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Skjul_automatisk_grupperingskontroll_n\u00e5_du_bytter_til_en_database_som_ikke_inneholder_grupper - Automatically_remove_exact_duplicates=Fjern_eksakte_duplikater_automatisk - -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Vis_automatisk_grupperingskontroll_n\u00e5_du_bytter_til_en_database_som_inneholder_grupper - - Allow_overwriting_existing_links.=Tillat_overskriving_av_eksisterende_linker. Do_not_overwrite_existing_links.=Skriv_ikke_over_eksisterende_linker. @@ -2808,5 +2802,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_pt_BR.properties b/src/main/resources/l10n/JabRef_pt_BR.properties index 44ef89b41c18..f62877912da2 100644 --- a/src/main/resources/l10n/JabRef_pt_BR.properties +++ b/src/main/resources/l10n/JabRef_pt_BR.properties @@ -73,9 +73,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Criar_links_automaticamente_soment Automatically_create_groups=Criar_grupos_automaticamente Automatically_create_groups_for_database.=Criar_grupos_automaticamente_para_a_base_de_dados. Automatically_created_groups=Grupos_criados_automaticamente -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Esconder_automaticamente_a_interface_de_grupos_quando_trocar_para_uma_base_de_dados_sem_grupos Automatically_remove_exact_duplicates=Remover_automaticamente_duplicatas_exatas -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Exibir_automaticamente_a_interface_de_grupos_quando_trocar_para_uma_base_de_dados_que_contém_grupos Allow_overwriting_existing_links.=Sobrescrever_links_existentes. Do_not_overwrite_existing_links.=Não_sobrescrever_links_existentes. AUX_file_import=Importação_de_arquivos_AUX @@ -1630,5 +1628,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_ru.properties b/src/main/resources/l10n/JabRef_ru.properties index c0da9f62c5d5..6825ceff5cc1 100644 --- a/src/main/resources/l10n/JabRef_ru.properties +++ b/src/main/resources/l10n/JabRef_ru.properties @@ -126,13 +126,8 @@ Automatically_create_groups_for_database.=Автоматическое_созд Automatically_created_groups=Автоматически_созданные_группы -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Автоматически_скрывать_интерфейс_групп_при_переключении_на_БД,_не_содержащую_групп - Automatically_remove_exact_duplicates=Автоматически_удалять_полные_дубликаты -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Автоматически_показывать_интерфейс_групп_при_переключении_на_БД,_содержащую_группы - - Allow_overwriting_existing_links.=Разрешить_перезапись_текущих_ссылок. Do_not_overwrite_existing_links.=Не_перезаписывать_текущие_ссылки. @@ -2380,5 +2375,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_sv.properties b/src/main/resources/l10n/JabRef_sv.properties index 1a2cf2d768d3..89ebbe7ad886 100644 --- a/src/main/resources/l10n/JabRef_sv.properties +++ b/src/main/resources/l10n/JabRef_sv.properties @@ -112,14 +112,12 @@ Automatically_assign_new_entry_to_selected_groups=Tilldela_automatiskt_nya_poste Automatically_create_groups=Skapa_grupper_automatiskt Automatically_create_groups_for_database.=Skapa_grupper_automatiskt_för_databasen. Automatically_created_groups=Skapade_grupper_automatiskt -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Göm_automatiskt_gruppgränssnittet_när_en_databas_som_inte_innehåller_grupper_blir_aktiv Automatically_open_browse_dialog_when_creating_new_file_link= Automatically_open_folders_of_attached_files= Automatically_remove_exact_duplicates=Ta_bort_exakta_dubbletter_automatiskt Automatically_set_file_links=Skapa_fillänkar_automatiskt Automatically_set_file_links_for_this_entry=Skapa_fillänkar_automatiskt_för_denna_post Automatically_setting_file_links=Skapar_fillänkar_automatiskt -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Visa_automatiskt_gruppgränssnittet_när_en_databas_som_innehåller_grupper_blir_aktiv Automatically_sync_bibliography_when_inserting_citations=Synkronisera_bibliografin_automatiskt_när_citeringar_infogas Autosave=Automatisk_sparning Autosave_interval_(minutes)=Intervall_för_automatisk_sparning_(minuter) @@ -1573,5 +1571,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_tr.properties b/src/main/resources/l10n/JabRef_tr.properties index bf4fe13af268..9217f8e63f65 100644 --- a/src/main/resources/l10n/JabRef_tr.properties +++ b/src/main/resources/l10n/JabRef_tr.properties @@ -73,9 +73,7 @@ Autolink_only_files_that_match_the_BibTeX_key=Yalnızca_BibTeX_anahtarıyla_eşl Automatically_create_groups=Grupları_otomatik_oluştur Automatically_create_groups_for_database.=Veritabanı_için_grupları_otomatik_oluştur Automatically_created_groups=Otomatik_oluşturulmuş_gruplar -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Grup_içermeyen_bir_veritabanına_geçildiğinde_grup_arayüzünü_otomatik_sakla Automatically_remove_exact_duplicates=Tıpkı_çift_nüshaları_otomatik_sil -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Grup_içeren_bir_veritabanına_geçildiğinde_otomatik_olarak_grup_aarayüzünü_göster Allow_overwriting_existing_links.=Mevcut_linklerin_üzerine_yazmaya_izin_ver. Do_not_overwrite_existing_links.=Mevcut_linklerin_üzerine_yazma. AUX_file_import=AUX_dosya_içe_aktarımı @@ -1649,5 +1647,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_vi.properties b/src/main/resources/l10n/JabRef_vi.properties index d051993f2c74..af4c17b44353 100644 --- a/src/main/resources/l10n/JabRef_vi.properties +++ b/src/main/resources/l10n/JabRef_vi.properties @@ -140,13 +140,8 @@ Automatically_create_groups_for_database.=Tự_động_tạo_các_nhóm_dùng_ch Automatically_created_groups=Các_nhóm_được_tạo_ra_tự_động -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=Tự_động_ẩn_đi_giao_diện_nhóm_khi_chuyển_qua_một_CSDL_không_chứa_nhóm - Automatically_remove_exact_duplicates=Tự_động_loại_bỏ_các_mục_trùng_nhau -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=Tự_động_hiển_thị_giao_diện_nhóm_khi_chuyển_qua_một_CSDL_chứa_nhóm - - Allow_overwriting_existing_links.=Cho_phép_ghi_đè_các_liên_kết_hiện_có. Do_not_overwrite_existing_links.=Không_ghi_đè_các_liên_kết_hiện_có. @@ -2404,5 +2399,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/main/resources/l10n/JabRef_zh.properties b/src/main/resources/l10n/JabRef_zh.properties index e1d69de28e18..1b3cf7f782f6 100644 --- a/src/main/resources/l10n/JabRef_zh.properties +++ b/src/main/resources/l10n/JabRef_zh.properties @@ -75,10 +75,8 @@ Autolink_only_files_that_match_the_BibTeX_key=自动链接文件名匹配_BibTeX Automatically_create_groups=自动创建分组 Automatically_create_groups_for_database.=自动为数据库创建分组。 Automatically_created_groups=自动创建的分组 -Automatically_hide_groups_interface_when_switching_to_a_database_that_contains_no_groups=当切换到一个不包含分组的数据库时自动隐藏分组界面 Automatically_remove_exact_duplicates=自动移除完全重复的项 Automatically_setting_file_links=自动设置文件链接 -Automatically_show_groups_interface_when_switching_to_a_database_that_contains_groups=当切换到一个包含分组的数据库时自动打开分组界面 Available_BibTeX_fields=可用的_BibTeX_域 Available_export_formats=可用的导出格式 Available_import_formats=可用的导入格式 @@ -1643,5 +1641,6 @@ Error_occured_while_executing_the_command_\"%0\".= Reformat_ISSN= -Generate_new_BIB_database= Unable_to_generate_new_database= + +Export_cited= diff --git a/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java b/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java index 7ee12e7891ff..02a13091c3a3 100644 --- a/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java +++ b/src/test/java/net/sf/jabref/cli/AuxCommandLineTest.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import net.sf.jabref.Globals; @@ -29,7 +30,7 @@ public void test() throws URISyntaxException, IOException { InputStream originalStream = AuxCommandLineTest.class.getResourceAsStream("origin.bib"); File auxFile = Paths.get(AuxCommandLineTest.class.getResource("paper.aux").toURI()).toFile(); - try (InputStreamReader originalReader = new InputStreamReader(originalStream)) { + try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { ParserResult result = BibtexParser.parse(originalReader); AuxCommandLine auxCommandLine = new AuxCommandLine(auxFile.getAbsolutePath(), result.getDatabase()); diff --git a/src/test/java/net/sf/jabref/cli/JabRefCLITest.java b/src/test/java/net/sf/jabref/cli/JabRefCLITest.java index 522b8d64daed..e3c8d1d5b9cf 100644 --- a/src/test/java/net/sf/jabref/cli/JabRefCLITest.java +++ b/src/test/java/net/sf/jabref/cli/JabRefCLITest.java @@ -1,6 +1,6 @@ package net.sf.jabref.cli; -import java.util.Arrays; +import java.util.Collections; import org.junit.Assert; import org.junit.Test; @@ -11,7 +11,7 @@ public class JabRefCLITest { public void testCLIParsingLongOptions() { JabRefCLI cli = new JabRefCLI(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"}); - Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver())); + Assert.assertEquals(Collections.emptyList(), cli.getLeftOver()); Assert.assertEquals("some/file", cli.getFileImport()); Assert.assertTrue(cli.isDisableGui()); Assert.assertEquals("some/export/file", cli.getFileExport()); @@ -21,7 +21,7 @@ public void testCLIParsingLongOptions() { public void testCLIParsingShortOptions() { JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-i=some/file", "-o=some/export/file"}); - Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver())); + Assert.assertEquals(Collections.emptyList(), cli.getLeftOver()); Assert.assertEquals("some/file", cli.getFileImport()); Assert.assertTrue(cli.isDisableGui()); Assert.assertEquals("some/export/file", cli.getFileExport()); @@ -31,7 +31,7 @@ public void testCLIParsingShortOptions() { public void testPreferencesExport() { JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-x=some/file"}); - Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver())); + Assert.assertEquals(Collections.emptyList(), cli.getLeftOver()); Assert.assertEquals("some/file", cli.getPreferencesExport()); Assert.assertTrue(cli.isDisableGui()); } diff --git a/src/test/java/net/sf/jabref/importer/fileformat/BibtexParserTest.java b/src/test/java/net/sf/jabref/importer/fileformat/BibtexParserTest.java index eca39f20a5ac..25298f91446e 100644 --- a/src/test/java/net/sf/jabref/importer/fileformat/BibtexParserTest.java +++ b/src/test/java/net/sf/jabref/importer/fileformat/BibtexParserTest.java @@ -630,9 +630,9 @@ public void parseRecognizesDuplicateBibtexKeys() throws IOException { .parse(new StringReader("@article{canh05," + " author = {Crowston, K. and Annabi, H.},\n" + " title = {Title A}}\n" + "@inProceedings{canh05," + " author={Norton Bar}}")); - String[] duplicateKeys = result.getDuplicateKeys(); - assertEquals(1, duplicateKeys.length); - assertEquals("canh05", duplicateKeys[0]); + List duplicateKeys = result.getDuplicateKeys(); + assertEquals(1, duplicateKeys.size()); + assertEquals("canh05", duplicateKeys.get(0)); } @Test diff --git a/src/test/java/net/sf/jabref/importer/fileformat/MedlinePlainImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/MedlinePlainImporterTest.java index 8c7aed816e9f..42ccccf48662 100644 --- a/src/test/java/net/sf/jabref/importer/fileformat/MedlinePlainImporterTest.java +++ b/src/test/java/net/sf/jabref/importer/fileformat/MedlinePlainImporterTest.java @@ -19,11 +19,13 @@ import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.preferences.JabRefPreferences; +import org.apache.commons.codec.Charsets; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class MedlinePlainImporterTest { @@ -197,6 +199,30 @@ public void testWithNbibFile() throws IOException, URISyntaxException { BibEntryAssert.assertEquals(MedlinePlainImporter.class, "NbibImporterTest.bib", entries); } + @Test + public void testWithMultipleEntries() throws IOException, URISyntaxException { + Path file = Paths + .get(MedlinePlainImporter.class.getResource("MedlinePlainImporterStringOutOfBounds.txt").toURI()); + List entries = importer.importDatabase(file, Charsets.UTF_8).getDatabase().getEntries(); + BibEntryAssert.assertEquals(MedlinePlainImporter.class, "MedlinePlainImporterStringOutOfBounds.bib", entries); + } + + @Test + public void testInvalidFormat() throws URISyntaxException, IOException { + Path file = Paths + .get(MedlinePlainImporter.class.getResource("MedlinePlainImporterTestInvalidFormat.xml").toURI()); + List entries = importer.importDatabase(file, Charsets.UTF_8).getDatabase().getEntries(); + assertEquals(Collections.emptyList(), entries); + } + + @Test(expected = NullPointerException.class) + public void testNullReader() throws IOException { + try (BufferedReader reader = null) { + importer.importDatabase(reader); + } + fail(); + } + @Test public void testAllArticleTypes() throws IOException { try (BufferedReader reader = readerForString("PMID-22664795" + "\n" + diff --git a/src/test/java/net/sf/jabref/importer/fileformat/PdfContentImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/PdfContentImporterTest.java index 6c39de1e9ebe..97bd858ac5c2 100644 --- a/src/test/java/net/sf/jabref/importer/fileformat/PdfContentImporterTest.java +++ b/src/test/java/net/sf/jabref/importer/fileformat/PdfContentImporterTest.java @@ -1,6 +1,5 @@ package net.sf.jabref.importer.fileformat; -import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Path; @@ -30,8 +29,7 @@ public void testGetDescription() { } @Test - public void doesNotHandleEncryptedPdfs() throws IOException, URISyntaxException { - PdfContentImporter importer = new PdfContentImporter(); + public void doesNotHandleEncryptedPdfs() throws URISyntaxException { Path file = Paths.get(PdfContentImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List result = importer.importDatabase(file, Charset.defaultCharset()).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); diff --git a/src/test/java/net/sf/jabref/importer/fileformat/PdfXmpImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/PdfXmpImporterTest.java index ab6147538e20..6d79b29ef8f4 100644 --- a/src/test/java/net/sf/jabref/importer/fileformat/PdfXmpImporterTest.java +++ b/src/test/java/net/sf/jabref/importer/fileformat/PdfXmpImporterTest.java @@ -49,14 +49,14 @@ public void testGetDescription() { } @Test - public void importEncryptedFileReturnsError() throws IOException, URISyntaxException { + public void importEncryptedFileReturnsError() throws URISyntaxException { Path file = Paths.get(PdfXmpImporterTest.class.getResource("/pdfs/encrypted.pdf").toURI()); ParserResult result = importer.importDatabase(file, Charset.defaultCharset()); Assert.assertTrue(result.hasWarnings()); } @Test - public void testImportEntries() throws IOException, URISyntaxException { + public void testImportEntries() throws URISyntaxException { Path file = Paths.get(PdfXmpImporterTest.class.getResource("annotated.pdf").toURI()); List bibEntries = importer.importDatabase(file, Charset.defaultCharset()).getDatabase().getEntries(); diff --git a/src/test/java/net/sf/jabref/logic/groups/GroupsUtilTest.java b/src/test/java/net/sf/jabref/logic/groups/GroupsUtilTest.java index 00bcff94b263..7f581108ff4c 100644 --- a/src/test/java/net/sf/jabref/logic/groups/GroupsUtilTest.java +++ b/src/test/java/net/sf/jabref/logic/groups/GroupsUtilTest.java @@ -1,7 +1,10 @@ package net.sf.jabref.logic.groups; -import java.io.FileReader; +import java.io.BufferedReader; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -33,7 +36,8 @@ public void tearDown() { @Test public void test() throws IOException { - try (FileReader fr = new FileReader("src/test/resources/testbib/testjabref.bib")) { + try (BufferedReader fr = Files.newBufferedReader(Paths.get("src/test/resources/testbib/testjabref.bib"), + StandardCharsets.UTF_8)) { ParserResult result = BibtexParser.parse(fr); diff --git a/src/test/java/net/sf/jabref/logic/search/SearchQueryTest.java b/src/test/java/net/sf/jabref/logic/search/SearchQueryTest.java index 930b22697f42..55381e0cbabf 100644 --- a/src/test/java/net/sf/jabref/logic/search/SearchQueryTest.java +++ b/src/test/java/net/sf/jabref/logic/search/SearchQueryTest.java @@ -1,6 +1,9 @@ package net.sf.jabref.logic.search; import net.sf.jabref.model.entry.BibEntry; +import net.sf.jabref.model.entry.BibtexEntryTypes; +import net.sf.jabref.model.entry.FieldName; +import net.sf.jabref.model.entry.IdGenerator; import org.junit.Test; @@ -38,4 +41,29 @@ public void testGrammarSearch() { assertTrue(searchQuery.isMatch(entry)); } -} \ No newline at end of file + @Test + public void testGrammarSearchFullEntryLastCharMissing() { + BibEntry entry = new BibEntry(); + entry.setField(FieldName.TITLE, "systematic revie"); + SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false); + assertFalse(searchQuery.isMatch(entry)); + } + + @Test + public void testGrammarSearchFullEntry() { + BibEntry entry = new BibEntry(); + entry.setField(FieldName.TITLE, "systematic review"); + SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false); + assertTrue(searchQuery.isMatch(entry)); + } + + @Test + public void testSearchingForOpenBraketInBooktitle() { + BibEntry e = new BibEntry(IdGenerator.next(), BibtexEntryTypes.INPROCEEDINGS.getName()); + e.setField(FieldName.BOOKTITLE, "Super Conference (SC)"); + + SearchQuery searchQuery = new SearchQuery("booktitle=\"(\"", false, false); + assertTrue(searchQuery.isMatch(e)); + } + +} diff --git a/src/test/java/net/sf/jabref/logic/xmp/XMPSchemaBibtexTest.java b/src/test/java/net/sf/jabref/logic/xmp/XMPSchemaBibtexTest.java index 92c234d85bfa..bf2cf5bbf5b9 100644 --- a/src/test/java/net/sf/jabref/logic/xmp/XMPSchemaBibtexTest.java +++ b/src/test/java/net/sf/jabref/logic/xmp/XMPSchemaBibtexTest.java @@ -2,6 +2,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; @@ -266,7 +267,7 @@ public void testGetTextContent() throws IOException { .bibtexDescription(bibtexString)); Document d = XMLUtil.parse(new ByteArrayInputStream(bibtexString - .getBytes())); + .getBytes(StandardCharsets.UTF_8))); Assert.assertEquals("Beach sand convolution by surf-wave optimzation", XMPSchemaBibtex.getTextContent( 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 11864d22c69c..96d61f9937f7 100644 --- a/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java +++ b/src/test/java/net/sf/jabref/logic/xmp/XMPUtilTest.java @@ -1,10 +1,10 @@ package net.sf.jabref.logic.xmp; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -13,6 +13,8 @@ import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; @@ -27,6 +29,7 @@ import javax.xml.transform.TransformerException; import net.sf.jabref.Globals; +import net.sf.jabref.cli.XMPUtilMain; import net.sf.jabref.importer.ParserResult; import net.sf.jabref.importer.fileformat.BibtexParser; import net.sf.jabref.logic.bibtex.BibEntryWriter; @@ -73,6 +76,8 @@ public class XMPUtilTest { private List privacyFilters; + private XMPPreferences xmpPreferences; + /** * Wrap bibtex-data (...) into an rdf:Description. @@ -239,6 +244,8 @@ public void setUp() throws IOException, COSVisitorException { Globals.prefs = JabRefPreferences.getInstance(); } + xmpPreferences = XMPPreferences.fromPreferences(Globals.prefs); + // Store Privacy Settings prefs = JabRefPreferences.getInstance(); @@ -269,7 +276,7 @@ public void testReadXMPSimple() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex))); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -294,7 +301,7 @@ public void testReadXMPUTF8() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex))); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -320,9 +327,9 @@ public void testPrivacyFilter() throws IOException, TransformerException { prefs.putBoolean("useXmpPrivacyFilter", true); prefs.putStringList(JabRefPreferences.XMP_PRIVACY_FILTERS, Arrays.asList("author", "title", "note")); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, XMPPreferences.fromPreferences(prefs)); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), XMPPreferences.fromPreferences(prefs)); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); @@ -338,9 +345,9 @@ public void testPrivacyFilter() throws IOException, TransformerException { BibEntry e = t1BibtexEntry(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, XMPPreferences.fromPreferences(prefs)); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), XMPPreferences.fromPreferences(prefs)); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); Set ts = x.getFieldNames(); @@ -368,7 +375,7 @@ public void testReadXMPSeq() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex))); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -392,7 +399,7 @@ public void testReadXMPEntryType() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex))); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -465,9 +472,9 @@ public void testReadWriteXMP() throws IOException, TransformerException { BibEntry e = c.iterator().next(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); @@ -489,7 +496,7 @@ public void testNewlineHandling() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(XMPUtilTest.bibtexDescription(bibtex))); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -513,7 +520,7 @@ public void testAttributeRead() throws COSVisitorException, IOException { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(bibtex)); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -523,7 +530,7 @@ public void testAttributeRead() throws COSVisitorException, IOException { @Test public void testEmpty() throws Exception { - Assert.assertEquals(Collections.emptyList(), XMPUtil.readXMP(pdfFile, Globals.prefs)); + Assert.assertEquals(Collections.emptyList(), XMPUtil.readXMP(pdfFile, xmpPreferences)); } @@ -551,7 +558,7 @@ public void testSimpleUpdate() throws Exception { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(s)); // Nothing there yet, but should not crash - Assert.assertEquals(Collections.emptyList(), XMPUtil.readXMP(pdfFile, Globals.prefs)); + Assert.assertEquals(Collections.emptyList(), XMPUtil.readXMP(pdfFile, xmpPreferences)); s = " " + " Acrobat PDFMaker 7.0.7" @@ -571,13 +578,13 @@ public void testSimpleUpdate() throws Exception { // Title is Questionnaire.pdf so the DublinCore fallback should hit // in... - Assert.assertEquals(1, XMPUtil.readXMP(pdfFile, Globals.prefs).size()); + Assert.assertEquals(1, XMPUtil.readXMP(pdfFile, xmpPreferences).size()); { // Now write new packet and check if it was correctly written - XMPUtil.writeXMP(pdfFile, t1BibtexEntry(), null); + XMPUtil.writeXMP(pdfFile, t1BibtexEntry(), null, xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -651,9 +658,9 @@ public void testSimpleUpdate() throws Exception { BibEntry toSet = t1BibtexEntry(); toSet.setField("author", "Pokemon!"); - XMPUtil.writeXMP(pdfFile, toSet, null); + XMPUtil.writeXMP(pdfFile, toSet, null, xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry e = l.get(0); @@ -742,9 +749,9 @@ public void testXMLEscape() throws Exception { BibEntry e = c.iterator().next(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); @@ -786,7 +793,7 @@ public void testXMPreadString() throws Exception { Collection c = result.getDatabase().getEntries(); Assert.assertEquals(2, c.size()); - String xmp = XMPUtil.toXMP(c, null); + String xmp = XMPUtil.toXMP(c, null, xmpPreferences); /* Test minimal syntaxical completeness */ Assert.assertTrue(xmp.indexOf("xpacket") > 0); @@ -804,7 +811,7 @@ public void testXMPreadString() throws Exception { /* Test contents of string */ writeManually(pdfFile, xmp); - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(2, l.size()); @@ -839,7 +846,7 @@ public void testReadMultiple() throws Exception { writeManually(pdfFile, XMPUtilTest.bibtexXPacket(bibtex)); // Read from file - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(2, l.size()); @@ -868,9 +875,9 @@ public void testWriteMultiple() throws IOException, TransformerException { l.add(t2BibtexEntry()); l.add(t3BibtexEntry()); - XMPUtil.writeXMP(pdfFile, l, null, false); + XMPUtil.writeXMP(pdfFile, l, null, false, xmpPreferences); - l = XMPUtil.readXMP(pdfFile, Globals.prefs); + l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(2, l.size()); @@ -893,7 +900,7 @@ public void testWriteMultiple() throws IOException, TransformerException { @Test public void testReadProtectedPDFHasMetaData() throws Exception { try (InputStream is = XMPUtilTest.class.getResourceAsStream("/pdfs/write-protected.pdf")) { - Assert.assertTrue(XMPUtil.hasMetadata(is, Globals.prefs)); + Assert.assertTrue(XMPUtil.hasMetadata(is, xmpPreferences)); } } @@ -903,7 +910,7 @@ public void testReadProtectedPDFHasMetaData() throws Exception { @Test public void testReadProtectedPDFHasCorrectMetaData() throws Exception { try (InputStream is = XMPUtilTest.class.getResourceAsStream("/pdfs/write-protected.pdf")) { - List readEntries = XMPUtil.readXMP(is, Globals.prefs); + List readEntries = XMPUtil.readXMP(is, xmpPreferences); BibEntry entry = new BibEntry(); entry.setType("misc"); @@ -919,7 +926,7 @@ public void testReadWriteDC() throws IOException, TransformerException { List l = new LinkedList<>(); l.add(t3BibtexEntry()); - XMPUtil.writeXMP(pdfFile, l, null, true); + XMPUtil.writeXMP(pdfFile, l, null, true, xmpPreferences); try (PDDocument document = PDDocument.load(pdfFile.getAbsoluteFile())) { if (document.isEncrypted()) { @@ -974,7 +981,7 @@ public void testReadWriteDC() throws IOException, TransformerException { Assert.assertEquals(4, dcSchema.getRelationships().size()); assertEqualsBibtexEntry(t3BibtexEntry(), - XMPUtil.getBibtexEntryFromDublinCore(dcSchema, Globals.prefs).get()); + XMPUtil.getBibtexEntryFromDublinCore(dcSchema, xmpPreferences).get()); } @@ -985,7 +992,7 @@ public void testWriteSingleUpdatesDCAndInfo() throws IOException, TransformerExc List l = new LinkedList<>(); l.add(t3BibtexEntry()); - XMPUtil.writeXMP(pdfFile, l, null, true); + XMPUtil.writeXMP(pdfFile, l, null, true, xmpPreferences); try (PDDocument document = PDDocument.load(pdfFile.getAbsoluteFile())) { if (document.isEncrypted()) { @@ -1040,7 +1047,7 @@ public void testWriteSingleUpdatesDCAndInfo() throws IOException, TransformerExc Assert.assertEquals(4, dcSchema.getRelationships().size()); assertEqualsBibtexEntry(t3BibtexEntry(), - XMPUtil.getBibtexEntryFromDublinCore(dcSchema, Globals.prefs).get()); + XMPUtil.getBibtexEntryFromDublinCore(dcSchema, xmpPreferences).get()); } } @@ -1060,7 +1067,7 @@ public void testReadRawXMP() throws IOException, TransformerException { BibEntry e = c.iterator().next(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); Optional metadata = XMPUtil.readRawXMP(pdfFile); @@ -1103,20 +1110,20 @@ public void testCommandLineSingleBib() throws IOException, TransformerException, // First check conversion from .bib to .xmp File tempBib = File.createTempFile("JabRef", ".bib"); - try (FileWriter fileWriter = new FileWriter(tempBib)) { + try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { fileWriter.write(t1BibtexString()); fileWriter.close(); try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); - XMPUtil.main(new String[] {tempBib.getAbsolutePath()}); + XMPUtilMain.main(new String[] {tempBib.getAbsolutePath()}); System.setOut(oldOut); String xmp = s.toString(); writeManually(pdfFile, xmp); } - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(1, l.size()); assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); @@ -1140,12 +1147,12 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, BibEntry e = t1BibtexEntry(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); - XMPUtil.main(new String[] {pdfFile.getAbsolutePath()}); + XMPUtilMain.main(new String[] {pdfFile.getAbsolutePath()}); System.setOut(oldOut); String bibtex = s.toString(); @@ -1160,12 +1167,12 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, // Write XMP to file BibEntry e = t1BibtexEntry(); - XMPUtil.writeXMP(pdfFile, e, null); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); - XMPUtil.main(new String[] {"-x", pdfFile.getAbsolutePath()}); + XMPUtilMain.main(new String[] {"-x", pdfFile.getAbsolutePath()}); System.setOut(oldOut); s.close(); String xmp = s.toString(); @@ -1185,7 +1192,7 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, /* Test contents of string */ writeManually(pdfFile, xmp); - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(1, l.size()); assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); @@ -1203,7 +1210,7 @@ public void testCommandLineSinglePdf() throws IOException, TransformerException, public void testCommandLineByKey() throws IOException, TransformerException { File tempBib = File.createTempFile("JabRef", ".bib"); - try (FileWriter fileWriter = new FileWriter(tempBib)) { + try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { fileWriter.write(t1BibtexString()); fileWriter.write(t2BibtexString()); @@ -1211,13 +1218,13 @@ public void testCommandLineByKey() throws IOException, TransformerException { PrintStream oldOut = System.out; try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { System.setOut(new PrintStream(s)); - XMPUtil.main(new String[] {"canh05", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); + XMPUtilMain.main(new String[] {"canh05", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); } finally { System.setOut(oldOut); } // PDF should be annotated: - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(1, l.size()); assertEqualsBibtexEntry(t1BibtexEntry(), l.get(0)); } @@ -1226,14 +1233,14 @@ public void testCommandLineByKey() throws IOException, TransformerException { PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); try { - XMPUtil.main(new String[] {"OezbekC06", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); + XMPUtilMain.main(new String[] {"OezbekC06", tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); } finally { System.setOut(oldOut); } } // PDF should be annotated: - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(1, l.size()); assertEqualsBibtexEntry(t2BibtexEntry(), l.get(0)); } finally { @@ -1254,7 +1261,7 @@ public void testCommandLineSeveral() throws IOException, TransformerException { File tempBib = File.createTempFile("JabRef", ".bib"); - try (FileWriter fileWriter = new FileWriter(tempBib)) { + try (BufferedWriter fileWriter = Files.newBufferedWriter(tempBib.toPath(), StandardCharsets.UTF_8)) { fileWriter.write(t1BibtexString()); fileWriter.write(t3BibtexString()); @@ -1263,10 +1270,10 @@ public void testCommandLineSeveral() throws IOException, TransformerException { try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { PrintStream oldOut = System.out; System.setOut(new PrintStream(s)); - XMPUtil.main(new String[] {tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); + XMPUtilMain.main(new String[] {tempBib.getAbsolutePath(), pdfFile.getAbsolutePath()}); System.setOut(oldOut); } - List l = XMPUtil.readXMP(pdfFile, Globals.prefs); + List l = XMPUtil.readXMP(pdfFile, xmpPreferences); Assert.assertEquals(2, l.size()); @@ -1318,9 +1325,9 @@ public void testResolveStrings() throws IOException, TransformerException { BibEntry e = c.iterator().next(); - XMPUtil.writeXMP(pdfFile, e, original.getDatabase()); + XMPUtil.writeXMP(pdfFile, e, original.getDatabase(), xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), Globals.prefs); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); @@ -1331,13 +1338,13 @@ public void testResolveStrings() throws IOException, TransformerException { @Test(expected = EncryptedPdfsNotSupportedException.class) public void expectedEncryptionNotSupportedExceptionAtRead() throws IOException { try (InputStream is = XMPUtilTest.class.getResourceAsStream("/pdfs/encrypted.pdf")) { - XMPUtil.readXMP(is, Globals.prefs); + XMPUtil.readXMP(is, xmpPreferences); } } @Test(expected = EncryptedPdfsNotSupportedException.class) public void expectedEncryptionNotSupportedExceptionAtWrite() throws IOException, TransformerException { - XMPUtil.writeXMP("src/test/resources/pdfs/encrypted.pdf", t1BibtexEntry(), null); + XMPUtil.writeXMP("src/test/resources/pdfs/encrypted.pdf", t1BibtexEntry(), null, xmpPreferences); } /** @@ -1352,7 +1359,8 @@ public void expectedEncryptionNotSupportedExceptionAtWrite() throws IOException, @Test public void testResolveStrings2() throws IOException, TransformerException { - try (FileReader fr = new FileReader("src/test/resources/net/sf/jabref/util/twente.bib")) { + try (BufferedReader fr = Files.newBufferedReader(Paths.get("src/test/resources/net/sf/jabref/util/twente.bib"), + StandardCharsets.UTF_8)) { ParserResult result = BibtexParser.parse(fr); Assert.assertEquals("Arvind", result.getDatabase().resolveForStrings("#Arvind#")); @@ -1362,10 +1370,10 @@ public void testResolveStrings2() throws IOException, TransformerException { try { XMPUtil.writeXMP(pdfFile, result.getDatabase().getEntryByKey("Patterson06").get(), - result.getDatabase()); + result.getDatabase(), xmpPreferences); // Test whether we the main function can load the bibtex correctly - BibEntry b = XMPUtil.readXMP(pdfFile, Globals.prefs).get(0); + BibEntry b = XMPUtil.readXMP(pdfFile, xmpPreferences).get(0); Assert.assertNotNull(b); Assert.assertEquals(originalAuthors, AuthorList.parse(b.getFieldOptional("author").get())); @@ -1400,7 +1408,7 @@ public void testResolveStrings2() throws IOException, TransformerException { Assert.assertEquals("Arvind", dcSchema.getCreators().get(1)); Assert.assertEquals("Krste Asanov\\'\\i{}c", dcSchema.getCreators().get(2)); - b = XMPUtil.getBibtexEntryFromDublinCore(dcSchema, Globals.prefs).get(); + b = XMPUtil.getBibtexEntryFromDublinCore(dcSchema, xmpPreferences).get(); Assert.assertNotNull(b); Assert.assertEquals(originalAuthors, AuthorList.parse(b.getFieldOptional("author").get())); } diff --git a/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.bib b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.bib new file mode 100644 index 000000000000..005a90f4969d --- /dev/null +++ b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.bib @@ -0,0 +1,5 @@ +@misc{, + title = {This is a test title} +}, @misc{, + title = {This is also a test title} +} diff --git a/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.txt b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.txt new file mode 100644 index 000000000000..3337997b30f1 --- /dev/null +++ b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterStringOutOfBounds.txt @@ -0,0 +1,8 @@ + +PMID- 27433151 +SO invalid line +TI - This is a test title + +PMID- 27394443 +SO- another invalid line +TI -This is also a test title diff --git a/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterTestInvalidFormat.xml b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterTestInvalidFormat.xml new file mode 100644 index 000000000000..62c549fdaf54 --- /dev/null +++ b/src/test/resources/net/sf/jabref/importer/fileformat/MedlinePlainImporterTestInvalidFormat.xml @@ -0,0 +1,5 @@ +PMC some PMC + PMID + + +SO-something stands here \ No newline at end of file