Search in sources :

Example 11 with SavePreferences

use of org.jabref.logic.exporter.SavePreferences in project jabref by JabRef.

the class BasePanel method saveDatabase.

private boolean saveDatabase(File file, boolean selectedOnly, Charset enc, SavePreferences.DatabaseSaveType saveType) throws SaveException {
    SaveSession session;
    frame.block();
    final String SAVE_DATABASE = Localization.lang("Save library");
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(enc).withSaveType(saveType);
        BibtexDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(bibDatabaseContext, mainTable.getSelectedEntries(), prefs);
        } else {
            session = databaseWriter.saveDatabase(bibDatabaseContext, prefs);
        }
        registerUndoableChanges(session);
    }// FIXME: not sure if this is really thrown anywhere
     catch (UnsupportedCharsetException ex) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + ' ' + Localization.lang("Character encoding '%0' is not supported.", enc.displayName()), SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex.specificEntry()) {
            // Error occurred during processing of the entry. Highlight it:
            highlightEntry(ex.getEntry());
            showEntry(ex.getEntry());
        } else {
            LOGGER.warn("Could not save", ex);
        }
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + ex.getMessage(), SAVE_DATABASE, JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } finally {
        frame.unblock();
    }
    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create().layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), SAVE_DATABASE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);
        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"), SAVE_DATABASE, JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, enc);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding, saveType);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }
    }
    if (commit) {
        session.commit(file.toPath());
        // Make sure to remember which encoding we used.
        this.bibDatabaseContext.getMetaData().setEncoding(enc);
    } else {
        session.cancel();
    }
    return commit;
}
Also used : FormLayout(com.jgoodies.forms.layout.FormLayout) FormBuilder(com.jgoodies.forms.builder.FormBuilder) SaveException(org.jabref.logic.exporter.SaveException) JTextArea(javax.swing.JTextArea) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) Charset(java.nio.charset.Charset) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) SavePreferences(org.jabref.logic.exporter.SavePreferences) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) SaveSession(org.jabref.logic.exporter.SaveSession)

Example 12 with SavePreferences

use of org.jabref.logic.exporter.SavePreferences 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 13 with SavePreferences

use of org.jabref.logic.exporter.SavePreferences in project jabref by JabRef.

the class BackupManager method performBackup.

private void performBackup(Path backupPath) {
    try {
        Charset charset = bibDatabaseContext.getMetaData().getEncoding().orElse(preferences.getDefaultEncoding());
        SavePreferences savePreferences = SavePreferences.loadForSaveFromPreferences(preferences).withEncoding(charset).withMakeBackup(false);
        new BibtexDatabaseWriter<>(FileSaveSession::new).saveDatabase(bibDatabaseContext, savePreferences).commit(backupPath);
    } catch (SaveException e) {
        LOGGER.error("Error while saving file.", e);
    }
}
Also used : SaveException(org.jabref.logic.exporter.SaveException) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) SavePreferences(org.jabref.logic.exporter.SavePreferences) Charset(java.nio.charset.Charset)

Aggregations

SavePreferences (org.jabref.logic.exporter.SavePreferences)13 BibtexDatabaseWriter (org.jabref.logic.exporter.BibtexDatabaseWriter)8 FileSaveSession (org.jabref.logic.exporter.FileSaveSession)6 SaveException (org.jabref.logic.exporter.SaveException)6 ExportFormat (org.jabref.logic.exporter.ExportFormat)5 SaveSession (org.jabref.logic.exporter.SaveSession)5 LayoutFormatterPreferences (org.jabref.logic.layout.LayoutFormatterPreferences)5 Defaults (org.jabref.model.Defaults)5 BibDatabaseContext (org.jabref.model.database.BibDatabaseContext)5 Charset (java.nio.charset.Charset)3 IExportFormat (org.jabref.logic.exporter.IExportFormat)3 BibEntry (org.jabref.model.entry.BibEntry)3 FormBuilder (com.jgoodies.forms.builder.FormBuilder)2 FormLayout (com.jgoodies.forms.layout.FormLayout)2 File (java.io.File)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 JTextArea (javax.swing.JTextArea)2 JabRefException (org.jabref.JabRefException)2 StringSaveSession (org.jabref.logic.exporter.StringSaveSession)2 ParserResult (org.jabref.logic.importer.ParserResult)2