use of org.jabref.logic.exporter.IExportFormat in project jabref by JabRef.
the class ArgumentProcessor method exportFile.
private void exportFile(List<ParserResult> loaded, String[] data) {
if (data.length == 1) {
// format to the given file.
if (!loaded.isEmpty()) {
ParserResult pr = loaded.get(loaded.size() - 1);
if (!pr.isInvalid()) {
try {
System.out.println(Localization.lang("Saving") + ": " + data[0]);
SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
Defaults defaults = new Defaults(Globals.prefs.getDefaultBibDatabaseMode());
BibDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
SaveSession session = databaseWriter.saveDatabase(new BibDatabaseContext(pr.getDatabase(), pr.getMetaData(), defaults), prefs);
// Show just a warning message if encoding did not work for all characters:
if (!session.getWriter().couldEncodeAll()) {
System.err.println(Localization.lang("Warning") + ": " + Localization.lang("The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName()) + " " + session.getWriter().getProblemCharacters());
}
session.commit(data[0]);
} catch (SaveException ex) {
System.err.println(Localization.lang("Could not save file.") + "\n" + ex.getLocalizedMessage());
}
}
} else {
System.err.println(Localization.lang("The output option depends on a valid import option."));
}
} else if (data.length == 2) {
// This signals that the latest import should be stored in the given
// format to the given file.
ParserResult pr = loaded.get(loaded.size() - 1);
// Set the global variable for this database's file directory before exporting,
// so formatters can resolve linked files correctly.
// (This is an ugly hack!)
File theFile = pr.getFile().get();
if (!theFile.isAbsolute()) {
theFile = theFile.getAbsoluteFile();
}
BibDatabaseContext databaseContext = pr.getDatabaseContext();
databaseContext.setDatabaseFile(theFile);
Globals.prefs.fileDirForDatabase = databaseContext.getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
System.out.println(Localization.lang("Exporting") + ": " + data[0]);
IExportFormat format = ExportFormats.getExportFormat(data[1]);
if (format == null) {
System.err.println(Localization.lang("Unknown export format") + ": " + data[1]);
} else {
// We have an ExportFormat instance:
try {
format.performExport(pr.getDatabaseContext(), data[0], pr.getDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()), pr.getDatabaseContext().getDatabase().getEntries());
} catch (Exception ex) {
System.err.println(Localization.lang("Could not export file") + " '" + data[0] + "': " + ExceptionUtils.getStackTrace(ex));
}
}
}
}
use of org.jabref.logic.exporter.IExportFormat in project jabref by JabRef.
the class ArgumentProcessor method exportMatches.
private boolean exportMatches(List<ParserResult> loaded) {
String[] data = cli.getExportMatches().split(",");
//enables blanks within the search term:
String searchTerm = data[0].replace("\\$", " ");
//$ stands for a blank
ParserResult pr = loaded.get(loaded.size() - 1);
BibDatabaseContext databaseContext = pr.getDatabaseContext();
BibDatabase dataBase = pr.getDatabase();
SearchPreferences searchPreferences = new SearchPreferences(Globals.prefs);
SearchQuery query = new SearchQuery(searchTerm, searchPreferences.isCaseSensitive(), searchPreferences.isRegularExpression());
List<BibEntry> matches = new DatabaseSearcher(query, dataBase).getMatches();
//export matches
if (!matches.isEmpty()) {
String formatName;
//read in the export format, take default format if no format entered
switch(data.length) {
case 3:
formatName = data[2];
break;
case 2:
//default ExportFormat: HTML table (with Abstract & BibTeX)
formatName = "tablerefsabsbib";
break;
default:
System.err.println(Localization.lang("Output file missing").concat(". \n \t ").concat(Localization.lang("Usage")).concat(": ") + JabRefCLI.getExportMatchesSyntax());
noGUINeeded = true;
return false;
}
//export new database
IExportFormat format = ExportFormats.getExportFormat(formatName);
if (format == null) {
System.err.println(Localization.lang("Unknown export format") + ": " + formatName);
} else {
// We have an ExportFormat instance:
try {
System.out.println(Localization.lang("Exporting") + ": " + data[1]);
format.performExport(databaseContext, data[1], databaseContext.getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()), matches);
} catch (Exception ex) {
System.err.println(Localization.lang("Could not export file") + " '" + data[1] + "': " + ExceptionUtils.getStackTrace(ex));
}
}
} else {
System.err.println(Localization.lang("No search matches."));
}
return true;
}
use of org.jabref.logic.exporter.IExportFormat in project jabref by JabRef.
the class ExportToClipboardAction method run.
@Override
public void run() {
BasePanel panel = frame.getCurrentBasePanel();
if (panel == null) {
return;
}
if (panel.getSelectedEntries().isEmpty()) {
message = Localization.lang("This operation requires one or more entries to be selected.");
getCallBack().update();
return;
}
List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
String[] exportFormatDisplayNames = new String[exportFormats.size()];
for (int i = 0; i < exportFormats.size(); i++) {
IExportFormat exportFormat = exportFormats.get(i);
exportFormatDisplayNames[i] = exportFormat.getDisplayName();
}
JList<String> list = new JList<>(exportFormatDisplayNames);
list.setBorder(BorderFactory.createEtchedBorder());
list.setSelectionInterval(0, 0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { Localization.lang("Export"), Localization.lang("Cancel") }, Localization.lang("Export"));
if (answer == JOptionPane.NO_OPTION) {
return;
}
IExportFormat format = exportFormats.get(list.getSelectedIndex());
// Set the global variable for this database's file directory before exporting,
// so formatters can resolve linked files correctly.
// (This is an ugly hack!)
Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
File tmp = null;
try {
// To simplify the exporter API we simply do a normal export to a temporary
// file, and read the contents afterwards:
tmp = File.createTempFile("jabrefCb", ".tmp");
tmp.deleteOnExit();
List<BibEntry> entries = panel.getSelectedEntries();
// Write to file:
format.performExport(panel.getBibDatabaseContext(), tmp.getPath(), panel.getBibDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()), entries);
// Read the file and put the contents on the clipboard:
StringBuilder sb = new StringBuilder();
try (Reader reader = new InputStreamReader(new FileInputStream(tmp), panel.getBibDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()))) {
int s;
while ((s = reader.read()) != -1) {
sb.append((char) s);
}
}
ClipboardOwner owner = (clipboard, content) -> {
// Do nothing
};
RtfTransferable rs = new RtfTransferable(sb.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();
} catch (Exception e) {
//To change body of catch statement use File | Settings | File Templates.
LOGGER.error("Error exporting to clipboard", e);
message = Localization.lang("Error exporting to clipboard");
} finally {
// Clean up:
if ((tmp != null) && !tmp.delete()) {
LOGGER.info("Cannot delete temporary clipboard file");
}
}
}
use of org.jabref.logic.exporter.IExportFormat in project jabref by JabRef.
the class ExportAction method getExportAction.
/**
* Create an AbstractAction for performing an export operation.
*
* @param frame
* The JabRefFrame of this JabRef instance.
* @param selectedOnly
* true indicates that only selected entries should be exported,
* false indicates that all entries should be exported.
* @return The action.
*/
public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {
class InternalExportAction extends MnemonicAwareAction {
private final JabRefFrame frame;
private final boolean selectedOnly;
public InternalExportAction(JabRefFrame frame, boolean selectedOnly) {
this.frame = frame;
this.selectedOnly = selectedOnly;
putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries") : Localization.menuTitle("Export"));
}
@Override
public void actionPerformed(ActionEvent e) {
Map<String, ExportFormat> customFormats = Globals.prefs.customExports.getCustomExportFormats(Globals.prefs, Globals.journalAbbreviationLoader);
LayoutFormatterPreferences layoutPreferences = Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader);
SavePreferences savePreferences = SavePreferences.loadForExportFromPreferences(Globals.prefs);
ExportFormats.initAllExports(customFormats, layoutPreferences, savePreferences);
JFileChooser fc = ExportAction.createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
fc.showSaveDialog(frame);
File file = fc.getSelectedFile();
if (file == null) {
return;
}
FileFilter ff = fc.getFileFilter();
if (ff instanceof ExportFileFilter) {
ExportFileFilter eff = (ExportFileFilter) ff;
String path = file.getPath();
if (!path.endsWith(eff.getExtension())) {
path = path + eff.getExtension();
}
file = new File(path);
if (file.exists()) {
// Warn that the file exists:
if (JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", file.getName()), Localization.lang("Export"), JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
return;
}
}
final IExportFormat format = eff.getExportFormat();
List<BibEntry> entries;
if (selectedOnly) {
// Selected entries
entries = frame.getCurrentBasePanel().getSelectedEntries();
} else {
// All entries
entries = frame.getCurrentBasePanel().getDatabase().getEntries();
}
// Set the global variable for this database's file directory before exporting,
// so formatters can resolve linked files correctly.
// (This is an ugly hack!)
Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
// Make sure we remember which filter was used, to set
// the default for next time:
Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName());
Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent());
final File finFile = file;
final List<BibEntry> finEntries = entries;
AbstractWorker exportWorker = new AbstractWorker() {
String errorMessage;
@Override
public void run() {
try {
format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(), finFile.getPath(), frame.getCurrentBasePanel().getBibDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()), finEntries);
} catch (Exception ex) {
LOGGER.warn("Problem exporting", ex);
if (ex.getMessage() == null) {
errorMessage = ex.toString();
} else {
errorMessage = ex.getMessage();
}
}
}
@Override
public void update() {
// No error message. Report success:
if (errorMessage == null) {
frame.output(Localization.lang("%0 export successful", format.getDisplayName()));
} else // ... or show an error dialog:
{
frame.output(Localization.lang("Could not save file.") + " - " + errorMessage);
// Need to warn the user that saving failed!
JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + errorMessage, Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
}
}
};
// Run the export action in a background thread:
exportWorker.getWorker().run();
// Run the update method:
exportWorker.update();
}
}
}
return new InternalExportAction(frame, selectedOnly);
}
use of org.jabref.logic.exporter.IExportFormat in project jabref by JabRef.
the class ExportAction method createExportFileChooser.
private static JFileChooser createExportFileChooser(String currentDir) {
String lastUsedFormat = Globals.prefs.get(JabRefPreferences.LAST_USED_EXPORT);
FileFilter defaultFilter = null;
JFileChooser fc = new JFileChooser(currentDir);
Set<FileFilter> filters = new TreeSet<>();
for (Map.Entry<String, IExportFormat> e : ExportFormats.getExportFormats().entrySet()) {
String formatName = e.getKey();
IExportFormat format = e.getValue();
ExportFileFilter exportFileFilter = new ExportFileFilter(format);
filters.add(exportFileFilter);
if (formatName.equals(lastUsedFormat)) {
defaultFilter = exportFileFilter;
}
}
for (FileFilter ff : filters) {
fc.addChoosableFileFilter(ff);
}
fc.setAcceptAllFileFilterUsed(false);
if (defaultFilter != null) {
fc.setFileFilter(defaultFilter);
}
return fc;
}
Aggregations