private void typeDeletion(String name) {
    BibtexEntryType type = BibtexEntryType.getType(name);

    if (type instanceof CustomEntryType) {
      if (BibtexEntryType.getStandardType(name) == null) {
        int reply =
            JOptionPane.showConfirmDialog(
                frame,
                Globals.lang(
                    "All entries of this " + "type will be declared " + "typeless. Continue?"),
                Globals.lang("Delete custom format") + " '" + StringUtil.nCase(name) + '\'',
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE);
        if (reply != JOptionPane.YES_OPTION) {
          return;
        }
      }
      BibtexEntryType.removeType(name);
      updateTypesForEntries(StringUtil.nCase(name));
      changed.remove(name);
      reqLists.remove(name);
      optLists.remove(name);
      if (biblatexMode) {
        opt2Lists.remove(name);
      }
    }
    // messageLabel.setText("'"+type.getName()+"' "+
    //        Globals.lang("is a standard type."));

  }
    @Override
    public void actionPerformed(ActionEvent e) {
      if (lastSelected == null) {
        return;
      }
      defaulted.add(lastSelected);

      BibtexEntryType type = BibtexEntryType.getStandardType(lastSelected);
      if (type != null) {
        String[] rf = type.getRequiredFieldsForCustomization(), of = type.getOptionalFields();
        List<String> req, opt1, opt2;
        if (rf != null) {
          req = java.util.Arrays.asList(rf);
        } else {
          req = new ArrayList<String>();
        }

        opt1 = new ArrayList<String>();
        opt2 = new ArrayList<String>();
        if (biblatexMode) {
          if (of != null) {
            String[] priOptArray = type.getPrimaryOptionalFields();
            String[] secOptArray = Util.getRemainder(of, priOptArray);
            if (priOptArray != null) {
              opt1 = java.util.Arrays.asList(priOptArray);
            }
            if (secOptArray != null) {
              opt2 = java.util.Arrays.asList(secOptArray);
            }
          }
        } else {
          if (of != null) {
            opt1 = java.util.Arrays.asList(of);
          }
        }

        reqComp.setFields(req);
        reqComp.setEnabled(true);
        optComp.setFields(opt1);
        if (biblatexMode) {
          optComp2.setFields(opt2);
        }
      }
    }
Example #3
0
 private static BibtexEntry getTestEntry() {
   if (PreviewPrefsTab.entry != null) {
     return PreviewPrefsTab.entry;
   }
   PreviewPrefsTab.entry = new BibtexEntry(IdGenerator.next(), BibtexEntryType.getType("article"));
   PreviewPrefsTab.entry.setField(BibtexFields.KEY_FIELD, "conceicao1997");
   PreviewPrefsTab.entry.setField(
       "author",
       "Luis E. C. Conceic{\\~a}o and Terje van der Meeren and Johan A. J. Verreth and M S. Evjen and D. F. Houlihan and H. J. Fyhn");
   PreviewPrefsTab.entry.setField(
       "title",
       "Amino acid metabolism and protein turnover in larval turbot (Scophthalmus maximus) fed natural zooplankton or Artemia");
   PreviewPrefsTab.entry.setField("year", "1997");
   PreviewPrefsTab.entry.setField("journal", "Marine Biology");
   PreviewPrefsTab.entry.setField("month", "January");
   PreviewPrefsTab.entry.setField("number", "2");
   PreviewPrefsTab.entry.setField("volume", "123");
   PreviewPrefsTab.entry.setField("pdf", "conceicao1997.pdf");
   PreviewPrefsTab.entry.setField("pages", "255--265");
   PreviewPrefsTab.entry.setField(
       "keywords", "energetics, artemia, metabolism, amino acid, turbot");
   PreviewPrefsTab.entry.setField(
       "url", "http://ejournals.ebsco.com/direct.asp?ArticleID=TYY4NT82XA9H7R8PFPPV");
   PreviewPrefsTab.entry.setField(
       "abstract",
       "Abstract The present paper studied the influence of different food regimes "
           + "on the free amino acid (FAA) pool, the rate of protein turnover, the flux of amino acids, and "
           + "their relation to growth of larval turbot (Scophthalmus maximus L.) from first feeding until "
           + "metamorphosis. The amino acid profile of protein was stable during the larval period although "
           + "some small, but significant, differences were found. Turbot larvae had proteins which were rich "
           + "in leucine and aspartate, and poor in glutamate, suggesting a high leucine requirement. The "
           + "profile of the FAA pool was highly variable and quite different from the amino acid profile in "
           + "protein. The proportion of essential FAA decreased with development. High contents of free tyrosine "
           + "and phenylalanine were found on Day 3, while free taurine was present at high levels throughout "
           + "the experimental period. Larval growth rates were positively correlated with taurine levels, "
           + "suggesting a dietary dependency for taurine and/or sulphur amino acids.\n\nReduced growth rates in "
           + "Artemia-fed larvae were associated with lower levels of free methionine, indicating that this diet "
           + "is deficient in methionine for turbot larvae. Leucine might also be limiting turbot growth as the "
           + "different diet organisms had lower levels of this amino acid in the free pool than was found in the "
           + "larval protein. A previously presented model was used to describe the flux of amino acids in growing "
           + "turbot larvae. The FAA pool was found to be small and variable. It was estimated that the daily dietary "
           + "amino acid intake might be up to ten times the larval FAA pool. In addition, protein synthesis and "
           + "protein degradation might daily remove and return, respectively, the equivalent of up to 20 and 10 "
           + "times the size of the FAA pool. In an early phase (Day 11) high growth rates were associated with a "
           + "relatively low protein turnover, while at a later stage (Day 17), a much higher turnover was observed.");
   return PreviewPrefsTab.entry;
 }
Example #4
0
  private BibtexEntry parseNextEntry(String allText, int startIndex) {
    BibtexEntry entry = null;

    int index = allText.indexOf("<div class=\"detail", piv);
    int endIndex = allText.indexOf("</div>", index);

    if (index >= 0 && endIndex > 0) {
      endIndex += 6;
      piv = endIndex;
      String text = allText.substring(index, endIndex);

      BibtexEntryType type = null;
      String sourceField = null;

      String typeName = "";
      Matcher typeMatcher = typePattern.matcher(text);
      if (typeMatcher.find()) {
        typeName = typeMatcher.group(1);
        if (typeName.equalsIgnoreCase("IEEE Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("IEEE Early Access Articles")
            || typeName.equalsIgnoreCase("IET Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("AIP Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("AVS Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("IBM Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("TUP Journals &amp; Magazines")
            || typeName.equalsIgnoreCase("BIAI Journals &amp; Magazines")) {
          type = BibtexEntryType.getType("article");
          sourceField = "journal";
        } else if (typeName.equalsIgnoreCase("IEEE Conference Publications")
            || typeName.equalsIgnoreCase("IET Conference Publications")
            || typeName.equalsIgnoreCase("VDE Conference Publications")) {
          type = BibtexEntryType.getType("inproceedings");
          sourceField = "booktitle";
        } else if (typeName.equalsIgnoreCase("IEEE Standards")
            || typeName.equalsIgnoreCase("Standards")) {
          type = BibtexEntryType.getType("standard");
          sourceField = "number";
        } else if (typeName.equalsIgnoreCase("IEEE eLearning Library Courses")) {
          type = BibtexEntryType.getType("Electronic");
          sourceField = "note";
        } else if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters")
            || typeName.equalsIgnoreCase("MIT Press eBook Chapters")
            || typeName.equalsIgnoreCase("IEEE USA Books &amp; eBooks")) {
          type = BibtexEntryType.getType("inCollection");
          sourceField = "booktitle";
        }
      }

      if (type == null) {
        type = BibtexEntryType.getType("misc");
        sourceField = "note";
        System.err.println("Type detection failed. Use MISC instead.");
        unparseable++;
        System.err.println(text);
      }

      entry = new BibtexEntry(IdGenerator.next(), type);

      if (typeName.equalsIgnoreCase("IEEE Standards")) {
        entry.setField("organization", "IEEE");
      }

      if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters")) {
        entry.setField("publisher", "Wiley-IEEE Press");
      } else if (typeName.equalsIgnoreCase("MIT Press eBook Chapters")) {
        entry.setField("publisher", "MIT Press");
      } else if (typeName.equalsIgnoreCase("IEEE USA Books &amp; eBooks")) {
        entry.setField("publisher", "IEEE USA");
      }

      if (typeName.equalsIgnoreCase("IEEE Early Access Articles")) {
        entry.setField("note", "Early Access");
      }

      Set<String> fields = fieldPatterns.keySet();
      for (String field : fields) {
        Matcher fieldMatcher = Pattern.compile(fieldPatterns.get(field)).matcher(text);
        if (fieldMatcher.find()) {
          entry.setField(field, htmlConverter.format(fieldMatcher.group(1)));
          if (field.equals("title") && fieldMatcher.find()) {
            String sec_title = htmlConverter.format(fieldMatcher.group(1));
            if (entry.getType() == BibtexEntryType.getStandardType("standard")) {
              sec_title = sec_title.replaceAll("IEEE Std ", "");
            }
            entry.setField(sourceField, sec_title);
          }
          if (field.equals("pages") && fieldMatcher.groupCount() == 2) {
            entry.setField(field, fieldMatcher.group(1) + "-" + fieldMatcher.group(2));
          }
        }
      }

      Matcher authorMatcher = authorPattern.matcher(text);
      // System.out.println(text);
      StringBuilder authorNames = new StringBuilder("");
      int authorCount = 0;
      while (authorMatcher.find()) {
        if (authorCount >= 1) {
          authorNames.append(" and ");
        }
        authorNames.append(htmlConverter.format(authorMatcher.group(1)));
        // System.out.println(authorCount + ": " + authorMatcher.group(1));
        authorCount++;
      }
      entry.setField("author", authorNames.toString());
      if (entry.getField("author") == null
          || entry.getField("author").startsWith("a href")
          || entry
              .getField("author")
              .startsWith("Topic(s)")) { // Fix for some documents without authors
        entry.setField("author", "");
      }
      if (entry.getType() == BibtexEntryType.getStandardType("inproceedings")
          && entry.getField("author").equals("")) {
        entry.setType(BibtexEntryType.getStandardType("proceedings"));
      }

      if (includeAbstract) {
        index = text.indexOf("id=\"abstract");
        if (index >= 0) {
          endIndex = text.indexOf("</div>", index) + 6;

          text = text.substring(index, endIndex);
          Matcher absMatcher = absPattern.matcher(text);
          if (absMatcher.find()) {
            // Clean-up abstract
            String abstr = absMatcher.group(1);
            abstr = abstr.replaceAll("<span class='snippet'>([\\w]+)</span>", "$1");

            entry.setField("abstract", htmlConverter.format(abstr));
          }
        }
      }
    }

    if (entry == null) {
      return null;
    } else {
      return cleanup(entry);
    }
  }
Example #5
0
  private BibtexEntry cleanup(BibtexEntry entry) {
    if (entry == null) {
      return null;
    }

    // clean up title
    String title = entry.getField("title");
    if (title != null) {
      // USe the alt-text and replace image links
      title = title.replaceAll("[ ]?img src=[^ ]+ alt=\"([^\"]+)\">[ ]?", "\\$$1\\$");
      // Try to sort out most of the /spl / conversions
      // Deal with this specific nested type first
      title = title.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
      title = title.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
      // Replace general expressions
      title = title.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
      // Deal with subscripts and superscripts
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_CONVERT_TO_EQUATION)) {
        title = title.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
        title = title.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
        title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
        title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
      } else {
        title = title.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
        title = title.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
        title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
        title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
      }

      // Replace \infin with \infty
      title = title.replaceAll("\\\\infin", "\\\\infty");

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

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

    // clean up author
    /*   	String author = (String)entry.getField("author");
       	if (author != null) {
        if (author.indexOf("a href=") >= 0) {  // Author parsing failed because it was empty
    	entry.setField("author","");  // Maybe not needed anymore due to another change
        } else {
        	author = author.replaceAll("\\s+", " ");
        	author = author.replaceAll("\\.", ". ");
        	author = author.replaceAll("([^;]+),([^;]+),([^;]+)","$1,$3,$2"); // Change order in case of Jr. etc
        	author = author.replaceAll("  ", " ");
        	author = author.replaceAll("\\. -", ".-");
                   author = author.replaceAll("; ", " and ");
        	author = author.replaceAll(" ,", ",");
        	author = author.replaceAll("  ", " ");
        	author = author.replaceAll("[ ,;]+$", "");
        	entry.setField("author", author);
        }
    }*/
    // clean up month
    String month = entry.getField("month");
    if (month != null && !month.isEmpty()) {
      month = month.replaceAll("\\.", "");
      month = month.toLowerCase();

      Pattern monthPattern = Pattern.compile("(\\d*+)\\s*([a-z]*+)-*(\\d*+)\\s*([a-z]*+)");
      Matcher mm = monthPattern.matcher(month);
      String date = month;
      if (mm.find()) {
        if (mm.group(3).isEmpty()) {
          if (!mm.group(2).isEmpty()) {
            date = "#" + mm.group(2).substring(0, 3) + "#";
            if (!mm.group(1).isEmpty()) {
              date += " " + mm.group(1) + ",";
            }
          } else {
            date = mm.group(1) + ",";
          }
        } else if (mm.group(2).isEmpty()) {
          if (!mm.group(4).isEmpty()) {
            date =
                "#" + mm.group(4).substring(0, 3) + "# " + mm.group(1) + "--" + mm.group(3) + ",";
          } else {
            date += ",";
          }
        } else {
          date =
              "#"
                  + mm.group(2).substring(0, 3)
                  + "# "
                  + mm.group(1)
                  + "--#"
                  + mm.group(4).substring(0, 3)
                  + "# "
                  + mm.group(3)
                  + ",";
        }
      }
      // date = date.trim();
      // if (!date.isEmpty()) {
      entry.setField("month", date);
      // }
    }

    // clean up pages
    String field = "pages";
    String pages = entry.getField(field);
    if (pages != null) {
      String[] pageNumbers = pages.split("-");
      if (pageNumbers.length == 2) {
        if (pageNumbers[0].equals(pageNumbers[1])) { // single page
          entry.setField(field, pageNumbers[0]);
        } else {
          entry.setField(field, pages.replaceAll("-", "--"));
        }
      }
    }

    // clean up publication field
    BibtexEntryType type = entry.getType();
    String sourceField = "";
    if (type.getName().equals("Article")) {
      sourceField = "journal";
      entry.clearField("booktitle");
    } else if (type.getName().equals("Inproceedings")) {
      sourceField = "booktitle";
    }
    String fullName = entry.getField(sourceField);
    if (fullName != null) {
      if (type.getName().equals("Article")) {
        int ind = fullName.indexOf(": Accepted for future publication");
        if (ind > 0) {
          fullName = fullName.substring(0, ind);
          entry.setField("year", "to be published");
          entry.clearField("month");
          entry.clearField("pages");
          entry.clearField("number");
        }
        String[] parts = fullName.split("[\\[\\]]"); // [see also...], [legacy...]
        fullName = parts[0];
        if (parts.length == 3) {
          fullName += parts[2];
        }
        if (entry.getField("note").equals("Early Access")) {
          entry.setField("year", "to be published");
          entry.clearField("month");
          entry.clearField("pages");
          entry.clearField("number");
        }
      } else {
        fullName =
            fullName
                .replace("Conference Proceedings", "Proceedings")
                .replace("Proceedings of", "Proceedings")
                .replace("Proceedings.", "Proceedings");
        fullName = fullName.replaceAll("International", "Int.");
        fullName = fullName.replaceAll("Symposium", "Symp.");
        fullName = fullName.replaceAll("Conference", "Conf.");
        fullName = fullName.replaceAll(" on", " ").replace("  ", " ");
      }

      Matcher m1 = publicationPattern.matcher(fullName);
      String abrvPattern = ".*[^,] '?\\d+\\)?";
      if (m1.find()) {
        String prefix = m1.group(2).trim();
        String postfix = m1.group(1).trim();
        String abrv = "";
        String[] parts = prefix.split("\\. ", 2);
        if (parts.length == 2) {
          if (parts[0].matches(abrvPattern)) {
            prefix = parts[1];
            abrv = parts[0];
          } else {
            prefix = parts[0];
            abrv = parts[1];
          }
        }
        if (!prefix.matches(abrvPattern)) {
          fullName = prefix + " " + postfix + " " + abrv;
          fullName = fullName.trim();
        } else {
          fullName = postfix + " " + prefix;
        }
      }
      if (type.getName().equals("Article")) {
        fullName = fullName.replace(" - ", "-"); // IEE Proceedings-

        fullName = fullName.trim();
        if (Globals.prefs.getBoolean(JabRefPreferences.USE_IEEE_ABRV)) {
          fullName = Globals.journalAbbrev.getMedlineAbbreviation(fullName).orElse(fullName);
        }
      }
      if (type.getName().equals("Inproceedings")) {
        Matcher m2 = proceedingPattern.matcher(fullName);
        if (m2.find()) {
          String prefix = m2.group(2);
          String postfix = m2.group(1).replaceAll("\\.$", "");
          if (!prefix.matches(abrvPattern)) {
            String abrv = "";

            String[] parts = postfix.split("\\. ", 2);
            if (parts.length == 2) {
              if (parts[0].matches(abrvPattern)) {
                postfix = parts[1];
                abrv = parts[0];
              } else {
                postfix = parts[0];
                abrv = parts[1];
              }
            }
            fullName = prefix.trim() + " " + postfix.trim() + " " + abrv;

          } else {
            fullName = postfix.trim() + " " + prefix.trim();
          }
        }

        fullName = fullName.trim();

        fullName =
            fullName.replaceAll("^[tT]he ", "").replaceAll("^\\d{4} ", "").replaceAll("[,.]$", "");
        String year = entry.getField("year");
        fullName = fullName.replaceAll(", " + year + "\\.?", "");

        if (!fullName.contains("Abstract")
            && !fullName.contains("Summaries")
            && !fullName.contains("Conference Record")) {
          fullName = "Proc. " + fullName;
        }
      }
      entry.setField(sourceField, fullName);
    }

    // clean up abstract
    String abstr = entry.getField("abstract");
    if (abstr != null) {
      // Try to sort out most of the /spl / conversions
      // Deal with this specific nested type first
      abstr = abstr.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
      abstr = abstr.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
      // Replace general expressions
      abstr = abstr.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
      // Deal with subscripts and superscripts
      if (Globals.prefs.getBoolean(JabRefPreferences.USE_CONVERT_TO_EQUATION)) {
        abstr = abstr.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
        abstr = abstr.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
        abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
        abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
      } else {
        abstr = abstr.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
        abstr = abstr.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
        abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
        abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
      }
      // Replace \infin with \infty
      abstr = abstr.replaceAll("\\\\infin", "\\\\infty");
      // Write back
      entry.setField("abstract", abstr);
    }

    // Clean up url
    String url = entry.getField("url");
    if (url != null) {
      entry.setField("url", "http://ieeexplore.ieee.org" + url.replace("tp=&", ""));
    }
    return entry;
  }
Example #6
0
  private boolean importPdfFiles(List<String> fileNames) {
    if (panel == null) return false;
    for (String fileName : fileNames) {
      List<BibtexEntry> xmpEntriesInFile = readXmpEntries(fileName);
      ImportDialog importDialog = new ImportDialog(dropRow, fileName);
      if (!hasXmpEntries(xmpEntriesInFile)) {
        importDialog.getRadioButtonXmp().setEnabled(false);
      }
      Tools.centerRelativeToWindow(importDialog, frame);
      importDialog.showDialog();
      if (importDialog.getResult() == JOptionPane.OK_OPTION) {
        if (importDialog.getRadioButtonXmp().isSelected()) {
          // SplDatabaseChangeListener dataListener = new SplDatabaseChangeListener(frame, panel,
          // entryTable, fileName);
          // panel.database().addDatabaseChangeListener(dataListener);
          ImportMenuItem importer = new ImportMenuItem(frame, (entryTable == null));
          importer.automatedImport(new String[] {fileName});

        } else if (importDialog.getRadioButtonMrDlib().isSelected()) {
          MetaDataListDialog metaDataListDialog = new MetaDataListDialog(fileName, true);
          Tools.centerRelativeToWindow(metaDataListDialog, frame);
          metaDataListDialog.showDialog();
          XmlDocuments documents = metaDataListDialog.getXmlDocuments();
          if (documents != null
              && documents.getDocuments() != null
              && documents.getDocuments().size() > 0
              && metaDataListDialog.getResult() == JOptionPane.OK_OPTION) {
            int selected = metaDataListDialog.getTableMetadata().getSelectedRow();
            if (selected > -1 && selected < documents.getDocuments().size()) {
              XmlDocument document = documents.getDocuments().get(selected);
              String id = Util.createNeutralId();
              BibtexEntry entry = new BibtexEntry(id);
              if (fieldExists(document.getType())) {
                BibtexEntryType type = BibtexEntryType.getStandardType(document.getType());
                if (type == null) {
                  type = BibtexEntryType.ARTICLE;
                }
                entry.setType(type);
              } else {
                entry.setType(BibtexEntryType.ARTICLE);
              }
              ArrayList<BibtexEntry> list = new ArrayList<BibtexEntry>();
              list.add(entry);
              Util.setAutomaticFields(list, true, true, false);
              insertFields(entry.getRequiredFields(), entry, document);
              insertFields(entry.getGeneralFields(), entry, document);
              insertFields(entry.getOptionalFields(), entry, document);
              panel.database().insertEntry(entry);
              DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
              dfh.linkPdfToEntry(fileName, entryTable, entry);
              LabelPatternUtil.makeLabel(Globals.prefs.getKeyPattern(), panel.database(), entry);
            } else {
              createNewBlankEntry(fileName);
            }
          } else if (metaDataListDialog.getResult() == JOptionPane.CANCEL_OPTION) {
            continue;
          } else if (metaDataListDialog.getResult() == JOptionPane.NO_OPTION) {
            createNewBlankEntry(fileName);
          } else if (documents == null
              || documents.getDocuments() == null
              || documents.getDocuments().size() <= 0
                  && metaDataListDialog.getResult() == JOptionPane.OK_OPTION) {
            createNewBlankEntry(fileName);
          }
        } else if (importDialog.getRadioButtonNoMeta().isSelected()) {
          createNewBlankEntry(fileName);
        } else if (importDialog.getRadioButtonUpdateEmptyFields().isSelected()) {
          MetaDataListDialog metaDataListDialog = new MetaDataListDialog(fileName, false);
          Tools.centerRelativeToWindow(metaDataListDialog, frame);
          metaDataListDialog.showDialog();
          XmlDocuments documents = metaDataListDialog.getXmlDocuments();
          if (documents != null
              && documents.getDocuments() != null
              && documents.getDocuments().size() > 0
              && metaDataListDialog.getResult() == JOptionPane.OK_OPTION) {
            int selected = metaDataListDialog.getTableMetadata().getSelectedRow();
            if (selected > -1 && selected < documents.getDocuments().size()) {
              XmlDocument document = documents.getDocuments().get(selected);
              BibtexEntry entry = entryTable.getEntryAt(dropRow);
              if (fieldExists(document.getType())) {
                BibtexEntryType type = BibtexEntryType.getStandardType(document.getType());
                if (type != null) {
                  entry.setType(type);
                }
              }
              insertFields(entry.getRequiredFields(), entry, document);
              insertFields(entry.getGeneralFields(), entry, document);
              insertFields(entry.getOptionalFields(), entry, document);

              DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
              dfh.linkPdfToEntry(fileName, entryTable, dropRow);
            }
          }
        } else if (importDialog.getRadioButtononlyAttachPDF().isSelected()) {
          DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
          dfh.linkPdfToEntry(fileName, entryTable, dropRow);
        }
      }
    }
    return true;
  }
Example #7
0
  private BibtexEntry createNewEntry() {

    // Find out what type is wanted.
    EntryTypeDialog etd = new EntryTypeDialog(frame);
    // We want to center the dialog, to make it look nicer.
    Util.placeDialog(etd, frame);
    etd.setVisible(true);
    BibtexEntryType type = etd.getChoice();

    if (type != null) { // Only if the dialog was not cancelled.
      String id = Util.createNeutralId();
      final BibtexEntry be = new BibtexEntry(id, type);
      try {
        panel.database().insertEntry(be);

        // Set owner/timestamp if options are enabled:
        ArrayList<BibtexEntry> list = new ArrayList<BibtexEntry>();
        list.add(be);
        Util.setAutomaticFields(list, true, true, false);

        // Create an UndoableInsertEntry object.
        panel.undoManager.addEdit(new UndoableInsertEntry(panel.database(), be, panel));
        panel.output(
            Globals.lang("Added new")
                + " '"
                + type.getName().toLowerCase()
                + "' "
                + Globals.lang("entry")
                + ".");

        // We are going to select the new entry. Before that, make sure that we are in
        // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR
        // mode which makes sure the selection will trigger display of the entry editor
        // and adjustment of the splitter.
        if (panel.getMode() != panel.SHOWING_EDITOR) {
          panel.setMode(panel.WILL_SHOW_EDITOR);
        }

        /*int row = entryTable.findEntry(be);
        if (row >= 0)
            // Selects the entry. The selection listener will open the editor.
             if (row >= 0) {
                try{
                    entryTable.setRowSelectionInterval(row, row);
                }catch(IllegalArgumentException e){
                    System.out.println("RowCount: " + entryTable.getRowCount());
                }

                //entryTable.setActiveRow(row);
                entryTable.ensureVisible(row);
             }
        else {
            // The entry is not visible in the table, perhaps due to a filtering search
            // or group selection. Show the entry editor anyway:
            panel.showEntry(be);
        }   */
        panel.showEntry(be);
        panel.markBaseChanged(); // The database just changed.
        new FocusRequester(panel.getEntryEditor(be));
        return be;
      } catch (KeyCollisionException ex) {
        Util.pr(ex.getMessage());
      }
    }
    return null;
  }
  private void applyChanges() {
    valueChanged(new ListSelectionEvent(new JList(), 0, 0, false));
    // Iterate over our map of required fields, and list those types if necessary:

    List<String> types = typeComp.getFields();
    for (Map.Entry<String, List<String>> stringListEntry : reqLists.entrySet()) {
      if (!types.contains(stringListEntry.getKey())) {
        continue;
      }

      List<String> reqFields = stringListEntry.getValue();
      List<String> optFields = optLists.get(stringListEntry.getKey());
      List<String> opt2Fields = opt2Lists.get(stringListEntry.getKey());
      String[] reqStr = new String[reqFields.size()];
      reqStr = reqFields.toArray(reqStr);
      String[] optStr = new String[optFields.size()];
      optStr = optFields.toArray(optStr);
      String[] opt2Str;
      if (opt2Fields != null) {
        opt2Str = opt2Fields.toArray(new String[opt2Fields.size()]);
      } else {
        opt2Str = new String[0];
      }

      // If this type is already existing, check if any changes have
      // been made
      boolean changesMade = true;

      if (defaulted.contains(stringListEntry.getKey())) {
        // This type should be reverted to its default setup.
        // System.out.println("Defaulting: "+typeName);
        String nm = StringUtil.nCase(stringListEntry.getKey());
        BibtexEntryType.removeType(nm);

        updateTypesForEntries(nm);
        continue;
      }

      BibtexEntryType oldType = BibtexEntryType.getType(stringListEntry.getKey());
      if (oldType != null) {
        String[] oldReq = oldType.getRequiredFields(), oldOpt = oldType.getOptionalFields();
        if (biblatexMode) {
          String[] priOpt = oldType.getPrimaryOptionalFields();
          String[] secOpt = Util.getRemainder(oldOpt, priOpt);
          if (equalArrays(oldReq, reqStr)
              && equalArrays(oldOpt, optStr)
              && equalArrays(secOpt, opt2Str)) {
            changesMade = false;
          }
        } else if (equalArrays(oldReq, reqStr) && equalArrays(oldOpt, optStr)) {
          changesMade = false;
        }
      }

      if (changesMade) {
        // System.out.println("Updating: "+typeName);
        CustomEntryType typ =
            biblatexMode
                ? new CustomEntryType(
                    StringUtil.nCase(stringListEntry.getKey()), reqStr, optStr, opt2Str)
                : new CustomEntryType(StringUtil.nCase(stringListEntry.getKey()), reqStr, optStr);

        BibtexEntryType.ALL_TYPES.put(stringListEntry.getKey().toLowerCase(), typ);
        updateTypesForEntries(typ.getName());
      }
    }

    Set<Object> toRemove = new HashSet<Object>();
    for (String o : BibtexEntryType.ALL_TYPES.keySet()) {
      if (!types.contains(o)) {
        toRemove.add(o);
      }
    }

    // Remove those that should be removed:
    if (!toRemove.isEmpty()) {
      for (Object aToRemove : toRemove) {
        typeDeletion((String) aToRemove);
      }
    }

    updateTables();
  }
  @Override
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) {
      return;
    }

    if (lastSelected != null) {
      // The entry type lastSelected is now unselected, so we store the current settings
      // for that type in our two maps.
      reqLists.put(lastSelected, reqComp.getFields());
      optLists.put(lastSelected, optComp.getFields());
      if (biblatexMode) {
        opt2Lists.put(lastSelected, optComp2.getFields());
      }
    }

    String s = typeComp.getFirstSelected();
    if (s == null) {
      return;
    }
    List<String> rl = reqLists.get(s);
    if (rl == null) {
      BibtexEntryType type = BibtexEntryType.getType(s);
      if (type != null) {
        String[] rf = type.getRequiredFieldsForCustomization(), of = type.getOptionalFields();
        List<String> req, opt;
        if (rf != null) {
          req = java.util.Arrays.asList(rf);
        } else {
          req = new ArrayList<String>();
        }

        if (!biblatexMode) {
          if (of != null) {
            opt = java.util.Arrays.asList(of);
          } else {
            opt = new ArrayList<String>();
          }
        } else {
          String[] priOf = type.getPrimaryOptionalFields();
          if (priOf != null) {
            opt = java.util.Arrays.asList(priOf);
          } else {
            opt = new ArrayList<String>();
          }
          List<String> opt2 = new ArrayList<String>();
          if (of != null) {
            for (String anOf : of) {
              if (!opt.contains(anOf)) {
                opt2.add(anOf);
              }
            }
          }
          optComp2.setFields(opt2);
          optComp2.setEnabled(true);
        }

        reqComp.setFields(req);
        reqComp.setEnabled(true);
        optComp.setFields(opt);
        optComp.setEnabled(true);
      } else {
        // New entry, veintle
        reqComp.setFields(new ArrayList<String>());
        reqComp.setEnabled(true);
        optComp.setFields(new ArrayList<String>());
        optComp.setEnabled(true);
        if (biblatexMode) {
          optComp2.setFields(new ArrayList<String>());
          optComp2.setEnabled(true);
        }
        new FocusRequester(reqComp);
      }
    } else {
      reqComp.setFields(rl);
      optComp.setFields(optLists.get(s));
      if (biblatexMode) {
        optComp2.setFields(opt2Lists.get(s));
      }
    }

    lastSelected = s;
    typeComp.enable(s, changed.contains(lastSelected) && !defaulted.contains(lastSelected));
  }
Example #10
0
  /**
   * Will parse the BibTex-Data found when reading from reader.
   *
   * <p>The reader will be consumed.
   *
   * <p>Multiple calls to parse() return the same results
   *
   * @return ParserResult
   * @throws IOException
   */
  public ParserResult parse() throws IOException {

    // If we already parsed this, just return it.
    if (_pr != null) return _pr;

    _db = new BibtexDatabase(); // Bibtex related contents.
    _meta = new HashMap<String, String>(); // Metadata in comments for Bibkeeper.
    entryTypes = new HashMap<String, BibtexEntryType>(); // To store custem entry types parsed.
    _pr = new ParserResult(_db, _meta, entryTypes);

    // First see if we can find the version number of the JabRef version that
    // wrote the file:
    String versionNum = readJabRefVersionNumber();
    if (versionNum != null) {
      _pr.setJabrefVersion(versionNum);
      setMajorMinorVersions();
    } else {
      // No version number found. However, we have only
    }

    skipWhitespace();

    try {
      while (!_eof) {
        boolean found = consumeUncritically('@');
        if (!found) break;
        skipWhitespace();
        String entryType = parseTextToken();
        BibtexEntryType tp = BibtexEntryType.getType(entryType);
        boolean isEntry = (tp != null);
        // Util.pr(tp.getName());
        if (!isEntry) {
          // The entry type name was not recognized. This can mean
          // that it is a string, preamble, or comment. If so,
          // parse and set accordingly. If not, assume it is an entry
          // with an unknown type.
          if (entryType.toLowerCase().equals("preamble")) {
            _db.setPreamble(parsePreamble());
          } else if (entryType.toLowerCase().equals("string")) {
            BibtexString bs = parseString();
            try {
              _db.addString(bs);
            } catch (KeyCollisionException ex) {
              _pr.addWarning(Globals.lang("Duplicate string name") + ": " + bs.getName());
              // ex.printStackTrace();
            }
          } else if (entryType.toLowerCase().equals("comment")) {
            StringBuffer commentBuf = parseBracketedTextExactly();
            /**
             * Metadata are used to store Bibkeeper-specific information in .bib files.
             *
             * <p>Metadata are stored in bibtex files in the format
             *
             * @comment{jabref-meta: type:data0;data1;data2;...}
             *     <p>Each comment that starts with the META_FLAG is stored in the meta HashMap,
             *     with type as key. Unluckily, the old META_FLAG bibkeeper-meta: was used in JabRef
             *     1.0 and 1.1, so we need to support it as well. At least for a while. We'll always
             *     save with the new one.
             */
            String comment = commentBuf.toString().replaceAll("[\\x0d\\x0a]", "");
            if (comment
                    .substring(0, Math.min(comment.length(), GUIGlobals.META_FLAG.length()))
                    .equals(GUIGlobals.META_FLAG)
                || comment
                    .substring(0, Math.min(comment.length(), GUIGlobals.META_FLAG_OLD.length()))
                    .equals(GUIGlobals.META_FLAG_OLD)) {

              String rest;
              if (comment.substring(0, GUIGlobals.META_FLAG.length()).equals(GUIGlobals.META_FLAG))
                rest = comment.substring(GUIGlobals.META_FLAG.length());
              else rest = comment.substring(GUIGlobals.META_FLAG_OLD.length());

              int pos = rest.indexOf(':');

              if (pos > 0) _meta.put(rest.substring(0, pos), rest.substring(pos + 1));
              // We remove all line breaks in the metadata - these
              // will have been inserted
              // to prevent too long lines when the file was
              // saved, and are not part of the data.
            }

            /**
             * A custom entry type can also be stored in a
             *
             * @comment:
             */
            if (comment
                .substring(0, Math.min(comment.length(), GUIGlobals.ENTRYTYPE_FLAG.length()))
                .equals(GUIGlobals.ENTRYTYPE_FLAG)) {

              CustomEntryType typ = CustomEntryType.parseEntryType(comment);
              entryTypes.put(typ.getName().toLowerCase(), typ);
            }
          } else {
            // The entry type was not recognized. This may mean that
            // it is a custom entry type whose definition will
            // appear
            // at the bottom of the file. So we use an
            // UnknownEntryType
            // to remember the type name by.
            tp = new UnknownEntryType(entryType.toLowerCase());
            // System.out.println("unknown type: "+entryType);
            isEntry = true;
          }
        }

        if (isEntry) // True if not comment, preamble or string.
        {
          /**
           * Morten Alver 13 Aug 2006: Trying to make the parser more robust. If an exception is
           * thrown when parsing an entry, drop the entry and try to resume parsing. Add a warning
           * for the user.
           *
           * <p>An alternative solution is to try rescuing the entry for which parsing failed, by
           * returning the entry with the exception and adding it before parsing is continued.
           */
          try {
            BibtexEntry be = parseEntry(tp);

            boolean duplicateKey = _db.insertEntry(be);
            if (duplicateKey) // JZTODO lyrics
            _pr.addWarning(
                  Globals.lang("duplicate BibTeX key")
                      + ": "
                      + be.getCiteKey()
                      + " ("
                      + Globals.lang("grouping may not work for this entry")
                      + ")");
            else if (be.getCiteKey() == null || be.getCiteKey().equals("")) {
              _pr.addWarning(
                  Globals.lang("empty BibTeX key")
                      + ": "
                      + be.getAuthorTitleYear(40)
                      + " ("
                      + Globals.lang("grouping may not work for this entry")
                      + ")");
            }
          } catch (IOException ex) {
            ex.printStackTrace();
            _pr.addWarning(
                Globals.lang("Error occured when parsing entry")
                    + ": '"
                    + ex.getMessage()
                    + "'. "
                    + Globals.lang("Skipped entry."));
          }
        }

        skipWhitespace();
      }

      // Before returning the database, update entries with unknown type
      // based on parsed type definitions, if possible.
      checkEntryTypes(_pr);

      return _pr;
    } catch (KeyCollisionException kce) {
      // kce.printStackTrace();
      throw new IOException("Duplicate ID in bibtex file: " + kce.toString());
    }
  }