Search in sources :

Example 11 with EntryType

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

the class PdfImporter method createNewEntry.

private Optional<BibEntry> createNewEntry() {
    // Find out what type is desired
    EntryTypeDialog etd = new EntryTypeDialog(frame);
    // We want to center the dialog, to make it look nicer.
    etd.setLocationRelativeTo(frame);
    etd.setVisible(true);
    EntryType type = etd.getChoice();
    if (type != null) {
        // Only if the dialog was not canceled.
        final BibEntry bibEntry = new BibEntry(type.getName());
        try {
            panel.getDatabase().insertEntry(bibEntry);
            // Set owner/timestamp if options are enabled:
            List<BibEntry> list = new ArrayList<>();
            list.add(bibEntry);
            UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences());
            // Create an UndoableInsertEntry object.
            panel.getUndoManager().addEdit(new UndoableInsertEntry(panel.getDatabase(), bibEntry, panel));
            panel.output(Localization.lang("Added new") + " '" + type.getName().toLowerCase(Locale.ROOT) + "' " + Localization.lang("entry") + ".");
            // and adjustment of the splitter.
            if (panel.getMode() != BasePanelMode.SHOWING_EDITOR) {
                panel.setMode(BasePanelMode.WILL_SHOW_EDITOR);
            }
            SwingUtilities.invokeLater(() -> panel.showEntry(bibEntry));
            // The database just changed.
            panel.markBaseChanged();
            return Optional.of(bibEntry);
        } catch (KeyCollisionException ex) {
            LOGGER.info("Key collision occurred", ex);
        }
    }
    return Optional.empty();
}
Also used : KeyCollisionException(org.jabref.model.database.KeyCollisionException) BibEntry(org.jabref.model.entry.BibEntry) EntryType(org.jabref.model.entry.EntryType) EntryTypeDialog(org.jabref.gui.EntryTypeDialog) ArrayList(java.util.ArrayList) UndoableInsertEntry(org.jabref.gui.undo.UndoableInsertEntry)

Example 12 with EntryType

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

the class BibtexParserTest method integrationTestCustomEntryType.

@Test
public void integrationTestCustomEntryType() throws IOException {
    ParserResult result = parser.parse(new StringReader("@comment{jabref-entrytype: Lecturenotes: req[author;title] opt[language;url]}"));
    Map<String, EntryType> customEntryTypes = result.getEntryTypes();
    assertEquals(1, customEntryTypes.size());
    assertEquals("Lecturenotes", customEntryTypes.keySet().toArray()[0]);
    EntryType entryType = customEntryTypes.get("Lecturenotes");
    assertEquals("Lecturenotes", entryType.getName());
    assertEquals(Arrays.asList("author", "title"), entryType.getRequiredFields());
    assertEquals(Arrays.asList("language", "url"), entryType.getOptionalFields());
}
Also used : ParserResult(org.jabref.logic.importer.ParserResult) EntryType(org.jabref.model.entry.EntryType) StringReader(java.io.StringReader) BibtexString(org.jabref.model.entry.BibtexString) Test(org.junit.Test)

Example 13 with EntryType

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

the class BibDatabaseWriter method savePartOfDatabase.

/**
     * Saves the database, including only the specified entries.
     */
public E savePartOfDatabase(BibDatabaseContext bibDatabaseContext, List<BibEntry> entries, SavePreferences preferences) throws SaveException {
    session = saveSessionFactory.createSaveSession(preferences.getEncodingOrDefault(), preferences.getMakeBackup());
    Optional<String> sharedDatabaseIDOptional = bibDatabaseContext.getDatabase().getSharedDatabaseID();
    if (sharedDatabaseIDOptional.isPresent()) {
        writeDatabaseID(sharedDatabaseIDOptional.get());
    }
    // Map to collect entry type definitions that we must save along with entries using them.
    Map<String, EntryType> typesToWrite = new TreeMap<>();
    // Some file formats write something at the start of the file (like the encoding)
    if (preferences.getSaveType() != SavePreferences.DatabaseSaveType.PLAIN_BIBTEX) {
        writePrelogue(bibDatabaseContext, preferences.getEncoding());
    }
    // Write preamble if there is one.
    writePreamble(bibDatabaseContext.getDatabase().getPreamble().orElse(""));
    // Write strings if there are any.
    writeStrings(bibDatabaseContext.getDatabase(), preferences.isReformatFile(), preferences.getLatexFieldFormatterPreferences());
    // Write database entries.
    List<BibEntry> sortedEntries = getSortedEntries(bibDatabaseContext, entries, preferences);
    List<FieldChange> saveActionChanges = applySaveActions(sortedEntries, bibDatabaseContext.getMetaData());
    session.addFieldChanges(saveActionChanges);
    for (BibEntry entry : sortedEntries) {
        // types (*not* all customized standard types) must be written.
        if (!EntryTypes.getStandardType(entry.getType(), bibDatabaseContext.getMode()).isPresent()) {
            // If user-defined entry type, then add it
            // Otherwise (getType returns empty optional) it is a completely unknown entry type, so ignore it
            EntryTypes.getType(entry.getType(), bibDatabaseContext.getMode()).ifPresent(entryType -> typesToWrite.put(entryType.getName(), entryType));
        }
        writeEntry(entry, bibDatabaseContext.getMode(), preferences.isReformatFile(), preferences.getLatexFieldFormatterPreferences());
    }
    if (preferences.getSaveType() != SavePreferences.DatabaseSaveType.PLAIN_BIBTEX) {
        // Write meta data.
        writeMetaData(bibDatabaseContext.getMetaData(), preferences.getGlobalCiteKeyPattern());
        // Write type definitions, if any:
        writeEntryTypeDefinitions(typesToWrite);
    }
    //finally write whatever remains of the file, but at least a concluding newline
    writeEpilogue(bibDatabaseContext.getDatabase().getEpilog());
    try {
        session.getWriter().close();
    } catch (IOException e) {
        throw new SaveException(e);
    }
    return session;
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) CustomEntryType(org.jabref.model.entry.CustomEntryType) EntryType(org.jabref.model.entry.EntryType) FieldChange(org.jabref.model.FieldChange) BibtexString(org.jabref.model.entry.BibtexString) IOException(java.io.IOException) TreeMap(java.util.TreeMap)

Example 14 with EntryType

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

the class FreeCiteImporter method importEntries.

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }
    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult.fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT) && "citation".equals(parser.getLocalName())) {
                parser.nextTag();
                StringBuilder noteSB = new StringBuilder();
                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;
                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT) && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();
                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());
                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                            // current tag is either begin:author or
                            // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || FieldName.INSTITUTION.equals(ln) || FieldName.LOCATION.equals(ln) || FieldName.NUMBER.equals(ln) || FieldName.NOTE.equals(ln) || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln) || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln) || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if (FieldName.BOOKTITLE.equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField(FieldName.BOOKTITLE, booktitle);
                        } else if ("raw_string".equals(ln)) {
                        // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(OS.NEWLINE);
                        }
                    }
                    parser.next();
                }
                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField(FieldName.NOTE)) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getField(FieldName.NOTE).get().concat(OS.NEWLINE).concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField(FieldName.NOTE, note);
                }
                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);
                // autogenerate label (BibTeX key)
                if (JabRefGUI.getMainFrame() != null) {
                    // only possible in GUI mode
                    BibtexKeyPatternUtil.makeAndSetLabel(JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData().getCiteKeyPattern(importFormatPreferences.getBibtexKeyPatternPreferences().getKeyPattern()), JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, importFormatPreferences.getBibtexKeyPatternPreferences());
                }
                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }
    return new ParserResult(res);
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) MalformedURLException(java.net.MalformedURLException) XMLStreamReader(javax.xml.stream.XMLStreamReader) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) ParserResult(org.jabref.logic.importer.ParserResult) EntryType(org.jabref.model.entry.EntryType) XMLStreamException(javax.xml.stream.XMLStreamException) OutputStreamWriter(java.io.OutputStreamWriter) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 15 with EntryType

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

the class EntryTypeDialog method createEntryGroupsPanel.

private JPanel createEntryGroupsPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new VerticalLayout());
    if (frame.getCurrentBasePanel().getBibDatabaseContext().isBiblatexMode()) {
        panel.add(createEntryGroupPanel("biblatex", BiblatexEntryTypes.ALL));
        List<EntryType> customTypes = EntryTypes.getAllCustomTypes(BibDatabaseMode.BIBLATEX);
        if (!customTypes.isEmpty()) {
            panel.add(createEntryGroupPanel(Localization.lang("Custom"), customTypes));
        }
    } else {
        panel.add(createEntryGroupPanel("BibTeX", BibtexEntryTypes.ALL));
        panel.add(createEntryGroupPanel("IEEETran", IEEETranEntryTypes.ALL));
        List<EntryType> customTypes = EntryTypes.getAllCustomTypes(BibDatabaseMode.BIBTEX);
        if (!customTypes.isEmpty()) {
            panel.add(createEntryGroupPanel(Localization.lang("Custom"), customTypes));
        }
    }
    panel.add(createIdFetcherPanel());
    return panel;
}
Also used : JPanel(javax.swing.JPanel) EntryType(org.jabref.model.entry.EntryType) VerticalLayout(org.jdesktop.swingx.VerticalLayout)

Aggregations

EntryType (org.jabref.model.entry.EntryType)22 ArrayList (java.util.ArrayList)8 BibEntry (org.jabref.model.entry.BibEntry)8 JPanel (javax.swing.JPanel)6 IOException (java.io.IOException)5 CustomEntryType (org.jabref.model.entry.CustomEntryType)5 Font (java.awt.Font)4 ParserResult (org.jabref.logic.importer.ParserResult)4 Insets (java.awt.Insets)3 JLabel (javax.swing.JLabel)3 StringReader (java.io.StringReader)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 ChangeEvent (javax.swing.event.ChangeEvent)2 ChangeListener (javax.swing.event.ChangeListener)2 EntryTypeDialog (org.jabref.gui.EntryTypeDialog)2 UndoableInsertEntry (org.jabref.gui.undo.UndoableInsertEntry)2 TypedBibEntry (org.jabref.logic.TypedBibEntry)2