diff --git a/CHANGELOG.md b/CHANGELOG.md index d7c18c5e89b2..debf0618d109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We fixed nested LaTeX formatting, spacing, and ampersand escaping in HTML output and JStyle bibliographies. [#17921](https://github.com/JabRef/jabref/pull/17921) - We fixed an issue where RIS import stored a book's ISBN in the ISSN field. [#17889](https://github.com/JabRef/jabref/issues/17889) - We fixed an issue with wrong text shown for preferences menu item and the preferences dialog shortcut opening directly LibreOffice panel in preferences. [#17966](https://github.com/JabRef/jabref/issues/17966) +- We fixed MODS contributor name and role handling, including names containing “and”, organizations, suffixes, and patent assignees. [#17898](https://github.com/JabRef/jabref/issues/17898) ### Removed diff --git a/_typos.toml b/_typos.toml index 10042d2047ae..0ab59b1594d1 100644 --- a/_typos.toml +++ b/_typos.toml @@ -48,6 +48,7 @@ bigrading = "bigrading" nd = "nd" edn = "edn" thes = "thes" +ths = "ths" rin = "rin" ein = "ein" ot = "ot" diff --git a/docs/requirements/export.md b/docs/requirements/export.md index 49ca46bf871c..1b0643284d50 100644 --- a/docs/requirements/export.md +++ b/docs/requirements/export.md @@ -60,5 +60,22 @@ Local attachments that cannot be resolved or represented relatively are omitted. Needs: impl, utest +## MODS exports must preserve supported contributor names +`req~export.mods.names~1` + +MODS exports preserve supported contributor names without incorrectly splitting names containing "and". +Brace-protected organizations are exported as corporate names, personal suffixes as `termsOfAddress`, and the BibTeX `and others` placeholder is omitted. +Exports preserve initial punctuation and attached prefixes. Explicit initials supply the given name when it is unavailable, and an extended name with no standard parts is exported as literal name text. +See the [MODS name guidelines](https://www.loc.gov/standards/mods/userguide/name.html) and the [MODS 3.6 to MARC 21 mapping](https://www.loc.gov/standards/mods/v3/mods2marc-mapping-3-6.html). + +Each supported contributor field is exported with its corresponding [MARC relator code](https://www.loc.gov/marc/relators/relaterm.html). +Re-importing the export restores each supported contributor role to its corresponding field. +Composer (`cmp`), illustrator (`ill`), and thesis advisor (`ths`) use custom fields. Generic contributors (`ctb`) and names with only unmapped roles use the `contributor` field. +Patent assignees and patent holders share the `pth` relator and re-import as patent holders. + +See [issue 17898](https://github.com/JabRef/jabref/issues/17898). + +Needs: impl, utest + diff --git a/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java b/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java index 7e6c0c1f2d81..62a0e3bc51e4 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.regex.Pattern; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -24,12 +25,16 @@ import javax.xml.transform.stream.StreamSource; import org.jabref.logic.util.StandardFileType; +import org.jabref.logic.util.strings.StringUtil; import org.jabref.model.database.BibDatabaseContext; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.EntryType; +import org.jabref.model.entry.types.IEEETranEntryType; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; @@ -42,6 +47,25 @@ class ModsExporter extends Exporter { private static final String MINUS = "-"; private static final String DOUBLE_MINUS = "--"; private static final String MODS_SCHEMA_LOCATION = "http://www.loc.gov/standards/mods/v3/mods-3-6.xsd"; + private static final Pattern REPEATED_HORIZONTAL_WHITESPACE = Pattern.compile("\\h{2,}"); + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + // https://www.loc.gov/marc/relators/relaterm.html + private static final Map PERSON_NAME_ROLES = Map.ofEntries( + Map.entry(StandardField.AFTERWORD, "waw"), + Map.entry(StandardField.ANNOTATOR, "ann"), + Map.entry(StandardField.ASSIGNEE, "asg"), + Map.entry(StandardField.AUTHOR, "aut"), + Map.entry(StandardField.COMMENTATOR, "cwt"), + Map.entry(new UnknownField("composer"), "cmp"), + Map.entry(new UnknownField("contributor"), "ctb"), + Map.entry(StandardField.EDITOR, "edt"), + Map.entry(StandardField.FOREWORD, "wfw"), + Map.entry(StandardField.HOLDER, "pth"), + Map.entry(new UnknownField("illustrator"), "ill"), + Map.entry(StandardField.INTRODUCTION, "win"), + Map.entry(new UnknownField("thesisadvisor"), "ths"), + Map.entry(StandardField.TRANSLATOR, "trl") + ); private static final Logger LOGGER = LoggerFactory.getLogger(ModsExporter.class); @@ -82,8 +106,12 @@ public void export(@NonNull final BibDatabaseContext databaseContext, Field field = entry.getKey(); String value = entry.getValue(); - if (StandardField.AUTHOR == field) { - handleAuthors(writer, value); + if (PERSON_NAME_ROLES.containsKey(field)) { + // MARC asg denotes a printing or publishing license assignee. + String role = field == StandardField.ASSIGNEE && bibEntry.getType() == IEEETranEntryType.Patent + ? "pth" + : PERSON_NAME_ROLES.get(field); + handleNames(writer, value, role); } else if (new UnknownField("affiliation").equals(field)) { addAffiliation(writer, value); } else if (StandardField.ABSTRACT == field) { @@ -359,44 +387,65 @@ private void addKeyWords(XMLStreamWriter writer, String value) throws XMLStreamE } } - private void handleAuthors(XMLStreamWriter writer, String value) throws XMLStreamException { - String[] authors = value.split("and"); - for (String author : authors) { + // [impl->req~export.mods.names~1] + private void handleNames(XMLStreamWriter writer, String value, String role) throws XMLStreamException { + // BibTeX names use "and" as a separator. The shared parser also accepts repeated spaces in pasted lists. + String names = REPEATED_HORIZONTAL_WHITESPACE.matcher(value).replaceAll(" "); + for (Author author : AuthorList.parse(names).getNamedAuthors()) { writer.writeStartElement("mods", "name", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "personal"); - - if (author.contains(",")) { - // if author contains "," then this indicates that the author has a forename and family name - int commaIndex = author.indexOf(','); - String familyName = author.substring(0, commaIndex); - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "family"); - writer.writeCharacters(familyName); - writer.writeEndElement(); - - // now take care of the forenames - String forename = author.substring(commaIndex + 1); - String[] forenames = forename.split(" "); - for (String given : forenames) { - if (!given.isEmpty()) { - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "given"); - writer.writeCharacters(given); - writer.writeEndElement(); - } - } - writer.writeEndElement(); + String familyName = author.getNamePrefixAndFamilyNameForDisplay(); + String givenName = author.getGivenNameWithOriginalPunctuation() + .or(() -> author.getExplicitGivenNameInitials().filter(initials -> !initials.isEmpty())) + .orElse(""); + String suffix = author.getNameSuffix().orElse(""); + // https://www.loc.gov/standards/mods/userguide/name.html + if (StringUtil.isInCurlyBrackets(familyName) && givenName.isEmpty() && suffix.isEmpty()) { + writer.writeAttribute("type", "corporate"); + writeNamePart(writer, "", Author.FORMATTER.format(familyName)); + } else if (familyName.isEmpty() && givenName.isEmpty() && suffix.isEmpty()) { + // A custom extended name may have no standard BibLaTeX name parts. + writeNamePart(writer, "", author.getAsBibtex()); } else { - // no "," indicates that there should only be a family name - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "family"); - writer.writeCharacters(author); - writer.writeEndElement(); - writer.writeEndElement(); + writer.writeAttribute("type", "personal"); + writePersonalNameParts(writer, familyName, givenName, suffix); } + + writer.writeStartElement("mods", "role", MODS_NAMESPACE_URI); + writer.writeStartElement("mods", "roleTerm", MODS_NAMESPACE_URI); + writer.writeAttribute("type", "code"); + writer.writeAttribute("authority", "marcrelator"); + writer.writeCharacters(role); + writer.writeEndElement(); + writer.writeEndElement(); + writer.writeEndElement(); } } + private void writePersonalNameParts(XMLStreamWriter writer, String familyName, String givenName, String suffix) throws XMLStreamException { + if (!familyName.isEmpty()) { + writeNamePart(writer, "family", familyName); + } + if (!givenName.isEmpty()) { + for (String given : WHITESPACE_PATTERN.split(givenName)) { + writeNamePart(writer, "given", given); + } + } + if (!suffix.isEmpty()) { + // termsOfAddress maps to MARC 100/700 $c. + // https://www.loc.gov/standards/mods/v3/mods2marc-mapping-3-6.html + writeNamePart(writer, "termsOfAddress", suffix); + } + } + + private void writeNamePart(XMLStreamWriter writer, String type, String name) throws XMLStreamException { + writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); + if (!type.isEmpty()) { + writer.writeAttribute("type", type); + } + writer.writeCharacters(name); + writer.writeEndElement(); + } + private void addIdentifier(XMLStreamWriter writer, Field field, String value) throws XMLStreamException { if (new UnknownField("citekey").equals(field)) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java index 70798aedb877..d11956d85852 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java @@ -8,12 +8,15 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.StringJoiner; import java.util.regex.Pattern; +import java.util.stream.Collectors; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; @@ -30,6 +33,7 @@ import org.jabref.logic.importer.fileformat.mods.RecordInfo; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.StandardFileType; +import org.jabref.logic.util.strings.StringUtil; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Date; import org.jabref.model.entry.field.Field; @@ -106,11 +110,9 @@ private void parseModsCollection(List bibItems, XMLStreamReader reader } private void parseModsGroup(Map fields, XMLStreamReader reader, BibEntry entry) throws XMLStreamException { - // These elements (subject, keywords and authors) can appear more than once, - // so they are collected in lists List notes = new ArrayList<>(); List keywords = new ArrayList<>(); - List authors = new ArrayList<>(); + Map> contributors = new HashMap<>(); TypeHints typeHints = new TypeHints(); while (reader.hasNext()) { @@ -163,7 +165,7 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B case "originInfo" -> parseOriginInfo(reader, fields, typeHints, false); case "name" -> - parseName(reader, fields, authors); + parseName(reader, fields, contributors); case "relatedItem" -> parseRelatedItem(reader, fields, typeHints); } @@ -176,7 +178,7 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B putIfListIsNotEmpty(fields, notes, StandardField.NOTE, ", "); putIfListIsNotEmpty(fields, keywords, StandardField.KEYWORDS, this.keywordSeparator); - putIfListIsNotEmpty(fields, authors, StandardField.AUTHOR, " and "); + contributors.forEach((field, names) -> putIfListIsNotEmpty(fields, names, field, " and ")); inferEntryType(typeHints) .ifPresent(entry::setType); @@ -296,8 +298,12 @@ private void handleDetail(XMLStreamReader reader, Map fields) thr } } - private void parseName(XMLStreamReader reader, Map fields, List authors) throws XMLStreamException { + // [impl->req~export.mods.names~1] + private void parseName(XMLStreamReader reader, Map fields, Map> contributors) throws XMLStreamException { + boolean corporate = "corporate".equals(reader.getAttributeValue(null, "type")); List names = new ArrayList<>(); + Set contributorFields = new LinkedHashSet<>(); + boolean hasRoleTerm = false; while (reader.hasNext()) { reader.next(); @@ -314,6 +320,12 @@ private void parseName(XMLStreamReader reader, Map fields, List fields, List contributorNames = new ArrayList<>(); + if (corporate) { + // MODS uses successive name parts for organizational subdivisions. + // https://www.loc.gov/standards/mods/userguide/name.html + String organization = names.stream() + .filter(name -> StringUtil.isBlank(name.type())) + .map(Name::value) + .map(String::strip) + .filter(value -> !value.isEmpty()) + .collect(Collectors.joining(". ")); + if (!organization.isEmpty()) { + contributorNames.add("{" + organization + "}"); + } + } else { + handleAuthorsInNamePart(names, contributorNames); + } + for (Field field : contributorFields) { + contributors.computeIfAbsent(field, _ -> new ArrayList<>()).addAll(contributorNames); + } + } + + private Optional contributorField(String role) { + return switch (role) { + case "ann", + "annotator" -> + Optional.of(StandardField.ANNOTATOR); + case "asg", + "assignee" -> + Optional.of(StandardField.ASSIGNEE); + case "aut", + "author", + "cre", + "creator" -> + Optional.of(StandardField.AUTHOR); + case "cmp", + "composer" -> + Optional.of(new UnknownField("composer")); + case "ctb", + "contributor" -> + Optional.of(new UnknownField("contributor")); + case "cwt", + "commentator for written text" -> + Optional.of(StandardField.COMMENTATOR); + case "edt", + "editor" -> + Optional.of(StandardField.EDITOR); + case "ill", + "illustrator" -> + Optional.of(new UnknownField("illustrator")); + case "pth", + "patent holder" -> + Optional.of(StandardField.HOLDER); + case "ths", + "thesis advisor" -> + Optional.of(new UnknownField("thesisadvisor")); + case "trl", + "translator" -> + Optional.of(StandardField.TRANSLATOR); + case "waw", + "writer of afterword" -> + Optional.of(StandardField.AFTERWORD); + case "wfw", + "writer of foreword" -> + Optional.of(StandardField.FOREWORD); + case "win", + "writer of introduction" -> + Optional.of(StandardField.INTRODUCTION); + default -> + Optional.empty(); + }; } private void parseOriginInfo(XMLStreamReader reader, Map fields, TypeHints typeHints, boolean hostOriginInfo) throws XMLStreamException { @@ -656,9 +740,9 @@ private void putIfListIsNotEmpty(Map fields, List list, F } private void handleAuthorsInNamePart(List names, List authors) { - List foreName = new ArrayList<>(); + List givenNames = new ArrayList<>(); + List termsOfAddress = new ArrayList<>(); String familyName = ""; - String author = ""; for (Name name : names) { String type = name.type(); // date, family, given, termsOfAddress @@ -668,31 +752,41 @@ private void handleAuthorsInNamePart(List names, List authors) { namePartValue = namePartValue.replaceAll(",$", ""); authors.add(namePartValue); } else if ("family".equals(type) && (name.value() != null)) { - // family should come first, so if family appears we can set the author then comes before - // we have to check if forename and family name are not empty in case it's the first author - if (!foreName.isEmpty() && !familyName.isEmpty()) { - // now set and add the old author - author = familyName + ", " + String.join(" ", foreName); - authors.add(author); - // remove old forenames - foreName.clear(); - } else if (foreName.isEmpty() && !familyName.isEmpty()) { - authors.add(familyName); + if (!familyName.isEmpty()) { + addPersonalName(authors, familyName, termsOfAddress, givenNames); + termsOfAddress.clear(); + givenNames.clear(); } familyName = name.value(); } else if ("given".equals(type) && (name.value() != null)) { - foreName.add(name.value()); + givenNames.add(name.value()); + } else if ("termsOfAddress".equals(type) && (name.value() != null)) { + termsOfAddress.add(name.value()); } } - // last author is not added, so do it here - if (!foreName.isEmpty() && !familyName.isEmpty()) { - author = familyName + ", " + String.join(" ", foreName); - authors.add(author.trim()); - foreName.clear(); - } else if (foreName.isEmpty() && !familyName.isEmpty()) { + if (!familyName.isEmpty()) { + addPersonalName(authors, familyName, termsOfAddress, givenNames); + } + } + + private void addPersonalName(List authors, String familyName, List termsOfAddress, List givenNames) { + String givenName = String.join(" ", givenNames); + if (givenName.isBlank()) { + // BibTeX removes trailing name commas, which would make the suffix a given name. + // See section 387 of the BibTeX source. + // https://mirror.las.iastate.edu/tex-archive/info/knuth-pdf/bibtex/bibtex.pdf authors.add(familyName.trim()); + return; + } + + StringJoiner name = new StringJoiner(", "); + name.add(familyName); + if (!termsOfAddress.isEmpty()) { + name.add(String.join(" ", termsOfAddress)); } + name.add(givenName); + authors.add(name.toString().trim()); } private void putIfValueNotNull(Map fields, Field field, String value) { diff --git a/jablib/src/main/java/org/jabref/model/entry/Author.java b/jablib/src/main/java/org/jabref/model/entry/Author.java index 375e0e9713c1..4117dbc9412d 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Author.java +++ b/jablib/src/main/java/org/jabref/model/entry/Author.java @@ -37,7 +37,8 @@ public class Author { private static final RemoveEnclosingBracesFormatter ENCLOSING_BRACES_FORMATTER = new RemoveEnclosingBracesFormatter(); - private final String givenName; + private final @Nullable String givenName; + private final @Nullable String givenNameWithOriginalPunctuation; private final String givenNameAbbreviated; private final String namePrefix; private final String familyName; @@ -87,11 +88,8 @@ private Author(@Nullable String givenName, @Nullable String givenNameAbbreviated this.listUsePrefix = listUsePrefix; boolean keepBracesAtLastPart = StringUtil.isBlank(givenName) && StringUtil.isBlank(givenNameAbbreviated) && StringUtil.isBlank(namePrefix) && !StringUtil.isBlank(familyName) && StringUtil.isBlank(nameSuffix); - if (!StringUtil.isBlank(givenName)) { - this.givenName = addDotIfAbbreviation(FORMATTER.format(givenName)); - } else { - this.givenName = null; - } + this.givenNameWithOriginalPunctuation = StringUtil.isBlank(givenName) ? null : FORMATTER.format(givenName); + this.givenName = addDotIfAbbreviation(givenNameWithOriginalPunctuation); if (!StringUtil.isBlank(givenNameAbbreviated)) { this.givenNameAbbreviated = FORMATTER.format(givenNameAbbreviated); } else { @@ -122,6 +120,7 @@ private Author(@Nullable String givenName, @Nullable String givenNameAbbreviated private Author(Author author, Optional listUsePrefix) { this.givenName = author.givenName; + this.givenNameWithOriginalPunctuation = author.givenNameWithOriginalPunctuation; this.givenNameAbbreviated = author.givenNameAbbreviated; this.namePrefix = author.namePrefix; this.familyName = author.familyName; @@ -137,7 +136,7 @@ public Author withListUsePrefix(Optional usePrefix) { return equals(OTHERS) ? this : new Author(this, usePrefix); } - public static String addDotIfAbbreviation(String name) { + public static @Nullable String addDotIfAbbreviation(@Nullable String name) { if ((name == null) || name.isEmpty()) { return name; } @@ -314,6 +313,11 @@ public Optional getGivenName() { return Optional.ofNullable(givenName); } + /// Returns the given name before normalizing punctuation and spacing between initials. + public @NonNull Optional getGivenNameWithOriginalPunctuation() { + return Optional.ofNullable(givenNameWithOriginalPunctuation); + } + /// Returns the abbreviated first name of the author stored in this object ("F."). /// /// @return abbreviated first name of the author (may consist of several tokens) @@ -360,10 +364,11 @@ public String getFamilyNameForDisplay() { if (!getUsePrefix().orElse(true)) { return getFamilyName().orElse(""); } - return getFullFamilyNameForDisplay(); + return getNamePrefixAndFamilyNameForDisplay(); } - private String getFullFamilyNameForDisplay() { + /// Returns the family name with its prefix, respecting punctuation that attaches the two parts. + public @NonNull String getNamePrefixAndFamilyNameForDisplay() { if (extendedNameParts.isEmpty()) { return getNamePrefixAndFamilyName(); } @@ -431,7 +436,7 @@ private String getConventionalFamilyGiven(boolean abbr) { public String getGivenFamily(boolean abbr) { if (!extendedNameParts.isEmpty()) { StringJoiner result = new StringJoiner(", "); - String name = joinDisplayParts(getGivenNameForDisplay(abbr).orElse(""), getFullFamilyNameForDisplay()); + String name = joinDisplayParts(getGivenNameForDisplay(abbr).orElse(""), getNamePrefixAndFamilyNameForDisplay()); if (!name.isEmpty()) { result.add(name); } @@ -465,7 +470,7 @@ public String toString() { public String getNameForAlphabetization() { StringBuilder res = new StringBuilder(); if (getUsePrefix().orElse(false)) { - res.append(getFullFamilyNameForDisplay()); + res.append(getNamePrefixAndFamilyNameForDisplay()); } else { getFamilyName().ifPresent(res::append); } @@ -480,7 +485,7 @@ public String getNameForAlphabetization() { /// Returns a LaTeX-free version of this `Author`. public Author latexFree() { if (latexFreeAuthor == null) { - String first = getGivenName().map(LatexToUnicodeAdapter::format).orElse(null); + String first = getGivenNameWithOriginalPunctuation().map(LatexToUnicodeAdapter::format).orElse(null); String givenNameAbbreviated = getGivenNameAbbreviated().map(LatexToUnicodeAdapter::format).orElse(null); String von = getNamePrefix().map(LatexToUnicodeAdapter::format).orElse(null); String last = getFamilyName().map(LatexToUnicodeAdapter::format).orElse(null); diff --git a/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java b/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java index 6dae5ed27760..32acb4edec6d 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java @@ -1,15 +1,25 @@ package org.jabref.logic.exporter; import java.io.IOException; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import javax.xml.parsers.DocumentBuilderFactory; import org.jabref.logic.importer.ImportFormatPreferences; -import org.jabref.logic.importer.fileformat.BibtexImporter; +import org.jabref.logic.importer.fileformat.ModsImporter; import org.jabref.model.database.BibDatabaseContext; -import org.jabref.model.util.DummyFileUpdateMonitor; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.entry.types.IEEETranEntryType; +import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,7 +27,11 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; +import org.w3c.dom.Element; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; @@ -28,13 +42,14 @@ class ModsExportFormatTest { private ModsExporter modsExportFormat; private BibDatabaseContext databaseContext; + private DocumentBuilderFactory documentBuilderFactory; @BeforeEach - void setUp() throws URISyntaxException { + void setUp() { databaseContext = new BibDatabaseContext(); modsExportFormat = new ModsExporter(); - new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); - Path.of(ModsExportFormatTest.class.getResource("ModsExportFormatTestAllFields.bib").toURI()); + documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); } @Test @@ -44,4 +59,257 @@ final void exportForNoEntriesWritesNothing(@TempDir Path tempFile) throws IOExce modsExportFormat.export(databaseContext, tempFile, List.of()); assertEquals(List.of(), Files.readAllLines(file)); } + + static Stream authorAndEditorNames() { + return Stream.of( + Arguments.of( + "Sandra Sanders and John Smith", + "Sam Flanders and Alice Johnson", + List.of( + "Sanders|Sandra|aut", + "Smith|John|aut", + "Flanders|Sam|edt", + "Johnson|Alice|edt" + ) + ), + Arguments.of( + "Doe, John and Smith, Sandra and Sanders, Bill", + "Flanders, Sam", + List.of( + "Doe|John|aut", + "Smith|Sandra|aut", + "Sanders|Bill|aut", + "Flanders|Sam|edt" + ) + ), + Arguments.of( + "Sandra Sanders", + "Sam Flanders and Alice Johnson", + List.of( + "Sanders|Sandra|aut", + "Flanders|Sam|edt", + "Johnson|Alice|edt" + ) + ), + Arguments.of( + "Sandra Sanders\nJohn Smith", + "Sam Flanders", + List.of( + "Sanders|Sandra|aut", + "Smith|John|aut", + "Flanders|Sam|edt" + ) + ) + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("authorAndEditorNames") + void exportNamesWithAuthorAndEditorRoles( + String authors, + String editors, + List expected, + @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.TITLE, "Sands") + .withField(StandardField.AUTHOR, authors) + .withField(StandardField.EDITOR, editors) + .withField(StandardField.DATE, "2026") + .withField(StandardField.PUBLISHER, "Sanders Academic"); + + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + + assertEquals(expected.size(), names.getLength()); + + for (int i = 0; i < names.getLength(); i++) { + Element name = (Element) names.item(i); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + + assertEquals(2, parts.getLength()); + + Element family = (Element) parts.item(0); + Element given = (Element) parts.item(1); + Element role = (Element) name.getElementsByTagNameNS(namespace, "roleTerm").item(0); + + assertEquals("personal", name.getAttribute("type")); + assertEquals("family", family.getAttribute("type")); + assertEquals("given", given.getAttribute("type")); + assertEquals("code", role.getAttribute("type")); + assertEquals("marcrelator", role.getAttribute("authority")); + + assertEquals(expected.get(i), + family.getTextContent() + "|" + given.getTextContent() + "|" + role.getTextContent()); + } + } + + // [utest->req~export.mods.names~1] + @Test + void roundTripKeepsAuthorsAndEditorsInTheirFields(@TempDir Path tempDir) throws Exception { + Map contributors = Map.of( + StandardField.AUTHOR, "Sanders, Sandra and Smith, Jr., John and {Research and Development}", + StandardField.EDITOR, "Flanders, Sam and Johnson, Alice", + StandardField.TRANSLATOR, "Doe, Jane" + ); + BibEntry entry = new BibEntry(StandardEntryType.Book); + contributors.forEach(entry::withField); + entry.withField(StandardField.AUTHOR, contributors.get(StandardField.AUTHOR) + " and others") + .withField(StandardField.EDITOR, contributors.get(StandardField.EDITOR) + " and others"); + Path file = tempDir.resolve("contributors.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + assertEquals(6, names.getLength()); + + Element personalName = (Element) names.item(1); + Element suffix = (Element) personalName.getElementsByTagNameNS(namespace, "namePart").item(2); + assertEquals("termsOfAddress", suffix.getAttribute("type")); + assertEquals("Jr.", suffix.getTextContent()); + + Element corporateName = (Element) names.item(2); + assertEquals("corporate", corporateName.getAttribute("type")); + var corporateParts = corporateName.getElementsByTagNameNS(namespace, "namePart"); + assertEquals(1, corporateParts.getLength()); + Element namePart = (Element) corporateParts.item(0); + assertEquals("", namePart.getAttribute("type")); + assertEquals("Research and Development", namePart.getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + contributors.forEach((field, expectedNames) -> assertEquals(Optional.of(expectedNames), imported.getField(field))); + } + } + + // [utest->req~export.mods.names~1] + @Test + void exportsPatentAssigneeAsPatentHolder(@TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(IEEETranEntryType.Patent) + .withField(StandardField.ASSIGNEE, "{Example Research}"); + Path file = tempDir.resolve("patent.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + var roles = document.getElementsByTagNameNS("http://www.loc.gov/mods/v3", "roleTerm"); + + assertEquals(1, roles.getLength()); + assertEquals("pth", roles.item(0).getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + assertEquals(Optional.of("{Example Research}"), imported.getField(StandardField.HOLDER)); + } + } + + static Stream contributorRoles() { + return Stream.of( + Arguments.of(StandardField.AFTERWORD, "waw"), + Arguments.of(StandardField.ANNOTATOR, "ann"), + Arguments.of(StandardField.ASSIGNEE, "asg"), + Arguments.of(StandardField.AUTHOR, "aut"), + Arguments.of(StandardField.COMMENTATOR, "cwt"), + Arguments.of(new UnknownField("composer"), "cmp"), + Arguments.of(new UnknownField("contributor"), "ctb"), + Arguments.of(StandardField.EDITOR, "edt"), + Arguments.of(StandardField.FOREWORD, "wfw"), + Arguments.of(StandardField.HOLDER, "pth"), + Arguments.of(new UnknownField("illustrator"), "ill"), + Arguments.of(StandardField.INTRODUCTION, "win"), + Arguments.of(new UnknownField("thesisadvisor"), "ths"), + Arguments.of(StandardField.TRANSLATOR, "trl") + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("contributorRoles") + void exportNamesWithContributorRoles( + Field field, + String expectedRole, + @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.TITLE, "Sands") + .withField(field, "Sandra Sanders") + .withField(StandardField.DATE, "2026") + .withField(StandardField.PUBLISHER, "Sanders Academic"); + + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + + assertEquals(1, names.getLength()); + + Element name = (Element) names.item(0); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + + assertEquals(2, parts.getLength()); + + Element family = (Element) parts.item(0); + Element given = (Element) parts.item(1); + Element role = (Element) name.getElementsByTagNameNS(namespace, "roleTerm").item(0); + + assertEquals("personal", name.getAttribute("type")); + assertEquals("family", family.getAttribute("type")); + assertEquals("given", given.getAttribute("type")); + assertEquals("code", role.getAttribute("type")); + assertEquals("marcrelator", role.getAttribute("authority")); + + assertEquals("Sanders", family.getTextContent()); + assertEquals("Sandra", given.getTextContent()); + assertEquals(expectedRole, role.getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + assertEquals(Optional.of("Sanders, Sandra"), imported.getField(field)); + } + } + + static Stream namePartsWithOriginalSpelling() { + return Stream.of( + Arguments.of("family=Antin, given=Guy, prefix=d’, useprefix=true", List.of("family|d’Antin", "given|Guy")), + Arguments.of("family=Antin, given=Guy, prefix=d', useprefix=false", List.of("family|d'Antin", "given|Guy")), + Arguments.of("nickname=Jane", List.of("|nickname=Jane")), + Arguments.of("Smith, J", List.of("family|Smith", "given|J")), + Arguments.of("Smith, A.A.", List.of("family|Smith", "given|A.A.")), + Arguments.of("given-i={JPS}, family=Harman", List.of("family|Harman", "given|JPS")), + Arguments.of("given=Jean, given-i=J, family=Harman", List.of("family|Harman", "given|Jean")) + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("namePartsWithOriginalSpelling") + void exportsNamePartsWithOriginalSpelling(String input, List expected, @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.AUTHOR, input) + .withField(StandardField.EDITOR, input); + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + assertEquals(2, names.getLength()); + for (int index = 0; index < names.getLength(); index++) { + Element name = (Element) names.item(index); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + assertEquals(expected, IntStream.range(0, parts.getLength()) + .mapToObj(parts::item) + .map(Element.class::cast) + .map(part -> part.getAttribute("type") + "|" + part.getTextContent()) + .toList()); + } + } } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java index 67197a02d08c..143bee447661 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java @@ -3,11 +3,17 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; +import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ImportException; import org.jabref.logic.importer.ImportFormatPreferences; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.field.UnknownField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +21,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,6 +54,95 @@ void importEntries(String fileName) throws ImportException, IOException { ImporterTestEngine.testImportEntries(new ModsImporter(importFormatPreferences), fileName, FILE_ENDING); } + @Test + void importsLegacyNamesAndDeduplicatesEquivalentRoleTerms() throws IOException { + String xml = """ + + + Doe, John + + + Sanders, Sandra + + edt + Editor + + + trl + + + + Smith, Jane + + ill + + + + Reed, Robert + Thesis advisor + + + Jones, Alice + ctb + + + Baker, Alex + Custom credit + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + assertEquals(Optional.of("Doe, John"), entry.getField(StandardField.AUTHOR)); + assertEquals(Optional.of("Sanders, Sandra"), entry.getField(StandardField.EDITOR)); + assertEquals(Optional.of("Sanders, Sandra"), entry.getField(StandardField.TRANSLATOR)); + assertEquals(Optional.of("Smith, Jane"), entry.getField(new UnknownField("illustrator"))); + assertEquals(Optional.of("Reed, Robert"), entry.getField(new UnknownField("thesisadvisor"))); + assertEquals(Optional.of("Jones, Alice and Baker, Alex"), entry.getField(new UnknownField("contributor"))); + } + + @Test + void importsCorporateNameWithoutTypedDatePart() throws IOException { + String xml = """ + + + Example University + Research Institute + 1890-1940 + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + assertEquals(Optional.of("{Example University. Research Institute}"), entry.getField(StandardField.AUTHOR)); + } + + @Test + void importsFamilyNameWhenOnlySuffixIsPresent() throws IOException { + String xml = """ + + + Smith + Jr. + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + String authorField = entry.getField(StandardField.AUTHOR).orElseThrow(); + assertEquals("Smith", authorField); + Author author = AuthorList.parse(authorField).getAuthor(0); + assertEquals(Optional.of("Smith"), author.getFamilyName()); + assertEquals(Optional.empty(), author.getNameSuffix()); + assertEquals(Optional.empty(), author.getGivenName()); + } + @Test void rejectsExternalEntities() throws IOException { String xmlWithExternalEntity = """ diff --git a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java index 65757e74a2c9..3ec0ed6c977e 100644 --- a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java @@ -32,6 +32,15 @@ void readsExplicitInitialsWithoutGeneratingOrRepunctuatingThem() { assertEquals(Optional.of("H. P."), author.getGivenNameAbbreviated()); } + @Test + void retainsOriginalGivenNamePunctuationAlongsideDisplayForm() { + Author author = AuthorList.parse("Smith, A.A.").getAuthor(0); + + assertEquals(Optional.of("A.A."), author.getGivenNameWithOriginalPunctuation()); + assertEquals(Optional.of("A. A."), author.getGivenName()); + assertEquals(Optional.of("A.A."), author.latexFree().getGivenNameWithOriginalPunctuation()); + } + @Test void absentInitialsRemainDistinctFromExplicitlyEmptyInitials() { Author conventional = new Author("Hado P.", "H. P.", "van", "Hasselt", ""); diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml index ae20411840c1..c6e20b156f01 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml @@ -9,11 +9,17 @@ Don't know + + aut + - Realy + Realy don't know + + aut + someDoi diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml index 1a3adf63b4b1..e2d8f675306f 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml @@ -6,13 +6,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Biomarkers @@ -60,13 +69,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Proteomics: A new perspective for cancer. diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml index 90424c9ceadb..a7d44249eca9 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml @@ -7,13 +7,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Proteomics: A new perspective for cancer. diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml index e940664884b9..63c367684a96 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml @@ -5,6 +5,9 @@ inbook Mustermann + + aut + keyword diff --git a/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib b/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib index e95c59df9b55..5e0252273850 100644 --- a/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib +++ b/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib @@ -28,8 +28,8 @@ @article{Schewe+Soltwedel2003 @book{Thomas+Dieckmann2003, address = {Oxford}, - author = {Thomas, DN and Dieckmann, GS}, date = {2003}, + editor = {Thomas, DN and Dieckmann, GS}, isbn = {0-632-05808-0}, keywords = {zoology, sea ice}, publisher = {Blackwell Science Ltd},