Esempio n. 1
0
  private void parseField(BibEntry entry) throws IOException {
    String key = parseTextToken().toLowerCase();

    skipWhitespace();
    consume('=');
    String content = parseFieldContent(key);
    if (!content.isEmpty()) {
      if (entry.hasField(key)) {
        // The following hack enables the parser to deal with multiple
        // author or
        // editor lines, stringing them together instead of getting just
        // one of them.
        // Multiple author or editor lines are not allowed by the bibtex
        // format, but
        // at least one online database exports bibtex like that, making
        // it inconvenient
        // for users if JabRef didn't accept it.
        if (InternalBibtexFields.getFieldExtras(key).contains(FieldProperties.PERSON_NAMES)) {
          entry.setField(key, entry.getFieldOptional(key).get() + " and " + content);
        } else if (FieldName.KEYWORDS.equals(key)) {
          // multiple keywords fields should be combined to one
          entry.addKeyword(content, Globals.prefs.get(JabRefPreferences.KEYWORD_SEPARATOR));
        }
      } else {
        entry.setField(key, content);
      }
    }
  }
Esempio n. 2
0
  @Test
  public void monthFieldSpecialSyntax() throws IOException {
    // @formatter:off
    String bibtexEntry =
        "@Article{test,"
            + OS.NEWLINE
            + "  Author                   = {Foo Bar},"
            + OS.NEWLINE
            + "  Month                    = mar,"
            + OS.NEWLINE
            + "  Number                   = {1}"
            + OS.NEWLINE
            + "}";
    // @formatter:on

    // read in bibtex string
    ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry));
    Collection<BibEntry> entries = result.getDatabase().getEntries();
    BibEntry entry = entries.iterator().next();

    // modify month field
    Set<String> fields = entry.getFieldNames();
    assertTrue(fields.contains("month"));
    assertEquals("#mar#", entry.getFieldOptional("month").get());

    // write out bibtex string
    StringWriter stringWriter = new StringWriter();
    writer.write(entry, stringWriter, BibDatabaseMode.BIBTEX);
    String actual = stringWriter.toString();

    assertEquals(bibtexEntry, actual);
  }
Esempio n. 3
0
  /**
   * Unabbreviate the journal name of the given entry.
   *
   * @param entry The entry to be treated.
   * @param fieldName The field name (e.g. "journal")
   * @param ce If the entry is changed, add an edit to this compound.
   * @return true if the entry was changed, false otherwise.
   */
  public boolean unabbreviate(
      BibDatabase database, BibEntry entry, String fieldName, CompoundEdit ce) {
    if (!entry.hasField(fieldName)) {
      return false;
    }
    String text = entry.getFieldOptional(fieldName).get();
    String origText = text;
    if (database != null) {
      text = database.resolveForStrings(text);
    }

    if (!journalAbbreviationRepository.isKnownName(text)) {
      return false; // cannot do anything if it is not known
    }

    if (!journalAbbreviationRepository.isAbbreviatedName(text)) {
      return false; // cannot unabbreviate unabbreviated name.
    }

    Abbreviation abbreviation =
        journalAbbreviationRepository.getAbbreviation(text).get(); // must be here
    String newText = abbreviation.getName();
    entry.setField(fieldName, newText);
    ce.addEdit(new UndoableFieldChange(entry, fieldName, origText, newText));
    return true;
  }
Esempio n. 4
0
  @Override
  public void getEntries(Map<String, Boolean> selection, ImportInspector inspector) {
    for (Map.Entry<String, Boolean> selentry : selection.entrySet()) {
      if (!shouldContinue) {
        break;
      }
      boolean sel = selentry.getValue();
      if (sel) {
        BibEntry entry = downloadEntryBibTeX(selentry.getKey(), fetchAbstract);
        if (entry != null) {
          // Convert from HTML and optionally add curly brackets around key words to keep the case
          entry
              .getFieldOptional("title")
              .ifPresent(
                  title -> {
                    title = title.replaceAll("\\\\&", "&").replaceAll("\\\\#", "#");
                    title = convertHTMLChars(title);

                    // Unit formatting
                    if (Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)) {
                      title = unitFormatter.format(title);
                    }

                    // Case keeping
                    if (Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)) {
                      title = caseKeeper.format(title);
                    }
                    entry.setField("title", title);
                  });

          entry
              .getFieldOptional("abstract")
              .ifPresent(
                  abstr -> {
                    entry.setField("abstract", convertHTMLChars(abstr));
                  });
          inspector.addEntry(entry);
        }
      }
    }
  }
Esempio n. 5
0
 private Icon getFileIconForSelectedEntry() {
   if (panel.getMainTable().getSelectedRowCount() == 1) {
     BibEntry entry = panel.getMainTable().getSelected().get(0);
     if (entry.hasField(FieldName.FILE)) {
       JLabel label =
           FileListTableModel.getFirstLabel(entry.getFieldOptional(FieldName.FILE).get());
       if (label != null) {
         return label.getIcon();
       }
     }
   }
   return IconTheme.JabRefIcon.FILE.getSmallIcon();
 }
Esempio n. 6
0
  @Override
  public List<IntegrityMessage> check(BibEntry entry) {
    if (!entry.hasField(FieldName.ISSN)) {
      return Collections.emptyList();
    }

    // Check that the ISSN is on the correct form
    String issnString = entry.getFieldOptional(FieldName.ISSN).get().trim();

    ISSN issn = new ISSN(issnString);
    if (!issn.isValidFormat()) {
      return Collections.singletonList(
          new IntegrityMessage(Localization.lang("incorrect format"), entry, FieldName.ISSN));
    }

    if (issn.isValidChecksum()) {
      return Collections.emptyList();
    } else {
      return Collections.singletonList(
          new IntegrityMessage(
              Localization.lang("incorrect control digit"), entry, FieldName.ISSN));
    }
  }
Esempio n. 7
0
  /**
   * Convert a JSONObject obtained from http://api.springer.com/metadata/json to a BibEntry
   *
   * @param springerJsonEntry the JSONObject from search results
   * @return the converted BibEntry
   */
  public static BibEntry parseSpringerJSONtoBibtex(JSONObject springerJsonEntry) {
    // Fields that are directly accessible at the top level Json object
    String[] singleFieldStrings = {
      FieldName.ISSN,
      FieldName.VOLUME,
      FieldName.ABSTRACT,
      FieldName.DOI,
      FieldName.TITLE,
      FieldName.NUMBER,
      FieldName.PUBLISHER
    };

    BibEntry entry = new BibEntry();
    String nametype;

    // Guess publication type
    String isbn = springerJsonEntry.optString("isbn");
    if (com.google.common.base.Strings.isNullOrEmpty(isbn)) {
      // Probably article
      entry.setType("article");
      nametype = FieldName.JOURNAL;
    } else {
      // Probably book chapter or from proceeding, go for book chapter
      entry.setType("incollection");
      nametype = FieldName.BOOKTITLE;
      entry.setField(FieldName.ISBN, isbn);
    }

    // Authors
    if (springerJsonEntry.has("creators")) {
      JSONArray authors = springerJsonEntry.getJSONArray("creators");
      List<String> authorList = new ArrayList<>();
      for (int i = 0; i < authors.length(); i++) {
        if (authors.getJSONObject(i).has("creator")) {
          authorList.add(authors.getJSONObject(i).getString("creator"));
        } else {
          LOGGER.info("Empty author name.");
        }
      }
      entry.setField(FieldName.AUTHOR, String.join(" and ", authorList));
    } else {
      LOGGER.info("No author found.");
    }

    // Direct accessible fields
    for (String field : singleFieldStrings) {
      if (springerJsonEntry.has(field)) {
        String text = springerJsonEntry.getString(field);
        if (!text.isEmpty()) {
          entry.setField(field, text);
        }
      }
    }

    // Page numbers
    if (springerJsonEntry.has("startingPage")
        && !(springerJsonEntry.getString("startingPage").isEmpty())) {
      if (springerJsonEntry.has("endPage") && !(springerJsonEntry.getString("endPage").isEmpty())) {
        entry.setField(
            FieldName.PAGES,
            springerJsonEntry.getString("startingPage")
                + "--"
                + springerJsonEntry.getString("endPage"));
      } else {
        entry.setField(FieldName.PAGES, springerJsonEntry.getString("startingPage"));
      }
    }

    // Journal
    if (springerJsonEntry.has("publicationName")) {
      entry.setField(nametype, springerJsonEntry.getString("publicationName"));
    }

    // URL
    if (springerJsonEntry.has("url")) {
      JSONArray urlarray = springerJsonEntry.optJSONArray("url");
      if (urlarray == null) {
        entry.setField(FieldName.URL, springerJsonEntry.optString("url"));
      } else {
        entry.setField(FieldName.URL, urlarray.getJSONObject(0).optString("value"));
      }
    }

    // Date
    if (springerJsonEntry.has("publicationDate")) {
      String date = springerJsonEntry.getString("publicationDate");
      entry.setField(FieldName.DATE, date); // For BibLatex
      String[] dateparts = date.split("-");
      entry.setField(FieldName.YEAR, dateparts[0]);
      entry.setField(
          FieldName.MONTH, MonthUtil.getMonthByNumber(Integer.parseInt(dateparts[1])).bibtexFormat);
    }

    // Clean up abstract (often starting with Abstract)
    entry
        .getFieldOptional(FieldName.ABSTRACT)
        .ifPresent(
            abstractContents -> {
              if (abstractContents.startsWith("Abstract")) {
                entry.setField(FieldName.ABSTRACT, abstractContents.substring(8));
              }
            });

    return entry;
  }
Esempio n. 8
0
  public RightClickMenu(JabRefFrame frame, BasePanel panel) {
    this.panel = panel;
    JMenu typeMenu = new ChangeEntryTypeMenu().getChangeEntryTypeMenu(panel);
    // Are multiple entries selected?
    boolean multiple = areMultipleEntriesSelected();

    // If only one entry is selected, get a reference to it for adapting the menu.
    BibEntry be = null;
    if (panel.getMainTable().getSelectedRowCount() == 1) {
      be = panel.getMainTable().getSelected().get(0);
    }

    addPopupMenuListener(this);

    JMenu copySpecialMenu = new JMenu(Localization.lang("Copy") + "...");
    copySpecialMenu.add(new GeneralAction(Actions.COPY_KEY, Localization.lang("Copy BibTeX key")));
    copySpecialMenu.add(
        new GeneralAction(Actions.COPY_CITE_KEY, Localization.lang("Copy \\cite{BibTeX key}")));
    copySpecialMenu.add(
        new GeneralAction(
            Actions.COPY_KEY_AND_TITLE, Localization.lang("Copy BibTeX key and title")));
    copySpecialMenu.add(
        new GeneralAction(
            Actions.EXPORT_TO_CLIPBOARD,
            Localization.lang("Export to clipboard"),
            IconTheme.JabRefIcon.EXPORT_TO_CLIPBOARD.getSmallIcon()));

    add(
        new GeneralAction(
            Actions.COPY, Localization.lang("Copy"), IconTheme.JabRefIcon.COPY.getSmallIcon()));
    add(copySpecialMenu);
    add(
        new GeneralAction(
            Actions.PASTE, Localization.lang("Paste"), IconTheme.JabRefIcon.PASTE.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.CUT, Localization.lang("Cut"), IconTheme.JabRefIcon.CUT.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.DELETE,
            Localization.lang("Delete"),
            IconTheme.JabRefIcon.DELETE_ENTRY.getSmallIcon()));
    add(
        new GeneralAction(
            Actions.PRINT_PREVIEW,
            Localization.lang("Print entry preview"),
            IconTheme.JabRefIcon.PRINTED.getSmallIcon()));
    addSeparator();

    add(
        new GeneralAction(
            Actions.SEND_AS_EMAIL,
            Localization.lang("Send as email"),
            IconTheme.JabRefIcon.EMAIL.getSmallIcon()));
    addSeparator();

    JMenu markSpecific = JabRefFrame.subMenu(Localization.menuTitle("Mark specific color"));
    for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) {
      markSpecific.add(new MarkEntriesAction(frame, i).getMenuItem());
    }

    if (multiple) {
      add(
          new GeneralAction(
              Actions.MARK_ENTRIES,
              Localization.lang("Mark entries"),
              IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()));
      add(markSpecific);
      add(
          new GeneralAction(
              Actions.UNMARK_ENTRIES,
              Localization.lang("Unmark entries"),
              IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()));
    } else if (be != null) {
      Optional<String> marked = be.getFieldOptional(FieldName.MARKED_INTERNAL);
      // We have to check for "" too as the marked field may be empty
      if ((!marked.isPresent()) || marked.get().isEmpty()) {
        add(
            new GeneralAction(
                Actions.MARK_ENTRIES,
                Localization.lang("Mark entry"),
                IconTheme.JabRefIcon.MARK_ENTRIES.getSmallIcon()));
        add(markSpecific);
      } else {
        add(markSpecific);
        add(
            new GeneralAction(
                Actions.UNMARK_ENTRIES,
                Localization.lang("Unmark entry"),
                IconTheme.JabRefIcon.UNMARK_ENTRIES.getSmallIcon()));
      }
    }

    if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SPECIALFIELDSENABLED)) {
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_RANKING)) {
        JMenu rankingMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(rankingMenu, Rank.getInstance(), frame);
        add(rankingMenu);
      }

      // TODO: multiple handling for relevance and quality-assurance
      // if multiple values are selected ("if (multiple)"), two options (set / clear) should be
      // offered
      // if one value is selected either set or clear should be offered
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_RELEVANCE)) {
        add(Relevance.getInstance().getValues().get(0).getMenuAction(frame));
      }
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_QUALITY)) {
        add(Quality.getInstance().getValues().get(0).getMenuAction(frame));
      }
      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_PRINTED)) {
        add(Printed.getInstance().getValues().get(0).getMenuAction(frame));
      }

      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_PRIORITY)) {
        JMenu priorityMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(priorityMenu, Priority.getInstance(), frame);
        add(priorityMenu);
      }

      if (Globals.prefs.getBoolean(JabRefPreferences.PREF_SHOWCOLUMN_READ)) {
        JMenu readStatusMenu = new JMenu();
        RightClickMenu.populateSpecialFieldMenu(readStatusMenu, ReadStatus.getInstance(), frame);
        add(readStatusMenu);
      }
    }

    addSeparator();

    add(
        new GeneralAction(Actions.OPEN_FOLDER, Localization.lang("Open folder")) {
          {
            if (!isFieldSetForSelectedEntry(FieldName.FILE)) {
              this.setEnabled(false);
            }
          }
        });

    add(
        new GeneralAction(
            Actions.OPEN_EXTERNAL_FILE,
            Localization.lang("Open file"),
            getFileIconForSelectedEntry()) {
          {
            if (!isFieldSetForSelectedEntry(FieldName.FILE)) {
              this.setEnabled(false);
            }
          }
        });

    add(
        new GeneralAction(
            Actions.OPEN_URL,
            Localization.lang("Open URL or DOI"),
            IconTheme.JabRefIcon.WWW.getSmallIcon()) {
          {
            if (!(isFieldSetForSelectedEntry(FieldName.URL)
                || isFieldSetForSelectedEntry(FieldName.DOI))) {
              this.setEnabled(false);
            }
          }
        });

    addSeparator();

    add(typeMenu);

    add(
        new GeneralAction(
            Actions.MERGE_WITH_FETCHED_ENTRY,
            Localization.lang(
                "Get BibTeX data from %0", FetchAndMergeEntry.getDisplayNameOfSupportedFields())) {
          {
            if (!(isAnyFieldSetForSelectedEntry(FetchAndMergeEntry.SUPPORTED_FIELDS))) {
              this.setEnabled(false);
            }
          }
        });
    add(frame.getMassSetField());
    add(
        new GeneralAction(
            Actions.ADD_FILE_LINK,
            Localization.lang("Attach file"),
            IconTheme.JabRefIcon.ATTACH_FILE.getSmallIcon()));
    add(frame.getManageKeywords());
    add(
        new GeneralAction(
            Actions.MERGE_ENTRIES,
            Localization.lang("Merge entries") + "...",
            IconTheme.JabRefIcon.MERGE_ENTRIES.getSmallIcon()) {

          {
            if (!(areExactlyTwoEntriesSelected())) {
              this.setEnabled(false);
            }
          }
        });

    addSeparator(); // for "add/move/remove to/from group" entries (appended here)

    groupAdd =
        new JMenuItem(new GeneralAction(Actions.ADD_TO_GROUP, Localization.lang("Add to group")));
    add(groupAdd);
    groupRemove =
        new JMenuItem(
            new GeneralAction(Actions.REMOVE_FROM_GROUP, Localization.lang("Remove from group")));
    add(groupRemove);

    groupMoveTo = add(new GeneralAction(Actions.MOVE_TO_GROUP, Localization.lang("Move to group")));
    add(groupMoveTo);

    // create disabledIcons for all menu entries
    frame.createDisabledIconsForMenuEntries(this);
  }
Esempio n. 9
0
  @Override
  public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    String q;
    try {
      q = URLEncoder.encode(query, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
      // this should never happen
      status.setStatus(Localization.lang("Error"));
      LOGGER.warn("Encoding issues", e);
      return false;
    }

    String urlString = String.format(DiVAtoBibTeXFetcher.URL_PATTERN, q);

    // Send the request
    URL url;
    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      LOGGER.warn("Bad URL", e);
      return false;
    }

    String bibtexString;
    try {
      URLDownload dl = new URLDownload(url);

      bibtexString = dl.downloadToString(StandardCharsets.UTF_8);
    } catch (FileNotFoundException e) {
      status.showMessage(
          Localization.lang("Unknown DiVA entry: '%0'.", query),
          Localization.lang("Get BibTeX entry from DiVA"),
          JOptionPane.INFORMATION_MESSAGE);
      return false;
    } catch (IOException e) {
      LOGGER.warn("Communication problems", e);
      return false;
    }

    BibEntry entry = BibtexParser.singleFromString(bibtexString);
    if (entry != null) {
      // Optionally add curly brackets around key words to keep the case
      entry
          .getFieldOptional(FieldName.TITLE)
          .ifPresent(
              title -> {
                // Unit formatting
                if (Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)) {
                  title = unitsToLatexFormatter.format(title);
                }

                // Case keeping
                if (Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)) {
                  title = protectTermsFormatter.format(title);
                }
                entry.setField(FieldName.TITLE, title);
              });

      entry
          .getFieldOptional("institution")
          .ifPresent(
              institution ->
                  entry.setField("institution", new UnicodeToLatexFormatter().format(institution)));
      // Do not use the provided key
      // entry.clearField(InternalBibtexFields.KEY_FIELD);
      inspector.addEntry(entry);

      return true;
    }
    return false;
  }