Search in sources :

Example 1 with BibtexDatabaseWriter

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

the class ArgumentProcessor method generateAux.

private boolean generateAux(List<ParserResult> loaded, String[] data) {
    if (data.length == 2) {
        ParserResult pr = loaded.get(0);
        AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase());
        BibDatabase newBase = acl.perform();
        boolean notSavedMsg = false;
        // write an output, if something could be resolved
        if ((newBase != null) && newBase.hasEntries()) {
            String subName = StringUtil.getCorrectFileName(data[1], "bib");
            try {
                System.out.println(Localization.lang("Saving") + ": " + subName);
                SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
                BibDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
                Defaults defaults = new Defaults(Globals.prefs.getDefaultBibDatabaseMode());
                SaveSession session = databaseWriter.saveDatabase(new BibDatabaseContext(newBase, 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(subName);
            } catch (SaveException ex) {
                System.err.println(Localization.lang("Could not save file.") + "\n" + ex.getLocalizedMessage());
            }
            notSavedMsg = true;
        }
        if (!notSavedMsg) {
            System.out.println(Localization.lang("no library generated"));
        }
        return false;
    } else {
        return true;
    }
}
Also used : SaveException(org.jabref.logic.exporter.SaveException) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) ParserResult(org.jabref.logic.importer.ParserResult) Defaults(org.jabref.model.Defaults) SavePreferences(org.jabref.logic.exporter.SavePreferences) BibDatabase(org.jabref.model.database.BibDatabase) SaveSession(org.jabref.logic.exporter.SaveSession) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext)

Example 2 with BibtexDatabaseWriter

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

the class Benchmarks method write.

@Benchmark
public String write() throws Exception {
    BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new);
    StringSaveSession saveSession = databaseWriter.savePartOfDatabase(new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences());
    return saveSession.getStringValue();
}
Also used : Defaults(org.jabref.model.Defaults) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) MetaData(org.jabref.model.metadata.MetaData) SavePreferences(org.jabref.logic.exporter.SavePreferences) StringSaveSession(org.jabref.logic.exporter.StringSaveSession) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 3 with BibtexDatabaseWriter

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

the class SaveDatabaseAction method saveDatabase.

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;
    // block user input
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(encoding);
        BibtexDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), panel.getSelectedEntries(), prefs);
        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);
        }
        panel.registerUndoableChanges(session);
    } catch (UnsupportedCharsetException ex) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
        // FIXME: rethrow anti-pattern
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            BibEntry entry = ex.getEntry();
            // Error occured during processing of an entry. Highlight it!
            panel.highlightEntry(entry);
        } else {
            LOGGER.error("A problem occured when trying to save the file", ex);
        }
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + ".\n" + ex.getMessage(), Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
        // FIXME: rethrow anti-pattern
        throw new SaveException("rt");
    } finally {
        // re-enable user input
        frame.unblock();
    }
    // handle encoding problems
    boolean success = 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(), Localization.lang("Save library"), 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"), Localization.lang("Save library"), JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                success = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            success = false;
        }
    }
    // backup file?
    try {
        if (success) {
            session.commit(file.toPath());
            // Make sure to remember which encoding we used.
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT);
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null, Localization.lang("Save failed during backup creation") + ". " + Localization.lang("Save without backup?"), Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT);
        } else {
            success = false;
        }
    }
    return success;
}
Also used : FormLayout(com.jgoodies.forms.layout.FormLayout) BibEntry(org.jabref.model.entry.BibEntry) 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) SaveSession(org.jabref.logic.exporter.SaveSession) FileSaveSession(org.jabref.logic.exporter.FileSaveSession)

Example 4 with BibtexDatabaseWriter

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

the class ChangeScanner method storeTempDatabase.

private void storeTempDatabase() {
    JabRefExecutorService.INSTANCE.execute(() -> {
        try {
            SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withMakeBackup(false).withEncoding(panel.getBibDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()));
            Defaults defaults = new Defaults(Globals.prefs.getDefaultBibDatabaseMode());
            BibDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
            SaveSession ss = databaseWriter.saveDatabase(new BibDatabaseContext(databaseInTemp, metadataInTemp, defaults), prefs);
            ss.commit(Globals.getFileUpdateMonitor().getTempFile(panel.fileMonitorHandle()));
        } catch (SaveException ex) {
            LOGGER.warn("Problem updating tmp file after accepting external changes", ex);
        }
    });
}
Also used : 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) SaveSession(org.jabref.logic.exporter.SaveSession) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext)

Example 5 with BibtexDatabaseWriter

use of org.jabref.logic.exporter.BibtexDatabaseWriter 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)

Aggregations

BibtexDatabaseWriter (org.jabref.logic.exporter.BibtexDatabaseWriter)8 SavePreferences (org.jabref.logic.exporter.SavePreferences)8 FileSaveSession (org.jabref.logic.exporter.FileSaveSession)6 SaveException (org.jabref.logic.exporter.SaveException)6 SaveSession (org.jabref.logic.exporter.SaveSession)5 Defaults (org.jabref.model.Defaults)5 BibDatabaseContext (org.jabref.model.database.BibDatabaseContext)5 Charset (java.nio.charset.Charset)3 FormBuilder (com.jgoodies.forms.builder.FormBuilder)2 FormLayout (com.jgoodies.forms.layout.FormLayout)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 JTextArea (javax.swing.JTextArea)2 StringSaveSession (org.jabref.logic.exporter.StringSaveSession)2 ParserResult (org.jabref.logic.importer.ParserResult)2 BibEntry (org.jabref.model.entry.BibEntry)2 MetaData (org.jabref.model.metadata.MetaData)2 File (java.io.File)1 IOException (java.io.IOException)1 Random (java.util.Random)1 BackingStoreException (java.util.prefs.BackingStoreException)1