Search in sources :

Example 21 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class OpenOfficePanel method checkThatEntriesHaveKeys.

/**
     * Check that all entries in the list have BibTeX keys, if not ask if they should be generated
     *
     * @param entries A list of entries to be checked
     * @return true if all entries have BibTeX keys, if it so may be after generating them
     */
private boolean checkThatEntriesHaveKeys(List<BibEntry> entries) {
    // Check if there are empty keys
    boolean emptyKeys = false;
    for (BibEntry entry : entries) {
        if (!entry.getCiteKeyOptional().isPresent()) {
            // Found one, no need to look further for now
            emptyKeys = true;
            break;
        }
    }
    // If no empty keys, return true
    if (!emptyKeys) {
        return true;
    }
    // Ask if keys should be generated
    String[] options = { Localization.lang("Generate keys"), Localization.lang("Cancel") };
    int answer = JOptionPane.showOptionDialog(this.frame, Localization.lang("Cannot cite entries without BibTeX keys. Generate keys now?"), Localization.lang("Cite"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, null);
    BasePanel panel = frame.getCurrentBasePanel();
    if ((answer == JOptionPane.OK_OPTION) && (panel != null)) {
        // Generate keys
        BibtexKeyPatternPreferences prefs = Globals.prefs.getBibtexKeyPatternPreferences();
        NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite"));
        for (BibEntry entry : entries) {
            if (!entry.getCiteKeyOptional().isPresent()) {
                // Generate key
                BibtexKeyPatternUtil.makeAndSetLabel(panel.getBibDatabaseContext().getMetaData().getCiteKeyPattern(prefs.getKeyPattern()), panel.getDatabase(), entry, prefs);
                // Add undo change
                undoCompound.addEdit(new UndoableKeyChange(entry, null, entry.getCiteKeyOptional().get()));
            }
        }
        undoCompound.end();
        // Add all undos
        panel.getUndoManager().addEdit(undoCompound);
        // Now every entry has a key
        return true;
    } else {
        // No, we canceled (or there is no panel to get the database from, highly unlikely)
        return false;
    }
}
Also used : UndoableKeyChange(org.jabref.gui.undo.UndoableKeyChange) BibEntry(org.jabref.model.entry.BibEntry) BasePanel(org.jabref.gui.BasePanel) BibtexKeyPatternPreferences(org.jabref.logic.bibtexkeypattern.BibtexKeyPatternPreferences) NamedCompound(org.jabref.gui.undo.NamedCompound)

Example 22 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class OpenOfficePanel method pushEntries.

private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) {
    if (!ooBase.isConnectedToDocument()) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Not connected to any Writer document. Please" + " make sure a document is open, and use the 'Select Writer document' button to connect to it."), Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
        return;
    }
    Boolean inParenthesis = inParenthesisIn;
    String pageInfo = null;
    if (addPageInfo) {
        AdvancedCiteDialog citeDialog = new AdvancedCiteDialog(frame);
        citeDialog.showDialog();
        if (citeDialog.canceled()) {
            return;
        }
        if (!citeDialog.getPageInfo().isEmpty()) {
            pageInfo = citeDialog.getPageInfo();
        }
        inParenthesis = citeDialog.isInParenthesisCite();
    }
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel != null) {
        final BibDatabase database = panel.getDatabase();
        List<BibEntry> entries = panel.getSelectedEntries();
        if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) {
            try {
                if (style == null) {
                    style = loader.getUsedStyle();
                }
                ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, preferences.syncWhenCiting());
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(frame, Localization.lang("You must select either a valid style file, or use one of the default styles."), Localization.lang("No valid style file defined"), JOptionPane.ERROR_MESSAGE);
                LOGGER.warn("Problem with style file", ex);
            } catch (ConnectionLostException ex) {
                showConnectionLostErrorMessage();
            } catch (UndefinedCharacterFormatException ex) {
                reportUndefinedCharacterFormat(ex);
            } catch (UndefinedParagraphFormatException ex) {
                reportUndefinedParagraphFormat(ex);
            } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | BibEntryNotFoundException | IllegalTypeException | PropertyExistException | NotRemoveableException ex) {
                LOGGER.warn("Could not insert entry", ex);
            }
        }
    }
}
Also used : BasePanel(org.jabref.gui.BasePanel) WrappedTargetException(com.sun.star.lang.WrappedTargetException) IllegalTypeException(com.sun.star.beans.IllegalTypeException) NotRemoveableException(com.sun.star.beans.NotRemoveableException) FileNotFoundException(java.io.FileNotFoundException) PropertyExistException(com.sun.star.beans.PropertyExistException) BibEntry(org.jabref.model.entry.BibEntry) IOException(java.io.IOException) UnknownPropertyException(com.sun.star.beans.UnknownPropertyException) PropertyVetoException(com.sun.star.beans.PropertyVetoException) BibDatabase(org.jabref.model.database.BibDatabase) UndefinedParagraphFormatException(org.jabref.logic.openoffice.UndefinedParagraphFormatException) NoSuchElementException(com.sun.star.container.NoSuchElementException)

Example 23 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class OOBibBase method insertEntry.

/**
     * This method inserts a cite marker in the text for the given BibEntry,
     * and may refresh the bibliography.
     * @param entries The entries to cite.
     * @param database The database the entry belongs to.
     * @param style The bibliography style we are using.
     * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis.
     *   This is not relevant if numbered citations are used.
     * @param withText Indicates whether this should be a normal citation (true) or an empty
     *   (invisible) citation (false).
     * @param sync Indicates whether the reference list should be refreshed.
     * @throws IllegalTypeException
     * @throws PropertyExistException
     * @throws NotRemoveableException
     * @throws UnknownPropertyException
     * @throws UndefinedCharacterFormatException
     * @throws NoSuchElementException
     * @throws WrappedTargetException
     * @throws IOException
     * @throws PropertyVetoException
     * @throws CreationException
     * @throws BibEntryNotFoundException
     * @throws UndefinedParagraphFormatException
     */
public void insertEntry(List<BibEntry> entries, BibDatabase database, List<BibDatabase> allBases, OOBibStyle style, boolean inParenthesis, boolean withText, String pageInfo, boolean sync) throws IllegalArgumentException, UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, UndefinedCharacterFormatException, WrappedTargetException, NoSuchElementException, PropertyVetoException, IOException, CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException {
    try {
        XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();
        if (entries.size() > 1) {
            if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) {
                entries.sort(yearAuthorTitleComparator);
            } else {
                entries.sort(entryComparator);
            }
        }
        String keyString = String.join(",", entries.stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toList()));
        // Insert bookmark:
        String bName = getUniqueReferenceMarkName(keyString, withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT);
        // If we should store metadata for page info, do that now:
        if (pageInfo != null) {
            LOGGER.info("Storing page info: " + pageInfo);
            setCustomProperty(bName, pageInfo);
        }
        xViewCursor.getText().insertString(xViewCursor, " ", false);
        if (style.isFormatCitations()) {
            XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor);
            String charStyle = style.getCitationCharacterFormat();
            try {
                xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
            } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex) {
                // Setting the character format failed, so we throw an exception that
                // will result in an error message for the user. Before that,
                // delete the space we inserted:
                xViewCursor.goLeft((short) 1, true);
                xViewCursor.setString("");
                throw new UndefinedCharacterFormatException(charStyle);
            }
        }
        xViewCursor.goLeft((short) 1, false);
        Map<BibEntry, BibDatabase> databaseMap = new HashMap<>();
        for (BibEntry entry : entries) {
            databaseMap.put(entry, database);
        }
        String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap, inParenthesis, null, null);
        insertReferenceMark(bName, citeText, xViewCursor, withText, style);
        xViewCursor.collapseToEnd();
        xViewCursor.goRight((short) 1, false);
        XTextRange position = xViewCursor.getEnd();
        if (sync) {
            // To account for numbering and for uniqiefiers, we must refresh the cite markers:
            updateSortedReferenceMarks();
            refreshCiteMarkers(allBases, style);
            // Insert it at the current position:
            rebuildBibTextSection(allBases, style);
        }
        // Go back to the relevant position:
        xViewCursor.gotoRange(position, false);
    } catch (DisposedException ex) {
        // or catch a DisposedException (which is in a OO JAR file).
        throw new ConnectionLostException(ex.getMessage());
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) XTextRange(com.sun.star.text.XTextRange) WrappedTargetException(com.sun.star.lang.WrappedTargetException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UnknownPropertyException(com.sun.star.beans.UnknownPropertyException) XPropertySet(com.sun.star.beans.XPropertySet) PropertyVetoException(com.sun.star.beans.PropertyVetoException) BibDatabase(org.jabref.model.database.BibDatabase) IllegalArgumentException(com.sun.star.lang.IllegalArgumentException) XTextViewCursor(com.sun.star.text.XTextViewCursor) DisposedException(com.sun.star.lang.DisposedException)

Example 24 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class OOBibBase method insertFullReferenceAtCursor.

private void insertFullReferenceAtCursor(XTextCursor cursor, Map<BibEntry, BibDatabase> entries, OOBibStyle style, String parFormat) throws UndefinedParagraphFormatException, IllegalArgumentException, UnknownPropertyException, PropertyVetoException, WrappedTargetException {
    Map<BibEntry, BibDatabase> correctEntries;
    // If we don't have numbered entries, we need to sort the entries before adding them:
    if (style.isSortByPosition()) {
        // Use the received map directly
        correctEntries = entries;
    } else {
        // Sort map
        Map<BibEntry, BibDatabase> newMap = new TreeMap<>(entryComparator);
        newMap.putAll(entries);
        correctEntries = newMap;
    }
    int number = 1;
    for (Map.Entry<BibEntry, BibDatabase> entry : correctEntries.entrySet()) {
        if (entry.getKey() instanceof UndefinedBibtexEntry) {
            continue;
        }
        OOUtil.insertParagraphBreak(text, cursor);
        if (style.isNumberEntries()) {
            int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT);
            OOUtil.insertTextAtCurrentLocation(text, cursor, style.getNumCitationMarker(Collections.singletonList(number++), minGroupingCount, true), Collections.emptyList());
        }
        Layout layout = style.getReferenceFormat(entry.getKey().getType());
        layout.setPostFormatter(POSTFORMATTER);
        OOUtil.insertFullReferenceAtCurrentLocation(text, cursor, layout, parFormat, entry.getKey(), entry.getValue(), uniquefiers.get(entry.getKey().getCiteKeyOptional().orElse(null)));
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) Layout(org.jabref.logic.layout.Layout) UndefinedBibtexEntry(org.jabref.logic.openoffice.UndefinedBibtexEntry) TreeMap(java.util.TreeMap) BibDatabase(org.jabref.model.database.BibDatabase) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Point(com.sun.star.awt.Point)

Example 25 with BibEntry

use of org.jabref.model.entry.BibEntry 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)

Aggregations

BibEntry (org.jabref.model.entry.BibEntry)716 Test (org.junit.Test)466 ParserResult (org.jabref.logic.importer.ParserResult)131 StringReader (java.io.StringReader)107 ArrayList (java.util.ArrayList)75 BibDatabase (org.jabref.model.database.BibDatabase)63 Path (java.nio.file.Path)52 IOException (java.io.IOException)43 HashMap (java.util.HashMap)37 Before (org.junit.Before)36 NamedCompound (org.jabref.gui.undo.NamedCompound)30 BibtexParser (org.jabref.logic.importer.fileformat.BibtexParser)28 BibtexString (org.jabref.model.entry.BibtexString)28 List (java.util.List)23 File (java.io.File)21 StringWriter (java.io.StringWriter)19 Optional (java.util.Optional)19 BasePanel (org.jabref.gui.BasePanel)19 FieldChange (org.jabref.model.FieldChange)18 InputStream (java.io.InputStream)16