From 237d658e8fcc8a899d950444c36e809b85869dc1 Mon Sep 17 00:00:00 2001
From: Tobias Diez
Date: Mon, 11 Apr 2016 20:45:37 +0200
Subject: [PATCH 001/268] Code cleanup in OpenDatabaseAction
---
.../jabref/importer/OpenDatabaseAction.java | 32 +++----------------
1 file changed, 5 insertions(+), 27 deletions(-)
diff --git a/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java b/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
index 66f673fb5358..db4975320340 100644
--- a/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
+++ b/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
@@ -103,23 +103,6 @@ public void actionPerformed(ActionEvent e) {
openFiles(filesToOpen, true);
}
- class OpenItSwingHelper implements Runnable {
-
- private final BasePanel basePanel;
- private final boolean raisePanel;
-
- OpenItSwingHelper(BasePanel basePanel, boolean raisePanel) {
- this.basePanel = basePanel;
- this.raisePanel = raisePanel;
- }
-
- @Override
- public void run() {
- frame.addTab(basePanel, raisePanel);
-
- }
- }
-
/**
* Opens the given file. If null or 404, nothing happens
*
@@ -172,7 +155,7 @@ public void openFiles(List filesToOpen, boolean raisePanel) {
// locking until the file is loaded.
if (!filesToOpen.isEmpty()) {
final List theFiles = Collections.unmodifiableList(filesToOpen);
- JabRefExecutorService.INSTANCE.execute((Runnable) () -> {
+ JabRefExecutorService.INSTANCE.execute(() -> {
for (File theFile : theFiles) {
openTheFile(theFile, raisePanel);
}
@@ -294,13 +277,8 @@ private void openTheFile(File file, boolean raisePanel) {
// if the database contents should be modified due to new features
// in this version of JabRef:
final ParserResult finalReferenceToResult = result;
- SwingUtilities.invokeLater(new Runnable() {
-
- @Override
- public void run() {
- OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult, true);
- }
- });
+ SwingUtilities.invokeLater(
+ () -> OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult, true));
}
}
@@ -337,7 +315,7 @@ public BasePanel addNewDatabase(ParserResult result, final File file, boolean ra
BasePanel basePanel = new BasePanel(frame, new BibDatabaseContext(database, meta, file, defaults), result.getEncoding());
// file is set to null inside the EventDispatcherThread
- SwingUtilities.invokeLater(new OpenItSwingHelper(basePanel, raisePanel));
+ SwingUtilities.invokeLater(() -> frame.addTab(basePanel, raisePanel));
frame.output(Localization.lang("Opened database") + " '" + fileName + "' " + Localization.lang("with") + " "
+ database.getEntryCount() + " " + Localization.lang("entries") + ".");
@@ -355,7 +333,7 @@ public static ParserResult loadDatabase(File fileToOpen, Charset defaultEncoding
// encoding in the first place. Since the signature doesn't contain any fancy characters, we can
// read it regardless of encoding, with either UTF-8 or UTF-16. That's the hypothesis, at any rate.
// 8 bit is most likely, so we try that first:
- Optional suppliedEncoding = Optional.empty();
+ Optional suppliedEncoding;
try (Reader utf8Reader = ImportFormatReader.getUTF8Reader(fileToOpen)) {
suppliedEncoding = OpenDatabaseAction.getSuppliedEncoding(utf8Reader);
}
From d5e298a7b75f9bb4f1bc8c1d96466be0247d1a6c Mon Sep 17 00:00:00 2001
From: Tobias Diez
Date: Wed, 13 Apr 2016 21:37:00 +0200
Subject: [PATCH 002/268] Rework importer interface
---
src/main/java/net/sf/jabref/Globals.java | 1 -
src/main/java/net/sf/jabref/JabRef.java | 60 +++++--
.../jabref/exporter/CustomExportDialog.java | 3 +-
.../jabref/exporter/SaveDatabaseAction.java | 35 ++--
.../external/ExternalFileTypeEntryEditor.java | 3 +-
.../sf/jabref/external/MoveFileAction.java | 26 ++-
.../java/net/sf/jabref/gui/BasePanel.java | 119 +++++++++----
.../java/net/sf/jabref/gui/FileDialogs.java | 65 ++++---
.../sf/jabref/gui/FileListEntryEditor.java | 53 ++++--
.../net/sf/jabref/gui/OpenFileFilter.java | 24 ++-
.../sf/jabref/gui/actions/BrowseAction.java | 23 +--
.../jabref/gui/auximport/FromAuxDialog.java | 5 +-
.../gui/journals/ManageJournalsPanel.java | 8 +-
.../gui/plaintextimport/TextInputDialog.java | 100 +++++------
.../gui/preftabs/PreferencesDialog.java | 9 +-
.../sf/jabref/importer/CustomImporter.java | 1 -
.../importer/ImportCustomizationDialog.java | 25 +--
.../jabref/importer/ImportFormatReader.java | 97 ++++++-----
.../sf/jabref/importer/ImportMenuItem.java | 24 ++-
.../jabref/importer/OpenDatabaseAction.java | 3 +-
.../net/sf/jabref/importer/ParserResult.java | 18 +-
.../sf/jabref/importer/ZipFileChooser.java | 2 +-
.../importer/fetcher/DOItoBibTeXFetcher.java | 39 ++---
.../importer/fetcher/MedlineFetcher.java | 24 ++-
.../fileformat/BiblioscapeImporter.java | 34 ++--
.../importer/fileformat/BibteXMLImporter.java | 41 ++---
.../importer/fileformat/BibtexImporter.java | 32 ++--
.../importer/fileformat/CopacImporter.java | 39 ++---
.../importer/fileformat/EndnoteImporter.java | 33 ++--
.../importer/fileformat/FreeCiteImporter.java | 50 +++---
.../importer/fileformat/ImportFormat.java | 159 +++++++-----------
.../importer/fileformat/InspecImporter.java | 42 ++---
.../importer/fileformat/IsiImporter.java | 42 ++---
.../importer/fileformat/MedlineImporter.java | 71 +++-----
.../fileformat/MedlinePlainImporter.java | 40 ++---
.../importer/fileformat/MsBibImporter.java | 35 ++--
.../importer/fileformat/OvidImporter.java | 44 ++---
.../fileformat/PdfContentImporter.java | 83 ++++-----
.../importer/fileformat/PdfXmpImporter.java | 35 ++--
.../importer/fileformat/RepecNepImporter.java | 47 ++----
.../importer/fileformat/RisImporter.java | 41 ++---
.../fileformat/SilverPlatterImporter.java | 39 ++---
...=> ImportFormatReaderIntegrationTest.java} | 23 ++-
.../ImportFormatReaderTestParameterless.java | 27 +--
.../fileformat/BiblioscapeImporterTest.java | 2 +-
.../fileformat/BibtexImporterTest.java | 16 +-
.../fileformat/EndnoteImporterTest.java | 2 +-
.../importer/fileformat/ImportFormatTest.java | 105 ++++++++++++
.../importer/fileformat/InspecImportTest.java | 17 +-
.../importer/fileformat/IsiImporterTest.java | 31 +---
.../fileformat/MedlinePlainImporterTest.java | 33 ++--
.../fileformat/MsBibImporterTest.java | 2 +-
.../importer/fileformat/OvidImporterTest.java | 2 +-
.../fileformat/PdfXmpImporterTest.java | 26 +--
.../importer/fileformat/RISImporterTest.java | 2 +-
.../fileformat/RepecNepImporterTest.java | 19 +--
...edlinePlainImporterTestMultipleEntries.txt | 4 +-
57 files changed, 1058 insertions(+), 927 deletions(-)
rename src/test/java/net/sf/jabref/importer/{ImportFormatReaderTest.java => ImportFormatReaderIntegrationTest.java} (76%)
create mode 100644 src/test/java/net/sf/jabref/importer/fileformat/ImportFormatTest.java
diff --git a/src/main/java/net/sf/jabref/Globals.java b/src/main/java/net/sf/jabref/Globals.java
index 78b9dce6034a..3db58a539a06 100644
--- a/src/main/java/net/sf/jabref/Globals.java
+++ b/src/main/java/net/sf/jabref/Globals.java
@@ -48,7 +48,6 @@ public class Globals {
public static final String SELECTOR_META_PREFIX = "selector_";
public static final String PROTECTED_FLAG_META = "protectedFlag";
- public static final String NONE = "_non__";
public static final String SPECIAL_COMMAND_CHARS = "\"`^~'c=";
diff --git a/src/main/java/net/sf/jabref/JabRef.java b/src/main/java/net/sf/jabref/JabRef.java
index ee9a0126ac9f..cb35d3cf4fef 100644
--- a/src/main/java/net/sf/jabref/JabRef.java
+++ b/src/main/java/net/sf/jabref/JabRef.java
@@ -20,20 +20,47 @@
import java.io.IOException;
import java.net.Authenticator;
import java.nio.charset.Charset;
-import java.util.*;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Vector;
import java.util.prefs.BackingStoreException;
-import javax.swing.*;
+
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
+import javax.swing.UIDefaults;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.FontUIResource;
-import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
-import com.jgoodies.looks.plastic.theme.SkyBluer;
import net.sf.jabref.bibtex.InternalBibtexFields;
import net.sf.jabref.cli.AuxCommandLine;
-import net.sf.jabref.exporter.*;
-import net.sf.jabref.gui.*;
+import net.sf.jabref.exporter.AutoSaveManager;
+import net.sf.jabref.exporter.BibDatabaseWriter;
+import net.sf.jabref.exporter.ExportFormats;
+import net.sf.jabref.exporter.IExportFormat;
+import net.sf.jabref.exporter.SaveException;
+import net.sf.jabref.exporter.SavePreferences;
+import net.sf.jabref.exporter.SaveSession;
+import net.sf.jabref.gui.BasePanel;
+import net.sf.jabref.gui.GUIGlobals;
+import net.sf.jabref.gui.JabRefFrame;
+import net.sf.jabref.gui.ParserResultWarningDialog;
import net.sf.jabref.gui.remote.JabRefMessageHandler;
import net.sf.jabref.gui.util.FocusRequester;
-import net.sf.jabref.importer.*;
+import net.sf.jabref.importer.AutosaveStartupPrompter;
+import net.sf.jabref.importer.ImportFormatReader;
+import net.sf.jabref.importer.ImportInspectionCommandLine;
+import net.sf.jabref.importer.OpenDatabaseAction;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.importer.fetcher.EntryFetcher;
import net.sf.jabref.importer.fetcher.EntryFetchers;
import net.sf.jabref.logic.CustomEntryTypesManager;
@@ -57,6 +84,9 @@
import net.sf.jabref.model.database.BibDatabaseMode;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.util.Util;
+
+import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
+import com.jgoodies.looks.plastic.theme.SkyBluer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -802,14 +832,20 @@ private static Optional importFile(String argument) {
if ((data.length > 1) && !"*".equals(data[1])) {
System.out.println(Localization.lang("Importing") + ": " + data[0]);
try {
- List entries;
+ ParserResult parserResult;
if (OS.WINDOWS) {
- entries = Globals.IMPORT_FORMAT_READER.importFromFile(data[1], data[0], JabRef.mainFrame);
+ Path file = Paths.get(data[0]);
+ parserResult = Globals.IMPORT_FORMAT_READER.importFromFile(data[1], file);
} else {
- entries = Globals.IMPORT_FORMAT_READER.importFromFile(data[1],
- data[0].replace("~", System.getProperty("user.home")), JabRef.mainFrame);
+ Path file = Paths.get(data[0].replace("~", System.getProperty("user.home")));
+ parserResult = Globals.IMPORT_FORMAT_READER.importFromFile(data[1], file);
+ }
+
+ if(parserResult.hasWarnings()) {
+ mainFrame.showMessage(parserResult.getErrorMessage());
}
- return Optional.of(new ParserResult(entries));
+
+ return Optional.of(parserResult);
} catch (IllegalArgumentException ex) {
System.err.println(Localization.lang("Unknown import format") + ": " + data[1]);
return Optional.empty();
diff --git a/src/main/java/net/sf/jabref/exporter/CustomExportDialog.java b/src/main/java/net/sf/jabref/exporter/CustomExportDialog.java
index 454b3f0b0b1d..95fc0c7b1630 100644
--- a/src/main/java/net/sf/jabref/exporter/CustomExportDialog.java
+++ b/src/main/java/net/sf/jabref/exporter/CustomExportDialog.java
@@ -22,6 +22,7 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
+import java.util.Collections;
import javax.swing.*;
@@ -93,7 +94,7 @@ public void actionPerformed(ActionEvent e) {
JButton browse = new JButton(Localization.lang("Browse"));
browse.addActionListener(e -> {
File directory = new File(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
- String chosenStr = FileDialogs.getNewFile(parent, directory, ".layout",
+ String chosenStr = FileDialogs.getNewFile(parent, directory, Collections.singletonList(".layout"),
JFileChooser.OPEN_DIALOG, false);
if (chosenStr == null) {
return;
diff --git a/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java b/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java
index 9f6231a93e54..cfaea741e27b 100644
--- a/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java
+++ b/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java
@@ -15,30 +15,37 @@
*/
package net.sf.jabref.exporter;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-import net.sf.jabref.*;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+import net.sf.jabref.Globals;
+import net.sf.jabref.JabRefExecutorService;
+import net.sf.jabref.JabRefPreferences;
+import net.sf.jabref.collab.ChangeScanner;
import net.sf.jabref.gui.BasePanel;
+import net.sf.jabref.gui.FileDialogs;
import net.sf.jabref.gui.JabRefFrame;
import net.sf.jabref.gui.worker.AbstractWorker;
-import net.sf.jabref.gui.FileDialogs;
-import net.sf.jabref.collab.ChangeScanner;
import net.sf.jabref.gui.worker.CallBack;
import net.sf.jabref.gui.worker.Worker;
import net.sf.jabref.logic.l10n.Encodings;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.io.FileBasedLock;
-import javax.swing.*;
+import com.jgoodies.forms.builder.FormBuilder;
+import com.jgoodies.forms.layout.FormLayout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.charset.UnsupportedCharsetException;
-import java.util.List;
-
/**
* Action for the "Save" and "Save as" operations called from BasePanel. This class is also used for
* save operations when closing a database or quitting the applications.
@@ -343,8 +350,8 @@ public void saveAs() throws Throwable {
String chosenFile = null;
File f = null;
while (f == null) {
- chosenFile = FileDialogs.getNewFile(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), ".bib",
- JFileChooser.SAVE_DIALOG, false, null);
+ chosenFile = FileDialogs.getNewFile(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)),
+ Collections.singletonList(".bib"), JFileChooser.SAVE_DIALOG, false, null);
if (chosenFile == null) {
cancelled = true;
return; // cancelled
diff --git a/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java b/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java
index 1c590feaa48d..53a08908f7e1 100644
--- a/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java
+++ b/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java
@@ -20,6 +20,7 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
+import java.util.Collections;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
@@ -254,7 +255,7 @@ public void actionPerformed(ActionEvent e) {
// Nothing in the field. Go to the last file dir used:
initial = new File(Globals.prefs.get(JabRefPreferences.FILE_WORKING_DIRECTORY));
}
- String chosen = FileDialogs.getNewFile(null, initial, Globals.NONE,
+ String chosen = FileDialogs.getNewFile(null, initial, Collections.emptyList(),
JFileChooser.OPEN_DIALOG, false);
if (chosen != null) {
File newFile = new File(chosen);
diff --git a/src/main/java/net/sf/jabref/external/MoveFileAction.java b/src/main/java/net/sf/jabref/external/MoveFileAction.java
index 5a40cc2fcf4b..cfa84a86e5e6 100644
--- a/src/main/java/net/sf/jabref/external/MoveFileAction.java
+++ b/src/main/java/net/sf/jabref/external/MoveFileAction.java
@@ -15,25 +15,32 @@
*/
package net.sf.jabref.external;
+import java.awt.event.ActionEvent;
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+
+import javax.swing.AbstractAction;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
-import net.sf.jabref.gui.*;
+import net.sf.jabref.gui.FileDialogs;
+import net.sf.jabref.gui.FileListEntry;
+import net.sf.jabref.gui.JabRefFrame;
import net.sf.jabref.gui.entryeditor.EntryEditor;
import net.sf.jabref.gui.fieldeditors.FileListEditor;
import net.sf.jabref.gui.util.component.CheckBoxMessage;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.io.FileUtil;
import net.sf.jabref.util.Util;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.swing.*;
-import java.awt.event.ActionEvent;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Locale;
-
/**
* Action for moving or renaming a file that is linked to from an entry in JabRef.
*/
@@ -136,7 +143,8 @@ public void actionPerformed(ActionEvent event) {
}
chosenFile = sb.toString();
} else {
- chosenFile = FileDialogs.getNewFile(frame, file, extension, JFileChooser.SAVE_DIALOG, false);
+ chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension),
+ JFileChooser.SAVE_DIALOG, false);
}
if (chosenFile == null) {
return; // cancelled
diff --git a/src/main/java/net/sf/jabref/gui/BasePanel.java b/src/main/java/net/sf/jabref/gui/BasePanel.java
index 6e6837e94d0c..54ab9320004a 100644
--- a/src/main/java/net/sf/jabref/gui/BasePanel.java
+++ b/src/main/java/net/sf/jabref/gui/BasePanel.java
@@ -15,15 +15,67 @@
*/
package net.sf.jabref.gui;
-import ca.odell.glazedlists.event.ListEventListener;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-import net.sf.jabref.*;
+import java.awt.BorderLayout;
+import java.awt.Toolkit;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.ClipboardOwner;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.StringSelection;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+import javax.swing.AbstractAction;
+import javax.swing.BorderFactory;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JSplitPane;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.tree.TreePath;
+import javax.swing.undo.CannotRedoException;
+import javax.swing.undo.CannotUndoException;
+
+import net.sf.jabref.BibDatabaseContext;
+import net.sf.jabref.Globals;
+import net.sf.jabref.HighlightMatchingGroupPreferences;
+import net.sf.jabref.JabRefExecutorService;
+import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.collab.ChangeScanner;
import net.sf.jabref.collab.FileUpdateListener;
import net.sf.jabref.collab.FileUpdatePanel;
-import net.sf.jabref.exporter.*;
-import net.sf.jabref.external.*;
+import net.sf.jabref.exporter.BibDatabaseWriter;
+import net.sf.jabref.exporter.ExportToClipboardAction;
+import net.sf.jabref.exporter.SaveDatabaseAction;
+import net.sf.jabref.exporter.SaveException;
+import net.sf.jabref.exporter.SavePreferences;
+import net.sf.jabref.exporter.SaveSession;
+import net.sf.jabref.external.AttachFileAction;
+import net.sf.jabref.external.ExternalFileMenuItem;
+import net.sf.jabref.external.ExternalFileType;
+import net.sf.jabref.external.ExternalFileTypes;
+import net.sf.jabref.external.FindFullTextAction;
+import net.sf.jabref.external.RegExpFileSearch;
+import net.sf.jabref.external.SynchronizeFileField;
+import net.sf.jabref.external.WriteXMPAction;
import net.sf.jabref.groups.GroupSelector;
import net.sf.jabref.groups.GroupTreeNode;
import net.sf.jabref.gui.actions.Actions;
@@ -43,10 +95,20 @@
import net.sf.jabref.gui.mergeentries.MergeEntryDOIDialog;
import net.sf.jabref.gui.plaintextimport.TextInputDialog;
import net.sf.jabref.gui.search.SearchBar;
-import net.sf.jabref.gui.undo.*;
+import net.sf.jabref.gui.undo.CountingUndoManager;
+import net.sf.jabref.gui.undo.NamedCompound;
+import net.sf.jabref.gui.undo.UndoableChangeType;
+import net.sf.jabref.gui.undo.UndoableFieldChange;
+import net.sf.jabref.gui.undo.UndoableInsertEntry;
+import net.sf.jabref.gui.undo.UndoableKeyChange;
+import net.sf.jabref.gui.undo.UndoableRemoveEntry;
import net.sf.jabref.gui.util.FocusRequester;
import net.sf.jabref.gui.util.component.CheckBoxMessage;
-import net.sf.jabref.gui.worker.*;
+import net.sf.jabref.gui.worker.AbstractWorker;
+import net.sf.jabref.gui.worker.CallBack;
+import net.sf.jabref.gui.worker.MarkEntriesAction;
+import net.sf.jabref.gui.worker.SendAsEMailAction;
+import net.sf.jabref.gui.worker.Worker;
import net.sf.jabref.importer.AppendDatabaseAction;
import net.sf.jabref.importer.fileformat.BibtexParser;
import net.sf.jabref.logic.FieldChange;
@@ -70,29 +132,28 @@
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.EntryType;
import net.sf.jabref.model.entry.IdGenerator;
-import net.sf.jabref.specialfields.*;
-import net.sf.jabref.sql.*;
+import net.sf.jabref.specialfields.Printed;
+import net.sf.jabref.specialfields.Priority;
+import net.sf.jabref.specialfields.Quality;
+import net.sf.jabref.specialfields.Rank;
+import net.sf.jabref.specialfields.ReadStatus;
+import net.sf.jabref.specialfields.Relevance;
+import net.sf.jabref.specialfields.SpecialFieldAction;
+import net.sf.jabref.specialfields.SpecialFieldDatabaseChangeListener;
+import net.sf.jabref.specialfields.SpecialFieldValue;
+import net.sf.jabref.sql.DBConnectDialog;
+import net.sf.jabref.sql.DBExporterAndImporterFactory;
+import net.sf.jabref.sql.DBStrings;
+import net.sf.jabref.sql.DbConnectAction;
+import net.sf.jabref.sql.SQLUtil;
import net.sf.jabref.sql.exporter.DBExporter;
+
+import ca.odell.glazedlists.event.ListEventListener;
+import com.jgoodies.forms.builder.FormBuilder;
+import com.jgoodies.forms.layout.FormLayout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.swing.*;
-import javax.swing.tree.TreePath;
-import javax.swing.undo.CannotRedoException;
-import javax.swing.undo.CannotUndoException;
-import java.awt.*;
-import java.awt.datatransfer.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.KeyAdapter;
-import java.awt.event.KeyEvent;
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.nio.charset.Charset;
-import java.nio.charset.UnsupportedCharsetException;
-import java.util.*;
-import java.util.List;
-
public class BasePanel extends JPanel implements ClipboardOwner, FileUpdateListener {
private static final Log LOGGER = LogFactory.getLog(BasePanel.class);
@@ -2287,8 +2348,8 @@ public SaveSelectedAction(SavePreferences.DatabaseSaveType saveType) {
public void action() throws SaveException {
String chosenFile = FileDialogs.getNewFile(frame,
- new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), ".bib", JFileChooser.SAVE_DIALOG,
- false);
+ new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Collections.singletonList(".bib"),
+ JFileChooser.SAVE_DIALOG, false);
if (chosenFile != null) {
File expFile = new File(chosenFile);
if (!expFile.exists() || (JOptionPane.showConfirmDialog(frame,
diff --git a/src/main/java/net/sf/jabref/gui/FileDialogs.java b/src/main/java/net/sf/jabref/gui/FileDialogs.java
index a921dab8cb9a..fb5fe46b60a9 100644
--- a/src/main/java/net/sf/jabref/gui/FileDialogs.java
+++ b/src/main/java/net/sf/jabref/gui/FileDialogs.java
@@ -19,6 +19,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
@@ -28,13 +29,6 @@
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.logic.util.OS;
-/**
- * Created by IntelliJ IDEA.
- * User: alver
- * Date: Apr 14, 2009
- * Time: 7:24:07 PM
- * To change this template use File | Settings | File Templates.
- */
public class FileDialogs {
/**
@@ -45,21 +39,24 @@ public class FileDialogs {
*
* @param owner
* @param directory
- * @param extension
+ * @param extensions
* @param updateWorkingdirectory
* @return an array of selected file paths, or an empty array if no selection is made.
*/
- public static List getMultipleFiles(JFrame owner, File directory, String extension,
+ public static List getMultipleFiles(JFrame owner, File directory, List extensions,
boolean updateWorkingdirectory) {
- OpenFileFilter off = null;
- if (extension == null) {
+ Objects.requireNonNull(extensions);
+
+ OpenFileFilter off;
+ if (extensions.isEmpty()) {
off = new OpenFileFilter();
- } else if (!extension.equals(Globals.NONE)) {
- off = new OpenFileFilter(extension);
+ } else {
+ off = new OpenFileFilter(extensions);
}
- Object files = FileDialogs.getNewFileImpl(owner, directory, extension, null, off, JFileChooser.OPEN_DIALOG, updateWorkingdirectory, false, true, null);
+ Object files = FileDialogs.getNewFileImpl(owner, directory, extensions, null, off, JFileChooser.OPEN_DIALOG,
+ updateWorkingdirectory, false, true, null);
if (files instanceof String[]) {
return Arrays.asList((String[]) files);
@@ -72,40 +69,42 @@ public static List getMultipleFiles(JFrame owner, File directory, String
return Collections.emptyList();
}
- public static String getNewFile(JFrame owner, File directory, String extension, int dialogType, boolean updateWorkingDirectory) {
- return FileDialogs.getNewFile(owner, directory, extension, null, dialogType, updateWorkingDirectory, false, null);
+ public static String getNewFile(JFrame owner, File directory, List extensions, int dialogType, boolean updateWorkingDirectory) {
+ return FileDialogs.getNewFile(owner, directory, extensions, null, dialogType, updateWorkingDirectory, false, null);
}
- public static String getNewFile(JFrame owner, File directory, String extension, int dialogType, boolean updateWorkingDirectory, JComponent accessory) {
- return FileDialogs.getNewFile(owner, directory, extension, null, dialogType, updateWorkingDirectory, false, accessory);
+ public static String getNewFile(JFrame owner, File directory, List extensions, int dialogType, boolean updateWorkingDirectory, JComponent accessory) {
+ return FileDialogs.getNewFile(owner, directory, extensions, null, dialogType, updateWorkingDirectory, false, accessory);
}
- public static String getNewFile(JFrame owner, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory) {
- return FileDialogs.getNewFile(owner, directory, extension, description, dialogType, updateWorkingDirectory, false, null);
+ public static String getNewFile(JFrame owner, File directory, List extensions, String description, int dialogType, boolean updateWorkingDirectory) {
+ return FileDialogs.getNewFile(owner, directory, extensions, description, dialogType, updateWorkingDirectory, false, null);
}
- public static String getNewDir(JFrame owner, File directory, String extension, int dialogType, boolean updateWorkingDirectory) {
- return FileDialogs.getNewFile(owner, directory, extension, null, dialogType, updateWorkingDirectory, true, null);
+ public static String getNewDir(JFrame owner, File directory, List extensions, int dialogType, boolean updateWorkingDirectory) {
+ return FileDialogs.getNewFile(owner, directory, extensions, null, dialogType, updateWorkingDirectory, true, null);
}
- public static String getNewDir(JFrame owner, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory) {
- return FileDialogs.getNewFile(owner, directory, extension, description, dialogType, updateWorkingDirectory, true, null);
+ public static String getNewDir(JFrame owner, File directory, List extensions, String description, int dialogType, boolean updateWorkingDirectory) {
+ return FileDialogs.getNewFile(owner, directory, extensions, description, dialogType, updateWorkingDirectory, true, null);
}
- private static String getNewFile(JFrame owner, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, JComponent accessory) {
+ private static String getNewFile(JFrame owner, File directory, List extensions, String description, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, JComponent accessory) {
- OpenFileFilter off = null;
+ OpenFileFilter off;
- if (extension == null) {
+ if (extensions.isEmpty()) {
off = new OpenFileFilter();
- } else if (!extension.equals(Globals.NONE)) {
- off = new OpenFileFilter(extension);
+ } else {
+ off = new OpenFileFilter(extensions);
}
- return (String) FileDialogs.getNewFileImpl(owner, directory, extension, description, off, dialogType, updateWorkingDirectory, dirOnly, false, accessory);
+ return (String) FileDialogs.getNewFileImpl(owner, directory, extensions, description, off, dialogType, updateWorkingDirectory, dirOnly, false, accessory);
}
- private static Object getNewFileImpl(JFrame owner, File directory, String extension, String description, OpenFileFilter off, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, boolean multipleSelection, JComponent accessory) {
+ private static Object getNewFileImpl(JFrame owner, File directory, List extensions, String description,
+ OpenFileFilter off, int dialogType, boolean updateWorkingDirectory, boolean dirOnly,
+ boolean multipleSelection, JComponent accessory) {
// Added the !dirOnly condition below as a workaround to the native file dialog
// not supporting directory selection:
@@ -160,10 +159,10 @@ private static Object getNewFileImpl(JFrame owner, File directory, String extens
// If this is a save dialog, and the user has not chosen "All files" as
// filter
// we enforce the given extension. But only if extension is not null.
- if ((extension != null) && (dialogType == JFileChooser.SAVE_DIALOG) && (fc.getFileFilter() == off) && !off.accept(selectedFile)) {
+ if ((!extensions.isEmpty()) && (dialogType == JFileChooser.SAVE_DIALOG) && (fc.getFileFilter() == off) && !off.accept(selectedFile)) {
// add the first extension if there are multiple extensions
- selectedFile = new File(selectedFile.getPath() + extension.split("[, ]+", 0)[0]);
+ selectedFile = new File(selectedFile.getPath() + extensions.get(0));
}
if (updateWorkingDirectory) {
diff --git a/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java b/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java
index e51c1356a417..a48c47333cd9 100644
--- a/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java
+++ b/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java
@@ -15,9 +15,38 @@
*/
package net.sf.jabref.gui;
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
+import java.awt.BorderLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Pattern;
+
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
+import javax.swing.BorderFactory;
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.InputMap;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JProgressBar;
+import javax.swing.JTextField;
+import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+
import net.sf.jabref.BibDatabaseContext;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
@@ -29,21 +58,13 @@
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.io.FileUtil;
+
+import com.jgoodies.forms.builder.ButtonBarBuilder;
+import com.jgoodies.forms.builder.FormBuilder;
+import com.jgoodies.forms.layout.FormLayout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.swing.*;
-import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
-import java.awt.*;
-import java.awt.event.*;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.List;
-import java.util.Optional;
-import java.util.regex.Pattern;
-
/**
* This class produces a dialog box for editing a single file link from a Bibtex entry.
*
@@ -343,7 +364,7 @@ public void actionPerformed(ActionEvent e) {
// Nothing in the field. Go to the last file dir used:
initial = new File(Globals.prefs.get(JabRefPreferences.FILE_WORKING_DIRECTORY));
}
- String chosen = FileDialogs.getNewFile(parent, initial, Globals.NONE,
+ String chosen = FileDialogs.getNewFile(parent, initial, Collections.emptyList(),
JFileChooser.OPEN_DIALOG, false);
if (chosen != null) {
File newFile = new File(chosen);
diff --git a/src/main/java/net/sf/jabref/gui/OpenFileFilter.java b/src/main/java/net/sf/jabref/gui/OpenFileFilter.java
index e499969fff17..c5a8fbb9150c 100644
--- a/src/main/java/net/sf/jabref/gui/OpenFileFilter.java
+++ b/src/main/java/net/sf/jabref/gui/OpenFileFilter.java
@@ -17,7 +17,9 @@
import java.io.File;
import java.io.FilenameFilter;
+import java.util.Arrays;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
public class OpenFileFilter extends javax.swing.filechooser.FileFilter implements FilenameFilter {
@@ -26,42 +28,38 @@ public class OpenFileFilter extends javax.swing.filechooser.FileFilter implement
private final String desc;
- public OpenFileFilter(String[] extensions) {
+ public OpenFileFilter(List extensions) {
StringBuilder buf = new StringBuilder();
- int numExt = extensions.length;
+ int numExt = extensions.size();
if (numExt > 0) {
buf.append('*');
- buf.append(extensions[0]);
+ buf.append(extensions.get(0));
- extSet.add(extensions[0]);
+ extSet.add(extensions.get(0));
}
for (int curExt = 1; curExt < numExt; curExt++) {
buf.append(", *");
- buf.append(extensions[curExt]);
+ buf.append(extensions.get(curExt));
- extSet.add(extensions[curExt]);
+ extSet.add(extensions.get(curExt));
}
desc = buf.toString();
}
public OpenFileFilter() {
- this(new String[] {
+ this(Arrays.asList(
".bib",
".dat", // silverplatter ending
- ".txt", // windows puts ".txt" extentions and for scifinder
+ ".txt", // windows puts ".txt" extensions and for scifinder
".ris",
".ref", // refer/endnote format
".fcgi", // default for pubmed
".bibx", // default for BibTeXML
".xml"
- });
- }
-
- public OpenFileFilter(String s) {
- this(s.split("[, ]+", 0));
+ ));
}
@Override
diff --git a/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java b/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java
index 14d628819f2d..94a1eaa14320 100644
--- a/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java
+++ b/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java
@@ -15,15 +15,19 @@
*/
package net.sf.jabref.gui.actions;
-import net.sf.jabref.Globals;
-import net.sf.jabref.gui.FileDialogs;
-import net.sf.jabref.gui.util.FocusRequester;
-import net.sf.jabref.logic.l10n.Localization;
-
-import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
+import java.util.Collections;
+
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JTextField;
+import net.sf.jabref.gui.FileDialogs;
+import net.sf.jabref.gui.util.FocusRequester;
+import net.sf.jabref.logic.l10n.Localization;
/**
* Action used to produce a "Browse" button for one of the text fields.
@@ -74,15 +78,14 @@ public void actionPerformed(ActionEvent e) {
}
}
}
-
+
private String askUser() {
if (dir) {
- return FileDialogs.getNewDir(frame, new File(comp.getText()), Globals.NONE,
+ return FileDialogs.getNewDir(frame, new File(comp.getText()), Collections.emptyList(),
JFileChooser.OPEN_DIALOG, false);
} else {
- return FileDialogs.getNewFile(frame, new File(comp.getText()), Globals.NONE,
+ return FileDialogs.getNewFile(frame, new File(comp.getText()), Collections.emptyList(),
JFileChooser.OPEN_DIALOG, false);
}
}
-
}
diff --git a/src/main/java/net/sf/jabref/gui/auximport/FromAuxDialog.java b/src/main/java/net/sf/jabref/gui/auximport/FromAuxDialog.java
index bd0597896038..bfc699689bfc 100644
--- a/src/main/java/net/sf/jabref/gui/auximport/FromAuxDialog.java
+++ b/src/main/java/net/sf/jabref/gui/auximport/FromAuxDialog.java
@@ -39,6 +39,7 @@
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;
+import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
@@ -264,9 +265,7 @@ public BrowseAction(JTextField tc, JabRefFrame frame) {
@Override
public void actionPerformed(ActionEvent e) {
- String chosen = FileDialogs.getNewFile(frame,
- new File(comp.getText()),
- ".aux",
+ String chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Collections.singletonList(".aux"),
JFileChooser.OPEN_DIALOG, false);
if (chosen != null) {
File newFile = new File(chosen);
diff --git a/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java b/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java
index e7ddb080db66..3e3a71df715f 100644
--- a/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java
+++ b/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java
@@ -439,11 +439,11 @@ public BrowseAction(JTextField tc, boolean dir) {
public void actionPerformed(ActionEvent e) {
String chosen;
if (dir) {
- chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG,
- false);
+ chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), Collections.emptyList(),
+ JFileChooser.OPEN_DIALOG, false);
} else {
- chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG,
- false);
+ chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Collections.emptyList(),
+ JFileChooser.OPEN_DIALOG, false);
}
if (chosen != null) {
File nFile = new File(chosen);
diff --git a/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java b/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java
index f80865a334d9..a0909c144b8a 100644
--- a/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java
+++ b/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java
@@ -51,29 +51,28 @@
package net.sf.jabref.gui.plaintextimport;
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-
-import net.sf.jabref.Globals;
-import net.sf.jabref.JabRefPreferences;
-import net.sf.jabref.bibtex.BibEntryWriter;
-import net.sf.jabref.bibtex.FieldProperties;
-import net.sf.jabref.bibtex.InternalBibtexFields;
-import net.sf.jabref.model.EntryTypes;
-import net.sf.jabref.exporter.LatexFieldFormatter;
-import net.sf.jabref.gui.ClipBoardManager;
-import net.sf.jabref.gui.EntryMarker;
-import net.sf.jabref.gui.FileDialogs;
-import net.sf.jabref.gui.IconTheme;
-import net.sf.jabref.gui.JabRefFrame;
-import net.sf.jabref.gui.OSXCompatibleToolbar;
-import net.sf.jabref.gui.keyboard.KeyBinding;
-import net.sf.jabref.gui.undo.NamedCompound;
-import net.sf.jabref.gui.util.component.OverlayPanel;
-import net.sf.jabref.importer.fileformat.FreeCiteImporter;
-import net.sf.jabref.logic.l10n.Localization;
-import net.sf.jabref.logic.util.UpdateField;
-import net.sf.jabref.model.entry.BibEntry;
-import net.sf.jabref.model.entry.EntryType;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.GridLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import javax.swing.AbstractAction;
import javax.swing.Action;
@@ -110,32 +109,33 @@
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
+import net.sf.jabref.Globals;
+import net.sf.jabref.JabRefPreferences;
+import net.sf.jabref.bibtex.BibEntryWriter;
+import net.sf.jabref.bibtex.FieldProperties;
+import net.sf.jabref.bibtex.InternalBibtexFields;
+import net.sf.jabref.exporter.LatexFieldFormatter;
+import net.sf.jabref.gui.ClipBoardManager;
+import net.sf.jabref.gui.EntryMarker;
+import net.sf.jabref.gui.FileDialogs;
+import net.sf.jabref.gui.IconTheme;
+import net.sf.jabref.gui.JabRefFrame;
+import net.sf.jabref.gui.OSXCompatibleToolbar;
+import net.sf.jabref.gui.keyboard.KeyBinding;
+import net.sf.jabref.gui.undo.NamedCompound;
+import net.sf.jabref.gui.util.component.OverlayPanel;
+import net.sf.jabref.importer.ParserResult;
+import net.sf.jabref.importer.fileformat.FreeCiteImporter;
+import net.sf.jabref.logic.l10n.Localization;
+import net.sf.jabref.logic.util.UpdateField;
+import net.sf.jabref.model.EntryTypes;
+import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.EntryType;
+
+import com.jgoodies.forms.builder.ButtonBarBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Dimension;
-import java.awt.Font;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.GridLayout;
-import java.awt.Insets;
-import java.awt.event.ActionEvent;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-
public class TextInputDialog extends JDialog {
private static final Log LOGGER = LogFactory.getLog(TextInputDialog.class);
@@ -511,8 +511,12 @@ private boolean parseWithFreeCiteAndAddEntries() {
text = text.replace(Globals.NEWLINE, " ");
text = text.replace("##NEWLINE##", Globals.NEWLINE);
- List importedEntries = fimp.importEntries(text, frame);
- if (importedEntries == null) {
+ ParserResult importerResult = fimp.importEntries(text);
+ if(importerResult.hasWarnings()) {
+ frame.showMessage(importerResult.getErrorMessage());
+ }
+ List importedEntries = importerResult.getDatabase().getEntries();
+ if (importedEntries.isEmpty()) {
return false;
} else {
UpdateField.setAutomaticFields(importedEntries, false, false);
diff --git a/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java b/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java
index 7e2d9a8958a0..f6ad87476f5f 100644
--- a/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java
+++ b/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java
@@ -19,6 +19,7 @@
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.prefs.BackingStoreException;
@@ -158,8 +159,8 @@ public PreferencesDialog(JabRefFrame parent, JabRef jabRef) {
// Import and export actions:
exportPreferences.setToolTipText(Localization.lang("Export preferences to file"));
exportPreferences.addActionListener(e -> {
- String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), ".xml",
- JFileChooser.SAVE_DIALOG, false);
+ String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
+ Collections.singletonList(".xml"), JFileChooser.SAVE_DIALOG, false);
if (filename == null) {
return;
}
@@ -180,8 +181,8 @@ public PreferencesDialog(JabRefFrame parent, JabRef jabRef) {
importPreferences.setToolTipText(Localization.lang("Import preferences from file"));
importPreferences.addActionListener(e -> {
- String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), ".xml",
- JFileChooser.OPEN_DIALOG, false);
+ String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
+ Collections.singletonList(".xml"), JFileChooser.OPEN_DIALOG, false);
if (filename != null) {
try {
prefs.importPreferences(filename);
diff --git a/src/main/java/net/sf/jabref/importer/CustomImporter.java b/src/main/java/net/sf/jabref/importer/CustomImporter.java
index 9347fa7a0ee9..5c9c4de27851 100644
--- a/src/main/java/net/sf/jabref/importer/CustomImporter.java
+++ b/src/main/java/net/sf/jabref/importer/CustomImporter.java
@@ -136,7 +136,6 @@ public ImportFormat getInstance() throws IOException, MalformedURLException, Cla
try (URLClassLoader cl = new URLClassLoader(new URL[] {getBasePathUrl()})) {
Class> clazz = Class.forName(className, true, cl);
ImportFormat importFormat = (ImportFormat) clazz.newInstance();
- importFormat.setIsCustomImporter(true);
return importFormat;
}
}
diff --git a/src/main/java/net/sf/jabref/importer/ImportCustomizationDialog.java b/src/main/java/net/sf/jabref/importer/ImportCustomizationDialog.java
index f203543ec98a..8ff4782c9d6e 100644
--- a/src/main/java/net/sf/jabref/importer/ImportCustomizationDialog.java
+++ b/src/main/java/net/sf/jabref/importer/ImportCustomizationDialog.java
@@ -22,6 +22,8 @@
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.zip.ZipFile;
import javax.swing.*;
@@ -54,8 +56,7 @@ public class ImportCustomizationDialog extends JDialog {
/**
*
- * @param frame_
- * @throws HeadlessException
+ * @param frame
*/
public ImportCustomizationDialog(final JabRefFrame frame) {
super(frame, Localization.lang("Manage custom imports"), false);
@@ -77,20 +78,22 @@ public ImportCustomizationDialog(final JabRefFrame frame) {
JButton addFromFolderButton = new JButton(Localization.lang("Add from folder"));
addFromFolderButton.addActionListener(e -> {
- String chosenFileStr = null;
CustomImporter importer = new CustomImporter();
- importer.setBasePath(
- FileDialogs.getNewDir(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)),
- "", Localization.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false));
+ importer.setBasePath(FileDialogs
+ .getNewDir(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)),
+ Collections.emptyList(), Localization.lang("Select Classpath of New Importer"),
+ JFileChooser.CUSTOM_DIALOG, false));
+ String chosenFileStr = null;
if (importer.getBasePath() != null) {
- chosenFileStr = FileDialogs.getNewFile(frame, importer.getFileFromBasePath(), ".class",
- Localization.lang("Select new ImportFormat Subclass"), JFileChooser.CUSTOM_DIALOG, false);
+ chosenFileStr = FileDialogs.getNewFile(frame, importer.getFileFromBasePath(),
+ Collections.singletonList(".class"), Localization.lang("Select new ImportFormat Subclass"),
+ JFileChooser.CUSTOM_DIALOG, false);
}
if (chosenFileStr != null) {
try {
importer.setClassName(pathToClass(importer.getFileFromBasePath(), new File(chosenFileStr)));
importer.setName(importer.getInstance().getFormatName());
- importer.setCliId(importer.getInstance().getCLIId());
+ importer.setCliId(importer.getInstance().getId());
addOrReplaceImporter(importer);
customImporterTable.revalidate();
customImporterTable.repaint();
@@ -108,8 +111,8 @@ public ImportCustomizationDialog(final JabRefFrame frame) {
JButton addFromJarButton = new JButton(Localization.lang("Add from jar"));
addFromJarButton.addActionListener(e -> {
String basePath = FileDialogs.getNewFile(frame,
- new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)),
- ".zip,.jar", Localization.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false);
+ new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Arrays.asList(".zip", ".jar"),
+ Localization.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false);
if (basePath != null) {
try (ZipFile zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ)) {
diff --git a/src/main/java/net/sf/jabref/importer/ImportFormatReader.java b/src/main/java/net/sf/jabref/importer/ImportFormatReader.java
index ffec4c726125..ef5336cdbf65 100644
--- a/src/main/java/net/sf/jabref/importer/ImportFormatReader.java
+++ b/src/main/java/net/sf/jabref/importer/ImportFormatReader.java
@@ -15,25 +15,54 @@
*/
package net.sf.jabref.importer;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-import java.util.*;
-
-import net.sf.jabref.importer.fileformat.*;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import net.sf.jabref.Globals;
+import net.sf.jabref.importer.fileformat.BiblioscapeImporter;
+import net.sf.jabref.importer.fileformat.BibteXMLImporter;
+import net.sf.jabref.importer.fileformat.BibtexImporter;
+import net.sf.jabref.importer.fileformat.CopacImporter;
+import net.sf.jabref.importer.fileformat.EndnoteImporter;
+import net.sf.jabref.importer.fileformat.FreeCiteImporter;
+import net.sf.jabref.importer.fileformat.ImportFormat;
+import net.sf.jabref.importer.fileformat.InspecImporter;
+import net.sf.jabref.importer.fileformat.IsiImporter;
+import net.sf.jabref.importer.fileformat.MedlineImporter;
+import net.sf.jabref.importer.fileformat.MedlinePlainImporter;
+import net.sf.jabref.importer.fileformat.MsBibImporter;
+import net.sf.jabref.importer.fileformat.OvidImporter;
+import net.sf.jabref.importer.fileformat.PdfContentImporter;
+import net.sf.jabref.importer.fileformat.PdfXmpImporter;
+import net.sf.jabref.importer.fileformat.RepecNepImporter;
+import net.sf.jabref.importer.fileformat.RisImporter;
+import net.sf.jabref.importer.fileformat.SilverPlatterImporter;
import net.sf.jabref.model.database.BibDatabases;
import net.sf.jabref.model.entry.BibEntry;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import net.sf.jabref.*;
-
public class ImportFormatReader {
public static final String BIBTEX_FORMAT = "BibTeX";
/**
- * all import formats, in the default order of import formats
+ * All import formats.
+ * Sorted accordingly to {@link ImportFormat#compareTo}, which defaults to alphabetically by the name
*/
private final SortedSet formats = new TreeSet<>();
@@ -86,14 +115,14 @@ public void resetImportFormats() {
*/
private Optional getByCliId(String cliId) {
for (ImportFormat format : formats) {
- if (format.getCLIId().equals(cliId)) {
+ if (format.getId().equals(cliId)) {
return Optional.of(format);
}
}
return Optional.empty();
}
- public List importFromFile(String format, String filename, OutputPrinter status)
+ public ParserResult importFromFile(String format, Path file)
throws IOException {
Optional importer = getByCliId(format);
@@ -101,28 +130,18 @@ public List importFromFile(String format, String filename, OutputPrint
throw new IllegalArgumentException("Unknown import format: " + format);
}
- return importFromFile(importer.get(), filename, status);
+ return importFromFile(importer.get(), file);
}
- public List importFromFile(ImportFormat importer, String filename, OutputPrinter status) throws IOException {
+ public ParserResult importFromFile(ImportFormat importer, Path file) throws IOException {
Objects.requireNonNull(importer);
- Objects.requireNonNull(filename);
- File file = new File(filename);
-
- try (InputStream stream = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(stream)) {
+ Objects.requireNonNull(file);
- bis.mark(Integer.MAX_VALUE);
-
- if (!importer.isRecognizedFormat(bis)) {
- throw new IOException("Wrong file format");
- }
+ if(!importer.isRecognizedFormat(file)) {
+ throw new IOException("Wrong file format");
}
- try (InputStream stream = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(stream)) {
- return importer.importEntries(bis, status);
- }
+ return importer.importDatabase(file);
}
/**
@@ -158,7 +177,7 @@ public String getImportFormatList() {
}
sb.append(" : ");
- sb.append(imFo.getCLIId());
+ sb.append(imFo.getId());
sb.append('\n');
}
@@ -199,6 +218,9 @@ public UnknownFormatImport(String format, ParserResult parserResult) {
}
}
+ public UnknownFormatImport importUnknownFormat(String filename) {
+ return importUnknownFormat(Paths.get(filename));
+ }
/**
* Tries to import a file by iterating through the available import filters,
@@ -208,26 +230,21 @@ public UnknownFormatImport(String format, ParserResult parserResult) {
*
* @throws IOException
*/
- public UnknownFormatImport importUnknownFormat(String filename) {
- Objects.requireNonNull(filename);
+ public UnknownFormatImport importUnknownFormat(Path file) {
+ Objects.requireNonNull(file);
// First, see if it is a BibTeX file:
try {
- ParserResult pr = OpenDatabaseAction.loadDatabase(new File(filename),
+ ParserResult pr = OpenDatabaseAction.loadDatabase(file.toFile(),
Globals.prefs.getDefaultEncoding());
if (pr.getDatabase().hasEntries() || !pr.getDatabase().hasNoStrings()) {
- pr.setFile(new File(filename));
+ pr.setFile(file.toFile());
return new UnknownFormatImport(ImportFormatReader.BIBTEX_FORMAT, pr);
}
} catch (IOException ignore) {
// Ignored
}
- // we don't use a provided OutputPrinter (such as the JabRef frame),
- // as we don't want to see any outputs from failed importers:
- // we expect failures and do not want to report them to the user
- OutputPrinterToNull nullOutput = new OutputPrinterToNull();
-
// stores ref to best result, gets updated at the next loop
List bestResult = null;
int bestResultCount = 0;
@@ -235,14 +252,16 @@ public UnknownFormatImport importUnknownFormat(String filename) {
// Cycle through all importers:
for (ImportFormat imFo : getImportFormats()) {
-
try {
+ if(!imFo.isRecognizedFormat(file)) {
+ continue;
+ }
- List entries = importFromFile(imFo, filename, nullOutput);
+ ParserResult parserResult = importFromFile(imFo, file);
+ List entries = parserResult.getDatabase().getEntries();
- int entryCount;
BibDatabases.purgeEmptyEntries(entries);
- entryCount = entries.size();
+ int entryCount = entries.size();
if (entryCount > bestResultCount) {
bestResult = entries;
diff --git a/src/main/java/net/sf/jabref/importer/ImportMenuItem.java b/src/main/java/net/sf/jabref/importer/ImportMenuItem.java
index cfe6a97fcfc7..090ff070ea91 100644
--- a/src/main/java/net/sf/jabref/importer/ImportMenuItem.java
+++ b/src/main/java/net/sf/jabref/importer/ImportMenuItem.java
@@ -19,16 +19,26 @@
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
-import net.sf.jabref.*;
-import net.sf.jabref.gui.*;
+import net.sf.jabref.Globals;
+import net.sf.jabref.JabRefPreferences;
+import net.sf.jabref.MetaData;
+import net.sf.jabref.gui.BasePanel;
+import net.sf.jabref.gui.EntryMarker;
+import net.sf.jabref.gui.FileDialogs;
+import net.sf.jabref.gui.ImportInspectionDialog;
+import net.sf.jabref.gui.JabRefFrame;
+import net.sf.jabref.gui.ParserResultWarningDialog;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.importer.fileformat.ImportFormat;
@@ -98,7 +108,7 @@ public void init() {
importError = null;
filenames = FileDialogs.getMultipleFiles(frame,
new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)),
- importer == null ? null : importer.getExtensions(), true);
+ importer == null ? Collections.emptyList() : importer.getExtensions(), true);
if (!filenames.isEmpty()) {
frame.block();
@@ -118,6 +128,7 @@ public void run() {
// We import all files and collect their results:
List imports = new ArrayList<>();
for (String filename : filenames) {
+ Path file = Paths.get(filename);
try {
if (importer == null) {
// Unknown format:
@@ -127,9 +138,10 @@ public void run() {
} else {
frame.output(Localization.lang("Importing in %0 format", importer.getFormatName()) + "...");
// Specific importer:
- ParserResult pr = new ParserResult(
- Globals.IMPORT_FORMAT_READER.importFromFile(importer,
- filename, frame));
+ ParserResult pr = Globals.IMPORT_FORMAT_READER.importFromFile(importer, file);
+ if (pr.hasWarnings()) {
+ frame.showMessage(pr.getErrorMessage());
+ }
imports.add(new ImportFormatReader.UnknownFormatImport(importer
.getFormatName(), pr));
diff --git a/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java b/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
index db4975320340..0921e247b55b 100644
--- a/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
+++ b/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
@@ -89,7 +89,8 @@ public void actionPerformed(ActionEvent e) {
if (showDialog) {
List chosenStrings = FileDialogs.getMultipleFiles(frame,
- new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), ".bib", true);
+ new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Collections.singletonList(".bib"),
+ true);
for (String chosen : chosenStrings) {
if (chosen != null) {
filesToOpen.add(new File(chosen));
diff --git a/src/main/java/net/sf/jabref/importer/ParserResult.java b/src/main/java/net/sf/jabref/importer/ParserResult.java
index 85c791c4383d..8e961d04c811 100644
--- a/src/main/java/net/sf/jabref/importer/ParserResult.java
+++ b/src/main/java/net/sf/jabref/importer/ParserResult.java
@@ -17,14 +17,15 @@
import java.io.File;
import java.nio.charset.Charset;
-
-import java.util.List;
-import java.util.Map;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-import net.sf.jabref.*;
+import net.sf.jabref.BibDatabaseContext;
+import net.sf.jabref.MetaData;
import net.sf.jabref.model.database.BibDatabase;
import net.sf.jabref.model.database.BibDatabases;
import net.sf.jabref.model.entry.BibEntry;
@@ -49,6 +50,9 @@ public class ParserResult {
private boolean invalid;
private boolean toOpenTab;
+ public ParserResult() {
+ this(Collections.emptyList());
+ }
public ParserResult(Collection entries) {
this(BibDatabases.createDatabase(BibDatabases.purgeEmptyEntries(entries)), null, new HashMap<>());
@@ -60,6 +64,12 @@ public ParserResult(BibDatabase base, MetaData metaData, Map
this.entryTypes = entryTypes;
}
+ public static ParserResult fromErrorMessage(String message) {
+ ParserResult parserResult = new ParserResult();
+ parserResult.addWarning(message);
+ return parserResult;
+ }
+
/**
* Check if this base is marked to be added to the currently open tab. Default is false.
*
diff --git a/src/main/java/net/sf/jabref/importer/ZipFileChooser.java b/src/main/java/net/sf/jabref/importer/ZipFileChooser.java
index fce892fff4fa..728f736052af 100644
--- a/src/main/java/net/sf/jabref/importer/ZipFileChooser.java
+++ b/src/main/java/net/sf/jabref/importer/ZipFileChooser.java
@@ -110,7 +110,7 @@ public ZipFileChooser(ImportCustomizationDialog importCustomizationDialog, ZipFi
try {
ImportFormat importFormat = importer.getInstance();
importer.setName(importFormat.getFormatName());
- importer.setCliId(importFormat.getCLIId());
+ importer.setCliId(importFormat.getId());
importCustomizationDialog.addOrReplaceImporter(importer);
dispose();
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exc) {
diff --git a/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java b/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
index 15bf27e25f35..c0d096115521 100644
--- a/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
+++ b/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
@@ -22,24 +22,26 @@
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
+import java.util.Objects;
import java.util.Optional;
-import javax.swing.JOptionPane;
import javax.swing.JPanel;
-import net.sf.jabref.logic.formatter.casechanger.ProtectTermsFormatter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import net.sf.jabref.importer.*;
-import net.sf.jabref.importer.fileformat.BibtexParser;
-import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
+import net.sf.jabref.importer.ImportInspector;
+import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
+import net.sf.jabref.importer.fileformat.BibtexParser;
import net.sf.jabref.logic.formatter.bibtexfields.UnitsToLatexFormatter;
+import net.sf.jabref.logic.formatter.casechanger.ProtectTermsFormatter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.net.URLDownload;
import net.sf.jabref.logic.util.DOI;
+import net.sf.jabref.model.entry.BibEntry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
public class DOItoBibTeXFetcher implements EntryFetcher {
@@ -56,7 +58,11 @@ public void stopFetching() {
@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
- BibEntry entry = getEntryFromDOI(query, status);
+ ParserResult parserResult = new ParserResult();
+ BibEntry entry = getEntryFromDOI(query, parserResult);
+ if(parserResult.hasWarnings()) {
+ status.showMessage(parserResult.getErrorMessage());
+ }
if (entry != null) {
inspector.addEntry(entry);
return true;
@@ -80,15 +86,14 @@ public JPanel getOptionsPanel() {
return null;
}
- public BibEntry getEntryFromDOI(String doiStr, OutputPrinter status) {
+ public BibEntry getEntryFromDOI(String doiStr, ParserResult parserResult) {
+ Objects.requireNonNull(parserResult);
+
DOI doi;
try {
doi = new DOI(doiStr);
} catch (IllegalArgumentException e) {
- status.showMessage(Localization.lang("Invalid DOI: '%0'.", doiStr),
- Localization.lang("Get BibTeX entry from DOI"),
- JOptionPane.INFORMATION_MESSAGE);
- LOGGER.warn("Invalid DOI", e);
+ parserResult.addWarning(Localization.lang("Invalid DOI: '%0'.", doiStr));
return null;
}
@@ -114,11 +119,7 @@ public BibEntry getEntryFromDOI(String doiStr, OutputPrinter status) {
dl.addParameters("Accept", "application/x-bibtex");
bibtexString = dl.downloadToString(StandardCharsets.UTF_8);
} catch (FileNotFoundException e) {
- if (status != null) {
- status.showMessage(Localization.lang("Unknown DOI: '%0'.", doi.getDOI()),
- Localization.lang("Get BibTeX entry from DOI"),
- JOptionPane.INFORMATION_MESSAGE);
- }
+ parserResult.addWarning(Localization.lang("Unknown DOI: '%0'.", doi.getDOI()));
LOGGER.debug("Unknown DOI", e);
return null;
} catch (IOException e) {
diff --git a/src/main/java/net/sf/jabref/importer/fetcher/MedlineFetcher.java b/src/main/java/net/sf/jabref/importer/fetcher/MedlineFetcher.java
index acb015faf357..24d620362123 100644
--- a/src/main/java/net/sf/jabref/importer/fetcher/MedlineFetcher.java
+++ b/src/main/java/net/sf/jabref/importer/fetcher/MedlineFetcher.java
@@ -20,6 +20,8 @@
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -150,7 +152,7 @@ public boolean processQuery(String query, ImportInspector iIDialog, OutputPrinte
if (cleanQuery.matches("\\d+[,\\d+]*")) {
frameOP.setStatus(Localization.lang("Fetching Medline by id..."));
- List bibs = MedlineImporter.fetchMedline(cleanQuery, frameOP);
+ List bibs = fetchMedline(cleanQuery, frameOP);
if (bibs.isEmpty()) {
frameOP.showMessage(Localization.lang("No references found"));
@@ -208,7 +210,7 @@ public boolean processQuery(String query, ImportInspector iIDialog, OutputPrinte
// get the ids from entrez
result = getIds(searchTerm, i, noToFetch);
- List bibs = MedlineImporter.fetchMedline(result.ids, frameOP);
+ List bibs = fetchMedline(result.ids, frameOP);
for (BibEntry entry : bibs) {
iIDialog.addEntry(entry);
}
@@ -222,6 +224,24 @@ public boolean processQuery(String query, ImportInspector iIDialog, OutputPrinte
return false;
}
+ /**
+ * Fetch and parse an medline item from eutils.ncbi.nlm.nih.gov.
+ *
+ * @param id One or several ids, separated by ","
+ *
+ * @return Will return an empty list on error.
+ */
+ private static List fetchMedline(String id, OutputPrinter status) {
+ String baseUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=citation&id=" +
+ id;
+ try {
+ URL url = new URL(baseUrl);
+ URLConnection data = url.openConnection();
+ return new MedlineImporter().importEntries(data.getInputStream(), status);
+ } catch (IOException e) {
+ return new ArrayList<>();
+ }
+ }
static class SearchResult {
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
index 2f9dc9a6389a..5d768b61def0 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
@@ -21,7 +21,7 @@
import java.util.*;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
/**
@@ -32,37 +32,29 @@
*/
public class BiblioscapeImporter extends ImportFormat {
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "Biblioscape";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "biblioscape";
+ public List getExtensions() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
+ public String getDescription() {
+ return null;
+ }
+
+ @Override
+ public boolean isRecognizedFormat(InputStream in) {
+ Objects.requireNonNull(in);
return true;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibItems = new ArrayList<>();
BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
@@ -291,12 +283,12 @@ public List importEntries(InputStream stream, OutputPrinter status) th
}
// continuation (folding) of previous line
if (previousLine == null) {
- return Collections.emptyList();
+ return new ParserResult();
}
previousLine.append(line.trim());
}
- return bibItems;
+ return new ParserResult(bibItems);
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/BibteXMLImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/BibteXMLImporter.java
index 665b96c53f2b..a7969758f83c 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BibteXMLImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BibteXMLImporter.java
@@ -20,13 +20,13 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.regex.Pattern;
-
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -43,28 +43,21 @@ public class BibteXMLImporter extends ImportFormat {
private static final Pattern START_PATTERN = Pattern.compile(" getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -80,12 +73,9 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
}
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
+ Objects.requireNonNull(stream);
List bibItems = new ArrayList<>();
@@ -107,16 +97,15 @@ public List importEntries(InputStream stream, OutputPrinter status) th
} catch (javax.xml.parsers.ParserConfigurationException e) {
LOGGER.error("Error with XML parser configuration", e);
- status.showMessage(e.getLocalizedMessage());
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
} catch (org.xml.sax.SAXException e) {
LOGGER.error("Error during XML parsing", e);
- status.showMessage(e.getLocalizedMessage());
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
} catch (IOException e) {
LOGGER.error("Error during file import", e);
- status.showMessage(e.getLocalizedMessage());
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
}
- return bibItems;
-
+ return new ParserResult(bibItems);
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
index 5eaf75eee5e5..a0822c906bc6 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
@@ -17,13 +17,12 @@
import java.io.IOException;
import java.io.InputStream;
-import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
import net.sf.jabref.importer.ParserResult;
-import net.sf.jabref.model.entry.BibEntry;
/**
* This importer exists only to enable `--importToOpen someEntry.bib`
@@ -38,24 +37,14 @@ public class BibtexImporter extends ImportFormat {
* https://github.com/JabRef/jabref/pull/379#issuecomment-158685726 for more details.
*/
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
+ public boolean isRecognizedFormat(InputStream in) {
+ Objects.requireNonNull(in);
return true;
}
- /**
- * Parses the given input stream.
- * Only plain bibtex entries are returned.
- * That especially means that metadata is ignored.
- *
- * @param in the inputStream to read from
- * @param status the OutputPrinter to put status to
- * @return a list of BibTeX entries contained in the given inputStream
- */
@Override
- public List importEntries(InputStream in, OutputPrinter status)
- throws IOException {
- ParserResult pr = BibtexParser.parse(ImportFormatReader.getReaderDefaultEncoding(in));
- return new ArrayList<>(pr.getDatabase().getEntries());
+ public ParserResult importDatabase(InputStream in) throws IOException {
+ return BibtexParser.parse(ImportFormatReader.getReaderDefaultEncoding(in));
}
@Override
@@ -64,8 +53,13 @@ public String getFormatName() {
}
@Override
- public String getExtensions() {
- return "bib";
+ public List getExtensions() {
+ return Collections.singletonList("bib");
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java
index ab43d01fdc06..4d0d5d78addb 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java
@@ -20,10 +20,11 @@
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
+import java.util.Objects;
import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
/**
@@ -37,30 +38,26 @@ public class CopacImporter extends ImportFormat {
private static final Pattern COPAC_PATTERN = Pattern.compile("^\\s*TI- ");
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "Copac";
}
- /*
- * (non-Javadoc)
- *
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "cpc";
+ public List getExtensions() {
+ return null;
}
+ @Override
+ public String getId() {
+ return "cpc";
+ }
+ @Override
+ public String getDescription() {
+ return null;
+ }
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -77,15 +74,9 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
- if (stream == null) {
- throw new IOException("No stream given.");
- }
+ public ParserResult importDatabase(InputStream stream) throws IOException {
+ Objects.requireNonNull(stream);
List entries = new LinkedList<>();
StringBuilder sb = new StringBuilder();
@@ -166,7 +157,7 @@ public List importEntries(InputStream stream, OutputPrinter status) th
results.add(b);
}
- return results;
+ return new ParserResult(results);
}
private static void setOrAppend(BibEntry b, String field, String value, String separator) {
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java
index 2d100f08dac4..a4445eff3190 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java
@@ -24,7 +24,7 @@
import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.logic.labelpattern.LabelPatternUtil;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibEntry;
@@ -44,27 +44,26 @@ public class EndnoteImporter extends ImportFormat {
private static final Pattern A_PATTERN = Pattern.compile("%A .*");
private static final Pattern E_PATTERN = Pattern.compile("%E .*");
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "Refer/Endnote";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getId() {
return "refer";
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -80,12 +79,8 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
@@ -280,7 +275,7 @@ else if ("P".equals(prefix)) {
}
- return bibitems;
+ return new ParserResult(bibitems);
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java
index 421007b5d6a8..ceadc4dd59b5 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java
@@ -25,8 +25,8 @@
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.Scanner;
import javax.xml.stream.XMLInputFactory;
@@ -34,18 +34,18 @@
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
-import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRef;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.labelpattern.LabelPatternUtil;
+import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* This importer parses text format citations using the online API of FreeCite -
* Open Source Citation Parser http://freecite.library.brown.edu/
@@ -56,21 +56,21 @@ public class FreeCiteImporter extends ImportFormat {
@Override
public boolean isRecognizedFormat(InputStream in) throws IOException {
- // TODO: We don't know how to recognize text files, therefore we return
- // "false"
+ Objects.requireNonNull(in);
+ // TODO: We don't know how to recognize text files, therefore we return "false"
return false;
}
@Override
- public List importEntries(InputStream in, OutputPrinter status)
+ public ParserResult importDatabase(InputStream in)
throws IOException {
try (Scanner scan = new Scanner(in)) {
String text = scan.useDelimiter("\\A").next();
- return importEntries(text, status);
+ return importEntries(text);
}
}
- public List importEntries(String text, OutputPrinter status) {
+ public ParserResult importEntries(String text) {
// URLencode the string for transmission
String urlencodedCitation = null;
try {
@@ -87,10 +87,10 @@ public List importEntries(String text, OutputPrinter status) {
conn = url.openConnection();
} catch (MalformedURLException e) {
LOGGER.warn("Bad URL", e);
- return Collections.emptyList();
+ return new ParserResult();
} catch (IOException e) {
LOGGER.warn("Could not download", e);
- return Collections.emptyList();
+ return new ParserResult();
}
try {
conn.setRequestProperty("accept", "text/xml");
@@ -104,13 +104,11 @@ public List importEntries(String text, OutputPrinter status) {
} catch (IllegalStateException e) {
LOGGER.warn("Already connected.", e);
} catch (IOException e) {
- status.showMessage(Localization.lang("Unable to connect to FreeCite online service."));
LOGGER.warn("Unable to connect to FreeCite online service.", e);
- return Collections.emptyList();
+ return ParserResult.fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
}
// output is in conn.getInputStream();
// new InputStreamReader(conn.getInputStream())
-
List res = new ArrayList<>();
XMLInputFactory factory = XMLInputFactory.newInstance();
@@ -214,8 +212,8 @@ public List importEntries(String text, OutputPrinter status) {
e.setType(type);
// autogenerate label (BibTeX key)
- LabelPatternUtil.makeLabel(JabRef.mainFrame.getCurrentBasePanel().getBibDatabaseContext().getMetaData(), JabRef.mainFrame.getCurrentBasePanel().getDatabase(), e);
-
+ LabelPatternUtil.makeLabel(JabRef.mainFrame.getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
+ JabRef.mainFrame.getCurrentBasePanel().getDatabase(), e);
res.add(e);
}
parser.next();
@@ -223,10 +221,10 @@ public List importEntries(String text, OutputPrinter status) {
parser.close();
} catch (IOException | XMLStreamException ex) {
LOGGER.warn("Could not parse", ex);
- return Collections.emptyList();
+ return new ParserResult();
}
- return res;
+ return new ParserResult(res);
}
@Override
@@ -234,4 +232,14 @@ public String getFormatName() {
return "text citations";
}
+ @Override
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/ImportFormat.java b/src/main/java/net/sf/jabref/importer/fileformat/ImportFormat.java
index bc1baa6229a0..fcc1cda2a3b1 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/ImportFormat.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/ImportFormat.java
@@ -15,68 +15,85 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedInputStream;
+import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Path;
import java.util.List;
+import java.util.Objects;
import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
/**
* Role of an importer for JabRef.
- *
- *
Importers are sorted according to following criteria
- *
- * custom importers come first, then importers shipped with JabRef
- *
- * then importers are sorted by name.
- *
- *
*/
public abstract class ImportFormat implements Comparable {
/**
* Using this when I have no database open or when I read
* non bibtex file formats (used by the ImportFormatReader.java)
+ *
+ * TODO: Is this field really needed or would calling IdGenerator.next() suffice?
*/
public static final String DEFAULT_BIBTEXENTRY_ID = "__ID";
- private boolean isCustomImporter;
-
-
- /**
- * Constructor for custom importers.
- */
- public ImportFormat() {
- this.isCustomImporter = false;
- }
-
/**
* Check whether the source is in the correct format for this importer.
+ *
+ * The effect of this method is primarily to avoid unnecessary processing of
+ * files when searching for a suitable import format. If this method returns
+ * false, the import routine will move on to the next import format.
+ *
+ * Thus the correct behaviour is to return false if it is certain that the file is
+ * not of the suitable type, and true otherwise. Returning true is the safe choice if not certain.
*/
public abstract boolean isRecognizedFormat(InputStream in) throws IOException;
+ public boolean isRecognizedFormat(Path filePath) throws IOException {
+ try (InputStream stream = new FileInputStream(filePath.toFile());
+ BufferedInputStream bufferedStream = new BufferedInputStream(stream)) {
+
+ bufferedStream.mark(Integer.MAX_VALUE);
+
+ return isRecognizedFormat(bufferedStream);
+ }
+ }
+
/**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
+ * Parse the database in the source.
*
* This method can be called in two different contexts - either when importing in
* a specified format, or when importing in unknown format. In the latter case,
* JabRef cycles through all available import formats. No error messages or feedback
* is displayed from individual import formats in this case.
*
- * If importing in a specified format, and an empty list is returned, JabRef reports
- * that no entries were found. If an IOException is thrown, JabRef displays the exception's
- * message in unmodified form.
+ * If importing in a specified format and an empty database is returned, JabRef reports
+ * that no entries were found.
*
- * This method should never return null. Return an empty list instead.
+ * This method should never return null.
*
- * TODO the return type should be changed to "ParseResult" as the parser could use a different encoding than the default encoding
+ * @param in the input stream to read from
*/
- public abstract List importEntries(InputStream in, OutputPrinter status) throws IOException;
+ public abstract ParserResult importDatabase(InputStream in) throws IOException ;
+
+ public ParserResult importDatabase(Path filePath) throws IOException {
+ try (InputStream stream = new FileInputStream(filePath.toFile());
+ BufferedInputStream bufferedStream = new BufferedInputStream(stream)) {
+
+ return importDatabase(bufferedStream);
+ }
+ }
+
+ @Deprecated
+ public List importEntries(InputStream in, OutputPrinter printer) throws IOException {
+ return importDatabase(in).getDatabase().getEntries();
+ }
/**
- * Name of this import format.
+ * Returns the name of this import format.
*
*
The name must be unique.
*
@@ -85,20 +102,20 @@ public ImportFormat() {
public abstract String getFormatName();
/**
- * Extensions that this importer can read.
+ * Returns the file extensions that this importer can read.
+ * The extension should contain the leading dot, so for example ".bib"
*
- * @return comma separated list of extensions or null for the default
+ * @return list of supported file extensions (not null but may be empty)
*/
- public String getExtensions() {
- return null;
- }
+ public abstract List getExtensions();
/**
- * Short, one token ID to identify the format from the command line.
+ * Returns a one-word ID which identifies this import format.
+ * Used for example, to identify the format when used from the command line.
*
- * @return command line ID
+ * @return ID, must be unique and not null
*/
- public String getCLIId() {
+ public String getId() {
String id = getFormatName();
StringBuilder result = new StringBuilder(id.length());
for (int i = 0; i < id.length(); i++) {
@@ -111,9 +128,9 @@ public String getCLIId() {
}
/**
- * Description of the ImportFormat.
+ * Returns the description of the import format.
*
- *
Implementors of ImportFormats should override this. Ideally, it should specify
+ * The description should specify
*
* what kind of entries from what sources and based on what specification it is able to import
*
@@ -122,80 +139,32 @@ public String getCLIId() {
*
* @return description of the import format
*/
- public String getDescription() {
- return "No description available for " + getFormatName() + ".";
- }
-
- /**
- * Sets if this is a custom importer.
- *
- *
For custom importers added dynamically to JabRef, this will be
- * set automatically by JabRef.
- *
- * @param isCustomImporter if this is a custom importer
- */
- public final void setIsCustomImporter(boolean isCustomImporter) {
- this.isCustomImporter = isCustomImporter;
- }
-
- /**
- * Wether this importer is a custom importer.
- *
- *
Custom importers will have precedence over built-in importers.
- *
- * @return wether this is a custom importer
- */
- public final boolean isCustomImporter() {
- return this.isCustomImporter;
- }
+ public abstract String getDescription();
- /*
- * (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
@Override
public int hashCode() {
return getFormatName().hashCode();
}
- /*
- * (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
@Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
+ public boolean equals(Object obj) {
+ if(obj == null) {
+ return false;
}
-
- if (o instanceof ImportFormat) {
- ImportFormat format = (ImportFormat) o;
- return (format.isCustomImporter() == isCustomImporter()) && format.getFormatName().equals(getFormatName());
+ if(!(obj instanceof ImportFormat)) {
+ return false;
}
- return false;
+ ImportFormat other = (ImportFormat)obj;
+ return Objects.equals(this.getFormatName(), other.getFormatName());
}
- /*
- * (non-Javadoc)
- * @see java.lang.Object#toString()
- */
@Override
public String toString() {
return getFormatName();
}
- /*
- * (non-Javadoc)
- * @see java.lang.Comparable#compareTo(java.lang.Object)
- */
@Override
- public int compareTo(ImportFormat importer) {
- int result;
- if (isCustomImporter() == importer.isCustomImporter()) {
- result = getFormatName().compareTo(importer.getFormatName());
- } else {
- result = isCustomImporter() ? 1 : -1;
- }
- return result;
+ public int compareTo(ImportFormat o) {
+ return getFormatName().compareTo(o.getFormatName());
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java
index 1e4a883843e2..efffc671eb80 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java
@@ -15,20 +15,19 @@
*/
package net.sf.jabref.importer.fileformat;
-import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.List;
-import java.util.Map;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.AuthorList;
-
-import java.util.regex.Pattern;
+import net.sf.jabref.model.entry.BibEntry;
/**
* INSPEC format importer.
@@ -37,27 +36,21 @@ public class InspecImporter extends ImportFormat {
private static final Pattern INSPEC_PATTERN = Pattern.compile("Record.*INSPEC.*");
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "INSPEC";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "inspec";
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
// Our strategy is to look for the "PY " line.
@@ -73,15 +66,12 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- String str;
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
+ String str;
while ((str = in.readLine()) != null) {
if (str.length() < 2) {
continue;
@@ -157,6 +147,6 @@ public List importEntries(InputStream stream, OutputPrinter status) th
}
- return bibitems;
+ return new ParserResult(bibitems);
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java
index b827ea1d5506..eae142a0cf4e 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java
@@ -22,14 +22,15 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.logic.formatter.CaseChangers;
-import net.sf.jabref.model.entry.MonthUtil;
import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.MonthUtil;
/**
* Importer for the ISI Web of Science, INSPEC and Medline format.
@@ -57,29 +58,26 @@ public class IsiImporter extends ImportFormat {
private static final Pattern ISI_PATTERN = Pattern.compile("FN ISI Export Format|VR 1.|PY \\d{4}");
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "ISI";
}
- /*
- * (non-Javadoc)
- *
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "isi";
+ public List getExtensions() {
+ return null;
}
+ @Override
+ public String getId() {
+ return "isi";
+ }
+ @Override
+ public String getDescription() {
+ return null;
+ }
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -106,8 +104,6 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
-
-
public static void processSubSup(Map map) {
String[] subsup = {"title", "abstract", "review", "notes"};
@@ -156,15 +152,9 @@ private static void processCapitalization(Map map) {
}
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
- if (stream == null) {
- throw new IOException("No stream given.");
- }
+ public ParserResult importDatabase(InputStream stream) throws IOException {
+ Objects.requireNonNull(stream);
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
@@ -355,7 +345,7 @@ public List importEntries(InputStream stream, OutputPrinter status) th
bibitems.add(b);
}
- return bibitems;
+ return new ParserResult(bibitems);
}
private static String parsePages(String value) {
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java
index 72c9068acb17..1d849ffce803 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java
@@ -16,16 +16,15 @@
package net.sf.jabref.importer.fileformat;
import java.io.*;
-import java.net.URL;
-import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -46,19 +45,21 @@ public String getFormatName() {
return "Medline";
}
- /*
- * (non-Javadoc)
- *
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getId() {
return "medline";
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -77,31 +78,9 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Fetch and parse an medline item from eutils.ncbi.nlm.nih.gov.
- *
- * @param id One or several ids, separated by ","
- *
- * @return Will return an empty list on error.
- */
- public static List fetchMedline(String id, OutputPrinter status) {
- String baseUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=citation&id=" +
- id;
- try {
- URL url = new URL(baseUrl);
- URLConnection data = url.openConnection();
- return new MedlineImporter().importEntries(data.getInputStream(), status);
- } catch (IOException e) {
- return new ArrayList<>();
- }
- }
-
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
+ Objects.requireNonNull(stream);
// Obtain a factory object for creating SAX parsers
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
@@ -135,18 +114,18 @@ public List importEntries(InputStream stream, OutputPrinter status) th
// When you're done, report the results stored by your handler
// object
bibItems.addAll(handler.getItems());
- } catch (javax.xml.parsers.ParserConfigurationException e1) {
- LOGGER.error("Error with XML parser configuration", e1);
- status.showMessage(e1.getLocalizedMessage());
- } catch (org.xml.sax.SAXException e2) {
- LOGGER.error("Error during XML parsing", e2);
- status.showMessage(e2.getLocalizedMessage());
- } catch (IOException e3) {
- LOGGER.error("Error during file import", e3);
- status.showMessage(e3.getLocalizedMessage());
+ } catch (javax.xml.parsers.ParserConfigurationException e) {
+ LOGGER.error("Error with XML parser configuration", e);
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
+ } catch (org.xml.sax.SAXException e) {
+ LOGGER.error("Error during XML parsing", e);
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
+ } catch (IOException e) {
+ LOGGER.error("Error during file import", e);
+ return ParserResult.fromErrorMessage(e.getLocalizedMessage());
}
- return bibItems;
+ return new ParserResult(bibItems);
}
}
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 ceec580d3cee..5e17ad000754 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java
@@ -17,19 +17,19 @@
package net.sf.jabref.importer.fileformat;
-import java.util.regex.Pattern;
-import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.List;
-import java.util.Map;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.AuthorList;
+import net.sf.jabref.model.entry.BibEntry;
/**
* Importer for the MEDLINE Plain format.
@@ -45,27 +45,21 @@ public class MedlinePlainImporter extends ImportFormat {
private static final Pattern PMC_PATTERN = Pattern.compile("PMC.*-.*");
private static final Pattern PMCR_PATTERN = Pattern.compile("PMCR.*-.*");
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "MedlinePlain";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "medlineplain";
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -84,12 +78,8 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
@@ -285,7 +275,7 @@ else if ("AID".equals(lab)) {
}
- return bibitems;
+ return new ParserResult(bibitems);
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java
index b17835c34c9b..c92503c7be59 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java
@@ -18,12 +18,12 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import java.util.Objects;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.logic.msbib.MSBibDatabase;
import org.w3c.dom.Document;
@@ -38,13 +38,9 @@ public class MsBibImporter extends ImportFormat {
@Override
public boolean isRecognizedFormat(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
/*
- This method is available for checking if a file can be of the MSBib type.
- The effect of this method is primarily to avoid unnecessary processing of
- files when searching for a suitable import format. If this method returns
- false, the import routine will move on to the next import format.
-
The correct behaviour is to return false if it is certain that the file is
not of the MsBib type, and true otherwise. Returning true is the safe choice
if not certain.
@@ -61,26 +57,27 @@ public boolean isRecognizedFormat(InputStream in) throws IOException {
return (docin == null) || docin.getDocumentElement().getTagName().contains("Sources");
}
- /**
- * String used to identify this import filter on the command line.
- * @return "msbib"
- */
- public String getCommandLineId() {
- return "msbib";
- }
-
@Override
- public List importEntries(InputStream in, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
MSBibDatabase dbase = new MSBibDatabase();
-
- return dbase.importEntries(in);
+ return new ParserResult(dbase.importEntries(in));
}
@Override
public String getFormatName() {
- // This method should return the name of this import format.
return "MSBib";
}
+ @Override
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java
index 2ce39b06723a..c922e3484f9f 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java
@@ -15,19 +15,21 @@
*/
package net.sf.jabref.importer.fileformat;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.List;
-import java.util.Map;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.*;
+import net.sf.jabref.importer.ParserResult;
+import net.sf.jabref.model.entry.AuthorList;
+import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.IdGenerator;
/**
* Imports an Ovid file.
@@ -53,28 +55,22 @@ public class OvidImporter extends ImportFormat {
private static final Pattern OVID_PATTERN = Pattern.compile(OVID_PATTERN_STRING);
private static final int MAX_ITEMS = 50;
- /**
- * Return the name of this import format.
- */
+
@Override
public String getFormatName() {
return "Ovid";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "ovid";
+ public List getExtensions() {
+ return null;
}
+ @Override
+ public String getDescription() {
+ return null;
+ }
-
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -93,12 +89,8 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
@@ -242,7 +234,7 @@ public List importEntries(InputStream stream, OutputPrinter status) th
}
- return bibitems;
+ return new ParserResult(bibitems);
}
/**
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
index 3d38236ce475..b93460ff0e19 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
@@ -1,8 +1,18 @@
package net.sf.jabref.importer.fileformat;
-import net.sf.jabref.importer.ImportInspector;
-import net.sf.jabref.importer.OutputPrinter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.importer.fetcher.DOItoBibTeXFetcher;
+import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.DOI;
import net.sf.jabref.logic.xmp.EncryptedPdfsNotSupportedException;
import net.sf.jabref.logic.xmp.XMPUtil;
@@ -10,23 +20,10 @@
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.model.entry.EntryType;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import com.google.common.base.Strings;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
-import com.google.common.base.Strings;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
/**
* PdfContentImporter parses data of the first page of the PDF and creates a BibTeX entry.
*
@@ -35,7 +32,6 @@
* Integrating XMP support is future work
*/
public class PdfContentImporter extends ImportFormat {
- private static final Log LOGGER = LogFactory.getLog(PdfContentImporter.class);
private static final Pattern YEAR_EXTRACT_PATTERN = Pattern.compile("\\d{4}");
// we can store the DOItoBibTeXFetcher as single reference as the fetcher doesn't hold internal state
@@ -180,41 +176,24 @@ private static String streamlineTitle(String title) {
@Override
public boolean isRecognizedFormat(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
return false;
}
@Override
- public List importEntries(InputStream in, OutputPrinter status) throws IOException {
- final ArrayList result = new ArrayList<>(1);
+ public ParserResult importDatabase(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
+ final ArrayList result = new ArrayList<>(1);
try (PDDocument document = XMPUtil.loadWithAutomaticDecryption(in)) {
String firstPageContents = getFirstPageContents(document);
Optional doi = DOI.findInText(firstPageContents);
if (doi.isPresent()) {
- ImportInspector inspector = new ImportInspector() {
-
- @Override
- public void toFront() {
- // Do nothing
- }
-
- @Override
- public void setProgress(int current, int max) {
- // Do nothing
- }
-
- @Override
- public void addEntry(BibEntry entry) {
- // add the entry to the result object
- result.add(entry);
- }
- };
-
- DOI_TO_BIBTEX_FETCHER.processQuery(doi.get().getDOI(), inspector, status);
- if (!result.isEmpty()) {
- return result;
- }
+ ParserResult parserResult = new ParserResult(result);
+ BibEntry entry = DOI_TO_BIBTEX_FETCHER.getEntryFromDOI(doi.get().getDOI(), parserResult);
+ parserResult.getDatabase().insertEntry(entry);
+ return parserResult;
}
// idea: split[] contains the different lines
@@ -231,7 +210,7 @@ public void addEntry(BibEntry entry) {
if (i >= lines.length) {
// PDF could not be parsed or is empty
// return empty list
- return result;
+ return new ParserResult();
}
// we start at the current line
@@ -480,10 +459,12 @@ public void addEntry(BibEntry entry) {
result.add(entry);
} catch (EncryptedPdfsNotSupportedException e) {
- LOGGER.info("Decryption not supported");
- return Collections.EMPTY_LIST;
+ return ParserResult.fromErrorMessage(Localization.lang("Decryption not supported."));
+ } catch(IOException exception) {
+ return ParserResult.fromErrorMessage(exception.getLocalizedMessage());
}
- return result;
+
+ return new ParserResult(result);
}
private String getFirstPageContents(PDDocument document) throws IOException {
@@ -589,4 +570,14 @@ public String getFormatName() {
return "PDFcontent";
}
+ @Override
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
}
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 65d54976c4fe..1dc8fd50aab2 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java
@@ -18,9 +18,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import java.util.Objects;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.xmp.XMPUtil;
@@ -34,12 +34,19 @@ public String getFormatName() {
return Localization.lang("XMP-annotated PDF");
}
- /**
- * Returns a list of all BibtexEntries found in the inputstream.
- */
@Override
- public List importEntries(InputStream in, OutputPrinter status) throws IOException {
- return XMPUtil.readXMP(in);
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public ParserResult importDatabase(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
+ try {
+ return new ParserResult(XMPUtil.readXMP(in));
+ } catch (IOException exception) {
+ return ParserResult.fromErrorMessage(exception.getLocalizedMessage());
+ }
}
/**
@@ -48,16 +55,18 @@ public List importEntries(InputStream in, OutputPrinter status) throws
*/
@Override
public boolean isRecognizedFormat(InputStream in) throws IOException {
+ Objects.requireNonNull(in);
return XMPUtil.hasMetadata(in);
}
- /**
- * String used to identify this import filter on the command line.
- *
- * @return "xmp"
- */
- public String getCommandLineId() {
+ @Override
+ public String getId() {
return "xmp";
}
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java
index a8cb862a2172..c7cd78f99f23 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java
@@ -25,9 +25,9 @@
import java.util.*;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.IdGenerator;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.IdGenerator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -162,37 +162,21 @@ public class RepecNepImporter extends ImportFormat {
private String preLine = "";
private boolean inOverviewSection;
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "REPEC New Economic Papers (NEP)";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
+ public String getId() {
return "repecnep";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getExtensions()
- */
@Override
- public String getExtensions() {
- return ".txt";
+ public List getExtensions() {
+ return Collections.singletonList(".txt");
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getDescription()
- */
@Override
public String getDescription() {
return
@@ -203,10 +187,6 @@ public String getDescription() {
+ "contains the line \"nep.repec.org\".";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#isRecognizedFormat(java.io.InputStream)
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
// read the first couple of lines
@@ -427,12 +407,10 @@ private boolean isStartOfWorkingPaper() {
return this.lastLine.matches("\\d+\\.\\s.*") && !this.inOverviewSection && "".equals(this.preLine.trim());
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#importEntries(java.io.InputStream)
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
+ Objects.requireNonNull(stream);
+
List bibitems = new ArrayList<>();
String paperNoStr = null;
this.line = 0;
@@ -475,14 +453,11 @@ public List importEntries(InputStream stream, OutputPrinter status) th
if (paperNoStr != null) {
message += ", paper no. " + paperNoStr + ": ";
}
- message += e.getMessage();
+ message += e.getLocalizedMessage();
LOGGER.error(message, e);
- if (!(e instanceof IOException)) {
- e = new IOException(message);
- }
- throw (IOException) e;
+ return ParserResult.fromErrorMessage(message);
}
- return bibitems;
+ return new ParserResult(bibitems);
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java
index 063c0b602a12..41c03516efeb 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java
@@ -15,18 +15,20 @@
*/
package net.sf.jabref.importer.fileformat;
-import java.util.regex.Pattern;
-import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.List;
-import java.util.Map;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.*;
+import net.sf.jabref.importer.ParserResult;
+import net.sf.jabref.model.entry.AuthorList;
+import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.model.entry.MonthUtil;
/**
* Imports a Biblioscape Tag File. The format is described on
@@ -38,26 +40,21 @@ public class RisImporter extends ImportFormat {
private static final Pattern RECOGNIZED_FORMAT_PATTERN = Pattern.compile("TY - .*");
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "RIS";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "ris";
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
@@ -74,12 +71,8 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
@@ -284,7 +277,7 @@ else if ("ID".equals(lab)) {
}
- return bibitems;
+ return new ParserResult(bibitems);
}
}
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 ff676bc73e4b..1cf5cca5f072 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/SilverPlatterImporter.java
@@ -15,19 +15,18 @@
*/
package net.sf.jabref.importer.fileformat;
-import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.List;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
+import java.util.regex.Pattern;
import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
-import net.sf.jabref.model.entry.BibEntry;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.AuthorList;
-
-import java.util.regex.Pattern;
+import net.sf.jabref.model.entry.BibEntry;
/**
* Imports a SilverPlatter exported file. This is a poor format to parse,
@@ -37,27 +36,21 @@ public class SilverPlatterImporter extends ImportFormat {
private static final Pattern START_PATTERN = Pattern.compile("Record.*INSPEC.*");
-
- /**
- * Return the name of this import format.
- */
@Override
public String getFormatName() {
return "SilverPlatter";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "silverplatter";
+ public List getExtensions() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
public boolean isRecognizedFormat(InputStream stream) throws IOException {
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
@@ -81,12 +74,8 @@ public boolean isRecognizedFormat(InputStream stream) throws IOException {
return false;
}
- /**
- * Parse the entries in the source, and return a List of BibEntry
- * objects.
- */
@Override
- public List importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(InputStream stream) throws IOException {
List bibitems = new ArrayList<>();
try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
boolean isChapter = false;
@@ -216,6 +205,6 @@ public List importEntries(InputStream stream, OutputPrinter status) th
}
}
- return bibitems;
+ return new ParserResult(bibitems);
}
}
diff --git a/src/test/java/net/sf/jabref/importer/ImportFormatReaderTest.java b/src/test/java/net/sf/jabref/importer/ImportFormatReaderIntegrationTest.java
similarity index 76%
rename from src/test/java/net/sf/jabref/importer/ImportFormatReaderTest.java
rename to src/test/java/net/sf/jabref/importer/ImportFormatReaderIntegrationTest.java
index 7b7090602497..8d1ad266ed47 100644
--- a/src/test/java/net/sf/jabref/importer/ImportFormatReaderTest.java
+++ b/src/test/java/net/sf/jabref/importer/ImportFormatReaderIntegrationTest.java
@@ -1,36 +1,34 @@
package net.sf.jabref.importer;
-import static org.junit.Assert.*;
-
import java.io.IOException;
import java.net.URISyntaxException;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
+import net.sf.jabref.Globals;
+import net.sf.jabref.JabRefPreferences;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import net.sf.jabref.Globals;
-import net.sf.jabref.JabRefPreferences;
+import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
-public class ImportFormatReaderTest {
+public class ImportFormatReaderIntegrationTest {
private ImportFormatReader reader;
- private final String resourceName;
private final int count;
public final String format;
- private final String fileName;
+ private final Path file;
- public ImportFormatReaderTest(String resource, String format, int count) throws URISyntaxException {
- this.resourceName = resource;
+ public ImportFormatReaderIntegrationTest(String resource, String format, int count) throws URISyntaxException {
this.format = format;
this.count = count;
- this.fileName = Paths.get(ImportFormatReaderTest.class.getResource(resourceName).toURI()).toString();
+ this.file = Paths.get(ImportFormatReaderIntegrationTest.class.getResource(resource).toURI());
}
@@ -43,14 +41,13 @@ public void setUp() {
@Test
public void testImportUnknownFormat() {
- ImportFormatReader.UnknownFormatImport unknownFormat = reader.importUnknownFormat(fileName);
+ ImportFormatReader.UnknownFormatImport unknownFormat = reader.importUnknownFormat(file);
assertEquals(count, unknownFormat.parserResult.getDatabase().getEntryCount());
}
@Test
public void testImportFormatFromFile() throws IOException {
- OutputPrinter nullPrinter = new OutputPrinterToNull();
- assertEquals(count, reader.importFromFile(format, fileName, nullPrinter).size());
+ assertEquals(count, reader.importFromFile(format, file).getDatabase().getEntries().size());
}
@Parameterized.Parameters(name = "{index}: {1}")
diff --git a/src/test/java/net/sf/jabref/importer/ImportFormatReaderTestParameterless.java b/src/test/java/net/sf/jabref/importer/ImportFormatReaderTestParameterless.java
index 366cb3d0690f..1b071b4a14ed 100644
--- a/src/test/java/net/sf/jabref/importer/ImportFormatReaderTestParameterless.java
+++ b/src/test/java/net/sf/jabref/importer/ImportFormatReaderTestParameterless.java
@@ -1,21 +1,22 @@
package net.sf.jabref.importer;
-import static org.junit.Assert.*;
-
import java.io.IOException;
-import java.util.List;
+import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
-import org.junit.Before;
-import org.junit.Test;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
-import net.sf.jabref.model.entry.BibEntry;
+
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
public class ImportFormatReaderTestParameterless {
private ImportFormatReader reader;
- private ImportFormatReader.UnknownFormatImport unknownFormat;
- public List result;
+
@Before
public void setUp() {
Globals.prefs = JabRefPreferences.getInstance();
@@ -24,21 +25,21 @@ public void setUp() {
}
@Test
- public void testImportUnknownFormatNotWorking() {
- String fileName = ImportFormatReaderTestParameterless.class.getResource("fileformat/emptyFile.xml").getFile();
- unknownFormat = reader.importUnknownFormat(fileName);
+ public void testImportUnknownFormatNotWorking() throws URISyntaxException {
+ Path file = Paths.get(ImportFormatReaderTestParameterless.class.getResource("fileformat/emptyFile.xml").toURI());
+ ImportFormatReader.UnknownFormatImport unknownFormat = reader.importUnknownFormat(file);
assertNull(unknownFormat);
}
@Test(expected = NullPointerException.class)
public void testNullImportUnknownFormat() {
- unknownFormat = reader.importUnknownFormat(null);
+ reader.importUnknownFormat((Path)null);
fail();
}
@Test(expected = IllegalArgumentException.class)
public void testImportFromFileUnknownFormat() throws IOException {
- result = reader.importFromFile("someunknownformat", "doesn't matter", new OutputPrinterToNull());
+ reader.importFromFile("someunknownformat", Paths.get("somepath"));
fail();
}
}
diff --git a/src/test/java/net/sf/jabref/importer/fileformat/BiblioscapeImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/BiblioscapeImporterTest.java
index 347df5e61e19..4952671fd515 100644
--- a/src/test/java/net/sf/jabref/importer/fileformat/BiblioscapeImporterTest.java
+++ b/src/test/java/net/sf/jabref/importer/fileformat/BiblioscapeImporterTest.java
@@ -29,7 +29,7 @@ public void testGetFormatName() {
@Test
public void testGetCLIID() {
BiblioscapeImporter importer = new BiblioscapeImporter();
- Assert.assertEquals(importer.getCLIId(), "biblioscape");
+ Assert.assertEquals(importer.getId(), "biblioscape");
}
@Test
diff --git a/src/test/java/net/sf/jabref/importer/fileformat/BibtexImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/BibtexImporterTest.java
index 9f3bf655215c..a34e125283bb 100644
--- a/src/test/java/net/sf/jabref/importer/fileformat/BibtexImporterTest.java
+++ b/src/test/java/net/sf/jabref/importer/fileformat/BibtexImporterTest.java
@@ -1,20 +1,19 @@
package net.sf.jabref.importer.fileformat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.importer.OutputPrinterToNull;
import net.sf.jabref.model.entry.BibEntry;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
/**
* This class tests the BibtexImporter.
* That importer is only used for --importToOpen, which is currently untested
@@ -97,9 +96,4 @@ public void testImportEntries() throws IOException {
public void testGetFormatName() {
assertEquals("BibTeX", importer.getFormatName());
}
-
- @Test
- public void testGetExtensions() {
- assertEquals("bib", importer.getExtensions());
- }
}
diff --git a/src/test/java/net/sf/jabref/importer/fileformat/EndnoteImporterTest.java b/src/test/java/net/sf/jabref/importer/fileformat/EndnoteImporterTest.java
index 07b90ef4f76c..8e7a8e88de07 100644
--- a/src/test/java/net/sf/jabref/importer/fileformat/EndnoteImporterTest.java
+++ b/src/test/java/net/sf/jabref/importer/fileformat/EndnoteImporterTest.java
@@ -34,7 +34,7 @@ public void testGetFormatName() {
@Test
public void testGetCLIId() {
- assertEquals("refer", importer.getCLIId());
+ assertEquals("refer", importer.getId());
}
@Test
diff --git a/src/test/java/net/sf/jabref/importer/fileformat/ImportFormatTest.java b/src/test/java/net/sf/jabref/importer/fileformat/ImportFormatTest.java
new file mode 100644
index 000000000000..2265ebf5b489
--- /dev/null
+++ b/src/test/java/net/sf/jabref/importer/fileformat/ImportFormatTest.java
@@ -0,0 +1,105 @@
+package net.sf.jabref.importer.fileformat;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.regex.Pattern;
+
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+import org.mockito.Mockito;
+import static org.mockito.Mockito.when;
+
+@RunWith(Parameterized.class)
+public class ImportFormatTest {
+
+ @Parameter
+ public ImportFormat format;
+
+ @Test(expected = NullPointerException.class)
+ public void isRecognizedFormatWithNullThrowsException() throws IOException {
+ format.isRecognizedFormat((InputStream)null);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void importDatabaseWithNullThrowsException() throws IOException {
+ format.importDatabase((InputStream)null);
+ }
+
+ @Test
+ public void importDatabaseWithUnrecognizedInputDoesNotReturnNull() throws IOException {
+ InputStream stream = new ByteArrayInputStream("!#!bad string".getBytes(StandardCharsets.UTF_8));
+ Assert.assertNotNull(format.importDatabase(stream));
+ }
+
+ @Test
+ public void getFormatterNameDoesNotReturnNull() {
+ Assert.assertNotNull(format.getFormatName());
+ }
+
+ @Test
+ @Ignore
+ public void getExtensionsDoesNotReturnNull() {
+ Assert.assertNotNull(format.getExtensions());
+ }
+
+ @Test
+ public void getIdDoesNotReturnNull() {
+ Assert.assertNotNull(format.getId());
+ }
+
+ @Test
+ public void getIdDoesNotContainWhitespace() {
+ Pattern whitespacePattern = Pattern.compile("\\s");
+ Assert.assertFalse(whitespacePattern.matcher(format.getId()).find());
+ }
+
+ @Test
+ public void getIdStripsSpecialCharactersAndConvertsToLowercase() {
+ ImportFormat importFormat = Mockito.mock(ImportFormat.class, Mockito.CALLS_REAL_METHODS);
+ when(importFormat.getFormatName()).thenReturn("*Test-Importer");
+ Assert.assertEquals("testimporter", importFormat.getId());
+ }
+
+ @Test
+ @Ignore
+ public void getDescriptionDoesNotReturnNull() {
+ Assert.assertNotNull(format.getDescription());
+ }
+
+ @Parameters(name = "{index}: {0}")
+ public static Collection