diff --git a/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java b/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java
index 873d7b09cb7..32c7c29a413 100644
--- a/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java
+++ b/src/main/java/net/sf/jabref/cli/ArgumentProcessor.java
@@ -2,6 +2,8 @@
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;
@@ -515,14 +517,19 @@ private static Optional importFile(String argument) {
if ((data.length > 1) && !"*".equals(data[1])) {
System.out.println(Localization.lang("Importing") + ": " + data[0]);
try {
- List entries;
+ Path file;
if (OS.WINDOWS) {
- entries = Globals.IMPORT_FORMAT_READER.importFromFile(data[1], data[0], JabRefGUI.getMainFrame());
+ file = Paths.get(data[0]);
} else {
- entries = Globals.IMPORT_FORMAT_READER.importFromFile(data[1],
- data[0].replace("~", System.getProperty("user.home")), JabRefGUI.getMainFrame());
+ file = Paths.get(data[0].replace("~", System.getProperty("user.home")));
}
- return Optional.of(new ParserResult(entries));
+ ParserResult result = Globals.IMPORT_FORMAT_READER.importFromFile(data[1], file);
+
+ if(result.hasWarnings()) {
+ JabRefGUI.getMainFrame().showMessage(result.getErrorMessage());
+ }
+
+ return Optional.of(result);
} 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 04704edb901..489a69af8c8 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.AbstractAction;
import javax.swing.ActionMap;
@@ -103,7 +104,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 8577e75d45c..f5ec6b6f6af 100644
--- a/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java
+++ b/src/main/java/net/sf/jabref/exporter/SaveDatabaseAction.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
+import java.util.Collections;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
@@ -303,8 +304,8 @@ public void saveAs() throws Throwable {
String chosenFile;
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) {
canceled = true;
return; // canceled
diff --git a/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java b/src/main/java/net/sf/jabref/external/ExternalFileTypeEntryEditor.java
index d7f0f93e3c0..99ceaf30c46 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.BorderFactory;
import javax.swing.ButtonGroup;
@@ -263,7 +264,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, "",
+ 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 23caa58e7ef..9533006abf3 100644
--- a/src/main/java/net/sf/jabref/external/MoveFileAction.java
+++ b/src/main/java/net/sf/jabref/external/MoveFileAction.java
@@ -18,6 +18,7 @@
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;
@@ -142,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; // canceled
diff --git a/src/main/java/net/sf/jabref/gui/BasePanel.java b/src/main/java/net/sf/jabref/gui/BasePanel.java
index 7b628b74099..3eae0ea90e1 100644
--- a/src/main/java/net/sf/jabref/gui/BasePanel.java
+++ b/src/main/java/net/sf/jabref/gui/BasePanel.java
@@ -2328,8 +2328,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 087b6eca5ac..de93d9657ce 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.isEmpty()) {
- 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.isEmpty()) {
- 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 e238934e40b..2858bffadf3 100644
--- a/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java
+++ b/src/main/java/net/sf/jabref/gui/FileListEntryEditor.java
@@ -23,6 +23,7 @@
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;
@@ -364,8 +365,8 @@ public void actionPerformed(ActionEvent e) {
} else {
workingDir = new File(Globals.prefs.get(JabRefPreferences.FILE_WORKING_DIRECTORY));
}
-
- String selection = FileDialogs.getNewFile(parent, workingDir, "", JFileChooser.OPEN_DIALOG, false);
+ String selection = FileDialogs.getNewFile(parent, workingDir, Collections.emptyList(),
+ JFileChooser.OPEN_DIALOG, false);
if (selection != null) {
File newFile = new File(selection);
// Store the directory for next time:
diff --git a/src/main/java/net/sf/jabref/gui/OpenFileFilter.java b/src/main/java/net/sf/jabref/gui/OpenFileFilter.java
index e499969fff1..c5a8fbb9150 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 2dc4e73a02a..88f5757e662 100644
--- a/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java
+++ b/src/main/java/net/sf/jabref/gui/actions/BrowseAction.java
@@ -17,6 +17,8 @@
import java.awt.event.ActionEvent;
import java.io.File;
+import java.util.Collections;
+import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
@@ -37,21 +39,21 @@ public final class BrowseAction extends AbstractAction {
private final JTextField comp;
private final boolean dir;
private final JComponent focusTarget;
- private final String extension;
+ private final List extension;
public static BrowseAction buildForDir(JFrame frame, JTextField tc) {
- return new BrowseAction(frame, tc, true, null, "");
+ return new BrowseAction(frame, tc, true, null, Collections.emptyList());
}
public static BrowseAction buildForDir(JTextField tc) {
- return new BrowseAction(null, tc, true, null, "");
+ return new BrowseAction(null, tc, true, null, Collections.emptyList());
}
public static BrowseAction buildForFile(JTextField tc) {
- return new BrowseAction(null, tc, false, null, "");
+ return new BrowseAction(null, tc, false, null, Collections.emptyList());
}
- public static BrowseAction buildForFile(JTextField tc, JComponent focusTarget, String extension) {
+ public static BrowseAction buildForFile(JTextField tc, JComponent focusTarget, List extension) {
return new BrowseAction(null, tc, false, focusTarget, extension);
}
@@ -59,7 +61,7 @@ public static BrowseAction buildForDir(JTextField tc, JComponent focusTarget) {
return new BrowseAction(null, tc, true, focusTarget, null);
}
- private BrowseAction(JFrame frame, JTextField tc, boolean dir, JComponent focusTarget, String extension) {
+ private BrowseAction(JFrame frame, JTextField tc, boolean dir, JComponent focusTarget, List extension) {
super(Localization.lang("Browse"));
this.frame = frame;
this.dir = dir;
@@ -90,5 +92,4 @@ private String askUser() {
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 33ebb4a8352..27f2731d5bb 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 aed710d96d7..cdcea17c256 100644
--- a/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java
+++ b/src/main/java/net/sf/jabref/gui/journals/ManageJournalsPanel.java
@@ -454,9 +454,11 @@ public BrowseAction(JTextField tc, boolean dir) {
public void actionPerformed(ActionEvent e) {
String chosen;
if (dir) {
- chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), "", 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()), "", JFileChooser.OPEN_DIALOG, false);
+ chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Collections.emptyList(),
+ JFileChooser.OPEN_DIALOG, false);
}
if (chosen != null) {
comp.setText(Paths.get(chosen).toString());
diff --git a/src/main/java/net/sf/jabref/gui/openoffice/StyleSelectDialog.java b/src/main/java/net/sf/jabref/gui/openoffice/StyleSelectDialog.java
index 667597e85a7..522b4baaf91 100644
--- a/src/main/java/net/sf/jabref/gui/openoffice/StyleSelectDialog.java
+++ b/src/main/java/net/sf/jabref/gui/openoffice/StyleSelectDialog.java
@@ -23,6 +23,7 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
+import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
@@ -497,7 +498,7 @@ public AddFileDialog() {
super(diag, Localization.lang("Add style file"), true);
JButton browse = new JButton(Localization.lang("Browse"));
- browse.addActionListener(BrowseAction.buildForFile(newFile, null, ".jstyle"));
+ browse.addActionListener(BrowseAction.buildForFile(newFile, null, Collections.singletonList(".jstyle")));
// Build content panel
FormBuilder builder = FormBuilder.create();
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 72bba9bd312..73eb5c7a180 100644
--- a/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java
+++ b/src/main/java/net/sf/jabref/gui/plaintextimport/TextInputDialog.java
@@ -120,6 +120,7 @@
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.bibtex.BibEntryWriter;
import net.sf.jabref.logic.bibtex.LatexFieldFormatter;
@@ -510,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 be238861aec..84d9f5bd31f 100644
--- a/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java
+++ b/src/main/java/net/sf/jabref/gui/preftabs/PreferencesDialog.java
@@ -22,6 +22,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;
@@ -166,8 +167,8 @@ public PreferencesDialog(JabRefFrame parent) {
// 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;
}
@@ -188,8 +189,8 @@ public PreferencesDialog(JabRefFrame parent) {
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 44394dbb91d..e4668770216 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, ClassNotFoundException,
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 aa0fe301dd8..579c7e662ff 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.AbstractAction;
@@ -95,20 +97,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();
@@ -126,8 +130,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 8b9ec7aea92..a5d099234b4 100644
--- a/src/main/java/net/sf/jabref/importer/ImportFormatReader.java
+++ b/src/main/java/net/sf/jabref/importer/ImportFormatReader.java
@@ -15,15 +15,9 @@
*/
package net.sf.jabref.importer;
-import java.io.BufferedInputStream;
-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.nio.file.Path;
+import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -61,7 +55,8 @@ 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<>();
@@ -114,14 +109,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);
@@ -129,28 +124,7 @@ public List importFromFile(String format, String filename, OutputPrint
throw new IllegalArgumentException("Unknown import format: " + format);
}
- return importFromFile(importer.get(), filename, status);
- }
-
- public List importFromFile(ImportFormat importer, String filename, OutputPrinter status) throws IOException {
- Objects.requireNonNull(importer);
- Objects.requireNonNull(filename);
- File file = new File(filename);
-
- try (InputStream stream = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(stream)) {
-
- bis.mark(Integer.MAX_VALUE);
-
- if (!importer.isRecognizedFormat(bis)) {
- throw new IOException("Wrong file format");
- }
- }
-
- try (InputStream stream = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(stream)) {
- return importer.importEntries(bis, status);
- }
+ return importer.get().importDatabase(file, Globals.prefs.getDefaultEncoding());
}
/**
@@ -184,35 +158,13 @@ public String getImportFormatList() {
sb.append(StringUtil.repeatSpaces(pad));
sb.append(" : ");
- sb.append(imFo.getCLIId());
+ sb.append(imFo.getId());
sb.append('\n');
}
return sb.toString();
}
-
-
- public static InputStreamReader getUTF8Reader(File f) throws IOException {
- return getReader(f, StandardCharsets.UTF_8);
- }
-
- public static InputStreamReader getUTF16Reader(File f) throws IOException {
- return getReader(f, StandardCharsets.UTF_16);
- }
-
- public static InputStreamReader getReader(File f, Charset charset)
- throws IOException {
- return new InputStreamReader(new FileInputStream(f), charset);
- }
-
- public static Reader getReaderDefaultEncoding(InputStream in) {
- InputStreamReader reader;
- reader = new InputStreamReader(in, Globals.prefs.getDefaultEncoding());
-
- return reader;
- }
-
public static class UnknownFormatImport {
public final String format;
@@ -225,6 +177,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,
@@ -234,26 +189,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;
@@ -261,14 +211,16 @@ public UnknownFormatImport importUnknownFormat(String filename) {
// Cycle through all importers:
for (ImportFormat imFo : getImportFormats()) {
-
try {
+ if(!imFo.isRecognizedFormat(file, Globals.prefs.getDefaultEncoding())) {
+ continue;
+ }
- List entries = importFromFile(imFo, filename, nullOutput);
+ ParserResult parserResult = imFo.importDatabase(file, Globals.prefs.getDefaultEncoding());
+ 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 0b6e036f79f..3956f8d67b9 100644
--- a/src/main/java/net/sf/jabref/importer/ImportMenuItem.java
+++ b/src/main/java/net/sf/jabref/importer/ImportMenuItem.java
@@ -19,8 +19,11 @@
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;
@@ -105,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();
@@ -125,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:
@@ -134,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 = importer.importDatabase(file, Globals.prefs.getDefaultEncoding());
+ 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 ab92590d65b..b485c9832c7 100644
--- a/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
+++ b/src/main/java/net/sf/jabref/importer/OpenDatabaseAction.java
@@ -16,17 +16,13 @@
package net.sf.jabref.importer;
import java.awt.event.ActionEvent;
-import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-import java.util.Optional;
import javax.swing.Action;
import javax.swing.JOptionPane;
@@ -48,7 +44,7 @@
import net.sf.jabref.gui.actions.MnemonicAwareAction;
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.gui.undo.NamedCompound;
-import net.sf.jabref.importer.fileformat.BibtexParser;
+import net.sf.jabref.importer.fileformat.BibtexImporter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.io.FileBasedLock;
import net.sf.jabref.logic.util.strings.StringUtil;
@@ -100,7 +96,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));
@@ -114,23 +111,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
*
@@ -305,7 +285,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(() -> OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult, true));
+ SwingUtilities.invokeLater(
+ () -> OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult, true));
}
}
@@ -342,7 +323,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") + ".");
@@ -354,30 +335,8 @@ public BasePanel addNewDatabase(ParserResult result, final File file, boolean ra
* Opens a new database.
*/
public static ParserResult loadDatabase(File fileToOpen, Charset defaultEncoding) throws IOException {
-
- // We want to check if there is a JabRef signature in the file, because that would tell us
- // which character encoding is used. However, to read the signature we must be using a compatible
- // 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();
- try (Reader utf8Reader = ImportFormatReader.getUTF8Reader(fileToOpen)) {
- suppliedEncoding = OpenDatabaseAction.getSuppliedEncoding(utf8Reader);
- }
- // Now if that didn't get us anywhere, we check with the 16 bit encoding:
- if (!suppliedEncoding.isPresent()) {
- try (Reader utf16Reader = ImportFormatReader.getUTF16Reader(fileToOpen)) {
- suppliedEncoding = OpenDatabaseAction.getSuppliedEncoding(utf16Reader);
- }
- }
-
// Open and parse file
- try (InputStreamReader reader = openFile(fileToOpen, suppliedEncoding, defaultEncoding)) {
- BibtexParser parser = new BibtexParser(reader);
-
- ParserResult result = parser.parse();
- result.setEncoding(Charset.forName(reader.getEncoding()));
- result.setFile(fileToOpen);
+ ParserResult result = new BibtexImporter().importDatabase(fileToOpen.toPath(), defaultEncoding);
if (SpecialFieldsUtils.keywordSyncEnabled()) {
NamedCompound compound = new NamedCompound("SpecialFieldSync");
@@ -387,81 +346,16 @@ public static ParserResult loadDatabase(File fileToOpen, Charset defaultEncoding
LOGGER.debug("Synchronized special fields based on keywords");
}
- return result;
- }
- }
-
- /**
- * Opens the file with the provided encoding. If this fails (or no encoding is provided), then the fallback encoding
- * will be used.
- */
- private static InputStreamReader openFile(File fileToOpen, Optional encoding, Charset defaultEncoding)
- throws IOException {
- if (encoding.isPresent()) {
- try {
- return ImportFormatReader.getReader(fileToOpen, encoding.get());
- } catch (IOException ex) {
- LOGGER.warn("Problem getting reader", ex);
- // The supplied encoding didn't work out, so we use the fallback.
- return ImportFormatReader.getReader(fileToOpen, defaultEncoding);
- }
- } else {
- // We couldn't find a header with info about encoding. Use fallback:
- return ImportFormatReader.getReader(fileToOpen, defaultEncoding);
-
- }
- }
-
- /**
- * Searches the file for "Encoding: myEncoding" and returns the found supplied encoding.
- */
- private static Optional getSuppliedEncoding(Reader reader) {
- try {
- BufferedReader bufferedReader = new BufferedReader(reader);
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- line = line.trim();
-
- // Line does not start with %, so there are no comment lines for us and we can stop parsing
- if (!line.startsWith("%")) {
- return Optional.empty();
- }
-
- // Only keep the part after %
- line = line.substring(1).trim();
-
- if (line.startsWith(Globals.SIGNATURE)) {
- // Signature line, so keep reading and skip to next line
- } else if (line.startsWith(Globals.ENCODING_PREFIX)) {
- // Line starts with "Encoding: ", so the rest of the line should contain the name of the encoding
- // Except if there is already a @ symbol signaling the starting of a BibEntry
- Integer atSymbolIndex = line.indexOf('@');
- String encoding;
- if (atSymbolIndex > 0) {
- encoding = line.substring(Globals.ENCODING_PREFIX.length(), atSymbolIndex);
- } else {
- encoding = line.substring(Globals.ENCODING_PREFIX.length());
- }
-
- return Optional.of(Charset.forName(encoding));
- } else {
- // Line not recognized so stop parsing
- return Optional.empty();
- }
- }
- } catch (IOException ignored) {
- // Ignored
- }
- return Optional.empty();
+ return result;
}
/**
* Load database (bib-file) or, if there exists, a newer autosave version, unless the flag is set to ignore the autosave
- *
- * @param name Name of the bib-file to open
- * @param ignoreAutosave true if autosave version of the file should be ignored
- * @return ParserResult which never is null
- */
+ *
+ * @param name Name of the bib-file to open
+ * @param ignoreAutosave true if autosave version of the file should be ignored
+ * @return ParserResult which never is null
+ */
public static ParserResult loadDatabaseOrAutoSave(String name, boolean ignoreAutosave) {
// String in OpenDatabaseAction.java
@@ -514,5 +408,4 @@ public static ParserResult loadDatabaseOrAutoSave(String name, boolean ignoreAut
}
}
-
}
diff --git a/src/main/java/net/sf/jabref/importer/OutputPrinterToNull.java b/src/main/java/net/sf/jabref/importer/OutputPrinterToNull.java
deleted file mode 100644
index f9b2ab40b14..00000000000
--- a/src/main/java/net/sf/jabref/importer/OutputPrinterToNull.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Copyright (C) 2011, 2015 JabRef contributors.
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-*/
-package net.sf.jabref.importer;
-
-/**
- * Outputs nothing
- *
- * Used where really no output is desired
- *
- */
-public class OutputPrinterToNull implements OutputPrinter {
-
- @Override
- public void setStatus(String s) {
- // Do nothing
- }
-
- @Override
- public void showMessage(Object message, String title, int msgType) {
- // Do nothing
- }
-
- @Override
- public void showMessage(String string) {
- // Do nothing
- }
-
-}
diff --git a/src/main/java/net/sf/jabref/importer/ParserResult.java b/src/main/java/net/sf/jabref/importer/ParserResult.java
index bd93ab57655..f0b165a0d6d 100644
--- a/src/main/java/net/sf/jabref/importer/ParserResult.java
+++ b/src/main/java/net/sf/jabref/importer/ParserResult.java
@@ -19,6 +19,7 @@
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -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)), new MetaData(), 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 3f81a97a38d..6266291f11d 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 24599577497..d83c1c77194 100644
--- a/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
+++ b/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
@@ -22,9 +22,9 @@
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.Globals;
@@ -32,6 +32,7 @@
import net.sf.jabref.gui.help.HelpFiles;
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;
@@ -57,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;
@@ -81,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;
}
@@ -115,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 74d1436f8a9..586870b691a 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;
@@ -30,6 +32,7 @@
import net.sf.jabref.gui.help.HelpFiles;
import net.sf.jabref.importer.ImportInspector;
import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.importer.fileformat.MedlineImporter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.entry.BibEntry;
@@ -150,7 +153,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 +211,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 +225,29 @@ 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();
+ ParserResult result = new MedlineImporter().importDatabase(
+ new BufferedReader(new InputStreamReader(data.getInputStream())));
+ if (result.hasWarnings()) {
+ status.showMessage(result.getErrorMessage());
+ }
+ return result.getDatabase().getEntries();
+ } catch (IOException e) {
+ return new ArrayList<>();
+ }
+ }
static class SearchResult {
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 36c8ae5ca07..725b72274a8 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BibTeXMLImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BibTeXMLImporter.java
@@ -17,20 +17,20 @@
import java.io.BufferedReader;
import java.io.IOException;
-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;
+import org.xml.sax.InputSource;
/**
* Importer for the Refer/Endnote format.
@@ -44,49 +44,36 @@ public class BibTeXMLImporter extends ImportFormat {
private static final Pattern START_PATTERN = Pattern.compile("<(bibtex:)?file .*");
-
- /**
- * Return the name of this import format.
- */
-
@Override
public String getFormatName() {
return "BibTeXML";
}
- /*
- * (non-Javadoc)
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "bibtexml";
+ public List getExtensions() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
- public boolean isRecognizedFormat(InputStream stream) throws IOException {
+ public String getDescription() {
+ return null;
+ }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
// Our strategy is to look for the " importEntries(InputStream stream, OutputPrinter status) throws IOException {
+ public ParserResult importDatabase(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
List bibItems = new ArrayList<>();
@@ -102,22 +89,21 @@ public List importEntries(InputStream stream, OutputPrinter status) th
SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions
BibTeXMLHandler handler = new BibTeXMLHandler();
// Start the parser. It reads the file and calls methods of the handler.
- parser.parse(stream, handler);
+ parser.parse(new InputSource(reader), handler);
// When you're done, report the results stored by your handler object
bibItems.addAll(handler.getItems());
} 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/BiblioscapeImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
index 08c54ab3619..29b8d4290c6 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BiblioscapeImporter.java
@@ -17,15 +17,13 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+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;
/**
@@ -36,45 +34,36 @@
*/
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(BufferedReader reader) {
+ Objects.requireNonNull(reader);
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(BufferedReader reader) throws IOException {
List bibItems = new ArrayList<>();
- BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
String line;
Map hm = new HashMap<>();
Map lines = new HashMap<>();
StringBuilder previousLine = null;
- while ((line = in.readLine()) != null) {
+ while ((line = reader.readLine()) != null) {
if (line.isEmpty()) {
continue; // ignore empty lines, e.g. at file
}
@@ -295,12 +284,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/BibtexImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
index 5eaf75eee5e..f84f9e8df25 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/BibtexImporter.java
@@ -15,15 +15,17 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
+import java.nio.charset.Charset;
+import java.nio.file.Path;
+import java.util.Collections;
import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
-import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.Globals;
import net.sf.jabref.importer.ParserResult;
-import net.sf.jabref.model.entry.BibEntry;
/**
* This importer exists only to enable `--importToOpen someEntry.bib`
@@ -38,24 +40,39 @@ 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(BufferedReader reader) {
+ Objects.requireNonNull(reader);
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(Path filePath, Charset defaultEncoding) throws IOException {
+ // We want to check if there is a JabRef signature in the file, because that would tell us
+ // which character encoding is used. However, to read the signature we must be using a compatible
+ // 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;
+ try (BufferedReader utf8Reader = getUTF8Reader(filePath)) {
+ suppliedEncoding = getSuppliedEncoding(utf8Reader);
+ }
+ // Now if that didn't get us anywhere, we check with the 16 bit encoding:
+ if (!suppliedEncoding.isPresent()) {
+ try (BufferedReader utf16Reader = getUTF16Reader(filePath)) {
+ suppliedEncoding = getSuppliedEncoding(utf16Reader);
+ }
+ }
+
+ if(suppliedEncoding.isPresent()) {
+ return super.importDatabase(filePath, suppliedEncoding.get());
+ } else {
+ return super.importDatabase(filePath, defaultEncoding);
+ }
+ }
+
+ @Override
+ public ParserResult importDatabase(BufferedReader reader) throws IOException {
+ return BibtexParser.parse(reader);
}
@Override
@@ -64,8 +81,54 @@ public String getFormatName() {
}
@Override
- public String getExtensions() {
- return "bib";
+ public List getExtensions() {
+ return Collections.singletonList("bib");
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
}
+ /**
+ * Searches the file for "Encoding: myEncoding" and returns the found supplied encoding.
+ */
+ private static Optional getSuppliedEncoding(BufferedReader reader) {
+ try {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ line = line.trim();
+
+ // Line does not start with %, so there are no comment lines for us and we can stop parsing
+ if (!line.startsWith("%")) {
+ return Optional.empty();
+ }
+
+ // Only keep the part after %
+ line = line.substring(1).trim();
+
+ if (line.startsWith(Globals.SIGNATURE)) {
+ // Signature line, so keep reading and skip to next line
+ } else if (line.startsWith(Globals.ENCODING_PREFIX)) {
+ // Line starts with "Encoding: ", so the rest of the line should contain the name of the encoding
+ // Except if there is already a @ symbol signaling the starting of a BibEntry
+ Integer atSymbolIndex = line.indexOf('@');
+ String encoding;
+ if (atSymbolIndex > 0) {
+ encoding = line.substring(Globals.ENCODING_PREFIX.length(), atSymbolIndex);
+ } else {
+ encoding = line.substring(Globals.ENCODING_PREFIX.length());
+ }
+
+ return Optional.of(Charset.forName(encoding));
+ } else {
+ // Line not recognized so stop parsing
+ return Optional.empty();
+ }
+ }
+ } catch (IOException ignored) {
+ // Ignored
+ }
+ return Optional.empty();
+ }
}
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 ab43d01fdc0..6a058417fc8 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/CopacImporter.java
@@ -17,13 +17,12 @@
import java.io.BufferedReader;
import java.io.IOException;
-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,84 +36,67 @@ 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;
}
-
-
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
- public boolean isRecognizedFormat(InputStream stream) throws IOException {
+ public String getId() {
+ return "cpc";
+ }
- BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
+ @Override
+ public String getDescription() {
+ return null;
+ }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
String str;
-
- while ((str = in.readLine()) != null) {
+ while ((str = reader.readLine()) != null) {
if (CopacImporter.COPAC_PATTERN.matcher(str).find()) {
return true;
}
}
-
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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
List entries = new LinkedList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- // Preprocess entries
- String str;
+ // Preprocess entries
+ String str;
- while ((str = in.readLine()) != null) {
+ while ((str = reader.readLine()) != null) {
- if (str.length() < 4) {
- continue;
- }
+ if (str.length() < 4) {
+ continue;
+ }
- String code = str.substring(0, 4);
+ String code = str.substring(0, 4);
- if (" ".equals(code)) {
- sb.append(' ').append(str.trim());
- } else {
+ if (" ".equals(code)) {
+ sb.append(' ').append(str.trim());
+ } else {
- // begining of a new item
- if ("TI- ".equals(str.substring(0, 4))) {
- if (sb.length() > 0) {
- entries.add(sb.toString());
- }
- sb = new StringBuilder();
+ // begining of a new item
+ if ("TI- ".equals(str.substring(0, 4))) {
+ if (sb.length() > 0) {
+ entries.add(sb.toString());
}
- sb.append('\n').append(str);
+ sb = new StringBuilder();
}
+ sb.append('\n').append(str);
}
}
@@ -166,7 +148,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 dbd5b0cc8ad..d597a352a77 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/EndnoteImporter.java
@@ -17,15 +17,13 @@
import java.io.BufferedReader;
import java.io.IOException;
-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.importer.ParserResult;
import net.sf.jabref.logic.labelpattern.LabelPatternUtil;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibEntry;
@@ -45,68 +43,57 @@ 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 boolean isRecognizedFormat(InputStream stream) throws IOException {
+ public String getDescription() {
+ return null;
+ }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
// Our strategy is to look for the "%A *" line.
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String str;
- while ((str = in.readLine()) != null) {
- if (A_PATTERN.matcher(str).matches() || E_PATTERN.matcher(str).matches()) {
- return true;
- }
+ String str;
+ while ((str = reader.readLine()) != null) {
+ if (A_PATTERN.matcher(str).matches() || E_PATTERN.matcher(str).matches()) {
+ return true;
}
}
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(BufferedReader reader) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
-
- String str;
- boolean first = true;
- while ((str = in.readLine()) != null) {
- str = str.trim();
- if (str.indexOf("%0") == 0) {
- if (first) {
- first = false;
- } else {
- sb.append(ENDOFRECORD);
- }
- sb.append(str);
+ String str;
+ boolean first = true;
+ while ((str = reader.readLine()) != null) {
+ str = str.trim();
+ if (str.indexOf("%0") == 0) {
+ if (first) {
+ first = false;
} else {
- sb.append(str);
+ sb.append(ENDOFRECORD);
}
- sb.append('\n');
+ sb.append(str);
+ } else {
+ sb.append(str);
}
+ sb.append('\n');
}
String[] entries = sb.toString().split(ENDOFRECORD);
@@ -279,7 +266,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 6a870db6026..5f654facda3 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/FreeCiteImporter.java
@@ -15,8 +15,8 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
@@ -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;
@@ -36,7 +36,7 @@
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefGUI;
-import net.sf.jabref.importer.OutputPrinter;
+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;
@@ -55,22 +55,22 @@ public class FreeCiteImporter extends ImportFormat {
private static final Log LOGGER = LogFactory.getLog(FreeCiteImporter.class);
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
- // TODO: We don't know how to recognize text files, therefore we return
- // "false"
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
+ // 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(BufferedReader reader)
throws IOException {
- try (Scanner scan = new Scanner(in)) {
+ try (Scanner scan = new Scanner(reader)) {
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();
@@ -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 bc1baa6229a..0c4887630bf 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,101 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
+import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
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;
/**
* 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;
+ protected abstract boolean isRecognizedFormat(BufferedReader input) throws IOException;
+
+ public boolean isRecognizedFormat(Path filePath, Charset encoding) throws IOException {
+ try (BufferedReader bufferedReader = getReader(filePath, encoding)) {
+ return isRecognizedFormat(bufferedReader);
+ }
+ }
/**
- * 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 input the input to read from
*/
- public abstract List importEntries(InputStream in, OutputPrinter status) throws IOException;
+ protected abstract ParserResult importDatabase(BufferedReader input) throws IOException ;
/**
- * Name of this import format.
+ * Parse the database in the specified file.
+ *
+ * Importer having the facilities to detect the correct encoding of a file should overwrite this method,
+ * determine the encoding and then call {@link #importDatabase(BufferedReader)}.
+ *
+ * @param filePath the path to the file which should be imported
+ * @param encoding the encoding used to decode the file
+ */
+ public ParserResult importDatabase(Path filePath, Charset encoding) throws IOException {
+ try (BufferedReader bufferedReader = getReader(filePath, encoding)) {
+ ParserResult parserResult = importDatabase(bufferedReader);
+ parserResult.setEncoding(encoding);
+ parserResult.setFile(filePath.toFile());
+ return parserResult;
+ }
+ }
+
+ public static BufferedReader getUTF8Reader(Path filePath) throws IOException {
+ return getReader(filePath, StandardCharsets.UTF_8);
+ }
+
+ public static BufferedReader getUTF16Reader(Path filePath) throws IOException {
+ return getReader(filePath, StandardCharsets.UTF_16);
+ }
+
+ public static BufferedReader getReader(Path filePath, Charset encoding)
+ throws IOException {
+ InputStream stream = new FileInputStream(filePath.toFile());
+ return new BufferedReader(new InputStreamReader(stream, encoding));
+ }
+
+ /**
+ * Returns the name of this import format.
*
*
The name must be unique.
*
@@ -85,20 +118,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,91 +144,43 @@ 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
*
- * by what criteria it {@link #isRecognizedFormat(InputStream) recognizes} an import format
+ * by what criteria it {@link #isRecognizedFormat(BufferedReader) recognizes} an import format
*
*
* @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 e2f283d8017..f60bad7fe4e 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/InspecImporter.java
@@ -17,15 +17,13 @@
import java.io.BufferedReader;
import java.io.IOException;
-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.importer.ParserResult;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibEntry;
@@ -36,60 +34,46 @@ 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;
}
- /**
- * 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.
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String str;
+ public String getDescription() {
+ return null;
+ }
- while ((str = in.readLine()) != null) {
- if (INSPEC_PATTERN.matcher(str).find()) {
- return true;
- }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ // Our strategy is to look for the "PY " line.
+ String str;
+ while ((str = reader.readLine()) != null) {
+ if (INSPEC_PATTERN.matcher(str).find()) {
+ return true;
}
}
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(BufferedReader reader) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String str;
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- while ((str = in.readLine()) != null) {
- if (str.length() < 2) {
- continue;
- }
- if (str.indexOf("Record") == 0) {
- sb.append("__::__").append(str);
- } else {
- sb.append("__NEWFIELD__").append(str);
- }
+ while ((str = reader.readLine()) != null) {
+ if (str.length() < 2) {
+ continue;
+ }
+ if (str.indexOf("Record") == 0) {
+ sb.append("__::__").append(str);
+ } else {
+ sb.append("__NEWFIELD__").append(str);
}
}
String[] entries = sb.toString().split("__::__");
@@ -156,6 +140,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 bb1c5931973..5b4db6b8661 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/IsiImporter.java
@@ -17,16 +17,15 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
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.casechanger.TitleCaseFormatter;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.MonthUtil;
@@ -57,57 +56,48 @@ 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";
+ }
-
- /**
- * 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))) {
-
- String str;
- int i = 0;
- while (((str = in.readLine()) != null) && (i < 50)) {
-
- /**
- * The following line gives false positives for RIS files, so it
- * should not be uncommented. The hypen is a characteristic of the
- * RIS format.
- *
- * str = str.replace(" - ", "")
- */
- if (IsiImporter.ISI_PATTERN.matcher(str).find()) {
- return true;
- }
+ public String getDescription() {
+ return null;
+ }
- i++;
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ String str;
+ int i = 0;
+ while (((str = reader.readLine()) != null) && (i < 50)) {
+
+ /**
+ * The following line gives false positives for RIS files, so it
+ * should not be uncommented. The hypen is a characteristic of the
+ * RIS format.
+ *
+ * str = str.replace(" - ", "")
+ */
+ if (IsiImporter.ISI_PATTERN.matcher(str).find()) {
+ return true;
}
+
+ i++;
}
return false;
}
-
-
public static void processSubSup(Map map) {
String[] subsup = {"title", "abstract", "review", "notes"};
@@ -156,45 +146,37 @@ 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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- // Pattern fieldPattern = Pattern.compile("^AU |^TI |^SO |^DT |^C1 |^AB
- // |^ID |^BP |^PY |^SE |^PY |^VL |^IS ");
- String str;
+ // Pattern fieldPattern = Pattern.compile("^AU |^TI |^SO |^DT |^C1 |^AB
+ // |^ID |^BP |^PY |^SE |^PY |^VL |^IS ");
+ String str;
- while ((str = in.readLine()) != null) {
- if (str.length() < 3) {
- continue;
- }
+ while ((str = reader.readLine()) != null) {
+ if (str.length() < 3) {
+ continue;
+ }
- // beginning of a new item
- if ("PT ".equals(str.substring(0, 3))) {
- sb.append("::").append(str);
+ // beginning of a new item
+ if ("PT ".equals(str.substring(0, 3))) {
+ sb.append("::").append(str);
+ } else {
+ String beg = str.substring(0, 3).trim();
+
+ // I could have used the fieldPattern regular expression instead
+ // however this seems to be
+ // quick and dirty and it works!
+ if (beg.length() == 2) {
+ sb.append(" ## "); // mark the beginning of each field
+ sb.append(str);
} else {
- String beg = str.substring(0, 3).trim();
-
- // I could have used the fieldPattern regular expression instead
- // however this seems to be
- // quick and dirty and it works!
- if (beg.length() == 2) {
- sb.append(" ## "); // mark the beginning of each field
- sb.append(str);
- } else {
- sb.append("EOLEOL"); // mark the end of each line
- sb.append(str.trim()); // remove the initial spaces
- }
+ sb.append("EOLEOL"); // mark the end of each line
+ sb.append(str.trim()); // remove the initial spaces
}
}
}
@@ -355,7 +337,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 f4e4b4e5b15..4a27483d3cc 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MedlineImporter.java
@@ -19,21 +19,19 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
-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;
+import org.xml.sax.InputSource;
/**
* Importer for the Refer/Endnote format.
@@ -51,62 +49,39 @@ public String getFormatName() {
return "Medline";
}
- /*
- * (non-Javadoc)
- *
- * @see net.sf.jabref.imports.ImportFormat#getCLIId()
- */
@Override
- public String getCLIId() {
- return "medline";
+ public List getExtensions() {
+ return null;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
- public boolean isRecognizedFormat(InputStream stream) throws IOException {
+ public String getId() {
+ return "medline";
+ }
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String str;
- int i = 0;
- while (((str = in.readLine()) != null) && (i < 50)) {
+ @Override
+ public String getDescription() {
+ return null;
+ }
- if (str.toLowerCase().contains("")) {
- return true;
- }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ String str;
+ int i = 0;
+ while (((str = reader.readLine()) != null) && (i < 50)) {
- i++;
+ if (str.toLowerCase().contains("")) {
+ return true;
}
- }
- 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<>();
+ i++;
}
+ 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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
// Obtain a factory object for creating SAX parsers
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
@@ -124,14 +99,14 @@ public List importEntries(InputStream stream, OutputPrinter status) th
MedlineHandler handler = new MedlineHandler();
// Start the parser. It reads the file and calls methods of the
// handler.
- parser.parse(stream, handler);
+ parser.parse(new InputSource(reader), handler);
// Switch this to true if you want to make a local copy for testing.
if (false) {
- stream.reset();
+ reader.reset();
try (FileOutputStream out = new FileOutputStream(new File("/home/alver/ut.txt"))) {
int c;
- while ((c = stream.read()) != -1) {
+ while ((c = reader.read()) != -1) {
out.write((char) c);
}
}
@@ -140,18 +115,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 7ef2d4c6923..00215f82b9d 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MedlinePlainImporter.java
@@ -19,7 +19,6 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -27,8 +26,7 @@
import java.util.regex.Pattern;
import net.sf.jabref.Globals;
-import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+import net.sf.jabref.importer.ParserResult;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibEntry;
@@ -46,59 +44,44 @@ 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 {
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
// Our strategy is to look for the "PMID - *", "PMC.*-.*", or "PMCR.*-.*" line
// (i.e., PubMed Unique Identifier, PubMed Central Identifier, PubMed Central Release)
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
-
- String str;
- while ((str = in.readLine()) != null) {
- if (PMID_PATTERN.matcher(str).find() || PMC_PATTERN.matcher(str).find()
- || PMCR_PATTERN.matcher(str).find()) {
- return true;
- }
+ String str;
+ while ((str = reader.readLine()) != null) {
+ if (PMID_PATTERN.matcher(str).find() || PMC_PATTERN.matcher(str).find() || PMCR_PATTERN.matcher(str)
+ .find()) {
+ return true;
}
}
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(BufferedReader reader) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String str;
- while ((str = in.readLine()) != null) {
- sb.append(str);
- sb.append('\n');
- }
+ String str;
+ while ((str = reader.readLine()) != null) {
+ sb.append(str);
+ sb.append('\n');
}
String[] entries = sb.toString().replace("\u2013", "-").replace("\u2014", "--").replace("\u2015", "--")
.split("\\n\\n");
@@ -286,7 +269,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 6157ce8fe87..52d11a7a5d8 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/MsBibImporter.java
@@ -15,18 +15,19 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
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.importer.ParserResult;
import net.sf.jabref.logic.msbib.MSBibDatabase;
-import net.sf.jabref.model.entry.BibEntry;
import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
/**
* Importer for the MS Office 2007 XML bibliography format
@@ -37,14 +38,10 @@
public class MsBibImporter extends ImportFormat {
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
/*
- 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.
@@ -54,33 +51,34 @@ public boolean isRecognizedFormat(InputStream in) throws IOException {
DocumentBuilder dbuild = DocumentBuilderFactory.
newInstance().
newDocumentBuilder();
- docin = dbuild.parse(in);
+ docin = dbuild.parse(new InputSource(reader));
} catch (Exception e) {
return false;
}
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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
MSBibDatabase dbase = new MSBibDatabase();
-
- return dbase.importEntries(in);
+ return new ParserResult(dbase.importEntries(reader));
}
@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 e7494faf3f0..de8fe3d3201 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/OvidImporter.java
@@ -17,7 +17,6 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -25,8 +24,7 @@
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.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.IdGenerator;
@@ -55,63 +53,48 @@ 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;
}
-
-
- /**
- * 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))) {
- String str;
- int i = 0;
- while (((str = in.readLine()) != null) && (i < MAX_ITEMS)) {
+ public String getDescription() {
+ return null;
+ }
- if (OvidImporter.OVID_PATTERN.matcher(str).find()) {
- return true;
- }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ String str;
+ int i = 0;
+ while (((str = reader.readLine()) != null) && (i < MAX_ITEMS)) {
- i++;
+ if (OvidImporter.OVID_PATTERN.matcher(str).find()) {
+ return true;
}
+
+ i++;
}
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(BufferedReader reader) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String line;
- while ((line = in.readLine()) != null) {
- if (!line.isEmpty() && (line.charAt(0) != ' ')) {
- sb.append("__NEWFIELD__");
- }
- sb.append(line);
- sb.append('\n');
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (!line.isEmpty() && (line.charAt(0) != ' ')) {
+ sb.append("__NEWFIELD__");
}
+ sb.append(line);
+ sb.append('\n');
}
String[] items = sb.toString().split(OVID_PATTERN_STRING);
@@ -244,7 +227,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 4393c57e8ba..a9a412ee975 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
@@ -1,18 +1,20 @@
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.io.StringWriter;
+import java.nio.charset.Charset;
+import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Collections;
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.ImportInspector;
-import net.sf.jabref.importer.OutputPrinter;
+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;
@@ -21,8 +23,6 @@
import net.sf.jabref.model.entry.EntryType;
import com.google.common.base.Strings;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
@@ -34,7 +34,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
@@ -178,36 +177,31 @@ private static String streamlineTitle(String title) {
}
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
return false;
}
@Override
- public List importEntries(InputStream in, OutputPrinter status) throws IOException {
- final ArrayList result = new ArrayList<>(1);
+ public ParserResult importDatabase(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
+ throw new UnsupportedOperationException(
+ "PdfContentImporter does not support importDatabase(BufferedReader reader)."
+ + "Instead use importDatabase(Path filePath, Charset defaultEncoding).");
+ }
- try (PDDocument document = XMPUtil.loadWithAutomaticDecryption(in)) {
+ @Override
+ public ParserResult importDatabase(Path filePath, Charset defaultEncoding) {
+ final ArrayList result = new ArrayList<>(1);
+ try (PDDocument document = XMPUtil.loadWithAutomaticDecryption(filePath)) {
String firstPageContents = getFirstPageContents(document);
Optional doi = DOI.findInText(firstPageContents);
if (doi.isPresent()) {
- ImportInspector inspector = new ImportInspector() {
- @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
@@ -224,7 +218,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
@@ -473,10 +467,12 @@ public void addEntry(BibEntry entry) {
result.add(entry);
} catch (EncryptedPdfsNotSupportedException e) {
- LOGGER.info("Decryption not supported");
- return Collections.emptyList();
+ 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 {
@@ -582,4 +578,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 8ba02c31153..14bb88b624c 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfXmpImporter.java
@@ -15,14 +15,16 @@
*/
package net.sf.jabref.importer.fileformat;
+import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
+import java.nio.charset.Charset;
+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.logic.l10n.Localization;
import net.sf.jabref.logic.xmp.XMPUtil;
-import net.sf.jabref.model.entry.BibEntry;
/**
* Wraps the XMPUtility function to be used as an ImportFormat.
@@ -34,12 +36,35 @@ 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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
+ throw new UnsupportedOperationException(
+ "PdfXmpImporter does not support importDatabase(BufferedReader reader)."
+ + "Instead use importDatabase(Path filePath, Charset defaultEncoding).");
+ }
+
+ @Override
+ public ParserResult importDatabase(Path filePath, Charset defaultEncoding) {
+ Objects.requireNonNull(filePath);
+ try {
+ return new ParserResult(XMPUtil.readXMP(filePath));
+ } catch (IOException exception) {
+ return ParserResult.fromErrorMessage(exception.getLocalizedMessage());
+ }
+ }
+
+ @Override
+ protected boolean isRecognizedFormat(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
+ throw new UnsupportedOperationException(
+ "PdfXmpImporter does not support isRecognizedFormat(BufferedReader reader)."
+ + "Instead use isRecognizedFormat(Path filePath, Charset defaultEncoding).");
}
/**
@@ -47,17 +72,19 @@ public List importEntries(InputStream in, OutputPrinter status) throws
* contains at least one BibEntry.
*/
@Override
- public boolean isRecognizedFormat(InputStream in) throws IOException {
- return XMPUtil.hasMetadata(in);
+ public boolean isRecognizedFormat(Path filePath, Charset defaultEncoding) throws IOException {
+ Objects.requireNonNull(filePath);
+ return XMPUtil.hasMetadata(filePath);
}
- /**
- * 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 4689bbec352..04871c5d41e 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/RepecNepImporter.java
@@ -19,19 +19,19 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
+import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
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;
import net.sf.jabref.model.entry.IdGenerator;
@@ -169,37 +169,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
@@ -210,25 +194,19 @@ 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 {
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
// read the first couple of lines
// NEP message usually contain the String 'NEP: New Economics Papers'
// or, they are from nep.repec.org
- try (BufferedReader inBR = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- StringBuilder startOfMessage = new StringBuilder();
- String tmpLine = inBR.readLine();
- for (int i = 0; (i < 25) && (tmpLine != null); i++) {
- startOfMessage.append(tmpLine);
- tmpLine = inBR.readLine();
- }
- return startOfMessage.toString().contains("NEP: New Economics Papers")
- || startOfMessage.toString().contains("nep.repec.org");
+ StringBuilder startOfMessage = new StringBuilder();
+ String tmpLine = reader.readLine();
+ for (int i = 0; (i < 25) && (tmpLine != null); i++) {
+ startOfMessage.append(tmpLine);
+ tmpLine = reader.readLine();
}
+ return startOfMessage.toString().contains("NEP: New Economics Papers") || startOfMessage.toString().contains(
+ "nep.repec.org");
}
private boolean startsWithKeyword(Collection keywords) {
@@ -434,18 +412,15 @@ 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(BufferedReader reader) throws IOException {
+ Objects.requireNonNull(reader);
+
List bibitems = new ArrayList<>();
String paperNoStr = null;
this.line = 0;
-
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- readLine(in); // skip header and editor information
+ try {
+ readLine(reader); // skip header and editor information
while (this.lastLine != null) {
if (this.lastLine.startsWith("-----------------------------")) {
@@ -455,25 +430,25 @@ public List importEntries(InputStream stream, OutputPrinter status) th
BibEntry be = new BibEntry(IdGenerator.next());
be.setType("techreport");
paperNoStr = this.lastLine.substring(0, this.lastLine.indexOf('.'));
- parseTitleString(be, in);
+ parseTitleString(be, reader);
if (startsWithKeyword(RepecNepImporter.RECOGNIZED_FIELDS)) {
- parseAdditionalFields(be, false, in);
+ parseAdditionalFields(be, false, reader);
} else {
- readLine(in); // skip empty line
- parseAuthors(be, in);
- readLine(in); // skip empty line
+ readLine(reader); // skip empty line
+ parseAuthors(be, reader);
+ readLine(reader); // skip empty line
}
if (!startsWithKeyword(RepecNepImporter.RECOGNIZED_FIELDS)) {
- parseAbstract(be, in);
+ parseAbstract(be, reader);
}
- parseAdditionalFields(be, true, in);
+ parseAdditionalFields(be, true, reader);
bibitems.add(be);
paperNoStr = null;
} else {
this.preLine = this.lastLine;
- readLine(in);
+ readLine(reader);
}
}
@@ -482,17 +457,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);
- IOException toThrow;
- if (e instanceof IOException) {
- toThrow = (IOException) e;
- } else {
- toThrow = new IOException(message);
- }
- throw toThrow;
+ 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 5d4f8403c29..667c2359df9 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/RisImporter.java
@@ -17,7 +17,6 @@
import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -25,8 +24,7 @@
import java.util.regex.Pattern;
import net.sf.jabref.Globals;
-import net.sf.jabref.importer.ImportFormatReader;
-import net.sf.jabref.importer.OutputPrinter;
+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;
@@ -41,56 +39,42 @@ 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;
}
- /**
- * Check whether the source is in the correct format for this importer.
- */
@Override
- public boolean isRecognizedFormat(InputStream stream) throws IOException {
+ public String getDescription() {
+ return null;
+ }
+ @Override
+ public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
// Our strategy is to look for the "AU - *" line.
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
-
- String str;
- while ((str = in.readLine()) != null) {
- if (RECOGNIZED_FORMAT_PATTERN.matcher(str).find()) {
- return true;
- }
+ String str;
+ while ((str = reader.readLine()) != null) {
+ if (RECOGNIZED_FORMAT_PATTERN.matcher(str).find()) {
+ return true;
}
}
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(BufferedReader reader) throws IOException {
List bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
- try (BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream))) {
- String str;
- while ((str = in.readLine()) != null) {
- sb.append(str);
- sb.append('\n');
- }
+
+ String line;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line);
+ sb.append('\n');
}
String[] entries = sb.toString().replace("\u2013", "-").replace("\u2014", "--").replace("\u2015", "--")
@@ -269,14 +253,14 @@ else if ("ID".equals(lab)) {
BibEntry b = new BibEntry(DEFAULT_BIBTEXENTRY_ID, type); // id assumes an existing database so don't
// Remove empty fields:
- List