Search in sources :

Example 1 with ParserResult

use of org.jabref.logic.importer.ParserResult in project jabref by JabRef.

the class JabRefGUI method openWindow.

private void openWindow() {
    // This property is set to make the Mac OSX Java VM move the menu bar to the top of the screen
    if (OS.OS_X) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
    }
    // Set antialiasing on everywhere. This only works in JRE >= 1.5.
    // Or... it doesn't work, period.
    // TODO test and maybe remove this! I found this commented out with no additional info ( payload@lavabit.com )
    // Enabled since JabRef 2.11 beta 4
    System.setProperty("swing.aatext", "true");
    // Default is "on".
    // "lcd" instead of "on" because of http://wiki.netbeans.org/FaqFontRendering and http://docs.oracle.com/javase/6/docs/technotes/guides/2d/flags.html#aaFonts
    System.setProperty("awt.useSystemAAFontSettings", "lcd");
    // look and feel. This MUST be the first thing to do before loading any Swing-specific code!
    setLookAndFeel();
    // If the option is enabled, open the last edited libraries, if any.
    if (!isBlank && Globals.prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) {
        openLastEditedDatabases();
    }
    GUIGlobals.init();
    LOGGER.debug("Initializing frame");
    JabRefGUI.mainFrame = new JabRefFrame();
    // Add all bibDatabases databases to the frame:
    boolean first = false;
    if (!bibDatabases.isEmpty()) {
        for (Iterator<ParserResult> parserResultIterator = bibDatabases.iterator(); parserResultIterator.hasNext(); ) {
            ParserResult pr = parserResultIterator.next();
            // Define focused tab
            if (pr.getFile().get().getAbsolutePath().equals(focusedFile)) {
                first = true;
            }
            if (pr.isInvalid()) {
                failed.add(pr);
                parserResultIterator.remove();
            } else if (pr.getDatabase().isShared()) {
                try {
                    new SharedDatabaseUIManager(mainFrame).openSharedDatabaseFromParserResult(pr);
                } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) {
                    // do not open the original file
                    pr.getDatabaseContext().clearDatabaseFile();
                    pr.getDatabase().clearSharedDatabaseID();
                    LOGGER.error("Connection error", e);
                    JOptionPane.showMessageDialog(mainFrame, e.getMessage() + "\n\n" + Localization.lang("A local copy will be opened."), Localization.lang("Connection error"), JOptionPane.WARNING_MESSAGE);
                }
                toOpenTab.add(pr);
            } else if (pr.toOpenTab()) {
                // things to be appended to an opened tab should be done after opening all tabs
                // add them to the list
                toOpenTab.add(pr);
            } else {
                JabRefGUI.getMainFrame().addParserResult(pr, first);
                first = false;
            }
        }
    }
    // finally add things to the currently opened tab
    for (ParserResult pr : toOpenTab) {
        JabRefGUI.getMainFrame().addParserResult(pr, first);
        first = false;
    }
    // do it here:
    if (Globals.prefs.getBoolean(JabRefPreferences.WINDOW_MAXIMISED)) {
        JabRefGUI.getMainFrame().setExtendedState(Frame.MAXIMIZED_BOTH);
    }
    JabRefGUI.getMainFrame().setVisible(true);
    for (ParserResult pr : failed) {
        String message = "<html>" + Localization.lang("Error opening file '%0'.", pr.getFile().get().getName()) + "<p>" + pr.getErrorMessage() + "</html>";
        JOptionPane.showMessageDialog(JabRefGUI.getMainFrame(), message, Localization.lang("Error opening file"), JOptionPane.ERROR_MESSAGE);
    }
    // Display warnings, if any
    int tabNumber = 0;
    for (ParserResult pr : bibDatabases) {
        ParserResultWarningDialog.showParserResultWarningDialog(pr, JabRefGUI.getMainFrame(), tabNumber++);
    }
    for (int i = 0; (i < bibDatabases.size()) && (i < JabRefGUI.getMainFrame().getBasePanelCount()); i++) {
        ParserResult pr = bibDatabases.get(i);
        BasePanel panel = JabRefGUI.getMainFrame().getBasePanelAt(i);
        OpenDatabaseAction.performPostOpenActions(panel, pr);
    }
    LOGGER.debug("Finished adding panels");
    if (!bibDatabases.isEmpty()) {
        JabRefGUI.getMainFrame().getCurrentBasePanel().getMainTable().requestFocus();
    }
}
Also used : JabRefFrame(org.jabref.gui.JabRefFrame) ParserResult(org.jabref.logic.importer.ParserResult) SharedDatabaseUIManager(org.jabref.gui.shared.SharedDatabaseUIManager) BasePanel(org.jabref.gui.BasePanel)

Example 2 with ParserResult

use of org.jabref.logic.importer.ParserResult 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 3 with ParserResult

use of org.jabref.logic.importer.ParserResult in project jabref by JabRef.

the class ArgumentProcessor method importFile.

private static Optional<ParserResult> importFile(Path file, String importFormat) {
    try {
        if (!"*".equals(importFormat)) {
            System.out.println(Localization.lang("Importing") + ": " + file);
            ParserResult result = Globals.IMPORT_FORMAT_READER.importFromFile(importFormat, file);
            return Optional.of(result);
        } else {
            // * means "guess the format":
            System.out.println(Localization.lang("Importing in unknown format") + ": " + file);
            ImportFormatReader.UnknownFormatImport importResult = Globals.IMPORT_FORMAT_READER.importUnknownFormat(file);
            System.out.println(Localization.lang("Format used") + ": " + importResult.format);
            return Optional.of(importResult.parserResult);
        }
    } catch (ImportException ex) {
        System.err.println(Localization.lang("Error opening file") + " '" + file + "': " + ex.getLocalizedMessage());
        return Optional.empty();
    }
}
Also used : ImportException(org.jabref.logic.importer.ImportException) ParserResult(org.jabref.logic.importer.ParserResult) ImportFormatReader(org.jabref.logic.importer.ImportFormatReader)

Example 4 with ParserResult

use of org.jabref.logic.importer.ParserResult in project jabref by JabRef.

the class BasicAction method parseWithFreeCiteAndAddEntries.

/**
     * tries to parse the pasted reference with freecite
     *
     * @return true if successful, false otherwise
     */
private boolean parseWithFreeCiteAndAddEntries() {
    FreeCiteImporter fimp = new FreeCiteImporter(Globals.prefs.getImportFormatPreferences());
    String text = textPane.getText();
    // we have to remove line breaks (but keep empty lines)
    // otherwise, the result is broken
    text = text.replace(OS.NEWLINE.concat(OS.NEWLINE), "##NEWLINE##");
    // possible URL line breaks are removed completely.
    text = text.replace("/".concat(OS.NEWLINE), "/");
    text = text.replace(OS.NEWLINE, " ");
    text = text.replace("##NEWLINE##", OS.NEWLINE);
    ParserResult importerResult = fimp.importEntries(text);
    if (importerResult.hasWarnings()) {
        frame.showMessage(importerResult.getErrorMessage());
    }
    List<BibEntry> importedEntries = importerResult.getDatabase().getEntries();
    if (importedEntries.isEmpty()) {
        return false;
    } else {
        UpdateField.setAutomaticFields(importedEntries, false, false, Globals.prefs.getUpdateFieldPreferences());
        boolean markEntries = EntryMarker.shouldMarkEntries();
        for (BibEntry e : importedEntries) {
            if (markEntries) {
                EntryMarker.markEntry(entry, EntryMarker.IMPORT_MARK_LEVEL, false, new NamedCompound(""));
            }
            frame.getCurrentBasePanel().insertEntry(e);
        }
        return true;
    }
}
Also used : ParserResult(org.jabref.logic.importer.ParserResult) BibEntry(org.jabref.model.entry.BibEntry) NamedCompound(org.jabref.gui.undo.NamedCompound) FreeCiteImporter(org.jabref.logic.importer.fileformat.FreeCiteImporter)

Example 5 with ParserResult

use of org.jabref.logic.importer.ParserResult in project jabref by JabRef.

the class ChangeScanner method run.

@Override
public void run() {
    try {
        // Parse the temporary file.
        Path tempFile = Globals.getFileUpdateMonitor().getTempFile(panel.fileMonitorHandle());
        ImportFormatPreferences importFormatPreferences = Globals.prefs.getImportFormatPreferences();
        ParserResult result = OpenDatabase.loadDatabase(tempFile.toFile(), importFormatPreferences);
        databaseInTemp = result.getDatabase();
        metadataInTemp = result.getMetaData();
        // Parse the modified file.
        result = OpenDatabase.loadDatabase(file, importFormatPreferences);
        BibDatabase databaseOnDisk = result.getDatabase();
        MetaData metadataOnDisk = result.getMetaData();
        // Sort both databases according to a common sort key.
        EntryComparator comparator = new EntryComparator(false, true, SORT_BY[2]);
        comparator = new EntryComparator(false, true, SORT_BY[1], comparator);
        comparator = new EntryComparator(false, true, SORT_BY[0], comparator);
        EntrySorter sorterInTemp = databaseInTemp.getSorter(comparator);
        comparator = new EntryComparator(false, true, SORT_BY[2]);
        comparator = new EntryComparator(false, true, SORT_BY[1], comparator);
        comparator = new EntryComparator(false, true, SORT_BY[0], comparator);
        EntrySorter sorterOnDisk = databaseOnDisk.getSorter(comparator);
        comparator = new EntryComparator(false, true, SORT_BY[2]);
        comparator = new EntryComparator(false, true, SORT_BY[1], comparator);
        comparator = new EntryComparator(false, true, SORT_BY[0], comparator);
        EntrySorter sorterInMem = databaseInMemory.getSorter(comparator);
        // Start looking at changes.
        scanMetaData(metadataInMemory, metadataInTemp, metadataOnDisk);
        scanPreamble(databaseInMemory, databaseInTemp, databaseOnDisk);
        scanStrings(databaseInMemory, databaseInTemp, databaseOnDisk);
        scanEntries(sorterInMem, sorterInTemp, sorterOnDisk);
        scanGroups(metadataInTemp, metadataOnDisk);
    } catch (IOException ex) {
        LOGGER.warn("Problem running", ex);
    }
}
Also used : Path(java.nio.file.Path) ParserResult(org.jabref.logic.importer.ParserResult) EntryComparator(org.jabref.logic.bibtex.comparator.EntryComparator) MetaData(org.jabref.model.metadata.MetaData) ImportFormatPreferences(org.jabref.logic.importer.ImportFormatPreferences) IOException(java.io.IOException) EntrySorter(org.jabref.model.database.EntrySorter) BibDatabase(org.jabref.model.database.BibDatabase)

Aggregations

ParserResult (org.jabref.logic.importer.ParserResult)196 Test (org.junit.Test)145 BibEntry (org.jabref.model.entry.BibEntry)131 StringReader (java.io.StringReader)130 BibtexParser (org.jabref.logic.importer.fileformat.BibtexParser)38 BibtexString (org.jabref.model.entry.BibtexString)30 ArrayList (java.util.ArrayList)23 BibDatabase (org.jabref.model.database.BibDatabase)20 Path (java.nio.file.Path)14 IOException (java.io.IOException)12 StringWriter (java.io.StringWriter)12 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 HashMap (java.util.HashMap)10 BibDatabaseContext (org.jabref.model.database.BibDatabaseContext)9 InputStream (java.io.InputStream)8 Defaults (org.jabref.model.Defaults)8 Charset (java.nio.charset.Charset)6 Scanner (java.util.Scanner)5 BufferedReader (java.io.BufferedReader)4