Search in sources :

Example 1 with IExportFormat

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));
            }
        }
    }
}
Also used : ParserResult(org.jabref.logic.importer.ParserResult) SaveException(org.jabref.logic.exporter.SaveException) Defaults(org.jabref.model.Defaults) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) SavePreferences(org.jabref.logic.exporter.SavePreferences) IExportFormat(org.jabref.logic.exporter.IExportFormat) SaveSession(org.jabref.logic.exporter.SaveSession) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext) File(java.io.File) JabRefException(org.jabref.JabRefException) BackingStoreException(java.util.prefs.BackingStoreException) SaveException(org.jabref.logic.exporter.SaveException) IOException(java.io.IOException) ImportException(org.jabref.logic.importer.ImportException)

Example 2 with IExportFormat

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;
}
Also used : SearchQuery(org.jabref.logic.search.SearchQuery) ParserResult(org.jabref.logic.importer.ParserResult) SearchPreferences(org.jabref.preferences.SearchPreferences) BibEntry(org.jabref.model.entry.BibEntry) IExportFormat(org.jabref.logic.exporter.IExportFormat) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext) BibDatabase(org.jabref.model.database.BibDatabase) JabRefException(org.jabref.JabRefException) BackingStoreException(java.util.prefs.BackingStoreException) SaveException(org.jabref.logic.exporter.SaveException) IOException(java.io.IOException) ImportException(org.jabref.logic.importer.ImportException) DatabaseSearcher(org.jabref.logic.search.DatabaseSearcher)

Example 3 with IExportFormat

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");
        }
    }
}
Also used : ListSelectionModel(javax.swing.ListSelectionModel) ClipboardOwner(java.awt.datatransfer.ClipboardOwner) IExportFormat(org.jabref.logic.exporter.IExportFormat) BibEntry(org.jabref.model.entry.BibEntry) JList(javax.swing.JList) AbstractWorker(org.jabref.gui.worker.AbstractWorker) ExportFormats(org.jabref.logic.exporter.ExportFormats) BorderFactory(javax.swing.BorderFactory) FileInputStream(java.io.FileInputStream) Reader(java.io.Reader) JOptionPane(javax.swing.JOptionPane) InputStreamReader(java.io.InputStreamReader) BasePanel(org.jabref.gui.BasePanel) File(java.io.File) Globals(org.jabref.Globals) Objects(java.util.Objects) List(java.util.List) JabRefFrame(org.jabref.gui.JabRefFrame) Localization(org.jabref.logic.l10n.Localization) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) LinkedList(java.util.LinkedList) Collections(java.util.Collections) Toolkit(java.awt.Toolkit) BibEntry(org.jabref.model.entry.BibEntry) BasePanel(org.jabref.gui.BasePanel) InputStreamReader(java.io.InputStreamReader) IExportFormat(org.jabref.logic.exporter.IExportFormat) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ClipboardOwner(java.awt.datatransfer.ClipboardOwner) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream) File(java.io.File) JList(javax.swing.JList)

Example 4 with IExportFormat

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);
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) ActionEvent(java.awt.event.ActionEvent) IExportFormat(org.jabref.logic.exporter.IExportFormat) ExportFormat(org.jabref.logic.exporter.ExportFormat) IExportFormat(org.jabref.logic.exporter.IExportFormat) JabRefFrame(org.jabref.gui.JabRefFrame) LayoutFormatterPreferences(org.jabref.logic.layout.LayoutFormatterPreferences) MnemonicAwareAction(org.jabref.gui.actions.MnemonicAwareAction) JFileChooser(javax.swing.JFileChooser) SavePreferences(org.jabref.logic.exporter.SavePreferences) AbstractWorker(org.jabref.gui.worker.AbstractWorker) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File)

Example 5 with IExportFormat

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;
}
Also used : JFileChooser(javax.swing.JFileChooser) TreeSet(java.util.TreeSet) IExportFormat(org.jabref.logic.exporter.IExportFormat) FileFilter(javax.swing.filechooser.FileFilter) Map(java.util.Map)

Aggregations

IExportFormat (org.jabref.logic.exporter.IExportFormat)5 File (java.io.File)3 BibEntry (org.jabref.model.entry.BibEntry)3 IOException (java.io.IOException)2 BackingStoreException (java.util.prefs.BackingStoreException)2 JFileChooser (javax.swing.JFileChooser)2 FileFilter (javax.swing.filechooser.FileFilter)2 JabRefException (org.jabref.JabRefException)2 JabRefFrame (org.jabref.gui.JabRefFrame)2 AbstractWorker (org.jabref.gui.worker.AbstractWorker)2 SaveException (org.jabref.logic.exporter.SaveException)2 SavePreferences (org.jabref.logic.exporter.SavePreferences)2 ImportException (org.jabref.logic.importer.ImportException)2 ParserResult (org.jabref.logic.importer.ParserResult)2 BibDatabaseContext (org.jabref.model.database.BibDatabaseContext)2 Toolkit (java.awt.Toolkit)1 ClipboardOwner (java.awt.datatransfer.ClipboardOwner)1 ActionEvent (java.awt.event.ActionEvent)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1