repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
jabref-main/src/main/java/org/jabref/model/entry/AuthorList.java
package org.jabref.model.entry; import java.util.List; import java.util.Objects; import java.util.WeakHashMap; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.importer.AuthorListParser; /** * This is an immutable class representing information of either <CODE>author</CODE> or <CODE>editor</CODE> field in bibtex record. * <p> * Constructor performs parsing of raw field text and stores preformatted data. Various accessor methods return author/editor field in different formats. * <p> * Parsing algorithm is designed to satisfy two requirements: (a) when author's name is typed correctly, the result should coincide with the one of BiBTeX; (b) for erroneous names, output should be reasonable (but may differ from BiBTeX output). The following rules are used: * <ol> * <li> 'author field' is a sequence of tokens; * <ul> * <li> tokens are separated by sequences of whitespaces (<CODE>Character.isWhitespace(c)==true</CODE>), * commas (,), dashes (-), and tildas (~); * <li> every comma separates tokens, while sequences of other separators are * equivalent to a single separator; for example: "a - b" consists of 2 tokens * ("a" and "b"), while "a,-,b" consists of 3 tokens ("a", "", and "b") * <li> anything enclosed in braces belongs to a single token; for example: * "abc x{a,b,-~ c}x" consists of 2 tokens, while "abc xa,b,-~ cx" consists of 4 * tokens ("abc", "xa","b", and "cx"); * <li> a token followed immediately by a dash is "dash-terminated" token, and * all other tokens are "space-terminated" tokens; for example: in "a-b- c - d" * tokens "a" and "b" are dash-terminated and "c" and "d" are space-terminated; * <li> for the purposes of splitting of 'author name' into parts and * construction of abbreviation of first name, one needs definitions of first * letter of a token, case of a token, and abbreviation of a token: * <ul> * <li> 'first letter' of a token is the first letter character (<CODE>Character.isLetter(c)==true</CODE>) * that does not belong to a sequence of letters that immediately follows "\" * character, with one exception: if "\" is followed by "aa", "AA", "ae", "AE", * "l", "L", "o", "O", "oe", "OE", "i", or "j" followed by non-letter, the * 'first letter' of a token is a letter that follows "\"; for example: in * "a{x}b" 'first letter' is "a", in "{\"{U}}bel" 'first letter' is "U", in * "{\noopsort{\"o}}xyz" 'first letter' is "o", in "{\AE}x" 'first letter' is * "A", in "\aex\ijk\Oe\j" 'first letter' is "j"; if there is no letter * satisfying the above rule, 'first letter' is undefined; * <li> token is "lower-case" token if its first letter is defined and is * lower-case (<CODE>Character.isLowerCase(c)==true</CODE>), and token is * "upper-case" token otherwise; * <li> 'abbreviation' of a token is the shortest prefix of the token that (a) * contains 'first letter' and (b) is braces-balanced; if 'first letter' is * undefined, 'abbreviation' is the token itself; in the above examples, * 'abbreviation's are "a", "{\"{U}}", "{\noopsort{\"o}}", "{\AE}", * "\aex\ijk\Oe\j"; * </ul> * <li> the behavior based on the above definitions will be erroneous only in * one case: if the first-name-token is "{\noopsort{A}}john", we abbreviate it * as "{\noopsort{A}}.", while BiBTeX produces "j."; fixing this problem, * however, requires processing of the preabmle; * </ul> * <li> 'author names' in 'author field' are subsequences of tokens separated by * token "and" ("and" is case-insensitive); if 'author name' is an empty * sequence of tokens, it is ignored; for examle, both "John Smith and Peter * Black" and "and and John Smith and and Peter Black" consists of 2 'author * name's "Johm Smith" and "Peter Black" (in erroneous situations, this is a bit * different from BiBTeX behavior); * <li> 'author name' consists of 'first-part', 'von-part', 'last-part', and * 'junior-part', each of which is a sequence of tokens; how a sequence of * tokens has to be split into these parts, depends the number of commas: * <ul> * <li> no commas, all tokens are upper-case: 'junior-part' and 'von-part' are * empty, 'last-part' consist of the last token, 'first-part' consists of all * other tokens ('first-part' is empty if 'author name' consists of a single * token); for example, in "John James Smith", 'last-part'="Smith" and * 'first-part'="John James"; * <li> no commas, there exists lower-case token: 'junior-part' is empty, * 'first-part' consists of all upper-case tokens before the first lower-case * token, 'von-part' consists of lower-case tokens starting the first lower-case * token and ending the lower-case token that is followed by upper-case token, * 'last-part' consists of the rest of tokens; note that both 'first-part' and * 'latst-part' may be empty and 'last-part' may contain lower-case tokens; for * example: in "von der", 'first-part'='last-part'="", 'von-part'="von der"; in * "Charles Louis Xavier Joseph de la Vall{\'e}e la Poussin", * 'first-part'="Charles Louis Xavier Joseph", 'von-part'="de la", * 'last-part'="Vall{\'e}e la Poussin"; * <li> one comma: 'junior-part' is empty, 'first-part' consists of all tokens * after comma, 'von-part' consists of the longest sequence of lower-case tokens * in the very beginning, 'last-part' consists of all tokens after 'von-part' * and before comma; note that any part can be empty; for example: in "de la * Vall{\'e}e la Poussin, Charles Louis Xavier Joseph", 'first-part'="Charles * Louis Xavier Joseph", 'von-part'="de la", 'last-part'="Vall{\'e}e la * Poussin"; in "Joseph de la Vall{\'e}e la Poussin, Charles Louis Xavier", * 'first-part'="Charles Louis Xavier", 'von-part'="", 'last-part'="Joseph de la * Vall{\'e}e la Poussin"; * <li> two or more commas (any comma after the second one is ignored; it merely * separates tokens): 'junior-part' consists of all tokens between first and * second commas, 'first-part' consists of all tokens after the second comma, * tokens before the first comma are split into 'von-part' and 'last-part' * similarly to the case of one comma; for example: in "de la Vall{\'e}e * Poussin, Jr., Charles Louis Xavier Joseph", 'first-part'="Charles Louis * Xavier Joseph", 'von-part'="de la", 'last-part'="Vall{\'e}e la Poussin", and * 'junior-part'="Jr."; * </ul> * <li> when 'first-part', 'last-part', 'von-part', or 'junior-part' is * reconstructed from tokens, tokens in a part are separated either by space or * by dash, depending on whether the token before the separator was * space-terminated or dash-terminated; for the last token in a part it does not * matter whether it was dash- or space-terminated; * <li> when 'first-part' is abbreviated, each token is replaced by its * abbreviation followed by a period; separators are the same as in the case of * non-abbreviated name; for example: in "Heinrich-{\"{U}}bel Kurt von Minich", * 'first-part'="Heinrich-{\"{U}}bel Kurt", and its abbreviation is "H.-{\"{U}}. * K." * </ol> */ @AllowedToUseLogic("because it needs access to AuthorList parser") public class AuthorList { private static final WeakHashMap<String, AuthorList> AUTHOR_CACHE = new WeakHashMap<>(); private final List<Author> authors; private AuthorList latexFreeAuthors; /** * Creates a new list of authors. * <p> * Don't call this constructor directly but rather use the getAuthorList() * method which caches its results. * * @param authors the list of authors which should underlie this instance */ private AuthorList(List<Author> authors) { this.authors = Objects.requireNonNull(authors); } public static AuthorList of(List<Author> authors) { return new AuthorList(List.copyOf(authors)); } public static AuthorList of(Author... authors) { return new AuthorList(List.of(authors)); } public static Collector<Author, ?, AuthorList> collect() { return Collectors.collectingAndThen(Collectors.toUnmodifiableList(), AuthorList::new); } private static String andCoordinatedConjunction(List<Author> authors, Function<Author, String> style, boolean oxfordComma) { var formattedAuthors = authors.stream().map(style).collect(Collectors.toUnmodifiableList()); return andCoordinatedConjunction(formattedAuthors, oxfordComma); } private static String andCoordinatedConjunction(List<String> authors, boolean oxfordComma) { String lastDelimiter = oxfordComma ? ", and " : " and "; int lastIndex = authors.size() - 1; return switch (authors.size()) { case 0 -> ""; case 1 -> authors.get(0); case 2 -> authors.get(0) + " and " + authors.get(1); default -> String.join(", ", authors.subList(0, lastIndex)) + lastDelimiter + authors.get(lastIndex); }; } /** * Retrieve an AuthorList for the given string of authors or editors. * <p> * This function tries to cache the parsed AuthorLists by the string passed in. * * @param authors The string of authors or editors in bibtex format to parse. * @return An AuthorList object representing the given authors. */ public static AuthorList parse(final String authors) { Objects.requireNonNull(authors); AuthorList authorList = AUTHOR_CACHE.get(authors); if (authorList == null) { AuthorListParser parser = new AuthorListParser(); authorList = parser.parse(authors); AUTHOR_CACHE.put(authors, authorList); } return authorList; } /** * This is a convenience method for getAuthorsFirstFirst() * * @see AuthorList#getAsFirstLastNames */ public static String fixAuthorFirstNameFirstCommas(String authors, boolean abbreviate, boolean oxfordComma) { return AuthorList.parse(authors).getAsFirstLastNames(abbreviate, oxfordComma); } /** * This is a convenience method for getAuthorsFirstFirstAnds() * * @see AuthorList#getAsFirstLastNamesWithAnd */ public static String fixAuthorFirstNameFirst(String authors) { return AuthorList.parse(authors).getAsFirstLastNamesWithAnd(); } /** * This is a convenience method for getAuthorsLastFirst() * * @see AuthorList#getAsLastFirstNames */ public static String fixAuthorLastNameFirstCommas(String authors, boolean abbreviate, boolean oxfordComma) { return AuthorList.parse(authors).getAsLastFirstNames(abbreviate, oxfordComma); } /** * This is a convenience method for getAuthorsLastFirstAnds(true) * * @see AuthorList#getAsLastFirstNamesWithAnd */ public static String fixAuthorLastNameFirst(String authors) { return AuthorList.parse(authors).getAsLastFirstNamesWithAnd(false); } /** * This is a convenience method for getAuthorsLastFirstAnds() * * @see AuthorList#getAsLastFirstNamesWithAnd */ public static String fixAuthorLastNameFirst(String authors, boolean abbreviate) { return AuthorList.parse(authors).getAsLastFirstNamesWithAnd(abbreviate); } /** * This is a convenience method for getAuthorsLastOnly() * * @see AuthorList#getAsLastNames */ public static String fixAuthorLastNameOnlyCommas(String authors, boolean oxfordComma) { return AuthorList.parse(authors).getAsLastNames(oxfordComma); } /** * This is a convenience method for getAuthorsForAlphabetization() * * @see AuthorList#getForAlphabetization */ public static String fixAuthorForAlphabetization(String authors) { return AuthorList.parse(authors).getForAlphabetization(); } /** * This is a convenience method for getAuthorsNatbib() * * @see AuthorList#getAsNatbib */ public static String fixAuthorNatbib(String authors) { return AuthorList.parse(authors).getAsNatbib(); } /** * Returns the number of author names in this object. * * @return the number of author names in this object. */ public int getNumberOfAuthors() { return authors.size(); } /** * Returns true if there are no authors in the list. * * @return true if there are no authors in the list. */ public boolean isEmpty() { return authors.isEmpty(); } /** * Returns the <CODE>Author</CODE> object for the i-th author. * * @param i Index of the author (from 0 to <CODE>size()-1</CODE>). * @return the <CODE>Author</CODE> object. */ public Author getAuthor(int i) { return authors.get(i); } /** * Returns the a list of <CODE>Author</CODE> objects. * * @return the <CODE>List&lt;Author></CODE> object. */ public List<Author> getAuthors() { return authors; } /** * Returns a LaTeX-free version of this `AuthorList`. */ public AuthorList latexFree() { if (latexFreeAuthors == null) { latexFreeAuthors = new AuthorList(authors.stream() .map(Author::latexFree) .collect(Collectors.toUnmodifiableList())); latexFreeAuthors.latexFreeAuthors = latexFreeAuthors; } return latexFreeAuthors; } /** * Returns the list of authors in "natbib" format. * <p> * <ul> * <li>"John Smith" -> "Smith"</li> * <li>"John Smith and Black Brown, Peter" ==> "Smith and Black Brown"</li> * <li>"John von Neumann and John Smith and Black Brown, Peter" ==> "von * Neumann et al." </li> * </ul> * * @return formatted list of authors. */ public String getAsNatbib() { var authors = getAuthors(); return switch (authors.size()) { case 0 -> ""; case 1 -> authors.get(0).getLastOnly(); case 2 -> authors.get(0).getLastOnly() + " and " + authors.get(1).getLastOnly(); default -> authors.get(0).getLastOnly() + " et al."; }; } /** * Returns the list of authors separated by commas with last name only; If the list consists of two or more authors, "and" is inserted before the last author's name. * <p> * <ul> * <li> "John Smith" ==> "Smith"</li> * <li> "John Smith and Black Brown, Peter" ==> "Smith and Black Brown"</li> * <li> "John von Neumann and John Smith and Black Brown, Peter" ==> "von * Neumann, Smith and Black Brown".</li> * </ul> * * @param oxfordComma Whether to put a comma before the and at the end. * @return formatted list of authors. * @see <a href="http://en.wikipedia.org/wiki/Serial_comma">serial comma for an detailed explaination about the * Oxford comma.</a> */ public String getAsLastNames(boolean oxfordComma) { return andCoordinatedConjunction(getAuthors(), Author::getLastOnly, oxfordComma); } /** * Returns the list of authors separated by commas with first names after last name; first names are abbreviated or not depending on parameter. If the list consists of three or more authors, "and" is inserted before the last author's name. * <p> * <ul> * <li> "John Smith" ==> "Smith, John" or "Smith, J."</li> * <li> "John Smith and Black Brown, Peter" ==> "Smith, John and Black * Brown, Peter" or "Smith, J. and Black Brown, P."</li> * <li> "John von Neumann and John Smith and Black Brown, Peter" ==> "von * Neumann, John, Smith, John and Black Brown, Peter" or "von Neumann, J., * Smith, J. and Black Brown, P.".</li> * </ul> * * @param abbreviate whether to abbreivate first names. * @param oxfordComma Whether to put a comma before the and at the end. * @return formatted list of authors. * @see <a href="http://en.wikipedia.org/wiki/Serial_comma">serial comma for an detailed explaination about the * Oxford comma.</a> */ public String getAsLastFirstNames(boolean abbreviate, boolean oxfordComma) { return andCoordinatedConjunction(getAuthors(), auth -> auth.getLastFirst(abbreviate), oxfordComma); } @Override public String toString() { return authors.toString(); } /** * Returns the list of authors separated by "and"s with first names after last name; first names are not abbreviated. * <p> * <ul> * <li>"John Smith" ==> "Smith, John"</li> * <li>"John Smith and Black Brown, Peter" ==> "Smith, John and Black * Brown, Peter"</li> * <li>"John von Neumann and John Smith and Black Brown, Peter" ==> "von * Neumann, John and Smith, John and Black Brown, Peter".</li> * </ul> * * @return formatted list of authors. */ public String getAsLastFirstNamesWithAnd(boolean abbreviate) { return getAuthors().stream() .map(author -> author.getLastFirst(abbreviate)) .collect(Collectors.joining(" and ")); } /** * Returns a list of authors separated with "and". The first author is formatted with {@link Author#getLastFirst(boolean)} and each subsequent author is formatted with {@link Author#getFirstLast(boolean)}. * * @param abbreviate first names. */ public String getAsLastFirstFirstLastNamesWithAnd(boolean abbreviate) { return switch (authors.size()) { case 0 -> ""; case 1 -> authors.get(0).getLastFirst(abbreviate); default -> authors.stream() .skip(1) .map(author -> author.getFirstLast(abbreviate)) .collect(Collectors.joining( " and ", authors.get(0).getLastFirst(abbreviate) + " and ", "")); }; } /** * Returns the list of authors separated by commas with first names before last name; first names are abbreviated or not depending on parameter. If the list consists of three or more authors, "and" is inserted before the last author's name. * <p> * <ul> * <li>"John Smith" ==> "John Smith" or "J. Smith"</li> * <li>"John Smith and Black Brown, Peter" ==> "John Smith and Peter Black * Brown" or "J. Smith and P. Black Brown"</li> * <li> "John von Neumann and John Smith and Black Brown, Peter" ==> "John * von Neumann, John Smith and Peter Black Brown" or "J. von Neumann, J. * Smith and P. Black Brown" </li> * </ul> * * @param abbreviate whether to abbreivate first names. * @param oxfordComma Whether to put a comma before the and at the end. * @return formatted list of authors. * @see <a href="http://en.wikipedia.org/wiki/Serial_comma">serial comma for an detailed explaination about the * Oxford comma.</a> */ public String getAsFirstLastNames(boolean abbreviate, boolean oxfordComma) { return andCoordinatedConjunction(getAuthors(), author -> author.getFirstLast(abbreviate), oxfordComma); } /** * Compare this object with the given one. * * @return `true` iff the other object is an AuthorList, all contained authors are in the same order (and these authors' fields are `Objects.equals`) */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AuthorList)) { return false; } AuthorList a = (AuthorList) o; return this.authors.equals(a.authors); } @Override public int hashCode() { return Objects.hash(authors); } /** * Returns the list of authors separated by "and"s with first names before last name; first names are not abbreviated. * <p> * <ul> * <li>"John Smith" ==> "John Smith"</li> * <li>"John Smith and Black Brown, Peter" ==> "John Smith and Peter Black * Brown"</li> * <li>"John von Neumann and John Smith and Black Brown, Peter" ==> "John * von Neumann and John Smith and Peter Black Brown" </li> * </ul> * * @return formatted list of authors. */ public String getAsFirstLastNamesWithAnd() { return getAuthors().stream() .map(author -> author.getFirstLast(false)) .collect(Collectors.joining(" and ")); } /** * Returns the list of authors in a form suitable for alphabetization. This means that last names come first, never preceded by "von" particles, and that any braces are removed. First names are abbreviated so the same name is treated similarly if abbreviated in one case and not in another. This form is not intended to be suitable for presentation, only for sorting. * <p> * <ul> * <li>"John Smith" ==> "Smith, J.";</li> * </ul> * * @return formatted list of authors */ public String getForAlphabetization() { return getAuthors().stream() .map(Author::getNameForAlphabetization) .collect(Collectors.joining(" and ")); } }
21,387
42.738241
371
java
null
jabref-main/src/main/java/org/jabref/model/entry/BibEntry.java
package org.jabref.model.entry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.stream.Collectors; import javafx.beans.Observable; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.event.FieldAddedOrRemovedEvent; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.entry.identifier.ISBN; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.IEEETranEntryType; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.strings.LatexToUnicodeAdapter; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.MultiKeyMap; import com.google.common.eventbus.EventBus; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.optional.OptionalBinding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a Bib(La)TeX entry, which can be BibTeX or BibLaTeX. * <p> * Example: * * <pre>{@code * Some commment * @misc{key, * fieldName = {fieldValue}, * otherFieldName = {otherVieldValue} * } * }</pre> * * Then, * <ul> * <li>"Some comment" is the comment before the entry,</li> * <li>"misc" is the entry type</li> * <li>"key" the citation key</li> * <li>"fieldName" and "otherFieldName" the fields of the BibEntry</li> * </ul> * </p> * <p> * A BibTeX entry has following properties: * <ul> * <li>comments before entry</li> * <li>entry type</li> * <li>citation key</li> * <li>fields</li> * </ul> * In JabRef, this is modeled the following way: * <ul> * <li>comments before entry --&gt; {@link BibEntry#commentsBeforeEntry}</li> * <li>entry type --&gt; {@link BibEntry#type}</li> * <li>citation key --&gt; contained in {@link BibEntry#fields} using they hashmap key {@link InternalField#KEY_FIELD}</li> * <li>fields --&gt; contained in {@link BibEntry#fields}</li> * </ul> * </p> * <p> * In case you search for a builder as described in Item 2 of the book "Effective Java", you won't find one. Please use the methods {@link #withCitationKey(String)} and {@link #withField(Field, String)}. * </p> */ @AllowedToUseLogic("because it needs access to parser and writers") public class BibEntry implements Cloneable { public static final EntryType DEFAULT_TYPE = StandardEntryType.Misc; private static final Logger LOGGER = LoggerFactory.getLogger(BibEntry.class); private final SharedBibEntryData sharedBibEntryData; /** * Map to store the words in every field */ private final Map<Field, Set<String>> fieldsAsWords = new HashMap<>(); /** * Cache that stores latex free versions of fields. */ private final Map<Field, String> latexFreeFields = new ConcurrentHashMap<>(); /** * Cache that stores the field as keyword lists (format &lt;Field, Separator, Keyword list>) */ private final MultiKeyMap<StandardField, Character, KeywordList> fieldsAsKeywords = new MultiKeyMap<>(StandardField.class); private final EventBus eventBus = new EventBus(); private String id; private final ObjectProperty<EntryType> type = new SimpleObjectProperty<>(DEFAULT_TYPE); private ObservableMap<Field, String> fields = FXCollections.observableMap(new ConcurrentHashMap<>()); /** * The part before the start of the entry */ private String commentsBeforeEntry = ""; /** * Stores the text "rendering" of the entry as read by the BibTeX reader. Includes comments. */ private String parsedSerialization = ""; /** * Marks whether the complete serialization, which was read from file, should be used. * <p> * Is set to <code>true</code>, if parts of the entry changed. This causes the entry to be serialized based on the internal state (and not based on the old serialization) */ private boolean changed; /** * Constructs a new BibEntry. The internal ID is set to IdGenerator.next() */ public BibEntry() { this(DEFAULT_TYPE); } /** * Constructs a new BibEntry. The internal ID is set to IdGenerator.next() */ public BibEntry(EntryType type) { this.id = IdGenerator.next(); setType(type); this.sharedBibEntryData = new SharedBibEntryData(); } public Optional<FieldChange> setMonth(Month parsedMonth) { return setField(StandardField.MONTH, parsedMonth.getJabRefFormat()); } public Optional<String> getResolvedFieldOrAlias(OrFields fields, BibDatabase database) { for (Field field : fields) { Optional<String> value = getResolvedFieldOrAlias(field, database); if (value.isPresent()) { return value; } } return Optional.empty(); } /** * Map an (empty) field of a BibEntry to a field of a cross-referenced entry. * * @param targetField field name of the BibEntry * @param targetEntry type of the BibEntry * @param sourceEntry type of the cross-referenced BibEntry * @return the mapped field or null if there is no valid mapping available */ private Optional<Field> getSourceField(Field targetField, EntryType targetEntry, EntryType sourceEntry) { //// 1. Sort out forbidden fields if ((targetField == StandardField.IDS) || (targetField == StandardField.CROSSREF) || (targetField == StandardField.XREF) || (targetField == StandardField.ENTRYSET) || (targetField == StandardField.RELATED) || (targetField == StandardField.SORTKEY)) { return Optional.empty(); } //// 2. Handle special field mappings if (((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.InBook)) || ((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.BookInBook)) || ((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.SuppBook)) || ((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.InBook)) || ((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.BookInBook)) || ((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.SuppBook))) { if (targetField == StandardField.AUTHOR) { return Optional.of(StandardField.AUTHOR); } if (targetField == StandardField.BOOKAUTHOR) { return Optional.of(StandardField.AUTHOR); } } if (((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.Book)) || ((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.InBook)) || ((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.BookInBook)) || ((sourceEntry == StandardEntryType.MvBook) && (targetEntry == StandardEntryType.SuppBook)) || ((sourceEntry == StandardEntryType.MvCollection) && (targetEntry == StandardEntryType.Collection)) || ((sourceEntry == StandardEntryType.MvCollection) && (targetEntry == StandardEntryType.InCollection)) || ((sourceEntry == StandardEntryType.MvCollection) && (targetEntry == StandardEntryType.SuppCollection)) || ((sourceEntry == StandardEntryType.MvProceedings) && (targetEntry == StandardEntryType.Proceedings)) || ((sourceEntry == StandardEntryType.MvProceedings) && (targetEntry == StandardEntryType.InProceedings)) || ((sourceEntry == StandardEntryType.MvReference) && (targetEntry == StandardEntryType.Reference)) || ((sourceEntry == StandardEntryType.MvReference) && (targetEntry == StandardEntryType.InReference))) { if (targetField == StandardField.MAINTITLE) { return Optional.of(StandardField.TITLE); } if (targetField == StandardField.MAINSUBTITLE) { return Optional.of(StandardField.SUBTITLE); } if (targetField == StandardField.MAINTITLEADDON) { return Optional.of(StandardField.TITLEADDON); } // those fields are no more available for the same-name inheritance strategy if ((targetField == StandardField.TITLE) || (targetField == StandardField.SUBTITLE) || (targetField == StandardField.TITLEADDON)) { return Optional.empty(); } // for these fields, inheritance is not allowed for the specified entry types if (targetField == StandardField.SHORTTITLE) { return Optional.empty(); } } if (((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.InBook)) || ((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.BookInBook)) || ((sourceEntry == StandardEntryType.Book) && (targetEntry == StandardEntryType.SuppBook)) || ((sourceEntry == StandardEntryType.Collection) && (targetEntry == StandardEntryType.InCollection)) || ((sourceEntry == StandardEntryType.Collection) && (targetEntry == StandardEntryType.SuppCollection)) || ((sourceEntry == StandardEntryType.Reference) && (targetEntry == StandardEntryType.InReference)) || ((sourceEntry == StandardEntryType.Proceedings) && (targetEntry == StandardEntryType.InProceedings))) { if (targetField == StandardField.BOOKTITLE) { return Optional.of(StandardField.TITLE); } if (targetField == StandardField.BOOKSUBTITLE) { return Optional.of(StandardField.SUBTITLE); } if (targetField == StandardField.BOOKTITLEADDON) { return Optional.of(StandardField.TITLEADDON); } // those fields are no more available for the same-name inheritance strategy if ((targetField == StandardField.TITLE) || (targetField == StandardField.SUBTITLE) || (targetField == StandardField.TITLEADDON)) { return Optional.empty(); } // for these fields, inheritance is not allowed for the specified entry types if (targetField == StandardField.SHORTTITLE) { return Optional.empty(); } } if (((sourceEntry == IEEETranEntryType.Periodical) && (targetEntry == StandardEntryType.Article)) || ((sourceEntry == IEEETranEntryType.Periodical) && (targetEntry == StandardEntryType.SuppPeriodical))) { if (targetField == StandardField.JOURNALTITLE) { return Optional.of(StandardField.TITLE); } if (targetField == StandardField.JOURNALSUBTITLE) { return Optional.of(StandardField.SUBTITLE); } // those fields are no more available for the same-name inheritance strategy if ((targetField == StandardField.TITLE) || (targetField == StandardField.SUBTITLE)) { return Optional.empty(); } // for these fields, inheritance is not allowed for the specified entry types if (targetField == StandardField.SHORTTITLE) { return Optional.empty(); } } //// 3. Fallback to inherit the field with the same name. return Optional.ofNullable(targetField); } /** * Returns the text stored in the given field of the given bibtex entry * which belongs to the given database. * <p> * If a database is given, this function will try to resolve any string * references in the field-value. * Also, if a database is given, this function will try to find values for * unset fields in the entry linked by the "crossref" field, if any. * * @param field The field to return the value of. * @param database maybenull * The database of the bibtex entry. * @return The resolved field value or null if not found. */ public Optional<String> getResolvedFieldOrAlias(Field field, BibDatabase database) { return genericGetResolvedFieldOrAlias(field, database, BibEntry::getFieldOrAlias); } public Optional<String> getResolvedFieldOrAliasLatexFree(Field field, BibDatabase database) { return genericGetResolvedFieldOrAlias(field, database, BibEntry::getFieldOrAliasLatexFree); } private Optional<String> genericGetResolvedFieldOrAlias(Field field, BibDatabase database, BiFunction<BibEntry, Field, Optional<String>> getFieldOrAlias) { if ((InternalField.TYPE_HEADER == field) || (InternalField.OBSOLETE_TYPE_HEADER == field)) { return Optional.of(type.get().getDisplayName()); } if (InternalField.KEY_FIELD == field) { return getCitationKey(); } Optional<String> result = getFieldOrAlias.apply(this, field); // If this field is not set, and the entry has a crossref, try to look up the // field in the referred entry, following the biblatex rules if (result.isEmpty() && (database != null)) { Optional<BibEntry> referred = database.getReferencedEntry(this); if (referred.isPresent()) { EntryType sourceEntry = referred.get().type.get(); EntryType targetEntry = type.get(); Optional<Field> sourceField = getSourceField(field, targetEntry, sourceEntry); if (sourceField.isPresent()) { result = getFieldOrAlias.apply(referred.get(), sourceField.get()); } } } return ((database == null) || result.isEmpty()) ? result : Optional.of(database.resolveForStrings(result.get())); } /** * Returns this entry's ID. */ public String getId() { return id; } /** * Sets this entry's identifier (ID). It is used internally to distinguish different BibTeX entries. It is <emph>not</emph> the citation key. The BibTexKey is the {@link InternalField#KEY_FIELD}. * <p> * The entry is also updated in the shared database - provided the database containing it doesn't veto the change. * * @param id The ID to be used */ public void setId(String id) { Objects.requireNonNull(id, "Every BibEntry must have an ID"); String oldId = this.id; eventBus.post(new FieldChangedEvent(this, InternalField.INTERNAL_ID_FIELD, id, oldId)); this.id = id; changed = true; } /** * Sets the citation key. Note: This is <emph>not</emph> the internal Id of this entry. * The internal Id is always present, whereas the citation key might not be present. * * @param newKey The cite key to set. Must not be null; use {@link #clearCiteKey()} to remove the cite key. */ public Optional<FieldChange> setCitationKey(String newKey) { return setField(InternalField.KEY_FIELD, newKey); } public BibEntry withCitationKey(String newKey) { setCitationKey(newKey); this.setChanged(false); return this; } public Optional<String> getCitationKey() { String key = fields.get(InternalField.KEY_FIELD); if (StringUtil.isBlank(key)) { return Optional.empty(); } else { return Optional.of(key); } } public boolean hasCitationKey() { return getCitationKey().isPresent(); } /** * Returns this entry's type. */ public EntryType getType() { return type.getValue(); } public ObjectProperty<EntryType> typeProperty() { return type; } /** * Sets this entry's type. */ public Optional<FieldChange> setType(EntryType type) { return setType(type, EntriesEventSource.LOCAL); } /** * Sets this entry's type and sets the changed flag to true <br> * If the new entry type equals the old entry type no changed flag is set. */ public Optional<FieldChange> setType(EntryType newType, EntriesEventSource eventSource) { Objects.requireNonNull(newType); EntryType oldType = type.get(); if (newType.equals(oldType)) { return Optional.empty(); } changed = true; this.type.setValue(newType); FieldChange change = new FieldChange(this, InternalField.TYPE_HEADER, oldType.getName(), newType.getName()); eventBus.post(new FieldChangedEvent(change, eventSource)); return Optional.of(change); } /** * Returns an {@link Collections#unmodifiableSet(Set)} containing the names of all fields that are set for this particular entry. * * @return a set of existing field names */ public Set<Field> getFields() { return Collections.unmodifiableSet(fields.keySet()); } /** * Returns the contents of the given field as an Optional. */ public Optional<String> getField(Field field) { return Optional.ofNullable(fields.get(field)); } /** * Returns true if the entry has the given field, or false if it is not set. */ public boolean hasField(Field field) { return fields.containsKey(field); } /** * Internal method used to get the content of a field (or its alias) * * Used by {@link #getFieldOrAlias(Field)} and {@link #getFieldOrAliasLatexFree(Field)} * * @param field the field * @param getFieldValue the method to get the value of a given field in a given entry * @return determined field value */ private Optional<String> genericGetFieldOrAlias(Field field, BiFunction<BibEntry, Field, Optional<String>> getFieldValue) { Optional<String> fieldValue = getFieldValue.apply(this, field); if (fieldValue.isPresent() && !fieldValue.get().isEmpty()) { return fieldValue; } // No value of this field found, so look at the alias Field aliasForField = EntryConverter.FIELD_ALIASES.get(field); if (aliasForField != null) { return getFieldValue.apply(this, aliasForField); } // Finally, handle dates if (StandardField.DATE == field) { Optional<Date> date = Date.parse( getFieldValue.apply(this, StandardField.YEAR), getFieldValue.apply(this, StandardField.MONTH), getFieldValue.apply(this, StandardField.DAY)); return date.map(Date::getNormalized); } if ((StandardField.YEAR == field) || (StandardField.MONTH == field) || (StandardField.DAY == field)) { Optional<String> date = getFieldValue.apply(this, StandardField.DATE); if (date.isEmpty()) { return Optional.empty(); } Optional<Date> parsedDate = Date.parse(date.get()); if (parsedDate.isPresent()) { if (StandardField.YEAR == field) { return parsedDate.get().getYear().map(Object::toString); } if (StandardField.MONTH == field) { return parsedDate.get().getMonth().map(Month::getJabRefFormat); } if (StandardField.DAY == field) { return parsedDate.get().getDay().map(Object::toString); } } else { // Date field not in valid format LOGGER.debug("Could not parse date {}", date.get()); return Optional.empty(); } } return Optional.empty(); } public Optional<DOI> getDOI() { return getField(StandardField.DOI).flatMap(DOI::parse); } public Optional<ISBN> getISBN() { return getField(StandardField.ISBN).flatMap(ISBN::parse); } /** * Return the LaTeX-free contents of the given field or its alias an an Optional * <p> * For details see also {@link #getFieldOrAlias(Field)} * * @param name the name of the field * @return the stored latex-free content of the field (or its alias) */ public Optional<String> getFieldOrAliasLatexFree(Field name) { return genericGetFieldOrAlias(name, BibEntry::getLatexFreeField); } /** * Returns the contents of the given field or its alias as an Optional * <p> * The following aliases are considered (old bibtex <-> new biblatex) based * on the biblatex documentation, chapter 2.2.5:<br> * address <-> location <br> * annote <-> annotation <br> * archiveprefix <-> eprinttype <br> * journal <-> journaltitle <br> * key <-> sortkey <br> * pdf <-> file <br> * primaryclass <-> eprintclass <br> * school <-> institution <br> * These work bidirectional. <br> * </p> * * <p> * Special attention is paid to dates: (see the biblatex documentation, * chapter 2.3.8) * The fields 'year' and 'month' are used if the 'date' * field is empty. Conversely, getFieldOrAlias("year") also tries to * extract the year from the 'date' field (analogously for 'month'). * </p> */ public Optional<String> getFieldOrAlias(Field field) { return genericGetFieldOrAlias(field, BibEntry::getField); } /** * Sets a number of fields simultaneously. The given HashMap contains field * names as keys, each mapped to the value to set. */ public void setField(Map<Field, String> fields) { Objects.requireNonNull(fields, "fields must not be null"); fields.forEach(this::setField); } /** * Set a field, and notify listeners about the change. * * @param field The field to set * @param value The value to set * @param eventSource Source the event is sent from */ public Optional<FieldChange> setField(Field field, String value, EntriesEventSource eventSource) { Objects.requireNonNull(field, "field name must not be null"); Objects.requireNonNull(value, "field value must not be null"); Objects.requireNonNull(eventSource, "field eventSource must not be null"); if (value.isEmpty()) { return clearField(field); } String oldValue = getField(field).orElse(null); boolean isNewField = oldValue == null; if (value.equals(oldValue)) { return Optional.empty(); } changed = true; invalidateFieldCache(field); fields.put(field, value.intern()); FieldChange change = new FieldChange(this, field, oldValue, value); if (isNewField) { eventBus.post(new FieldAddedOrRemovedEvent(change, eventSource)); } else { eventBus.post(new FieldChangedEvent(change, eventSource)); } return Optional.of(change); } /** * Set a field, and notify listeners about the change. * * @param field The field to set. * @param value The value to set. */ public Optional<FieldChange> setField(Field field, String value) { return setField(field, value, EntriesEventSource.LOCAL); } /** * Remove the mapping for the field name, and notify listeners about the change. * * @param field The field to clear. */ public Optional<FieldChange> clearField(Field field) { return clearField(field, EntriesEventSource.LOCAL); } /** * Remove the mapping for the field name, and notify listeners about * the change including the {@link EntriesEventSource}. * * @param field the field to clear. * @param eventSource the source a new {@link FieldChangedEvent} should be posten from. */ public Optional<FieldChange> clearField(Field field, EntriesEventSource eventSource) { Optional<String> oldValue = getField(field); if (oldValue.isEmpty()) { return Optional.empty(); } changed = true; invalidateFieldCache(field); fields.remove(field); FieldChange change = new FieldChange(this, field, oldValue.get(), null); eventBus.post(new FieldAddedOrRemovedEvent(change, eventSource)); return Optional.of(change); } /** * Determines whether this entry has all the given fields present. If a non-null * database argument is given, this method will try to look up missing fields in * entries linked by the "crossref" field, if any. * * @param fields An array of field names to be checked. * @param database The database in which to look up crossref'd entries, if any. This argument can be null, meaning * that no attempt will be made to follow crossrefs. * @return true if all fields are set or could be resolved, false otherwise. */ public boolean allFieldsPresent(Collection<OrFields> fields, BibDatabase database) { return fields.stream().allMatch(field -> this.getResolvedFieldOrAlias(field, database).isPresent()); } /** * Returns a clone of this entry. Useful for copying. * This will set a new ID for the cloned entry to be able to distinguish both copies. */ @Override public Object clone() { BibEntry clone = new BibEntry(type.getValue()); clone.fields = FXCollections.observableMap(new ConcurrentHashMap<>(fields)); clone.commentsBeforeEntry = commentsBeforeEntry; clone.parsedSerialization = parsedSerialization; clone.changed = changed; return clone; } /** * This returns a canonical BibTeX serialization. Special characters such as "{" or "&" are NOT escaped, but written * as is. In case the JabRef "hack" for distinguishing "field = value" and "field = {value}" (in .bib files) is * used, it is output as "field = {#value#}", which may cause headaches in debugging. We nevertheless do it this way * to a) enable debugging the internal representation and b) save time at this method. * <p> * Serializes all fields, even the JabRef internal ones. Does NOT serialize "KEY_FIELD" as field, but as key. */ @Override public String toString() { return CanonicalBibEntry.getCanonicalRepresentation(this); } /** * @param maxCharacters The maximum number of characters (additional * characters are replaced with "..."). Set to 0 to disable truncation. * @return A short textual description of the entry in the format: * Author1, Author2: Title (Year) */ public String getAuthorTitleYear(int maxCharacters) { String[] s = new String[]{getField(StandardField.AUTHOR).orElse("N/A"), getField(StandardField.TITLE).orElse("N/A"), getField(StandardField.YEAR).orElse("N/A")}; String text = s[0] + ": \"" + s[1] + "\" (" + s[2] + ')'; if ((maxCharacters <= 0) || (text.length() <= maxCharacters)) { return text; } return text.substring(0, maxCharacters + 1) + "..."; } /** * Returns the title of the given BibTeX entry as an Optional. * * @return an Optional containing the title of a BibTeX entry in case it exists, otherwise return an empty Optional. */ public Optional<String> getTitle() { return getField(StandardField.TITLE); } /** * Will return the publication date of the given bibtex entry conforming to ISO 8601, i.e. either YYYY or YYYY-MM. * * @return will return the publication date of the entry or null if no year was found. */ public Optional<Date> getPublicationDate() { return getFieldOrAlias(StandardField.DATE).flatMap(Date::parse); } public String getParsedSerialization() { return parsedSerialization; } public void setParsedSerialization(String parsedSerialization) { changed = false; this.parsedSerialization = parsedSerialization; } public void setCommentsBeforeEntry(String parsedComments) { this.commentsBeforeEntry = parsedComments; } public boolean hasChanged() { return changed; } public void setChanged(boolean changed) { this.changed = changed; } /** * Required to trigger new serialization of the entry. * Reason: We don't have a <code>build()</code> command, we don't want to create a new serialization at each call, * we need to construct a BibEntry with <code>changed=false</code> (which is the default) and thus we need a workaround. */ public BibEntry withChanged(boolean changed) { this.changed = changed; return this; } public Optional<FieldChange> putKeywords(List<String> keywords, Character delimiter) { Objects.requireNonNull(delimiter); return putKeywords(new KeywordList(keywords), delimiter); } public Optional<FieldChange> putKeywords(KeywordList keywords, Character delimiter) { Objects.requireNonNull(keywords); Optional<String> oldValue = this.getField(StandardField.KEYWORDS); if (keywords.isEmpty()) { // Clear keyword field if (oldValue.isPresent()) { return this.clearField(StandardField.KEYWORDS); } else { return Optional.empty(); } } // Set new keyword field String newValue = keywords.getAsString(delimiter); return this.setField(StandardField.KEYWORDS, newValue); } /** * Check if a keyword already exists (case insensitive), if not: add it * * @param keyword Keyword to add */ public void addKeyword(String keyword, Character delimiter) { Objects.requireNonNull(keyword, "keyword must not be null"); if (keyword.isEmpty()) { return; } addKeyword(new Keyword(keyword), delimiter); } public void addKeyword(Keyword keyword, Character delimiter) { KeywordList keywords = this.getKeywords(delimiter); keywords.add(keyword); this.putKeywords(keywords, delimiter); } /** * Add multiple keywords to entry * * @param keywords Keywords to add */ public void addKeywords(Collection<String> keywords, Character delimiter) { Objects.requireNonNull(keywords); keywords.forEach(keyword -> addKeyword(keyword, delimiter)); } public KeywordList getKeywords(Character delimiter) { return getFieldAsKeywords(StandardField.KEYWORDS, delimiter); } public KeywordList getResolvedKeywords(Character delimiter, BibDatabase database) { Optional<String> keywordsContent = getResolvedFieldOrAlias(StandardField.KEYWORDS, database); return keywordsContent.map(content -> KeywordList.parse(content, delimiter)).orElse(new KeywordList()); } public Optional<FieldChange> removeKeywords(KeywordList keywordsToRemove, Character keywordDelimiter) { KeywordList keywordList = getKeywords(keywordDelimiter); // We need to fix "file has changed on disk" for duplicate keywords // The input of the set may contain duplicate keywords (which are present as single keyword in the set) // Even if no "keywordsToRemove" is contained, the method "putKeywords" will return a change, because the duplicate keywords will have been removed int oldSize = keywordList.size(); keywordList.removeAll(keywordsToRemove); // claim 1: The size of a set is the same, if no element is removed // claim 2: The size of a set is different if an element was removed // With claim 1, we can assume no change if there is no change on the size if (oldSize == keywordList.size()) { return Optional.empty(); } else { return putKeywords(keywordList, keywordDelimiter); } } public Optional<FieldChange> replaceKeywords(KeywordList keywordsToReplace, Keyword newValue, Character keywordDelimiter) { KeywordList keywordList = getKeywords(keywordDelimiter); keywordList.replaceAll(keywordsToReplace, newValue); return putKeywords(keywordList, keywordDelimiter); } public Collection<String> getFieldValues() { return fields.values(); } public Map<Field, String> getFieldMap() { return fields; } public SharedBibEntryData getSharedBibEntryData() { return sharedBibEntryData; } public BibEntry withSharedBibEntryData(int sharedId, int version) { sharedBibEntryData.setSharedID(sharedId); sharedBibEntryData.setVersion(version); return this; } public BibEntry withSharedBibEntryData(SharedBibEntryData sharedBibEntryData) { sharedBibEntryData = sharedBibEntryData; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } BibEntry entry = (BibEntry) o; return Objects.equals(type.getValue(), entry.type.getValue()) && Objects.equals(fields, entry.fields) && Objects.equals(commentsBeforeEntry, entry.commentsBeforeEntry); } /** * On purpose, this hashes the "content" of the BibEntry, not the {@link #sharedBibEntryData}. * * The content is * * <ul> * <li>comments before entry</li> * <li>entry type</li> * <li>fields (including the citation key {@link InternalField#KEY_FIELD}</li> * </ul> */ @Override public int hashCode() { return Objects.hash(commentsBeforeEntry, type.getValue(), fields); } public void registerListener(Object object) { this.eventBus.register(object); } public void unregisterListener(Object object) { try { this.eventBus.unregister(object); } catch (IllegalArgumentException e) { // occurs if the event source has not been registered, should not prevent shutdown LOGGER.debug("Problem unregistering", e); } } public BibEntry withField(Field field, String value) { setField(field, value); this.setChanged(false); return this; } /** * A copy is made of the parameter */ public BibEntry withFields(Map<Field, String> content) { this.fields = FXCollections.observableMap(new HashMap<>(content)); return this; } public BibEntry withDate(Date date) { setDate(date); this.setChanged(false); return this; } public BibEntry withMonth(Month parsedMonth) { setMonth(parsedMonth); this.setChanged(false); return this; } /* * Returns user comments (arbitrary text before the entry), if they exist. If not, returns the empty String */ public String getUserComments() { return commentsBeforeEntry; } public BibEntry withUserComments(String commentsBeforeEntry) { this.commentsBeforeEntry = commentsBeforeEntry; return this; } public List<ParsedEntryLink> getEntryLinkList(Field field, BibDatabase database) { return getField(field).map(fieldValue -> EntryLinkList.parse(fieldValue, database)) .orElse(Collections.emptyList()); } public Optional<FieldChange> setEntryLinkList(Field field, List<ParsedEntryLink> list) { return setField(field, EntryLinkList.serialize(list)); } public Set<String> getFieldAsWords(Field field) { Set<String> storedList = fieldsAsWords.get(field); if (storedList != null) { return storedList; } else { String fieldValue = fields.get(field); if (fieldValue == null) { return Collections.emptySet(); } else { HashSet<String> words = new HashSet<>(StringUtil.getStringAsWords(fieldValue)); fieldsAsWords.put(field, words); return words; } } } public KeywordList getFieldAsKeywords(Field field, Character keywordSeparator) { if (field instanceof StandardField standardField) { Optional<KeywordList> storedList = fieldsAsKeywords.get(standardField, keywordSeparator); if (storedList.isPresent()) { return storedList.get(); } } KeywordList keywords = getField(field) .map(content -> KeywordList.parse(content, keywordSeparator)) .orElse(new KeywordList()); if (field instanceof StandardField standardField) { fieldsAsKeywords.put(standardField, keywordSeparator, keywords); } return keywords; } public Optional<FieldChange> clearCiteKey() { return clearField(InternalField.KEY_FIELD); } private void invalidateFieldCache(Field field) { latexFreeFields.remove(field); fieldsAsWords.remove(field); if (field instanceof StandardField standardField) { fieldsAsKeywords.remove(standardField); } } public Optional<String> getLatexFreeField(Field field) { if (InternalField.KEY_FIELD == field) { // the key field should not be converted return getCitationKey(); } else if (InternalField.TYPE_HEADER == field) { return Optional.of(type.get().getDisplayName()); } else if (latexFreeFields.containsKey(field)) { return Optional.ofNullable(latexFreeFields.get(field)); } else { Optional<String> fieldValue = getField(field); if (fieldValue.isPresent()) { String latexFreeValue = LatexToUnicodeAdapter.format(fieldValue.get()).intern(); latexFreeFields.put(field, latexFreeValue); return Optional.of(latexFreeValue); } else { return Optional.empty(); } } } public Optional<FieldChange> setFiles(List<LinkedFile> files) { Optional<String> oldValue = this.getField(StandardField.FILE); String newValue = FileFieldWriter.getStringRepresentation(files); if (oldValue.isPresent() && oldValue.get().equals(newValue)) { return Optional.empty(); } return this.setField(StandardField.FILE, newValue); } /** * Gets a list of linked files. * * @return the list of linked files, is never null but can be empty. * Changes to the underlying list will have no effect on the entry itself. Use {@link #addFile(LinkedFile)} */ public List<LinkedFile> getFiles() { // Extract the path Optional<String> oldValue = getField(StandardField.FILE); if (oldValue.isEmpty()) { return new ArrayList<>(); // Return new ArrayList because emptyList is immutable } return FileFieldParser.parse(oldValue.get()); } public void setDate(Date date) { date.getYear().ifPresent(year -> setField(StandardField.YEAR, year.toString())); date.getMonth().ifPresent(this::setMonth); date.getDay().ifPresent(day -> setField(StandardField.DAY, day.toString())); } public Optional<Month> getMonth() { return getFieldOrAlias(StandardField.MONTH).flatMap(Month::parse); } public OptionalBinding<String> getFieldBinding(Field field) { if ((field == InternalField.TYPE_HEADER) || (field == InternalField.OBSOLETE_TYPE_HEADER)) { return EasyBind.wrapNullable(type).mapOpt(EntryType::getDisplayName); } return EasyBind.valueAt(fields, field); } public OptionalBinding<String> getCiteKeyBinding() { return getFieldBinding(InternalField.KEY_FIELD); } public Optional<FieldChange> addFile(LinkedFile file) { List<LinkedFile> linkedFiles = getFiles(); linkedFiles.add(file); return setFiles(linkedFiles); } public Optional<FieldChange> addFile(int index, LinkedFile file) { List<LinkedFile> linkedFiles = getFiles(); linkedFiles.add(index, file); return setFiles(linkedFiles); } public ObservableMap<Field, String> getFieldsObservable() { return fields; } /** * Returns a list of observables that represent the data of the entry. */ public Observable[] getObservables() { return new Observable[] {fields, type}; } /** * Helper method to add a downloaded file to the entry. * <p> * Use-case: URL is contained in the file, the file is downloaded and should then replace the url. * This method. adds the given path (as file) to the entry and removes the url. * * @param linkToDownloadedFile the link to the file, which was downloaded * @param downloadedFile the path to be added to the entry */ public void replaceDownloadedFile(String linkToDownloadedFile, LinkedFile downloadedFile) { List<LinkedFile> linkedFiles = this.getFiles(); int oldFileIndex = -1; int i = 0; while ((i < linkedFiles.size()) && (oldFileIndex == -1)) { LinkedFile file = linkedFiles.get(i); // The file type changes as part of download process (see prepareDownloadTask), thus we only compare by link if (file.getLink().equalsIgnoreCase(linkToDownloadedFile)) { oldFileIndex = i; } i++; } if (oldFileIndex == -1) { linkedFiles.add(0, downloadedFile); } else { linkedFiles.set(oldFileIndex, downloadedFile); } this.setFiles(linkedFiles); } /** * Merge this entry's fields with another BibEntry. Non-intersecting fields will be automatically merged. In cases of * intersection, priority is given to THIS entry's field value. * * @param other another BibEntry from which fields are sourced from */ public void mergeWith(BibEntry other) { mergeWith(other, Set.of()); } /** * Merge this entry's fields with another BibEntry. Non-intersecting fields will be automatically merged. In cases of * intersection, priority is given to THIS entry's field value, UNLESS specified otherwise in the arguments. * * @param other another BibEntry from which fields are sourced from * @param otherPrioritizedFields collection of Fields in which 'other' has a priority into final result */ public void mergeWith(BibEntry other, Set<Field> otherPrioritizedFields) { Set<Field> thisFields = new TreeSet<>(Comparator.comparing(Field::getName)); Set<Field> otherFields = new TreeSet<>(Comparator.comparing(Field::getName)); thisFields.addAll(this.getFields()); otherFields.addAll(other.getFields()); // At the moment, "Field" interface does not provide explicit equality, so using their names instead. Set<String> thisFieldsNames = thisFields.stream().map(Field::getName).collect(Collectors.toSet()); Set<String> otherPrioritizedFieldsNames = otherPrioritizedFields.stream().map(Field::getName).collect(Collectors.toSet()); for (Field otherField : otherFields) { Optional<String> otherFieldValue = other.getField(otherField); if (!thisFieldsNames.contains(otherField.getName()) || otherPrioritizedFieldsNames.contains(otherField.getName())) { // As iterator only goes through non-null fields from OTHER, otherFieldValue can never be empty otherFieldValue.ifPresent(s -> this.setField(otherField, s)); } } } public boolean isEmpty() { if (this.fields.isEmpty()) { return true; } return StandardField.AUTOMATIC_FIELDS.containsAll(this.getFields()); } }
45,517
37.640068
203
java
null
jabref-main/src/main/java/org/jabref/model/entry/BibEntryType.java
package org.jabref.model.entry; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jabref.gui.importer.BibEntryTypePrefsAndFileViewModel; import org.jabref.logic.exporter.MetaDataSerializer; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; public class BibEntryType implements Comparable<BibEntryType> { private final EntryType type; private final LinkedHashSet<OrFields> requiredFields; private final LinkedHashSet<BibField> fields; /** * Provides an enriched EntryType with information about defined standards as mandatory fields etc. * * A builder is available at {@link BibEntryTypeBuilder} * * @param type The EntryType this BibEntryType is wrapped around. * @param fields A BibFields list of all fields, including the required fields * @param requiredFields A OrFields list of just the required fields */ public BibEntryType(EntryType type, Collection<BibField> fields, Collection<OrFields> requiredFields) { this.type = Objects.requireNonNull(type); this.fields = new LinkedHashSet<>(fields); this.requiredFields = new LinkedHashSet<>(requiredFields); } public EntryType getType() { return type; } public Set<BibField> getOptionalFields() { return getAllBibFields().stream() .filter(field -> !isRequired(field.field())) .collect(Collectors.toCollection(LinkedHashSet::new)); } public boolean isRequired(Field field) { return getRequiredFields().stream() .anyMatch(fields -> fields.contains(field)); } /** * Returns all required field names. * If fields have an OR relationship the name includes both field names divided by /, e.g. author/editor. * If you need all required fields as sole entities use @see{getRequiredFieldsFlat} . * * @return a Set of required field name Strings */ public Set<OrFields> getRequiredFields() { return Collections.unmodifiableSet(requiredFields); } /** * Returns all defined fields. */ public Set<BibField> getAllBibFields() { return Collections.unmodifiableSet(fields); } public Set<Field> getAllFields() { return fields.stream().map(BibField::field).collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<Field> getPrimaryOptionalFields() { return getOptionalFields().stream() .filter(field -> field.priority() == FieldPriority.IMPORTANT) .map(BibField::field) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<Field> getSecondaryOptionalFields() { return getOptionalFields().stream() .filter(field -> field.priority() == FieldPriority.DETAIL) .map(BibField::field) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<Field> getDeprecatedFields(BibDatabaseMode mode) { if (mode == BibDatabaseMode.BIBTEX) { return Collections.emptySet(); } Set<Field> deprecatedFields = new LinkedHashSet<>(EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.keySet()); // Only the optional fields which are mapped to another BibLaTeX name should be shown as "deprecated" deprecatedFields.retainAll(getOptionalFieldsAndAliases()); // BibLaTeX aims for that field "date" is used // Thus, year + month is deprecated // However, year is used in the wild very often, so we do not mark that as default as deprecated deprecatedFields.add(StandardField.MONTH); return deprecatedFields; } public Set<Field> getSecondaryOptionalNotDeprecatedFields(BibDatabaseMode mode) { Set<Field> optionalFieldsNotPrimaryOrDeprecated = new LinkedHashSet<>(getSecondaryOptionalFields()); optionalFieldsNotPrimaryOrDeprecated.removeAll(getDeprecatedFields(mode)); return optionalFieldsNotPrimaryOrDeprecated; } /** * Get list of all optional fields of this entry and all fields being source for a BibTeX to BibLaTeX conversion. */ private Set<Field> getOptionalFieldsAndAliases() { Set<Field> optionalFieldsAndAliases = new LinkedHashSet<>(getOptionalFields().size()); for (BibField field : getOptionalFields()) { optionalFieldsAndAliases.add(field.field()); if (EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.containsKey(field.field())) { optionalFieldsAndAliases.add(field.field()); } } return optionalFieldsAndAliases; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } BibEntryType that = (BibEntryType) o; return type.equals(that.type) && Objects.equals(requiredFields, that.requiredFields) && Objects.equals(fields, that.fields); } @Override public int hashCode() { return Objects.hash(type, requiredFields, fields); } /** * Generates a **single line** string containing the information. This is used for debugging purposes. * * See "<a href="https://biratkirat.medium.com/learning-effective-java-item-10-84cc3ab553bc">Effective Java, Item 10</a>" for a discussion on contracts. * * We are sure, we are using this method in a) logs (which should use single lines for output) and b) in the UI. For the UI, we use {@link BibEntryTypePrefsAndFileViewModel}, * which in turn uses {@link MetaDataSerializer#serializeCustomEntryTypes(BibEntryType)} */ @Override public String toString() { return "BibEntryType{" + "type=" + type + ", allFields=" + fields + ", requiredFields=" + requiredFields + '}'; } @Override public int compareTo(BibEntryType o) { return this.getType().getName().compareTo(o.getType().getName()); } }
6,702
38.429412
178
java
null
jabref-main/src/main/java/org/jabref/model/entry/BibEntryTypeBuilder.java
package org.jabref.model.entry; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.StandardEntryType; import com.google.common.collect.Streams; public class BibEntryTypeBuilder { private EntryType type = StandardEntryType.Misc; private Set<BibField> fields = new LinkedHashSet<>(); private Set<OrFields> requiredFields = new LinkedHashSet<>(); public BibEntryTypeBuilder withType(EntryType type) { this.type = type; return this; } public BibEntryTypeBuilder withImportantFields(Set<BibField> newFields) { return withImportantFields(newFields.stream().map(BibField::field).collect(Collectors.toCollection(LinkedHashSet::new))); } public BibEntryTypeBuilder withImportantFields(Collection<Field> newFields) { this.fields = Streams.concat(fields.stream(), newFields.stream().map(field -> new BibField(field, FieldPriority.IMPORTANT))) .collect(Collectors.toCollection(LinkedHashSet::new)); return this; } public BibEntryTypeBuilder withImportantFields(Field... newFields) { return withImportantFields(Arrays.asList(newFields)); } public BibEntryTypeBuilder withDetailFields(Collection<Field> newFields) { this.fields = Streams.concat(fields.stream(), newFields.stream().map(field -> new BibField(field, FieldPriority.DETAIL))) .collect(Collectors.toCollection(LinkedHashSet::new)); return this; } public BibEntryTypeBuilder withDetailFields(Field... fields) { return withDetailFields(Arrays.asList(fields)); } public BibEntryTypeBuilder withRequiredFields(Set<OrFields> requiredFields) { this.requiredFields = requiredFields; return this; } public BibEntryTypeBuilder withRequiredFields(Field... requiredFields) { this.requiredFields = Arrays.stream(requiredFields).map(OrFields::new).collect(Collectors.toCollection(LinkedHashSet::new)); return this; } public BibEntryTypeBuilder withRequiredFields(OrFields first, Field... requiredFields) { this.requiredFields = Stream.concat(Stream.of(first), Arrays.stream(requiredFields).map(OrFields::new)).collect(Collectors.toCollection(LinkedHashSet::new)); return this; } public BibEntryTypeBuilder withRequiredFields(List<OrFields> first, Field... requiredFields) { this.requiredFields = Stream.concat(first.stream(), Arrays.stream(requiredFields).map(OrFields::new)).collect(Collectors.toCollection(LinkedHashSet::new)); return this; } public BibEntryType build() { // Treat required fields as important ones Stream<BibField> requiredAsImportant = requiredFields.stream() .flatMap(Set::stream) .map(field -> new BibField(field, FieldPriority.IMPORTANT)); Set<BibField> allFields = Stream.concat(fields.stream(), requiredAsImportant).collect(Collectors.toCollection(LinkedHashSet::new)); return new BibEntryType(type, allFields, requiredFields); } }
3,573
41.547619
165
java
null
jabref-main/src/main/java/org/jabref/model/entry/BibEntryTypesManager.java
package org.jabref.model.entry; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.types.BiblatexAPAEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexSoftwareEntryTypeDefinitions; import org.jabref.model.entry.types.BibtexEntryTypeDefinitions; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.entry.types.IEEETranEntryTypeDefinitions; public class BibEntryTypesManager { private final InternalEntryTypes BIBTEX_ENTRYTYPES = new InternalEntryTypes( Stream.concat(BibtexEntryTypeDefinitions.ALL.stream(), IEEETranEntryTypeDefinitions.ALL.stream()) .collect(Collectors.toList())); private final InternalEntryTypes BIBLATEX_ENTRYTYPES = new InternalEntryTypes( Stream.concat(BiblatexEntryTypeDefinitions.ALL.stream(), Stream.concat(BiblatexSoftwareEntryTypeDefinitions.ALL.stream(), BiblatexAPAEntryTypeDefinitions.ALL.stream())) .collect(Collectors.toList())); public BibEntryTypesManager() { } private InternalEntryTypes getEntryTypes(BibDatabaseMode mode) { return switch (mode) { case BIBTEX -> BIBTEX_ENTRYTYPES; case BIBLATEX -> BIBLATEX_ENTRYTYPES; }; } /** * For a given database mode, determine all custom entry types, i.e. types that are not overwritten standard types but real custom types. * For example, a modified "article" type will not be included in the list, but an entry type like "MyCustomType" will be included. * * @param mode the BibDatabaseMode to be checked * @return the list of all found custom types */ public List<BibEntryType> getAllCustomTypes(BibDatabaseMode mode) { return getEntryTypes(mode).getAllCustomTypes(); } /** * Returns true if the type is a custom type, or if it is a standard type which has customized fields */ public boolean isCustomOrModifiedType(BibEntryType type, BibDatabaseMode mode) { return getEntryTypes(mode).isCustomOrModifiedType(type); } /** * Sets the given custom entry types for BibTeX and biblatex mode */ public void addCustomOrModifiedTypes(List<BibEntryType> customizedEntryTypes, BibDatabaseMode mode) { InternalEntryTypes entryTypes = getEntryTypes(mode); customizedEntryTypes.forEach(entryTypes::addCustomOrModifiedType); } public void addCustomOrModifiedType(BibEntryType entryType, BibDatabaseMode mode) { getEntryTypes(mode).addCustomOrModifiedType(entryType); } public void removeCustomOrModifiedEntryType(BibEntryType entryType, BibDatabaseMode mode) { getEntryTypes(mode).removeCustomOrModifiedEntryType(entryType); } public void clearAllCustomEntryTypes(BibDatabaseMode mode) { getEntryTypes(mode).clearAllCustomEntryTypes(); } public Collection<BibEntryType> getAllTypes(BibDatabaseMode mode) { return getEntryTypes(mode).getAllTypes(); } public boolean isCustomType(EntryType type, BibDatabaseMode mode) { return getAllCustomTypes(mode).stream().anyMatch(customType -> customType.getType().equals(type)); } /** * This method returns the BibEntryType for the entry type. * * @param mode the mode of the BibDatabase, may be null */ public Optional<BibEntryType> enrich(EntryType type, BibDatabaseMode mode) { return getEntryTypes(mode).enrich(type); } public boolean isDifferentCustomOrModifiedType(BibEntryType type, BibDatabaseMode mode) { Optional<BibEntryType> currentlyStoredType = enrich(type.getType(), mode); if (currentlyStoredType.isEmpty()) { // new customization return true; } else { // different customization return !EntryTypeFactory.nameAndFieldsAreEqual(type, currentlyStoredType.get()); } } /** * This class is used to specify entry types for either BIBTEX and BIBLATEX. */ private static class InternalEntryTypes { private final SortedSet<BibEntryType> customOrModifiedType = new TreeSet<>(); private final SortedSet<BibEntryType> standardTypes; private InternalEntryTypes(List<BibEntryType> standardTypes) { this.standardTypes = new TreeSet<>(standardTypes); } private List<BibEntryType> getAllCustomTypes() { Collection<BibEntryType> customizedTypes = getAllTypes(); return customizedTypes.stream() .filter(bibEntryType -> standardTypes.stream() .noneMatch(item -> item.getType().equals(bibEntryType.getType()))) .toList(); } /** * This method returns the BibtexEntryType for the name of a type, * or an empty optional if it does not exist. */ private Optional<BibEntryType> enrich(EntryType type) { Optional<BibEntryType> enrichedType = customOrModifiedType.stream() .filter(typeEquals(type)) .findFirst(); if (enrichedType.isPresent()) { return enrichedType; } else { return standardTypes.stream() .filter(typeEquals(type)) .findFirst(); } } private Predicate<BibEntryType> typeEquals(EntryType toCompare) { return item -> item.getType().equals(toCompare); } private void addCustomOrModifiedType(BibEntryType type) { customOrModifiedType.remove(type); customOrModifiedType.add(type); } private void removeCustomOrModifiedEntryType(BibEntryType type) { customOrModifiedType.remove(type); } private void clearAllCustomEntryTypes() { customOrModifiedType.clear(); } private SortedSet<BibEntryType> getAllTypes() { SortedSet<BibEntryType> allTypes = new TreeSet<>(customOrModifiedType); allTypes.addAll(standardTypes); return allTypes; } private boolean isCustomOrModifiedType(BibEntryType entryType) { return customOrModifiedType.stream() .anyMatch(customizedType -> customizedType.equals(entryType)); } } }
6,958
39.459302
141
java
null
jabref-main/src/main/java/org/jabref/model/entry/BibtexString.java
package org.jabref.model.entry; import java.util.Locale; import java.util.Objects; /** * This class models a BibTex String ("@String") */ public class BibtexString implements Cloneable { /** * Type of a \@String. * <p> * Differentiate a \@String based on its usage: * <p> * - {@link #AUTHOR}: prefix "a", for author and editor fields. * - {@link #INSTITUTION}: prefix "i", for institution and organization * field * - {@link #PUBLISHER}: prefix "p", for publisher fields * - {@link #OTHER}: no prefix, for any field * <p> * Examples: * <p> * \@String { aKahle = "Kahle, Brewster " } -> author * \@String { aStallman = "Stallman, Richard" } -> author * \@String { iMIT = "{Massachusetts Institute of Technology ({MIT})}" } -> institution * \@String { pMIT = "{Massachusetts Institute of Technology ({MIT}) press}" } -> publisher * \@String { anct = "Anecdote" } -> other * \@String { eg = "for example" } -> other * \@String { et = " and " } -> other * \@String { lBigMac = "Big Mac" } -> other * <p> * Usage: * <p> * \@Misc { * title = "The GNU Project" * author = aStallman # et # aKahle * institution = iMIT * publisher = pMIT * note = "Just " # eg * } */ public enum Type { AUTHOR("a"), INSTITUTION("i"), PUBLISHER("p"), OTHER(""); private final String prefix; Type(String prefix) { this.prefix = prefix; } public static Type get(String key) { if (key.length() <= 1) { return OTHER; } // Second character is not upper case // aStallman -> AUTHOR // asdf -> OTHER if (!(String.valueOf(key.charAt(1))).toUpperCase(Locale.ROOT).equals(String.valueOf(key.charAt(1)))) { return OTHER; } for (Type t : Type.values()) { if (t.prefix.equals(String.valueOf(key.charAt(0)))) { return t; } } return OTHER; } } private String name; private String content; private String id; private Type type; private String parsedSerialization; private boolean hasChanged; public BibtexString(String name, String content) { this.id = IdGenerator.next(); this.name = name; this.content = content; hasChanged = true; type = Type.get(name); } public String getId() { return id; } public void setId(String id) { this.id = id; hasChanged = true; } /** * Returns the name/label of the string */ public String getName() { return name; } public void setName(String name) { this.name = name; hasChanged = true; type = Type.get(name); } /* * Never returns null */ public String getContent() { return content == null ? "" : content; } public void setContent(String content) { this.content = content; hasChanged = true; } public Type getType() { return type; } public void setParsedSerialization(String parsedSerialization) { this.parsedSerialization = parsedSerialization; hasChanged = false; } public String getParsedSerialization() { return parsedSerialization; } public boolean hasChanged() { return hasChanged; } /* * Returns user comments (arbitrary text before the string) if there are any. If not returns the empty string */ public String getUserComments() { if (parsedSerialization != null) { try { // get the text before the string String prolog = parsedSerialization.substring(0, parsedSerialization.indexOf('@')); return prolog; } catch (StringIndexOutOfBoundsException ignore) { // if this occurs a broken parsed serialization has been set, so just do nothing } } return ""; } @Override public Object clone() { BibtexString clone = new BibtexString(name, content); clone.setId(id); return clone; } @Override public String toString() { return name + "=" + content; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } BibtexString that = (BibtexString) o; return Objects.equals(hasChanged, that.hasChanged) && Objects.equals(name, that.name) && Objects.equals(content, that.content) && Objects.equals(type, that.type) && Objects.equals(parsedSerialization, that.parsedSerialization); } @Override public int hashCode() { return Objects.hash(hasChanged, name, content, type, parsedSerialization); } }
5,173
26.089005
114
java
null
jabref-main/src/main/java/org/jabref/model/entry/CanonicalBibEntry.java
package org.jabref.model.entry; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.StringJoiner; import java.util.TreeSet; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; public class CanonicalBibEntry { private CanonicalBibEntry() { } /** * This returns a canonical BibTeX serialization. * The result is close to BibTeX, but not a valid BibTeX representation in all cases * * <ul> * <li>Serializes all fields, even the JabRef internal ones.</li> * <li>Does NOT serialize "KEY_FIELD" as field, but as key.</li> * <li>Special characters such as "{" or "&" are NOT escaped, but written as is.</li> * <li>New lines are written as is.</li> * <li>String constants are not handled. That means, <code>month = apr</code> in a bib file gets <code>month = {#apr#}</code>. * This indicates that the month field is correctly stored.</li> * </ul> */ public static String getCanonicalRepresentation(BibEntry entry) { StringBuilder sb = new StringBuilder(); sb.append(entry.getUserComments()); // generate first line: type and citation key String citeKey = entry.getCitationKey().orElse(""); sb.append(String.format("@%s{%s,", entry.getType().getName(), citeKey)).append('\n'); // we have to introduce a new Map as fields are stored case-sensitive in JabRef (see https://github.com/koppor/jabref/issues/45). Map<String, String> mapFieldToValue = new HashMap<>(); // determine sorted fields -- all fields lower case SortedSet<String> sortedFields = new TreeSet<>(); for (Entry<Field, String> field : entry.getFieldMap().entrySet()) { Field fieldName = field.getKey(); String fieldValue = field.getValue(); // JabRef stores the key in the field KEY_FIELD, which must not be serialized if (!fieldName.equals(InternalField.KEY_FIELD)) { String lowerCaseFieldName = fieldName.getName().toLowerCase(Locale.US); sortedFields.add(lowerCaseFieldName); mapFieldToValue.put(lowerCaseFieldName, fieldValue); } } // generate field entries StringJoiner sj = new StringJoiner(",\n", "", "\n"); for (String fieldName : sortedFields) { String line = String.format(" %s = {%s}", fieldName, mapFieldToValue.get(fieldName)); sj.add(line); } sj.add(String.format(" _jabref_shared = {sharedId: %d, version: %d}", entry.getSharedBibEntryData().getSharedID(), entry.getSharedBibEntryData().getVersion())); sb.append(sj); // append the closing entry bracket sb.append('}'); return sb.toString(); } }
2,916
38.958904
169
java
null
jabref-main/src/main/java/org/jabref/model/entry/Date.java
package org.jabref.model.entry; import java.time.LocalDate; import java.time.Year; import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Date { public static final String DATE_REGEX; private static final DateTimeFormatter NORMALIZED_DATE_FORMATTER = DateTimeFormatter.ofPattern("uuuu[-MM][-dd]"); private static final DateTimeFormatter SIMPLE_DATE_FORMATS; private static final Logger LOGGER = LoggerFactory.getLogger(Date.class); static { List<String> formatStrings = Arrays.asList( "uuuu-MM-dd'T'HH:mm[:ss][xxx][xx][X]", // covers 2018-10-03T07:24:14+03:00 "uuuu-MM-dd'T'HH:m[:ss][xxx][xx][X]", // covers 2018-10-03T17:2 "uuuu-MM-dd'T'H:mm[:ss][xxx][xx][X]", // covers 2018-10-03T7:24 "uuuu-MM-dd'T'H:m[:ss][xxx][xx][X]", // covers 2018-10-03T7:7 "uuuu-MM-dd'T'HH[:ss][xxx][xx][X]", // covers 2018-10-03T07 "uuuu-MM-dd'T'H[:ss][xxx][xx][X]", // covers 2018-10-03T7 "uuuu-M-d", // covers 2009-1-15 "uuuu-M", // covers 2009-11 "uuuu/M", // covers 2020/10 "d-M-uuuu", // covers 15-1-2012 "M-uuuu", // covers 1-2012 "M/uuuu", // covers 9/2015 and 09/2015 "M/uu", // covers 9/15 "MMMM d, uuuu", // covers September 1, 2015 "MMMM, uuuu", // covers September, 2015 "d.M.uuuu", // covers 15.1.2015 "uuuu.M.d", // covers 2015.1.15 "uuuu", // covers 2015 "MMM, uuuu", // covers Jan, 2020 "uuuu.MM.d", // covers 2015.10.15 "d MMMM u/d MMMM u", // covers 20 January 2015/20 February 2015 "d MMMM u", // covers 20 January 2015 "d MMMM u / d MMMM u" ); /* TODO: The following date formats do not yet work and need to be created with tests * "u G", // covers 1 BC * "u G / u G", // covers 30 BC / 5 AD * "uuuu G / uuuu G", // covers 0030 BC / 0005 AD * "uuuu-MM G / uuuu-MM G", // covers 0030-01 BC / 0005-02 AD * "u'-'", // covers 2015- * "u'?'", // covers 2023? */ SIMPLE_DATE_FORMATS = formatStrings.stream() .map(DateTimeFormatter::ofPattern) .reduce(new DateTimeFormatterBuilder(), DateTimeFormatterBuilder::appendOptional, (builder, formatterBuilder) -> builder.append(formatterBuilder.toFormatter())) .toFormatter(Locale.US); /* * There is also {@link org.jabref.model.entry.Date#parse(java.lang.String)}. * The regex of that method cannot be used as we parse single dates here and that method parses: * i) date ranges * ii) two dates separated by '/' * Additionally, parse method requires the reviewed String to hold only a date. */ DATE_REGEX = "\\d{4}-\\d{1,2}-\\d{1,2}" + // covers YYYY-MM-DD, YYYY-M-DD, YYYY-MM-D, YYYY-M-D "|\\d{4}\\.\\d{1,2}\\.\\d{1,2}|" + // covers YYYY.MM.DD, YYYY.M.DD, YYYY.MM.D, YYYY.M.D "(January|February|March|April|May|June|July|August|September|" + "October|November|December) \\d{1,2}, \\d{4}"; // covers Month DD, YYYY & Month D, YYYY } private final TemporalAccessor date; private final TemporalAccessor endDate; public Date(int year, int month, int dayOfMonth) { this(LocalDate.of(year, month, dayOfMonth)); } public Date(int year, int month) { this(YearMonth.of(year, month)); } public Date(int year) { this(Year.of(year)); } public Date(TemporalAccessor date) { this.date = date; endDate = null; } /** * Creates a Date from date and endDate. * * @param date the start date * @param endDate the start date */ public Date(TemporalAccessor date, TemporalAccessor endDate) { this.date = date; this.endDate = endDate; } /** * Creates a Date from date and endDate. * * @param dateString the string to extract the date information * @throws DateTimeParseException if dataString is mal-formatted */ public static Optional<Date> parse(String dateString) { Objects.requireNonNull(dateString); if (dateString.isEmpty()) { return Optional.empty(); } // if dateString has range format, treat as date range if (dateString.matches( "\\d{4}/\\d{4}|" + // uuuu/uuuu "\\d{4}-\\d{2}/\\d{4}-\\d{2}|" + // uuuu-mm/uuuu-mm "\\d{4}-\\d{2}-\\d{2}/\\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd/uuuu-mm-dd "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4})/(January|February|March|April|May|June|July|August|September|October|November" + "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4})/(\\d{1,2})( )" + "(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 )) { try { String[] strDates = dateString.split("/"); TemporalAccessor parsedDate = SIMPLE_DATE_FORMATS.parse(strDates[0].strip()); TemporalAccessor parsedEndDate = SIMPLE_DATE_FORMATS.parse(strDates[1].strip()); return Optional.of(new Date(parsedDate, parsedEndDate)); } catch (DateTimeParseException e) { LOGGER.debug("Invalid Date format for range", e); return Optional.empty(); } } else if (dateString.matches( "\\d{4} / \\d{4}|" + // uuuu / uuuu "\\d{4}-\\d{2} / \\d{4}-\\d{2}|" + // uuuu-mm / uuuu-mm "\\d{4}-\\d{2}-\\d{2} / \\d{4}-\\d{2}-\\d{2}|" + // uuuu-mm-dd / uuuu-mm-dd "(?i)(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4}) / (January|February|March|April|May|June|July|August|September|October|November" + "|December)( |\\-)(\\d{1,4})(?i-)|" + // January 2015/January 2015 "(?i)(\\d{1,2})( )(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4}) / (\\d{1,2})( )" + "(January|February|March|April|May|June|July|August|September|October|November|December)" + "( |\\-)(\\d{1,4})(?i-)" // 20 January 2015/20 January 2015 )) { try { String[] strDates = dateString.split(" / "); TemporalAccessor parsedDate = SIMPLE_DATE_FORMATS.parse(strDates[0].strip()); TemporalAccessor parsedEndDate = SIMPLE_DATE_FORMATS.parse(strDates[1].strip()); return Optional.of(new Date(parsedDate, parsedEndDate)); } catch (DateTimeParseException e) { LOGGER.debug("Invalid Date format range", e); return Optional.empty(); } } try { TemporalAccessor parsedDate = SIMPLE_DATE_FORMATS.parse(dateString); return Optional.of(new Date(parsedDate)); } catch (DateTimeParseException e) { LOGGER.debug("Invalid Date format", e); return Optional.empty(); } } public static Optional<Date> parse(Optional<String> yearValue, Optional<String> monthValue, Optional<String> dayValue) { Optional<Year> year = yearValue.flatMap(Date::convertToInt).map(Year::of); Optional<Month> month = monthValue.flatMap(Month::parse); Optional<Integer> day = dayValue.flatMap(Date::convertToInt); if (year.isPresent()) { TemporalAccessor date; if (month.isPresent()) { if (day.isPresent()) { date = LocalDate.of(year.get().getValue(), month.get().getNumber(), day.get()); } else { date = YearMonth.of(year.get().getValue(), month.get().getNumber()); } } else { date = year.get(); } return Optional.of(new Date(date)); } return Optional.empty(); } private static Optional<Integer> convertToInt(String value) { try { return Optional.of(Integer.valueOf(value)); } catch (NumberFormatException ex) { return Optional.empty(); } } public String getNormalized() { return NORMALIZED_DATE_FORMATTER.format(date); } public Optional<Integer> getYear() { return get(ChronoField.YEAR); } public Optional<Integer> get(ChronoField field) { if (date.isSupported(field)) { return Optional.of(date.get(field)); } else { return Optional.empty(); } } public Optional<Month> getMonth() { return get(ChronoField.MONTH_OF_YEAR).flatMap(Month::getMonthByNumber); } public Optional<Integer> getDay() { return get(ChronoField.DAY_OF_MONTH); } public TemporalAccessor toTemporalAccessor() { return date; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } Date date1 = (Date) o; return Objects.equals(getYear(), date1.getYear()) && Objects.equals(getMonth(), date1.getMonth()) && Objects.equals(getDay(), date1.getDay()) && Objects.equals(get(ChronoField.HOUR_OF_DAY), date1.get(ChronoField.HOUR_OF_DAY)) && Objects.equals(get(ChronoField.MINUTE_OF_HOUR), date1.get(ChronoField.MINUTE_OF_HOUR)) && Objects.equals(get(ChronoField.SECOND_OF_DAY), date1.get(ChronoField.SECOND_OF_DAY)) && Objects.equals(get(ChronoField.OFFSET_SECONDS), date1.get(ChronoField.OFFSET_SECONDS)); } @Override public String toString() { String formattedDate = date.toString(); if (date.isSupported(ChronoField.OFFSET_SECONDS)) { formattedDate = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(date); } else if (date.isSupported(ChronoField.HOUR_OF_DAY)) { formattedDate = DateTimeFormatter.ISO_DATE_TIME.format(date); } else if (date.isSupported(ChronoField.MONTH_OF_YEAR) && date.isSupported(ChronoField.DAY_OF_MONTH)) { formattedDate = DateTimeFormatter.ISO_DATE.format(date); } return "Date{" + "date=" + formattedDate + '}'; } @Override public int hashCode() { return Objects.hash(getYear(), getMonth(), getDay(), get(ChronoField.HOUR_OF_DAY), get(ChronoField.MINUTE_OF_HOUR), get(ChronoField.OFFSET_SECONDS)); } }
12,519
43.714286
157
java
null
jabref-main/src/main/java/org/jabref/model/entry/EntryConverter.java
package org.jabref.model.entry; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; /** * Converts Entry models from BibTex to biblatex and back. */ public class EntryConverter { public static Map<Field, Field> FIELD_ALIASES_BIBTEX_TO_BIBLATEX; public static Map<Field, Field> FIELD_ALIASES_BIBLATEX_TO_BIBTEX; // All aliases public static Map<Field, Field> FIELD_ALIASES; static { EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX = new HashMap<>(); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.ADDRESS, StandardField.LOCATION); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.ANNOTE, StandardField.ANNOTATION); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.ARCHIVEPREFIX, StandardField.EPRINTTYPE); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.JOURNAL, StandardField.JOURNALTITLE); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.KEY, StandardField.SORTKEY); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.PRIMARYCLASS, StandardField.EPRINTCLASS); EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX.put(StandardField.SCHOOL, StandardField.INSTITUTION); // inverse map EntryConverter.FIELD_ALIASES_BIBLATEX_TO_BIBTEX = EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); // all aliases FIELD_ALIASES = new HashMap<>(); FIELD_ALIASES.putAll(EntryConverter.FIELD_ALIASES_BIBTEX_TO_BIBLATEX); FIELD_ALIASES.putAll(EntryConverter.FIELD_ALIASES_BIBLATEX_TO_BIBTEX); } private EntryConverter() { } }
1,906
40.456522
115
java
null
jabref-main/src/main/java/org/jabref/model/entry/EntryLinkList.java
package org.jabref.model.entry; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.jabref.model.database.BibDatabase; public class EntryLinkList { private static String SEPARATOR = ","; private EntryLinkList() { } public static List<ParsedEntryLink> parse(String fieldValue, BibDatabase database) { List<ParsedEntryLink> result = new ArrayList<>(); if ((fieldValue != null) && !fieldValue.isEmpty()) { String[] entries = fieldValue.split(SEPARATOR); for (String entry : entries) { result.add(new ParsedEntryLink(entry, database)); } } return result; } public static String serialize(List<ParsedEntryLink> list) { return String.join(SEPARATOR, list.stream().map(ParsedEntryLink::getKey).collect(Collectors.toList())); } }
896
27.03125
111
java
null
jabref-main/src/main/java/org/jabref/model/entry/IdGenerator.java
package org.jabref.model.entry; import java.text.NumberFormat; /** * IDs are at least 8 digit long. The lowest ID is 00000000, the next would be 00000001. * <p/> * The generator is thread safe! */ public class IdGenerator { private static final NumberFormat ID_FORMAT; static { ID_FORMAT = NumberFormat.getInstance(); IdGenerator.ID_FORMAT.setMinimumIntegerDigits(8); IdGenerator.ID_FORMAT.setGroupingUsed(false); } private static int idCounter; private IdGenerator() { } public static synchronized String next() { String result = ID_FORMAT.format(idCounter); idCounter++; return result; } }
683
21.064516
88
java
null
jabref-main/src/main/java/org/jabref/model/entry/Keyword.java
package org.jabref.model.entry; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.model.ChainNode; import org.jabref.model.util.OptionalUtil; /** * Represents a keyword in a chain of keywords. * For example, "JabRef" in "Bibliographic manager > Awesome ones > JabRef" */ public class Keyword extends ChainNode<Keyword> implements Comparable<Keyword> { public static Character DEFAULT_HIERARCHICAL_DELIMITER = '>'; private final String keyword; public Keyword(String keyword) { super(Keyword.class); this.keyword = Objects.requireNonNull(keyword).trim(); } /** * Connects all the given keywords into one chain and returns its root, * e.g. "A", "B", "C" is transformed into "A > B > C". */ public static Keyword of(String... keywords) { if (keywords.length == 0) { return new Keyword(""); } Keyword root = new Keyword(keywords[0]); for (int i = 1; i < keywords.length; i++) { root.addAtEnd(keywords[i]); } return root; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Keyword other = (Keyword) o; return Objects.equals(this.keyword, other.keyword) // && Objects.equals(this.getParent(), other.getParent()) : we can't check the parents because then we would run in circles && Objects.equals(this.getChild(), other.getChild()); } @Override public int hashCode() { return Objects.hash(keyword); } @Override public String toString() { return getSubchainAsString(DEFAULT_HIERARCHICAL_DELIMITER); } @Override public int compareTo(Keyword o) { return keyword.compareTo(o.keyword); } /** * Adds the given keyword at the end of the chain. * E.g., "A > B > C" + "D" -> "A > B > C > D". */ private void addAtEnd(String keyword) { addAtEnd(new Keyword(keyword)); } /** * Returns a text representation of the subchain starting at this item. * E.g., calling {@link #getSubchainAsString(Character)} on the node "B" in "A > B > C" returns "B > C". */ private String getSubchainAsString(Character hierarchicalDelimiter) { return keyword + getChild().map(child -> " " + hierarchicalDelimiter + " " + child.getSubchainAsString(hierarchicalDelimiter)) .orElse(""); } /** * Gets the keyword of this node in the chain. */ public String get() { return keyword; } /** * Returns a text representation of the path from the root to this item. * E.g., calling {@link #getPathFromRootAsString(Character)} on the node "B" in "A > B > C" returns "A > B". */ public String getPathFromRootAsString(Character hierarchicalDelimiter) { return getParent() .map(parent -> parent.getPathFromRootAsString(hierarchicalDelimiter) + " " + hierarchicalDelimiter + " ") .orElse("") + keyword; } /** * Returns all nodes in this chain as separate keywords. * E.g, for "A > B > C" we get {"A", "B", "C"}. */ public Set<Keyword> flatten() { return Stream.concat( Stream.of(this), OptionalUtil.toStream(getChild()).flatMap(child -> child.flatten().stream())) .collect(Collectors.toSet()); } /** * Returns all subchains starting at this node. * E.g., for the chain "A > B > C" the subchains {"A", "A > B", "A > B > C"} are returned. */ public Set<String> getAllSubchainsAsString(Character hierarchicalDelimiter) { return flatten().stream() .map(subchain -> subchain.getPathFromRootAsString(hierarchicalDelimiter)) .collect(Collectors.toSet()); } }
4,094
31.244094
139
java
null
jabref-main/src/main/java/org/jabref/model/entry/KeywordList.java
package org.jabref.model.entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.model.strings.StringUtil; /** * Represents a list of keyword chains. * For example, "Type > A, Type > B, Something else". */ public class KeywordList implements Iterable<Keyword> { private final List<Keyword> keywordChains; public KeywordList() { keywordChains = new ArrayList<>(); } public KeywordList(Collection<Keyword> keywordChains) { this.keywordChains = new ArrayList<>(); keywordChains.forEach(this::add); } public KeywordList(List<String> keywordChains) { this(keywordChains.stream().map(Keyword::new).collect(Collectors.toList())); } public KeywordList(String... keywordChains) { this(Arrays.stream(keywordChains).map(Keyword::new).collect(Collectors.toList())); } public KeywordList(Keyword... keywordChains) { this(Arrays.asList(keywordChains)); } public static KeywordList parse(String keywordString, Character delimiter, Character hierarchicalDelimiter) { if (StringUtil.isBlank(keywordString)) { return new KeywordList(); } Objects.requireNonNull(delimiter); Objects.requireNonNull(hierarchicalDelimiter); KeywordList keywordList = new KeywordList(); StringTokenizer tok = new StringTokenizer(keywordString, delimiter.toString()); while (tok.hasMoreTokens()) { String chain = tok.nextToken(); Keyword chainRoot = Keyword.of(chain.split(hierarchicalDelimiter.toString())); keywordList.add(chainRoot); } return keywordList; } /** * Parses the keyword list and uses {@link Keyword#DEFAULT_HIERARCHICAL_DELIMITER} as hierarchical delimiter. * * @param keywordString a String of keywordChains * @param delimiter The delimiter used for separating the keywords * @return an parsed list containing the keywordChains */ public static KeywordList parse(String keywordString, Character delimiter) { return parse(keywordString, delimiter, Keyword.DEFAULT_HIERARCHICAL_DELIMITER); } public static KeywordList merge(String keywordStringA, String keywordStringB, Character delimiter) { KeywordList keywordListA = parse(keywordStringA, delimiter); KeywordList keywordListB = parse(keywordStringB, delimiter); List<Keyword> distinctKeywords = Stream.concat(keywordListA.stream(), keywordListB.stream()).distinct().toList(); return new KeywordList(distinctKeywords); } public KeywordList createClone() { return new KeywordList(this.keywordChains); } public void replaceAll(KeywordList keywordsToReplace, Keyword newValue) { Objects.requireNonNull(newValue); // Remove keywordChains which should be replaced int foundPosition = -1; // remember position of the last found keyword for (Keyword specialFieldKeyword : keywordsToReplace) { int pos = keywordChains.indexOf(specialFieldKeyword); if (pos >= 0) { foundPosition = pos; keywordChains.remove(pos); } } // Add new keyword at right position if (foundPosition == -1) { add(newValue); } else { keywordChains.add(foundPosition, newValue); } } public void removeAll(KeywordList keywordsToRemove) { keywordChains.removeAll(keywordsToRemove.keywordChains); } public boolean add(Keyword keyword) { if (contains(keyword)) { return false; // Don't add duplicate keywordChains } return keywordChains.add(keyword); } /** * Keywords are separated by the given delimiter and an additional space, i.e. "one, two". */ public String getAsString(Character delimiter) { return keywordChains.stream().map(Keyword::toString).collect(Collectors.joining(delimiter + " ")); } public void add(String keywordsString) { add(new Keyword(keywordsString)); } @Override public Iterator<Keyword> iterator() { return keywordChains.iterator(); } public int size() { return keywordChains.size(); } public boolean isEmpty() { return keywordChains.isEmpty(); } public boolean contains(Keyword o) { return keywordChains.contains(o); } public boolean contains(String keywordString) { return contains(new Keyword(keywordString)); } public boolean remove(Keyword o) { return keywordChains.remove(o); } public boolean remove(String keywordsString) { return keywordChains.remove(new Keyword(keywordsString)); } public void addAll(KeywordList keywordsToAdd) { keywordChains.addAll(keywordsToAdd.keywordChains); } public void retainAll(KeywordList keywordToRetain) { keywordChains.retainAll(keywordToRetain.keywordChains); } public void clear() { keywordChains.clear(); } public Keyword get(int index) { return keywordChains.get(index); } public Stream<Keyword> stream() { return keywordChains.stream(); } @Override public String toString() { return getAsString(','); } public Set<String> toStringList() { return keywordChains.stream().map(Keyword::toString).collect(Collectors.toSet()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } KeywordList keywords1 = (KeywordList) o; return Objects.equals(new HashSet<>(keywordChains), new HashSet<>(keywords1.keywordChains)); } @Override public int hashCode() { return Objects.hash(keywordChains); } }
6,192
29.209756
121
java
null
jabref-main/src/main/java/org/jabref/model/entry/LinkedFile.java
package org.jabref.model.entry; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import javafx.beans.Observable; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.FilePreferences; /** * Represents the link to an external file (e.g. associated PDF file). * This class is {@link Serializable} which is needed for drag and drop in gui */ @AllowedToUseLogic("Uses FileUtil from logic") public class LinkedFile implements Serializable { private static final String REGEX_URL = "^((?:https?\\:\\/\\/|www\\.)(?:[-a-z0-9]+\\.)*[-a-z0-9]+.*)"; private static final Pattern URL_PATTERN = Pattern.compile(REGEX_URL); private static final LinkedFile NULL_OBJECT = new LinkedFile("", Path.of(""), ""); // We have to mark these properties as transient because they can't be serialized directly private transient StringProperty description = new SimpleStringProperty(); private transient StringProperty link = new SimpleStringProperty(); private transient StringProperty fileType = new SimpleStringProperty(); public LinkedFile(String description, Path link, String fileType) { this(Objects.requireNonNull(description), Objects.requireNonNull(link).toString(), Objects.requireNonNull(fileType)); } /** * Constructor for non-valid paths. We need to parse them, because the GUI needs to render it. */ public LinkedFile(String description, String link, String fileType) { this.description.setValue(Objects.requireNonNull(description)); setLink(link); this.fileType.setValue(Objects.requireNonNull(fileType)); } public LinkedFile(URL link, String fileType) { this("", Objects.requireNonNull(link).toString(), Objects.requireNonNull(fileType)); } public LinkedFile(String description, URL link, String fileType) { this(description, Objects.requireNonNull(link).toString(), Objects.requireNonNull(fileType)); } public StringProperty descriptionProperty() { return description; } public StringProperty linkProperty() { return link; } public StringProperty fileTypeProperty() { return fileType; } public String getFileType() { return fileType.get(); } public void setFileType(String fileType) { this.fileType.setValue(fileType); } public String getDescription() { return description.get(); } public void setDescription(String description) { this.description.setValue(description); } public String getLink() { return link.get(); } public void setLink(String link) { if (!isOnlineLink(link)) { this.link.setValue(link.replace("\\", "/")); } else { this.link.setValue(link); } } public Observable[] getObservables() { return new Observable[] {this.link, this.description, this.fileType}; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof LinkedFile that) { return Objects.equals(description.get(), that.description.get()) && Objects.equals(link.get(), that.link.get()) && Objects.equals(fileType.get(), that.fileType.get()); } return false; } /** * Writes serialized object to ObjectOutputStream, automatically called */ private void writeObject(ObjectOutputStream out) throws IOException { out.writeUTF(getFileType()); out.writeUTF(getLink()); out.writeUTF(getDescription()); out.flush(); } /** * Reads serialized object from ObjectInputStreamm, automatically called */ private void readObject(ObjectInputStream in) throws IOException { fileType = new SimpleStringProperty(in.readUTF()); link = new SimpleStringProperty(in.readUTF()); description = new SimpleStringProperty(in.readUTF()); } /** * Checks if the given String is an online link * * @param toCheck The String to check * @return <code>true</code>, if it starts with "http://", "https://" or contains "www."; <code>false</code> otherwise */ public static boolean isOnlineLink(String toCheck) { String normalizedFilePath = toCheck.trim().toLowerCase(); return URL_PATTERN.matcher(normalizedFilePath).matches(); } @Override public int hashCode() { return Objects.hash(description.get(), link.get(), fileType.get()); } @Override public String toString() { return "ParsedFileField{" + "description='" + description.get() + '\'' + ", link='" + link.get() + '\'' + ", fileType='" + fileType.get() + '\'' + '}'; } public boolean isEmpty() { return NULL_OBJECT.equals(this); } public boolean isOnlineLink() { return isOnlineLink(link.get()); } public Optional<Path> findIn(BibDatabaseContext databaseContext, FilePreferences filePreferences) { List<Path> dirs = databaseContext.getFileDirectories(filePreferences); return findIn(dirs); } /** * Tries to find the file in the given directories and returns the path to the file (if found). Returns an empty * optional if the file cannot be found. */ public Optional<Path> findIn(List<Path> directories) { try { if (link.get().isEmpty()) { // We do not want to match empty paths (which could be any file or none ?!) return Optional.empty(); } Path file = Path.of(link.get()); if (file.isAbsolute() || directories.isEmpty()) { if (Files.exists(file)) { return Optional.of(file); } else { return Optional.empty(); } } else { return FileUtil.find(link.get(), directories); } } catch (InvalidPathException ex) { return Optional.empty(); } } }
6,640
31.714286
125
java
null
jabref-main/src/main/java/org/jabref/model/entry/Month.java
package org.jabref.model.entry; import java.util.Optional; import org.jabref.logic.bibtex.FieldWriter; import org.jabref.model.strings.StringUtil; /** * Represents a Month of the Year. */ public enum Month { JANUARY("January", "jan", 1), FEBRUARY("February", "feb", 2), MARCH("March", "mar", 3), APRIL("April", "apr", 4), MAY("May", "may", 5), JUNE("June", "jun", 6), JULY("July", "jul", 7), AUGUST("August", "aug", 8), SEPTEMBER("September", "sep", 9), OCTOBER("October", "oct", 10), NOVEMBER("November", "nov", 11), DECEMBER("December", "dec", 12); private final String fullName; private final String shortName; private final String twoDigitNumber; private final int number; Month(String fullName, String shortName, int number) { this.fullName = fullName; this.shortName = shortName; this.twoDigitNumber = String.format("%02d", number); this.number = number; } /** * Find month by one-based number. * If the number is not in the valid range, then an empty Optional is returned. * * @param number 1-12 is valid */ public static Optional<Month> getMonthByNumber(int number) { for (Month month : Month.values()) { if (month.number == number) { return Optional.of(month); } } return Optional.empty(); } /** * Find month by shortName (3 letters) case insensitive. * If no matching month is found, then an empty Optional is returned. * * @param shortName "jan", "feb", ... */ public static Optional<Month> getMonthByShortName(String shortName) { for (Month month : Month.values()) { if (month.shortName.equalsIgnoreCase(shortName)) { return Optional.of(month); } } return Optional.empty(); } /** * This method accepts three types of months: * - Single and Double Digit months from 1 to 12 (01 to 12) * - 3 Digit BibTeX strings (jan, feb, mar...) possibly with # prepended * - Full English Month identifiers. * * @param value the given value * @return the corresponding Month instance */ public static Optional<Month> parse(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // Much more liberal matching covering most known abbreviations etc. String testString = value.replace("#", "").trim(); if (testString.length() > 3) { testString = testString.substring(0, 3); } Optional<Month> month = Month.getMonthByShortName(testString); if (month.isPresent()) { return month; } month = Month.parseGermanShortMonth(testString); if (month.isPresent()) { return month; } try { int number = Integer.parseInt(value); return Month.getMonthByNumber(number); } catch (NumberFormatException e) { return Optional.empty(); } } /** * Parses a month having the string in German standard form such as * "Oktober" or in German short form such as "Okt" * * @param value a String that represents a month in German form * @return the corresponding month instance, empty if input is not in German * form */ static Optional<Month> parseGermanShortMonth(String value) { value = value.toLowerCase(); switch (value) { case "jan": case "januar": return Month.getMonthByNumber(1); case "feb": case "februar": return Month.getMonthByNumber(2); case "mär": case "mae": case "märz": case "maerz": return Month.getMonthByNumber(3); case "apr": case "april": return Month.getMonthByNumber(4); case "mai": return Month.getMonthByNumber(5); case "jun": case "juni": return Month.getMonthByNumber(6); case "jul": case "juli": return Month.getMonthByNumber(7); case "aug": case "august": return Month.getMonthByNumber(8); case "sep": case "september": return Month.getMonthByNumber(9); case "okt": case "oktober": return Month.getMonthByNumber(10); case "nov": case "november": return Month.getMonthByNumber(11); case "dez": case "dezember": return Month.getMonthByNumber(12); default: return Optional.empty(); } } /** * Returns the name of a Month in a short (3-letter) format. (jan, feb, mar, ...) * * @return 3-letter identifier for a Month */ public String getShortName() { return shortName; } /** * Returns the month in JabRef format. The format is the short 3-digit name surrounded by a '#' (FieldWriter.BIBTEX_STRING_START_END_SYMBOL). * Example: #jan#, #feb#, etc. * <p> * See <a href="https://github.com/JabRef/jabref/issues/263#issuecomment-151246595">Issue 263</a> for a discussion on that thing. * This seems to be an <em>invalid</em> format in terms of plain BiBTeX, but a <em>valid</em> format in the case of JabRef. * The documentation is available at the <a href="https://docs.jabref.org/fields/strings">Strings help</a> of JabRef. * * @return Month in JabRef format */ public String getJabRefFormat() { return String.format(FieldWriter.BIBTEX_STRING_START_END_SYMBOL + "%s" + FieldWriter.BIBTEX_STRING_START_END_SYMBOL, shortName); } /** * Returns the number of the Month in a 1-indexed fashion: 1 -> January, 2 -> February etc. * * @return number of the month in the Year */ public int getNumber() { return number; } /** * Returns the name of the long in unabbreviated english. * * @return Month */ public String getFullName() { return fullName; } /** * Returns the number of the Month in a 1-indexed fashion using exactly two digits: 01 -> January, 02 -> February... * * @return number of the month in the Year with two digits */ public String getTwoDigitNumber() { return twoDigitNumber; } }
6,592
30.545455
145
java
null
jabref-main/src/main/java/org/jabref/model/entry/ParsedEntryLink.java
package org.jabref.model.entry; import java.util.Objects; import java.util.Optional; import org.jabref.model.database.BibDatabase; public class ParsedEntryLink { private String key; private Optional<BibEntry> linkedEntry; private BibDatabase database; public ParsedEntryLink(String key, BibDatabase database) { this.key = key; this.linkedEntry = database.getEntryByCitationKey(this.key); this.database = database; } public ParsedEntryLink(BibEntry bibEntry) { this.key = bibEntry.getCitationKey().orElse(""); this.linkedEntry = Optional.of(bibEntry); } public String getKey() { return key; } public Optional<BibEntry> getLinkedEntry() { return linkedEntry; } public void setKey(String newKey) { this.key = newKey; this.linkedEntry = getDatabase().getEntryByCitationKey(this.key); } @Override public int hashCode() { return Objects.hash(key, linkedEntry); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ParsedEntryLink)) { return false; } ParsedEntryLink other = (ParsedEntryLink) obj; return Objects.equals(key, other.key) && Objects.equals(linkedEntry, other.linkedEntry); } public BibDatabase getDatabase() { return database; } }
1,444
23.491525
96
java
null
jabref-main/src/main/java/org/jabref/model/entry/SharedBibEntryData.java
package org.jabref.model.entry; import com.google.common.base.MoreObjects; /** * Stores all information needed to manage entries on a shared (SQL) database. */ public class SharedBibEntryData implements Comparable<SharedBibEntryData> { // This id is set by the remote database system (DBS). // It has to be unique on remote DBS for all connected JabRef instances. // The old id above does not satisfy this requirement. // This is "ID" in JabDrive sync private int sharedID; // Needed for version controlling if used on shared database // This is "Revision" in JabDrive sync private int version; public SharedBibEntryData() { this.sharedID = -1; this.version = 1; } public int getSharedID() { return sharedID; } public void setSharedID(int sharedID) { this.sharedID = sharedID; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("sharedID", sharedID) .add("version", version) .toString(); } @Override public int compareTo(SharedBibEntryData o) { if (this.sharedID == o.sharedID) { return Integer.compare(this.version, o.version); } else { return Integer.compare(this.sharedID, o.sharedID); } } }
1,527
25.344828
78
java
null
jabref-main/src/main/java/org/jabref/model/entry/event/EntriesEvent.java
package org.jabref.model.entry.event; import java.util.List; import java.util.Objects; import org.jabref.model.database.event.BibDatabaseContextChangedEvent; import org.jabref.model.entry.BibEntry; /** * This abstract class pretends a minimal set of attributes and methods which an entries event should have. */ public abstract class EntriesEvent extends BibDatabaseContextChangedEvent { private final List<BibEntry> bibEntries; private final EntriesEventSource location; /** * @param bibEntries List of BibEntry objects which are involved in this event */ public EntriesEvent(List<BibEntry> bibEntries) { this(bibEntries, EntriesEventSource.LOCAL); } /** * @param bibEntries List of BibEntry objects which are involved in this event * @param location Location affected by this event */ public EntriesEvent(List<BibEntry> bibEntries, EntriesEventSource location) { super(); this.bibEntries = Objects.requireNonNull(bibEntries); this.location = Objects.requireNonNull(location); } public List<BibEntry> getBibEntries() { return this.bibEntries; } public EntriesEventSource getEntriesEventSource() { return this.location; } }
1,257
28.952381
107
java
null
jabref-main/src/main/java/org/jabref/model/entry/event/EntriesEventSource.java
package org.jabref.model.entry.event; /** * This enum represents the context EntriesEvents were sent from. */ public enum EntriesEventSource { LOCAL, SHARED, UNDO, CLEANUP_TIMESTAMP, SAVE_ACTION }
220
16
65
java
null
jabref-main/src/main/java/org/jabref/model/entry/event/EntryChangedEvent.java
package org.jabref.model.entry.event; import java.util.Collections; import org.jabref.model.entry.BibEntry; /** * <code>EntryChangedEvent</code> is fired when a <code>BibEntry</code> has been changed. */ public class EntryChangedEvent extends EntriesEvent { /** * @param bibEntry <code>BibEntry</code> object the changes were applied on. */ public EntryChangedEvent(BibEntry bibEntry) { super(Collections.singletonList(bibEntry)); } /** * @param bibEntry <code>BibEntry</code> object the changes were applied on. * @param location Location affected by this event */ public EntryChangedEvent(BibEntry bibEntry, EntriesEventSource location) { super(Collections.singletonList(bibEntry), location); } public BibEntry getBibEntry() { // An entryChangedEvent should only have one BibEntry, but its parent class stores a List<BibEntry> return getBibEntries().get(0); } }
962
28.181818
107
java
null
jabref-main/src/main/java/org/jabref/model/entry/event/FieldAddedOrRemovedEvent.java
package org.jabref.model.entry.event; import org.jabref.model.FieldChange; public class FieldAddedOrRemovedEvent extends FieldChangedEvent { public FieldAddedOrRemovedEvent(FieldChange fieldChange, EntriesEventSource location) { super(fieldChange, location); } }
282
24.727273
91
java
null
jabref-main/src/main/java/org/jabref/model/entry/event/FieldChangedEvent.java
package org.jabref.model.entry.event; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; /** * <code>FieldChangedEvent</code> is fired when a field of <code>BibEntry</code> has been modified, removed or added. */ public class FieldChangedEvent extends EntryChangedEvent { private final Field field; private final String newValue; private final String oldValue; private int majorCharacterChange = 0; /** * @param bibEntry Affected BibEntry object * @param field Name of field which has been changed * @param oldValue old field value * @param newValue new field value * @param location Location affected by this event */ public FieldChangedEvent(BibEntry bibEntry, Field field, String newValue, String oldValue, EntriesEventSource location) { super(bibEntry, location); this.field = field; this.newValue = newValue; this.oldValue = oldValue; this.majorCharacterChange = computeMajorCharacterChange(oldValue, newValue); } /** * @param bibEntry Affected BibEntry object * @param field Name of field which has been changed * @param newValue new field value */ public FieldChangedEvent(BibEntry bibEntry, Field field, String newValue, String oldValue) { super(bibEntry); this.field = field; this.newValue = newValue; this.oldValue = oldValue; this.majorCharacterChange = computeMajorCharacterChange(oldValue, newValue); } /** * @param location Location affected by this event */ public FieldChangedEvent(FieldChange fieldChange, EntriesEventSource location) { super(fieldChange.getEntry(), location); this.field = fieldChange.getField(); this.newValue = fieldChange.getNewValue(); this.oldValue = fieldChange.getOldValue(); this.majorCharacterChange = computeMajorCharacterChange(oldValue, newValue); } public FieldChangedEvent(FieldChange fieldChange) { this(fieldChange, EntriesEventSource.LOCAL); } private int computeMajorCharacterChange(String oldValue, String newValue) { // We do == because of performance reasons if (oldValue == newValue) { return 0; } else if ((oldValue == null) && (newValue != null)) { return newValue.length(); } else if ((newValue == null) && (oldValue != null)) { return oldValue.length(); } else if ((oldValue.length() == newValue.length()) && !oldValue.equals(newValue)) { return newValue.length(); } else { return Math.abs(newValue.length() - oldValue.length()); } } public Field getField() { return field; } public String getNewValue() { return newValue; } public String getOldValue() { return oldValue; } public int getMajorCharacterChange() { return majorCharacterChange; } }
3,061
32.282609
117
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/AMSField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; public enum AMSField implements Field { FJOURNAL("fjournal"); private final String name; private final String displayName; private final Set<FieldProperty> properties; AMSField(String name) { this.name = name; this.displayName = null; this.properties = EnumSet.noneOf(FieldProperty.class); } AMSField(String name, String displayName) { this.name = name; this.displayName = displayName; this.properties = EnumSet.noneOf(FieldProperty.class); } AMSField(String name, String displayName, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = displayName; this.properties = EnumSet.of(first, rest); } AMSField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = null; this.properties = EnumSet.of(first, rest); } public static <T> Optional<AMSField> fromName(T type, String name) { return Arrays.stream(AMSField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } @Override public String getDisplayName() { if (displayName == null) { return Field.super.getDisplayName(); } else { return displayName; } } }
1,764
24.214286
91
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/BibField.java
package org.jabref.model.entry.field; import java.util.Objects; public record BibField(Field field, FieldPriority priority) implements Comparable<BibField> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BibField)) { return false; } BibField other = (BibField) o; return field.getName().equalsIgnoreCase(other.field.getName()); } @Override public int hashCode() { return Objects.hash(field.getName()); } @Override public String toString() { return "BibField{" + "field=" + field.getDisplayName() + ", priority=" + priority + '}'; } @Override public int compareTo(BibField o) { return field.getName().compareTo(o.field.getName()); } }
881
22.837838
93
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/BiblatexApaField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; import org.jabref.model.entry.types.BiblatexApaEntryType; public enum BiblatexApaField implements Field { AMENDMENT("amendment"), ARTICLE("article"), CITATION("citation"), CITATION_CITEORG("citation_citeorg"), CITATION_CITEDATE("citation_citedate", FieldProperty.DATE), CITATION_CITEINFO("citation_citeinfo"), SECTION("section", FieldProperty.NUMERIC), SOURCE("source"); private final String name; private final String displayName; private final Set<FieldProperty> properties; BiblatexApaField(String name) { this.name = name; this.displayName = null; this.properties = EnumSet.noneOf(FieldProperty.class); } BiblatexApaField(String name, String displayName) { this.name = name; this.displayName = displayName; this.properties = EnumSet.noneOf(FieldProperty.class); } BiblatexApaField(String name, String displayName, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = displayName; this.properties = EnumSet.of(first, rest); } BiblatexApaField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = null; this.properties = EnumSet.of(first, rest); } public static <T> Optional<BiblatexApaField> fromName(T type, String name) { if (!(type instanceof BiblatexApaEntryType)) { return Optional.empty(); } return Arrays.stream(BiblatexApaField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } @Override public String getDisplayName() { if (displayName == null) { return Field.super.getDisplayName(); } else { return displayName; } } }
2,252
26.47561
99
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/BiblatexSoftwareField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; import org.jabref.model.entry.types.BiblatexSoftwareEntryType; public enum BiblatexSoftwareField implements Field { HALID("hal_id"), HALVERSION("hal_version"), INTRODUCEDIN("introducedin"), LICENSE("license"), RELATEDTYPE("relatedtype"), RELATEDSTRING("relatedstring"), REPOSITORY("repository"), SWHID("swhid"); private final String name; private final String displayName; private final Set<FieldProperty> properties; BiblatexSoftwareField(String name) { this.name = name; this.displayName = null; this.properties = EnumSet.noneOf(FieldProperty.class); } BiblatexSoftwareField(String name, String displayName) { this.name = name; this.displayName = displayName; this.properties = EnumSet.noneOf(FieldProperty.class); } BiblatexSoftwareField(String name, String displayName, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = displayName; this.properties = EnumSet.of(first, rest); } BiblatexSoftwareField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = null; this.properties = EnumSet.of(first, rest); } public static <T> Optional<BiblatexSoftwareField> fromName(T type, String name) { if (!(type instanceof BiblatexSoftwareEntryType)) { return Optional.empty(); } return Arrays.stream(BiblatexSoftwareField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } @Override public String getDisplayName() { if (displayName == null) { return Field.super.getDisplayName(); } else { return displayName; } } }
2,228
26.182927
104
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/Field.java
package org.jabref.model.entry.field; import java.util.Optional; import java.util.Set; import org.jabref.model.strings.StringUtil; public interface Field { /** * properties contains mappings to tell the EntryEditor to add a specific function to this field, * for instance a dropdown for selecting the month for the month field. * * Note that this set needs to be mutable. This is required, because we allow standard fields to be modifiable via the UI. */ Set<FieldProperty> getProperties(); /** * @return A version of the field name more suitable for display */ default String getDisplayName() { return StringUtil.capitalizeFirst(getName()); } String getName(); boolean isStandardField(); default boolean isDeprecated() { return false; } default Optional<Field> getAlias() { return Optional.empty(); } default boolean isNumeric() { return getProperties().contains(FieldProperty.NUMERIC); } default boolean isMultiLineDefined() { return getProperties().contains(FieldProperty.MULTILINE_TEXT); } }
1,142
24.4
126
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/FieldFactory.java
package org.jabref.model.entry.field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jabref.model.entry.types.EntryType; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.OptionalUtil; public class FieldFactory { /** * Character separating field names that are to be used in sequence as fallbacks for a single column * (e.g. "author/editor" to use editor where author is not set): */ private static final String FIELD_OR_SEPARATOR = "/"; private static final String DELIMITER = ";"; public static String serializeOrFields(Field... fields) { return serializeOrFields(new OrFields(fields)); } public static String serializeOrFields(OrFields fields) { return fields.stream() .map(field -> { if (field instanceof UnknownField unknownField) { // In case a user has put a user-defined field, the casing of that field is kept return unknownField.getDisplayName(); } else { // In all fields known to JabRef, the name is used - JabRef knows better than the user how to case the field return field.getName(); } }) .collect(Collectors.joining(FIELD_OR_SEPARATOR)); } public static String serializeOrFieldsList(Set<OrFields> fields) { return fields.stream().map(FieldFactory::serializeOrFields).collect(Collectors.joining(DELIMITER)); } public static List<Field> getNotTextFieldNames() { return Arrays.asList(StandardField.DOI, StandardField.FILE, StandardField.URL, StandardField.URI, StandardField.ISBN, StandardField.ISSN, StandardField.MONTH, StandardField.DATE, StandardField.YEAR); } public static List<Field> getIdentifierFieldNames() { return Arrays.asList(StandardField.DOI, StandardField.EPRINT, StandardField.PMID); } public static OrFields parseOrFields(String fieldNames) { Set<Field> fields = Arrays.stream(fieldNames.split(FieldFactory.FIELD_OR_SEPARATOR)) .filter(StringUtil::isNotBlank) .map(FieldFactory::parseField) .collect(Collectors.toCollection(LinkedHashSet::new)); return new OrFields(fields); } public static Set<OrFields> parseOrFieldsList(String fieldNames) { return Arrays.stream(fieldNames.split(FieldFactory.DELIMITER)) .filter(StringUtil::isNotBlank) .map(FieldFactory::parseOrFields) .collect(Collectors.toCollection(LinkedHashSet::new)); } public static Set<Field> parseFieldList(String fieldNames) { return Arrays.stream(fieldNames.split(FieldFactory.DELIMITER)) .filter(StringUtil::isNotBlank) .map(FieldFactory::parseField) .collect(Collectors.toCollection(LinkedHashSet::new)); } public static String serializeFieldsList(Collection<Field> fields) { return fields.stream() .map(field -> { if (field instanceof UnknownField unknownField) { // In case a user has put a user-defined field, the casing of that field is kept return unknownField.getDisplayName(); } else { // In all fields known to JabRef, the name is used - JabRef knows better than the user how to case the field return field.getName(); } }) .collect(Collectors.joining(DELIMITER)); } /** * Type T is an entry type and is used to direct the mapping to the Java field class. * This somehow acts as filter, BibLaTeX "APA" entry type has field "article", but we want to have StandardField (if not explicitly requested otherwise) */ public static <T extends EntryType> Field parseField(T type, String fieldName) { // Check if the field name starts with "comment-" which indicates it's a UserSpecificCommentField if (fieldName.startsWith("comment-")) { String username = fieldName.substring("comment-".length()); return new UserSpecificCommentField(username); } return OptionalUtil.<Field>orElse( OptionalUtil.<Field>orElse( OptionalUtil.<Field>orElse( OptionalUtil.<Field>orElse( OptionalUtil.<Field>orElse( OptionalUtil.<Field>orElse( InternalField.fromName(fieldName), StandardField.fromName(fieldName)), SpecialField.fromName(fieldName)), IEEEField.fromName(fieldName)), BiblatexSoftwareField.fromName(type, fieldName)), BiblatexApaField.fromName(type, fieldName)), AMSField.fromName(type, fieldName)) .orElse(UnknownField.fromDisplayName(fieldName)); } public static Field parseField(String fieldName) { return parseField(null, fieldName); } public static Set<Field> getKeyFields() { return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.SINGLE_ENTRY_LINK) || field.getProperties().contains(FieldProperty.MULTIPLE_ENTRY_LINK)); } public static boolean isInternalField(Field field) { return field.getName().startsWith("__"); } public static Set<Field> getJournalNameFields() { return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.JOURNAL_NAME)); } /** * Returns a Set with all standard fields and including some common internal fields */ public static Set<Field> getCommonFields() { EnumSet<StandardField> allFields = EnumSet.allOf(StandardField.class); LinkedHashSet<Field> publicAndInternalFields = new LinkedHashSet<>(allFields.size() + 3); publicAndInternalFields.add(InternalField.INTERNAL_ALL_FIELD); publicAndInternalFields.add(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD); publicAndInternalFields.add(InternalField.KEY_FIELD); publicAndInternalFields.addAll(allFields); return publicAndInternalFields; } /** * Returns a sorted Set of Fields (by {@link Field#getDisplayName} with all fields without internal ones */ public static Set<Field> getAllFieldsWithOutInternal() { Set<Field> fields = new TreeSet<>(Comparator.comparing(Field::getDisplayName)); fields.addAll(getAllFields()); fields.removeAll(EnumSet.allOf(InternalField.class)); return fields; } /** * Returns a List with all standard fields and the citation key field */ public static Set<Field> getStandardFieldsWithCitationKey() { EnumSet<StandardField> allFields = EnumSet.allOf(StandardField.class); LinkedHashSet<Field> standardFieldsWithBibtexKey = new LinkedHashSet<>(allFields.size() + 1); standardFieldsWithBibtexKey.add(InternalField.KEY_FIELD); standardFieldsWithBibtexKey.addAll(allFields); return standardFieldsWithBibtexKey; } public static Set<Field> getBookNameFields() { return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.BOOK_NAME)); } public static Set<Field> getPersonNameFields() { return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.PERSON_NAMES)); } private static Set<Field> getFieldsFiltered(Predicate<Field> selector) { return getAllFields().stream() .filter(selector) .collect(Collectors.toSet()); } private static Set<Field> getAllFields() { Set<Field> fields = new HashSet<>(); fields.addAll(EnumSet.allOf(BiblatexApaField.class)); fields.addAll(EnumSet.allOf(BiblatexSoftwareField.class)); fields.addAll(EnumSet.allOf(IEEEField.class)); fields.addAll(EnumSet.allOf(InternalField.class)); fields.addAll(EnumSet.allOf(SpecialField.class)); fields.addAll(EnumSet.allOf(StandardField.class)); fields.removeIf(field -> field instanceof UserSpecificCommentField); return fields; } /** * These are the fields JabRef always displays as default {@link org.jabref.preferences.JabRefPreferences#setLanguageDependentDefaultValues()} * <p> * A user can change them. The change is currently stored in the preferences only and not explicitly exposed as * separate preferences object */ public static List<Field> getDefaultGeneralFields() { List<Field> defaultGeneralFields = new ArrayList<>(Arrays.asList(StandardField.DOI, StandardField.CROSSREF, StandardField.KEYWORDS, StandardField.EPRINT, StandardField.URL, StandardField.FILE, StandardField.GROUPS, StandardField.OWNER, StandardField.TIMESTAMP)); defaultGeneralFields.addAll(EnumSet.allOf(SpecialField.class)); return defaultGeneralFields; } // TODO: This should ideally be user configurable! (https://github.com/JabRef/jabref/issues/9840) // TODO: Move somewhere more appropriate in the future public static boolean isMultiLineField(final Field field, List<Field> nonWrappableFields) { return field.getProperties().contains(FieldProperty.MULTILINE_TEXT) || nonWrappableFields.contains(field); } }
9,909
44.045455
270
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/FieldPriority.java
package org.jabref.model.entry.field; import java.util.Locale; /** * Determines whether the field is in the Optional1 or Optional2 tab * * See {@link org.jabref.model.entry.BibEntryType#getPrimaryOptionalFields()} * and {@link org.jabref.model.entry.BibEntryType#getSecondaryOptionalFields()}. */ public enum FieldPriority { IMPORTANT, DETAIL; @Override public String toString() { return this.name().toLowerCase(Locale.ROOT); } }
466
22.35
80
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/FieldProperty.java
package org.jabref.model.entry.field; public enum FieldProperty { BOOK_NAME, DATE, DOI, EDITOR_TYPE, EPRINT, EXTERNAL, FILE_EDITOR, GENDER, ISBN, JOURNAL_NAME, LANGUAGE, MONTH, MULTIPLE_ENTRY_LINK, MULTILINE_TEXT, NUMERIC, PAGES, PAGINATION, PERSON_NAMES, PUBLICATION_STATE, SINGLE_ENTRY_LINK, TYPE, VERBATIM, YES_NO, COMMENT }
425
13.689655
37
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/IEEEField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; /** * IEEE BSTctl fields */ public enum IEEEField implements Field { CTLALT_STRETCH_FACTOR("ctlalt_stretch_factor", FieldProperty.NUMERIC), CTLDASH_REPEATED_NAMES("ctldash_repeated_names", FieldProperty.YES_NO), CTLMAX_NAMES_FORCED_ETAL("ctlmax_names_forced_etal", FieldProperty.NUMERIC), CTLNAME_FORMAT_STRING("ctlname_format_string", FieldProperty.VERBATIM), CTLNAME_LATEX_CMD("ctlname_latex_cmd", FieldProperty.VERBATIM), CTLNAME_URL_PREFIX("ctlname_url_prefix", FieldProperty.VERBATIM), CTLNAMES_SHOW_ETAL("ctlnames_show_etal", FieldProperty.NUMERIC), CTLUSE_ALT_SPACING("ctluse_alt_spacing", FieldProperty.YES_NO), CTLUSE_ARTICLE_NUMBER("ctluse_article_number", FieldProperty.YES_NO), CTLUSE_FORCED_ETAL("ctluse_forced_etal", FieldProperty.YES_NO), CTLUSE_PAPER("ctluse_paper", FieldProperty.YES_NO), CTLUSE_URL("ctluse_url", FieldProperty.YES_NO); private final String name; private final Set<FieldProperty> properties; IEEEField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.properties = EnumSet.of(first, rest); } public static Optional<IEEEField> fromName(String name) { return Arrays.stream(IEEEField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } @Override public Set<FieldProperty> getProperties() { return properties; } }
1,763
31.666667
80
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/InternalField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; /** * JabRef internal fields. These are not normal fields but mostly placeholders with special functions. */ public enum InternalField implements Field { /** * The BibTeX key (which is used at \cite{key} in LaTeX */ KEY_FIELD("citationkey"), /** * field which indicates the entrytype * * Example: @misc{key} */ TYPE_HEADER("entrytype"), /** * Used in old layout files */ OBSOLETE_TYPE_HEADER("bibtextype"), /** * used in old versions of JabRef. Currently used for conversion only */ MARKED_INTERNAL("__markedentry"), /** * Marker that the content is just a BibTeX string */ BIBTEX_STRING("__string"), /** * virtual field to denote "all fields". Used in the metadata serialization for save actions. */ INTERNAL_ALL_FIELD("all"), /** * virtual field to denote "all text fields". Used in the metadata serialization for save actions. */ INTERNAL_ALL_TEXT_FIELDS_FIELD("all-text-fields"), /** * all field names starting with "Jabref-internal-" are not appearing in .bib files */ INTERNAL_ID_FIELD("JabRef-internal-id"); private final String name; private final Set<FieldProperty> properties; InternalField(String name) { this.name = name; this.properties = EnumSet.noneOf(FieldProperty.class); } InternalField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.properties = EnumSet.of(first, rest); } public static Optional<InternalField> fromName(String name) { if ("bibtexkey".equalsIgnoreCase(name)) { // For backwards compatibility return Optional.of(InternalField.KEY_FIELD); } return Arrays.stream(InternalField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } }
2,339
24.16129
102
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/OrFields.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.StringJoiner; public class OrFields extends LinkedHashSet<Field> implements Comparable<OrFields> { public OrFields(Field field) { add(field); } public OrFields(Field... fields) { addAll(Arrays.asList(fields)); } public OrFields(Collection<Field> fields) { addAll(fields); } public String getDisplayName() { StringJoiner joiner = new StringJoiner("/"); for (Field field : this) { joiner.add(field.getDisplayName()); } return joiner.toString(); } public Field getPrimary() { return this.iterator().next(); } @Override public int compareTo(OrFields o) { return FieldFactory.serializeOrFields(this).compareTo(FieldFactory.serializeOrFields(o)); } }
930
22.871795
97
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/SpecialField.java
package org.jabref.model.entry.field; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.Set; import org.jabref.model.entry.KeywordList; public enum SpecialField implements Field { PRINTED("printed", SpecialFieldValue.PRINTED ), PRIORITY("priority", SpecialFieldValue.CLEAR_PRIORITY, SpecialFieldValue.PRIORITY_HIGH, SpecialFieldValue.PRIORITY_MEDIUM, SpecialFieldValue.PRIORITY_LOW ), QUALITY("qualityassured", SpecialFieldValue.QUALITY_ASSURED ), RANKING("ranking", SpecialFieldValue.CLEAR_RANK, SpecialFieldValue.RANK_1, SpecialFieldValue.RANK_2, SpecialFieldValue.RANK_3, SpecialFieldValue.RANK_4, SpecialFieldValue.RANK_5 ), READ_STATUS("readstatus", SpecialFieldValue.CLEAR_READ_STATUS, SpecialFieldValue.READ, SpecialFieldValue.SKIMMED ), RELEVANCE("relevance", SpecialFieldValue.RELEVANT ); private final List<SpecialFieldValue> values; private final KeywordList keywords; private final HashMap<String, SpecialFieldValue> map; private final String fieldName; SpecialField(String fieldName, SpecialFieldValue... values) { this.fieldName = fieldName; this.values = new ArrayList<>(); this.keywords = new KeywordList(); this.map = new HashMap<>(); for (SpecialFieldValue value : values) { this.values.add(value); value.getKeyword().ifPresent(keywords::add); value.getFieldValue().ifPresent(fieldValue -> map.put(fieldValue, value)); } } public List<SpecialFieldValue> getValues() { return this.values; } public KeywordList getKeyWords() { return this.keywords; } public static Optional<SpecialField> fromName(String name) { return Arrays.stream(SpecialField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } public boolean isSingleValueField() { return this.values.size() == 1; } public Optional<SpecialFieldValue> parseValue(String value) { return Optional.ofNullable(map.get(value)); } @Override public Set<FieldProperty> getProperties() { return EnumSet.noneOf(FieldProperty.class); } @Override public String getName() { return fieldName; } @Override public boolean isStandardField() { return false; } }
2,713
25.349515
86
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/SpecialFieldValue.java
package org.jabref.model.entry.field; import java.util.Optional; import org.jabref.model.entry.Keyword; public enum SpecialFieldValue { PRINTED("printed"), CLEAR_PRIORITY(null), PRIORITY_HIGH("prio1"), PRIORITY_MEDIUM("prio2"), PRIORITY_LOW("prio3"), QUALITY_ASSURED("qualityAssured"), CLEAR_RANK(null), RANK_1("rank1"), RANK_2("rank2"), RANK_3("rank3"), RANK_4("rank4"), RANK_5("rank5"), CLEAR_READ_STATUS(null), READ("read"), SKIMMED("skimmed"), RELEVANT("relevant"); // keyword used in keyword field private final Optional<Keyword> keyword; /** * @param keyword - The keyword to be used at BibTex's keyword field. May be "null" if no keyword is to be set */ SpecialFieldValue(String keyword) { this.keyword = Optional.ofNullable(keyword).map(Keyword::new); } public static SpecialFieldValue getRating(int ranking) { return switch (ranking) { case 0 -> CLEAR_RANK; case 1 -> RANK_1; case 2 -> RANK_2; case 3 -> RANK_3; case 4 -> RANK_4; case 5 -> RANK_5; default -> throw new UnsupportedOperationException(ranking + "is not a valid ranking"); }; } public Optional<Keyword> getKeyword() { return keyword; } public Optional<String> getFieldValue() { return keyword.map(Keyword::toString); } public int toRating() { return switch (this) { case CLEAR_RANK -> 0; case RANK_1 -> 1; case RANK_2 -> 2; case RANK_3 -> 3; case RANK_4 -> 4; case RANK_5 -> 5; default -> throw new UnsupportedOperationException(this + "is not a valid ranking"); }; } }
1,806
24.097222
114
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/StandardField.java
package org.jabref.model.entry.field; import java.util.Arrays; import java.util.EnumSet; import java.util.Optional; import java.util.Set; import org.jabref.gui.fieldeditors.FieldNameLabel; /** * Standard BibTeX and BibLaTeX fields, as well as "normal" JabRef specific fields. * * See {@link FieldNameLabel#getDescription(org.jabref.model.entry.field.Field)} for a description of each field. */ public enum StandardField implements Field { ABSTRACT("abstract", FieldProperty.MULTILINE_TEXT), ADDENDUM("addendum"), ADDRESS("address"), AFTERWORD("afterword", FieldProperty.PERSON_NAMES), ANNOTE("annote"), ANNOTATION("annotation"), ANNOTATOR("annotator", FieldProperty.PERSON_NAMES), ARCHIVEPREFIX("archiveprefix"), ASSIGNEE("assignee", FieldProperty.PERSON_NAMES), AUTHOR("author", FieldProperty.PERSON_NAMES), BOOKAUTHOR("bookauthor", FieldProperty.PERSON_NAMES), BOOKPAGINATION("bookpagination", FieldProperty.PAGINATION), BOOKSUBTITLE("booksubtitle", FieldProperty.BOOK_NAME), BOOKTITLE("booktitle", FieldProperty.BOOK_NAME), BOOKTITLEADDON("booktitleaddon"), CHAPTER("chapter"), COMMENTATOR("commentator", FieldProperty.PERSON_NAMES), COMMENT("comment", FieldProperty.COMMENT, FieldProperty.MULTILINE_TEXT), CROSSREF("crossref", FieldProperty.SINGLE_ENTRY_LINK), DATE("date", FieldProperty.DATE), DAY("day"), DAYFILED("dayfiled"), DOI("doi", "DOI", FieldProperty.DOI), EDITION("edition", FieldProperty.NUMERIC), EDITOR("editor", FieldProperty.PERSON_NAMES), EDITORA("editora", FieldProperty.PERSON_NAMES), EDITORB("editorb", FieldProperty.PERSON_NAMES), EDITORC("editorc", FieldProperty.PERSON_NAMES), EDITORTYPE("editortype", FieldProperty.EDITOR_TYPE), EDITORATYPE("editoratype", FieldProperty.EDITOR_TYPE), EDITORBTYPE("editorbtype", FieldProperty.EDITOR_TYPE), EDITORCTYPE("editorctype", FieldProperty.EDITOR_TYPE), EID("eid"), ENTRYSET("entryset", FieldProperty.MULTIPLE_ENTRY_LINK), EPRINT("eprint", FieldProperty.EPRINT), EPRINTCLASS("eprintclass"), EPRINTTYPE("eprinttype"), EVENTDATE("eventdate", FieldProperty.DATE), EVENTTITLE("eventtitle"), EVENTTITLEADDON("eventtitleaddon"), FILE("file", FieldProperty.FILE_EDITOR, FieldProperty.VERBATIM), FOREWORD("foreword", FieldProperty.PERSON_NAMES), FOLDER("folder"), GENDER("gender", FieldProperty.GENDER), HOLDER("holder", FieldProperty.PERSON_NAMES), HOWPUBLISHED("howpublished"), IDS("ids", FieldProperty.MULTIPLE_ENTRY_LINK), INSTITUTION("institution"), INTRODUCTION("introduction", FieldProperty.PERSON_NAMES), ISBN("isbn", "ISBN", FieldProperty.ISBN), ISRN("isrn", "ISRN"), ISSN("issn", "ISSN"), ISSUE("issue"), ISSUETITLE("issuetitle"), ISSUESUBTITLE("issuesubtitle"), JOURNAL("journal", FieldProperty.JOURNAL_NAME), JOURNALSUBTITLE("journalsubtitle", FieldProperty.JOURNAL_NAME), JOURNALTITLE("journaltitle", FieldProperty.JOURNAL_NAME), KEY("key"), KEYWORDS("keywords"), LANGUAGE("language", FieldProperty.LANGUAGE), LABEL("label"), LIBRARY("library"), LOCATION("location"), MAINSUBTITLE("mainsubtitle", FieldProperty.BOOK_NAME), MAINTITLE("maintitle", FieldProperty.BOOK_NAME), MAINTITLEADDON("maintitleaddon"), MONTH("month", FieldProperty.MONTH), MONTHFILED("monthfiled", FieldProperty.MONTH), NAMEADDON("nameaddon"), NATIONALITY("nationality"), NOTE("note"), NUMBER("number", FieldProperty.NUMERIC), ORGANIZATION("organization"), ORIGDATE("origdate", FieldProperty.DATE), ORIGLANGUAGE("origlanguage", FieldProperty.LANGUAGE), PAGES("pages", FieldProperty.PAGES), PAGETOTAL("pagetotal"), PAGINATION("pagination", FieldProperty.PAGINATION), PART("part"), PDF("pdf", "PDF"), PMID("pmid", "PMID", FieldProperty.NUMERIC), PS("ps", "PS"), PUBLISHER("publisher"), PUBSTATE("pubstate", FieldProperty.PUBLICATION_STATE), PRIMARYCLASS("primaryclass"), RELATED("related", FieldProperty.MULTIPLE_ENTRY_LINK), REPORTNO("reportno"), REVIEW("review", FieldProperty.MULTILINE_TEXT), REVISION("revision"), SCHOOL("school"), SERIES("series"), SHORTAUTHOR("shortauthor", FieldProperty.PERSON_NAMES), SHORTEDITOR("shorteditor", FieldProperty.PERSON_NAMES), SHORTTITLE("shorttitle"), SORTKEY("sortkey"), SORTNAME("sortname", FieldProperty.PERSON_NAMES), SUBTITLE("subtitle"), TITLE("title"), TITLEADDON("titleaddon"), TRANSLATOR("translator", FieldProperty.PERSON_NAMES), TYPE("type", FieldProperty.TYPE), URI("uri", "URI"), URL("url", "URL", FieldProperty.EXTERNAL, FieldProperty.VERBATIM), URLDATE("urldate", FieldProperty.DATE), VENUE("venue"), VERSION("version"), VOLUME("volume", FieldProperty.NUMERIC), VOLUMES("volumes", FieldProperty.NUMERIC), YEAR("year", FieldProperty.NUMERIC), YEARFILED("yearfiled"), MR_NUMBER("mrnumber"), ZBL_NUMBER("zbl"), // needed for fetcher XDATA("xdata", FieldProperty.MULTIPLE_ENTRY_LINK), XREF("xref", FieldProperty.SINGLE_ENTRY_LINK), // JabRef-specific fields GROUPS("groups"), OWNER("owner"), TIMESTAMP("timestamp", FieldProperty.DATE), CREATIONDATE("creationdate", FieldProperty.DATE), MODIFICATIONDATE("modificationdate", FieldProperty.DATE); public static Set<Field> AUTOMATIC_FIELDS = Set.of(OWNER, TIMESTAMP, CREATIONDATE, MODIFICATIONDATE); private final String name; private final String displayName; private final Set<FieldProperty> properties; StandardField(String name) { this.name = name; this.displayName = null; this.properties = EnumSet.noneOf(FieldProperty.class); } StandardField(String name, String displayName) { this.name = name; this.displayName = displayName; this.properties = EnumSet.noneOf(FieldProperty.class); } StandardField(String name, String displayName, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = displayName; this.properties = EnumSet.of(first, rest); } StandardField(String name, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = null; this.properties = EnumSet.of(first, rest); } public static Optional<StandardField> fromName(String name) { return Arrays.stream(StandardField.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return true; } @Override public String getDisplayName() { if (displayName == null) { return Field.super.getDisplayName(); } else { return displayName; } } }
7,110
34.555
113
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/UnknownField.java
package org.jabref.model.entry.field; import java.util.EnumSet; import java.util.Locale; import java.util.Objects; import java.util.Set; import org.jabref.model.strings.StringUtil; public class UnknownField implements Field { private String name; private final Set<FieldProperty> properties; private final String displayName; public UnknownField(String name) { this(name, StringUtil.capitalizeFirst(name)); } public UnknownField(String name, String displayName) { this.name = name; this.displayName = displayName; this.properties = EnumSet.noneOf(FieldProperty.class); } public UnknownField(String name, FieldProperty first, FieldProperty... rest) { this(name, StringUtil.capitalizeFirst(name), first, rest); } public UnknownField(String name, String displayName, FieldProperty first, FieldProperty... rest) { this.name = name; this.displayName = displayName; this.properties = EnumSet.of(first, rest); } public static UnknownField fromDisplayName(String displayName) { return new UnknownField(displayName.toLowerCase(Locale.ROOT), displayName); } @Override public Set<FieldProperty> getProperties() { return properties; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getDisplayName() { return displayName; } @Override public boolean isStandardField() { return false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Field)) { return false; } Field other = (Field) o; return name.equalsIgnoreCase(other.getName()); } @Override public int hashCode() { return Objects.hash(name.toLowerCase(Locale.ENGLISH)); } @Override public String toString() { return "UnknownField{" + "name='" + name + '\'' + '}'; } }
2,127
23.45977
102
java
null
jabref-main/src/main/java/org/jabref/model/entry/field/UserSpecificCommentField.java
package org.jabref.model.entry.field; import java.util.EnumSet; import java.util.Objects; import java.util.Set; public class UserSpecificCommentField implements Field { private static final Set<FieldProperty> PROPERTIES = EnumSet.of(FieldProperty.COMMENT, FieldProperty.MULTILINE_TEXT); private final String name; public UserSpecificCommentField(String username) { this.name = "comment-" + username; } @Override public Set<FieldProperty> getProperties() { return PROPERTIES; } @Override public String getName() { return name; } @Override public boolean isStandardField() { return false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Field)) { return false; } Field other = (Field) o; return name.equals(other.getName()); } @Override public int hashCode() { return Objects.hash(name); } @Override public String toString() { return "UnknownCommentField{" + "name='" + name + '\'' + '}'; } }
1,189
21.037037
121
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/ARK.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.util.Optional; /** * Archival Resource Key (ARK) identifiers are URLs that support long-term access to information. They are similar to DOIs * only that we don't know of any service that can extract bibliography information from ARKs. For this reason, if an ARK * is used in an eprint field, it will only be possible to open the ARK in the browner; no lookup * or extraction of biography information will be possible. * <br><br> * <p> * ARK identifiers are typically prefixed with "ark:/". Even though the prefix does not help identify the resource, it appears * to be the standard because many websites that feature ARKs, such as archive.org, include it. For the convenience of our users * and to provide them with ability to copy/paste the ark as is, we support arks with or without the prefix. * </p> */ public class ARK extends EprintIdentifier { private final String ark; private ARK(String ark) { this.ark = ark; } public static Optional<ARK> parse(String value) { // TODO: Validate ARK return Optional.of(new ARK(value)); } @Override public String getNormalized() { String cleanARK = ark.strip(); return cleanARK.replaceFirst("^ark:/", ""); } @Override public Optional<URI> getExternalURI() { return Optional.of(URI.create("https://n2t.net/ark:/" + getNormalized())); } }
1,464
34.731707
128
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/ArXivIdentifier.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.strings.StringUtil; /** * Identifier for the arXiv. See https://arxiv.org/help/arxiv_identifier */ public class ArXivIdentifier extends EprintIdentifier { private static final String ARXIV_PREFIX = "http(s)?://arxiv.org/(abs|pdf)/|arxiv|arXiv"; private final String identifier; private final String classification; private final String version; ArXivIdentifier(String identifier) { this(identifier, "", ""); } ArXivIdentifier(String identifier, String classification) { this(identifier, "", classification); } ArXivIdentifier(String identifier, String version, String classification) { this.identifier = identifier.trim(); this.version = version.trim(); this.classification = classification.trim(); } public static Optional<ArXivIdentifier> parse(String value) { String identifier = value.replaceAll(" ", ""); Pattern identifierPattern = Pattern.compile("(" + ARXIV_PREFIX + ")?\\s?:?\\s?(?<id>\\d{4}\\.\\d{4,5})(v(?<version>\\d+))?\\s?(\\[(?<classification>\\S+)\\])?"); Matcher identifierMatcher = identifierPattern.matcher(identifier); if (identifierMatcher.matches()) { return getArXivIdentifier(identifierMatcher); } Pattern oldIdentifierPattern = Pattern.compile("(" + ARXIV_PREFIX + ")?\\s?:?\\s?(?<id>(?<classification>[a-z\\-]+(\\.[A-Z]{2})?)/\\d{7})(v(?<version>\\d+))?"); Matcher oldIdentifierMatcher = oldIdentifierPattern.matcher(identifier); if (oldIdentifierMatcher.matches()) { return getArXivIdentifier(oldIdentifierMatcher); } return Optional.empty(); } private static Optional<ArXivIdentifier> getArXivIdentifier(Matcher matcher) { String id = matcher.group("id"); String classification = matcher.group("classification"); if (classification == null) { classification = ""; } String version = matcher.group("version"); if (version == null) { version = ""; } return Optional.of(new ArXivIdentifier(id, version, classification)); } public Optional<String> getClassification() { if (classification.isEmpty()) { return Optional.empty(); } else { return Optional.of(classification); } } @Override public String toString() { return "ArXivIdentifier{" + "identifier='" + identifier + '\'' + ", classification='" + classification + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArXivIdentifier that = (ArXivIdentifier) o; return Objects.equals(identifier, that.identifier) && Objects.equals(classification, that.classification); } @Override public int hashCode() { return Objects.hash(identifier, classification); } @Override public String getNormalized() { if (StringUtil.isNotBlank(version)) { return identifier + "v" + version; } else { return identifier; } } public String getNormalizedWithoutVersion() { return identifier; } @Override public Optional<URI> getExternalURI() { try { return Optional.of(new URI("https://arxiv.org/abs/" + getNormalized())); } catch (URISyntaxException e) { return Optional.empty(); } } }
3,870
30.471545
169
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/DOI.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for working with <a href="https://en.wikipedia.org/wiki/Digital_object_identifier">Digital object identifiers (DOIs)</a> and <a href="http://shortdoi.org">Short DOIs</a> */ @AllowedToUseLogic("because we want to have this class 'smart' an be able to parse obscure DOIs, too. For this, we need the LatexToUnicodeformatter.") public class DOI implements Identifier { public static final URI AGENCY_RESOLVER = URI.create("https://doi.org/doiRA"); public static final URI RESOLVER = URI.create("https://doi.org/"); private static final Logger LOGGER = LoggerFactory.getLogger(DOI.class); // Regex // (see http://www.doi.org/doi_handbook/2_Numbering.html) private static final String DOI_EXP = "" + "(?:urn:)?" // optional urn + "(?:doi:)?" // optional doi + "(" // begin group \1 + "10" // directory indicator + "(?:\\.[0-9]+)+" // registrant codes + "[/:%]" // divider + "(?:.+)" // suffix alphanumeric string + ")"; // end group \1 private static final String FIND_DOI_EXP = "" + "(?:urn:)?" // optional urn + "(?:doi:)?" // optional doi + "(" // begin group \1 + "10" // directory indicator + "(?:\\.[0-9]+)+" // registrant codes + "[/:]" // divider + "(?:[^\\s,;]+[^,;(\\.\\s)])" // suffix alphanumeric without " "/","/";" and not ending on "."/","/";" + ")"; // end group \1 // Regex (Short DOI) private static final String SHORT_DOI_SHORTCUT = "" + "^\\s*(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})\\s*$"; // eg https://doi.org/bfrhmx private static final String IN_TEXT_SHORT_DOI_SHORTCUT = "" + "(?:https?://)?(?:www\\.)?(?:doi\\.org/)([a-z0-9]{4,10})"; // eg https://doi.org/bfrhmx somewhere in the text private static final String SHORT_DOI_EXP_PREFIX = "" + "^(?:" // can begin with... + "\\s*(?:https?://)?(?:www\\.)?" // optional url parts "http(s)://"+"www." + "[a-zA-Z\\.]*doi[a-zA-Z\\.]*" // eg "dx.doi." or "doi.acm." or "doi." if with url, must include "doi", otherwise too ambiguous + "\\.[a-zA-Z]{2,10}/)?"; // ".org" or ".de" or ".academy" private static final String SHORT_DOI_EXP = "" + "(?:" // begin "any one of these" + "(?:[\\s/]?(?:(?:urn:)|(?:doi:)|(?:urn:doi:)))" // "doi:10/12ab" or " urn:10/12ab" or "/urn:doi:/10/12ab" ... + "|(?:\\s?/?)" // or "/10/12ab" or " /10/12ab" or "10/12ab" or " 10/12ab" + ")" // end "any one of these" + "(" // begin group \1 + "10" // directory indicator + "[/%:]" // divider + "[a-zA-Z0-9]{3,}" // at least 3 characters + ")" // end group \1 + "\\s*$"; // must be the end private static final String FIND_SHORT_DOI_EXP = "" + "(?:" // begin "any one of these" (but not none of those!) + "(?:(?:www\\.)?doi\\.org/)" // either doi.org + "|" // or any of the following with doi.org or not... + "(?:(?:doi.org/)?(?:(?:urn:)|(?:doi:)|(?:urn:doi:)))" // "doi:10/12ab" or " urn:10/12ab" or "/urn:doi:/10/12ab" or "doi.org/doi:10/12ab"... + ")" // end "any one of these" + "(" // begin group \1 + "10" // directory indicator + "[/%:]" // divider + "[a-zA-Z0-9]{3,}" // at least 3 characters + ")"; // end group \1 private static final String HTTP_EXP = "https?://[^\\s]+?" + DOI_EXP; private static final String SHORT_DOI_HTTP_EXP = "https?://[^\\s]+?" + SHORT_DOI_EXP; // Pattern private static final Pattern EXACT_DOI_PATT = Pattern.compile("^(?:https?://[^\\s]+?)?" + DOI_EXP + "$", Pattern.CASE_INSENSITIVE); private static final Pattern FIND_DOI_PATT = Pattern.compile("(?:https?://[^\\s]+?)?" + FIND_DOI_EXP, Pattern.CASE_INSENSITIVE); // Pattern (short DOI) private static final Pattern EXACT_SHORT_DOI_SHORTCUT = Pattern.compile(SHORT_DOI_SHORTCUT, Pattern.CASE_INSENSITIVE); // eg doi.org/bfrhmx (no "10/") private static final Pattern FIND_SHORT_DOI_SHORTCUT = Pattern.compile(IN_TEXT_SHORT_DOI_SHORTCUT, Pattern.CASE_INSENSITIVE); // eg doi.org/bfrhmx (no "10/") private static final Pattern EXACT_SHORT_DOI_PATT = Pattern.compile(SHORT_DOI_EXP_PREFIX + SHORT_DOI_EXP, Pattern.CASE_INSENSITIVE); private static final Pattern FIND_SHORT_DOI_PATT = Pattern.compile("(?:https?://[^\\s]+?)?" + FIND_SHORT_DOI_EXP, Pattern.CASE_INSENSITIVE); // See https://www.baeldung.com/java-regex-s-splus for explanation of \\s+ // See https://stackoverflow.com/questions/3203190/regex-any-ascii-character for the regexp that includes ASCII characters only // Another reference for regexp for ASCII characters: https://howtodoinjava.com/java/regex/java-clean-ascii-text-non-printable-chars/ private static final String CHARS_TO_REMOVE = "[\\s+" // remove white space characters, i.e, \t, \n, \x0B, \f, \r . + is a greedy quantifier + "[^\\x00-\\x7F]" // strips off all non-ASCII characters + "]"; // DOI private final String doi; // Short DOI private boolean isShortDoi = false; /** * Creates a DOI from various schemes including URL, URN, and plain DOIs/Short DOIs. * * @param doi the DOI/Short DOI string * @throws NullPointerException if DOI/Short DOI is null * @throws IllegalArgumentException if doi does not include a valid DOI/Short DOI */ public DOI(String doi) { Objects.requireNonNull(doi); // Remove whitespace String trimmedDoi = doi.trim(); // HTTP URL decoding if (doi.matches(HTTP_EXP) || doi.matches(SHORT_DOI_HTTP_EXP)) { try { // decodes path segment URI url = new URI(trimmedDoi); trimmedDoi = url.getScheme() + "://" + url.getHost() + url.getPath(); } catch (URISyntaxException e) { throw new IllegalArgumentException(doi + " is not a valid HTTP DOI/Short DOI."); } } // Extract DOI/Short DOI Matcher matcher = EXACT_DOI_PATT.matcher(trimmedDoi); if (matcher.find()) { // match only group \1 this.doi = matcher.group(1); } else { // Short DOI Matcher shortDoiMatcher = EXACT_SHORT_DOI_PATT.matcher(trimmedDoi); if (shortDoiMatcher.find()) { this.doi = shortDoiMatcher.group(1); isShortDoi = true; } else { // Shortcut DOI without the "10/" as in "doi.org/d8dn" Matcher shortcutDoiMatcher = EXACT_SHORT_DOI_SHORTCUT.matcher(trimmedDoi); if (shortcutDoiMatcher.find()) { this.doi = "10/" + shortcutDoiMatcher.group(1); isShortDoi = true; } else { throw new IllegalArgumentException(trimmedDoi + " is not a valid DOI/Short DOI."); } } } } /** * Creates an Optional&lt;DOI> from various schemes including URL, URN, and plain DOIs. * <p> * Useful for suppressing the <c>IllegalArgumentException</c> of the Constructor and checking for Optional.isPresent() instead. * * @param doi the DOI/Short DOI string * @return an Optional containing the DOI or an empty Optional */ public static Optional<DOI> parse(String doi) { try { LatexToUnicodeFormatter formatter = new LatexToUnicodeFormatter(); String cleanedDOI = doi; cleanedDOI = URLDecoder.decode(cleanedDOI, StandardCharsets.UTF_8); cleanedDOI = formatter.format(cleanedDOI); cleanedDOI = cleanedDOI.replaceAll(CHARS_TO_REMOVE, ""); if (cleanedDOI.startsWith("_") && cleanedDOI.endsWith("_")) { cleanedDOI = cleanedDOI.substring(1, cleanedDOI.length() - 1); } return Optional.of(new DOI(cleanedDOI)); } catch (IllegalArgumentException | NullPointerException e) { return Optional.empty(); } } /** * Determines whether a DOI/Short DOI is valid or not * * @param doi the DOI/Short DOI string * @return true if DOI is valid, false otherwise */ public static boolean isValid(String doi) { return parse(doi).isPresent(); } /** * Tries to find a DOI/Short DOI inside the given text. * * @param text the Text which might contain a DOI/Short DOI * @return an Optional containing the DOI or an empty Optional */ public static Optional<DOI> findInText(String text) { Optional<DOI> result = Optional.empty(); Matcher matcher = FIND_DOI_PATT.matcher(text); if (matcher.find()) { // match only group \1 result = Optional.of(new DOI(matcher.group(1))); } matcher = FIND_SHORT_DOI_PATT.matcher(text); if (matcher.find()) { result = Optional.of(new DOI(matcher.group(1))); } matcher = FIND_SHORT_DOI_SHORTCUT.matcher(text); if (matcher.find()) { result = Optional.of(new DOI(matcher.group(0))); } return result; } @Override public String toString() { return "DOI{" + "doi='" + doi + '\'' + '}'; } /** * Return the plain DOI/Short DOI * * @return the plain DOI/Short DOI value. */ public String getDOI() { return doi; } /** * Determines whether DOI is short DOI or not * * @return true if DOI is short DOI, false otherwise */ public boolean isShortDoi() { return isShortDoi; } /** * Return a URI presentation for the DOI/Short DOI * * @return an encoded URI representation of the DOI/Short DOI */ @Override public Optional<URI> getExternalURI() { // TODO: We need dependency injection here. It should never happen that this method is called. // Always, the user preferences should be honored --> #getExternalURIWithCustomBase return getExternalURIFromBase(RESOLVER); } public Optional<URI> getExternalURIWithCustomBase(String customBase) { return getExternalURIFromBase(URI.create(customBase)); } private Optional<URI> getExternalURIFromBase(URI base) { try { URI uri = new URI(base.getScheme(), base.getHost(), "/" + doi, null); return Optional.of(uri); } catch (URISyntaxException e) { // should never happen LOGGER.error(doi + " could not be encoded as URI.", e); return Optional.empty(); } } /** * Return an ASCII URL presentation for the DOI/Short DOI * * @return an encoded URL representation of the DOI/Short DOI */ public String getURIAsASCIIString() { return getExternalURI().map(URI::toASCIIString).orElse(""); } @Override public Field getDefaultField() { return StandardField.DOI; } @Override public String getNormalized() { return doi; } /** * DOIs are case-insensitive. Thus, 10.1109/cloud.2017.89 equals 10.1109/CLOUD.2017.89 */ @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } DOI other = (DOI) o; return doi.equalsIgnoreCase(other.doi); } @Override public int hashCode() { return Objects.hash(doi.toLowerCase(Locale.ENGLISH)); } }
13,288
41.592949
178
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/EprintIdentifier.java
package org.jabref.model.entry.identifier; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; /** * NOTE: This class is mainly used to keep track of eprint parsers, and make it easier to navigate the code. * */ public abstract class EprintIdentifier implements Identifier { @Override public Field getDefaultField() { return StandardField.EPRINT; } }
418
25.1875
108
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/ISBN.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; public class ISBN implements Identifier { private static final Pattern ISBN_PATTERN = Pattern.compile("^(\\d{9}[\\dxX]|\\d{13})$"); private final String isbnString; public ISBN(String isbnString) { this.isbnString = Objects.requireNonNull(isbnString).trim().replace("-", ""); } public static Optional<ISBN> parse(String input) { ISBN isbn = new ISBN(input); if (isbn.isValid()) { return Optional.of(isbn); } else { return Optional.empty(); } } public boolean isValidFormat() { Matcher isbnMatcher = ISBN_PATTERN.matcher(isbnString); return isbnMatcher.matches(); } public boolean isValidChecksum() { boolean valid; if (isbnString.length() == 10) { valid = isbn10check(); } else { // length is either 10 or 13 based on regexp so will be 13 here valid = isbn13check(); } return valid; } public boolean isIsbn10() { return isbn10check(); } public boolean isIsbn13() { return isbn13check(); } // Check that the control digit is correct, see e.g. https://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits private boolean isbn10check() { if (isbnString.length() != 10) { return false; } int sum = 0; for (int pos = 0; pos <= 8; pos++) { sum += (isbnString.charAt(pos) - '0') * (10 - pos); } char control = isbnString.charAt(9); if ((control == 'x') || (control == 'X')) { control = '9' + 1; } sum += control - '0'; return (sum % 11) == 0; } // Check that the control digit is correct, see e.g. https://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits private boolean isbn13check() { if (isbnString.length() != 13) { return false; } int sum = 0; for (int pos = 0; pos <= 12; pos++) { sum += (isbnString.charAt(pos) - '0') * ((pos % 2) == 0 ? 1 : 3); } return (sum % 10) == 0; } public boolean isValid() { return isValidFormat() && isValidChecksum(); } @Override public Field getDefaultField() { return StandardField.ISBN; } @Override public String getNormalized() { return isbnString; } @Override public Optional<URI> getExternalURI() { try { return Optional.of(new URI("https://www.worldcat.org/isbn/" + isbnString)); } catch (URISyntaxException e) { return Optional.empty(); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } ISBN other = (ISBN) o; return isbnString.equalsIgnoreCase(other.isbnString); } @Override public int hashCode() { return Objects.hash(isbnString.toLowerCase(Locale.ENGLISH)); } }
3,453
25.984375
134
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/ISSN.java
package org.jabref.model.entry.identifier; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ISSN { private static final Pattern ISSN_PATTERN = Pattern.compile("^\\d{4}-\\d{3}[\\dxX]$"); private static final Pattern ISSN_PATTERN_NODASH = Pattern.compile("^(\\d{4})(\\d{3}[\\dxX])$"); private final String issnString; public ISSN(String issnString) { this.issnString = Objects.requireNonNull(issnString).trim(); } public boolean isValidFormat() { Matcher issnMatcher = ISSN_PATTERN.matcher(issnString); return issnMatcher.matches(); } public boolean isCanBeCleaned() { Matcher issnNoDashMatcher = ISSN_PATTERN_NODASH.matcher(issnString); return issnNoDashMatcher.matches(); } public String getCleanedISSN() { Matcher issnNoDashMatcher = ISSN_PATTERN_NODASH.matcher(issnString); if (issnNoDashMatcher.find()) { return issnNoDashMatcher.replaceFirst("$1-$2"); } return issnString; } public boolean isValidChecksum() { // Check that the control digit is correct, see e.g. https://en.wikipedia.org/wiki/International_Standard_Serial_Number int sum = 0; for (int pos = 0; pos <= 7; pos++) { char c = issnString.charAt(pos); if (pos != 4) { sum += (c - '0') * ((8 - pos) + (pos > 4 ? 1 : 0)); } } char control = issnString.charAt(8); if ((control == 'x') || (control == 'X')) { control = '9' + 1; } return ((((sum % 11) + control) - '0') == 11) || ((sum % 11) == 0); } }
1,690
31.519231
127
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/IacrEprint.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IacrEprint implements Identifier { public static final URI RESOLVER = URI.create("https://ia.cr"); private static final Logger LOGGER = LoggerFactory.getLogger(IacrEprint.class); private static final String IACR_EPRINT_EXP = "\\d{4}\\/\\d{3,5}"; private final String iacrEprint; IacrEprint(String iacrEprint) { Objects.requireNonNull(iacrEprint); String trimmedId = iacrEprint.trim(); if (matchesExcepted(trimmedId)) { Matcher matcher = Pattern.compile(IACR_EPRINT_EXP).matcher(trimmedId); matcher.find(); this.iacrEprint = matcher.group(0); } else { throw new IllegalArgumentException(trimmedId + " is not a valid IacrEprint identifier."); } } private static boolean matchesExcepted(String identifier) { return identifier.matches( "(https\\:\\/\\/)?(ia\\.cr\\/|eprint\\.iacr\\.org\\/)?" + IACR_EPRINT_EXP ); } public static Optional<IacrEprint> parse(String identifier) { String trimmed = identifier.strip(); try { return Optional.of(new IacrEprint(trimmed)); } catch (IllegalArgumentException illegalArgumentException) { return Optional.empty(); } } @Override public String getNormalized() { return iacrEprint; } @Override public Field getDefaultField() { return StandardField.EPRINT; } @Override public Optional<URI> getExternalURI() { try { URI uri = new URI(RESOLVER.getScheme(), RESOLVER.getHost(), "/" + iacrEprint, null); return Optional.of(uri); } catch (URISyntaxException e) { // should never happen LOGGER.error(iacrEprint + " could not be encoded as URI.", e); return Optional.empty(); } } public String getAsciiUrl() { return getExternalURI().map(URI::toASCIIString).orElse(""); } }
2,360
29.269231
101
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/Identifier.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.util.Optional; import org.jabref.model.entry.field.Field; public interface Identifier { /** * Returns the identifier. */ String getNormalized(); Field getDefaultField(); Optional<URI> getExternalURI(); }
312
15.473684
42
java
null
jabref-main/src/main/java/org/jabref/model/entry/identifier/MathSciNetId.java
package org.jabref.model.entry.identifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; import java.util.Optional; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; /** * Article identifier for MathSciNet (also sometimes called "MRNumber") */ public class MathSciNetId implements Identifier { private String identifier; public MathSciNetId(String identifier) { this.identifier = Objects.requireNonNull(identifier); } public static Optional<MathSciNetId> parse(String mrNumberRaw) { // Take everything before whitespace or open bracket, so something like `619693 (82j:58046)` gets parsed correctly String identifier = StringUtil.tokenizeToList(mrNumberRaw, " (").get(0).trim(); return Optional.of(new MathSciNetId(identifier)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MathSciNetId that = (MathSciNetId) o; return Objects.equals(identifier, that.identifier); } @Override public int hashCode() { return Objects.hash(identifier); } @Override public String toString() { return identifier; } /** * Get URL in online database. */ @Override public Optional<URI> getExternalURI() { try { return Optional.of(new URI("https://www.ams.org/mathscinet-getitem?mr=" + identifier)); } catch (URISyntaxException e) { return Optional.empty(); } } @Override public Field getDefaultField() { return StandardField.MR_NUMBER; } @Override public String getNormalized() { return identifier; } }
1,902
25.068493
122
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BiblatexAPAEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.BiblatexApaField; import org.jabref.model.entry.field.StandardField; public class BiblatexAPAEntryTypeDefinitions { private static final BibEntryType JURISDICTION = new BibEntryTypeBuilder() .withType(BiblatexApaEntryType.Jurisdiction) .withImportantFields(StandardField.ORGANIZATION, BiblatexApaField.CITATION_CITEORG, BiblatexApaField.CITATION_CITEDATE, BiblatexApaField.CITATION_CITEDATE, StandardField.ORIGDATE) .withRequiredFields(StandardField.TITLE, BiblatexApaField.CITATION, BiblatexApaField.CITATION_CITEINFO, StandardField.URL, StandardField.DATE) .build(); private static final BibEntryType LEGISLATION = new BibEntryTypeBuilder() .withType(BiblatexApaEntryType.Legislation) .withImportantFields(StandardField.TITLEADDON, StandardField.ORIGDATE) .withRequiredFields(StandardField.TITLE, StandardField.LOCATION, StandardField.URL, StandardField.DATE) .build(); private static final BibEntryType LEGADMINMATERIAL = new BibEntryTypeBuilder() .withType(BiblatexApaEntryType.Legadminmaterial) .withImportantFields(StandardField.NUMBER, StandardField.SHORTTITLE, StandardField.NOTE, StandardField.KEYWORDS) .withRequiredFields(StandardField.TITLE, BiblatexApaField.CITATION, StandardField.URL, StandardField.DATE) .build(); private static final BibEntryType CONSTITUTION = new BibEntryTypeBuilder() .withType(BiblatexApaEntryType.Constitution) .withImportantFields(BiblatexApaField.ARTICLE, BiblatexApaField.AMENDMENT, StandardField.EVENTDATE, StandardField.KEYWORDS, StandardField.PART, BiblatexApaField.SECTION) .withRequiredFields(BiblatexApaField.SOURCE, StandardField.TYPE) .build(); private static final BibEntryType LEGAL = new BibEntryTypeBuilder() .withType(BiblatexApaEntryType.Legal) .withRequiredFields(StandardField.TITLE, StandardField.DATE, StandardField.URI, StandardField.KEYWORDS, StandardField.PART, BiblatexApaField.SECTION) .build(); public static final List<BibEntryType> ALL = Arrays.asList(JURISDICTION, LEGISLATION, LEGADMINMATERIAL, CONSTITUTION, LEGAL); }
2,455
54.818182
191
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BiblatexApaEntryType.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.Locale; import java.util.Optional; public enum BiblatexApaEntryType implements EntryType { Legislation("Legislation"), Legadminmaterial("Legadminmaterial"), Jurisdiction("Jurisdiction"), Constitution("Constitution"), Legal("Legal"); private final String displayName; BiblatexApaEntryType(String displayName) { this.displayName = displayName; } @Override public String getName() { return displayName.toLowerCase(Locale.ENGLISH); } @Override public String getDisplayName() { return displayName; } public static Optional<BiblatexApaEntryType> fromName(String name) { return Arrays.stream(BiblatexApaEntryType.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } }
915
23.756757
77
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BiblatexEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; /** * This class defines entry types for biblatex support. * * @see <a href="http://mirrors.concertpass.com/tex-archive/macros/latex/contrib/biblatex/doc/biblatex.pdf">biblatex documentation</a> */ public class BiblatexEntryTypeDefinitions { private static final BibEntryType ARTICLE = new BibEntryTypeBuilder() .withType(StandardEntryType.Article) .withImportantFields( StandardField.SUBTITLE, StandardField.EDITOR, StandardField.SERIES, StandardField.VOLUME, StandardField.NUMBER, StandardField.EID, StandardField.ISSUE, StandardField.PAGES, StandardField.NOTE, StandardField.ISSN, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withDetailFields( StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.EDITOR, StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.JOURNALSUBTITLE, StandardField.ISSUETITLE, StandardField.ISSUESUBTITLE, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.SERIES, StandardField.VOLUME, StandardField.NUMBER, StandardField.EID, StandardField.ISSUE, StandardField.PAGES, StandardField.VERSION, StandardField.NOTE, StandardField.ISSN, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields( StandardField.AUTHOR, StandardField.TITLE, StandardField.JOURNALTITLE, StandardField.DATE) .build(); private static final BibEntryType BOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.Book) .withImportantFields(StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.VOLUME, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType MVBOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.MvBook) .withImportantFields(StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType INBOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.InBook) .withImportantFields( StandardField.BOOKAUTHOR, StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.VOLUME, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.DATE) .withDetailFields(StandardField.BOOKAUTHOR, StandardField.EDITOR, StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType BOOKINBOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.BookInBook) .withImportantFields(INBOOK.getPrimaryOptionalFields()) .withDetailFields(INBOOK.getSecondaryOptionalFields()) .withRequiredFields(INBOOK.getRequiredFields()) .build(); private static final BibEntryType SUPPBOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.SuppBook) .withImportantFields(INBOOK.getPrimaryOptionalFields()) .withDetailFields(INBOOK.getSecondaryOptionalFields()) .withRequiredFields(INBOOK.getRequiredFields()) .build(); private static final BibEntryType BOOKLET = new BibEntryTypeBuilder() .withType(StandardEntryType.Booklet) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.HOWPUBLISHED, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.TYPE, StandardField.NOTE, StandardField.LOCATION, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType COLLECTION = new BibEntryTypeBuilder() .withType(StandardEntryType.Collection) .withImportantFields( StandardField.TRANSLATOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.VOLUME, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.EDITOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType MVCOLLECTION = new BibEntryTypeBuilder() .withType(StandardEntryType.MvCollection) .withImportantFields(StandardField.TRANSLATOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.EDITOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType INCOLLECTION = new BibEntryTypeBuilder() .withType(StandardEntryType.InCollection) .withImportantFields(StandardField.TRANSLATOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.VOLUME, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.TRANSLATOR, StandardField.ANNOTATOR, StandardField.COMMENTATOR, StandardField.INTRODUCTION, StandardField.FOREWORD, StandardField.AFTERWORD, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.LANGUAGE, StandardField.ORIGLANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.EDITION, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType SUPPCOLLECTION = new BibEntryTypeBuilder() .withType(StandardEntryType.SuppCollection) .withImportantFields(INCOLLECTION.getPrimaryOptionalFields()) .withDetailFields(INCOLLECTION.getSecondaryOptionalFields()) .withRequiredFields(INCOLLECTION.getRequiredFields()) .build(); private static final BibEntryType MANUAL = new BibEntryTypeBuilder() .withType(StandardEntryType.Manual) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.EDITION, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.EDITION, StandardField.TYPE, StandardField.SERIES, StandardField.NUMBER, StandardField.VERSION, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType MISC = new BibEntryTypeBuilder() .withType(StandardEntryType.Misc) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.HOWPUBLISHED, StandardField.LOCATION, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.TYPE, StandardField.VERSION, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.LOCATION, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType ONLINE = new BibEntryTypeBuilder() .withType(StandardEntryType.Online) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE, StandardField.URL) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.VERSION, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.URLDATE) .build(); private static final BibEntryType PATENT = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Patent) .withImportantFields(StandardField.HOLDER, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.NUMBER, StandardField.DATE) .withDetailFields(StandardField.HOLDER, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.TYPE, StandardField.VERSION, StandardField.LOCATION, StandardField.NOTE, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType PERIODICAL = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Periodical) .withImportantFields( StandardField.SUBTITLE, StandardField.ISSUETITLE, StandardField.ISSUESUBTITLE, StandardField.ISSN, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.EDITOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITORA, StandardField.EDITORB, StandardField.EDITORC, StandardField.SUBTITLE, StandardField.ISSUETITLE, StandardField.ISSUESUBTITLE, StandardField.LANGUAGE, StandardField.SERIES, StandardField.VOLUME, StandardField.NUMBER, StandardField.ISSUE, StandardField.NOTE, StandardField.ISSN, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType SUPPPERIODICAL = new BibEntryTypeBuilder() .withType(StandardEntryType.SuppPeriodical) .withImportantFields(ARTICLE.getPrimaryOptionalFields()) .withDetailFields(ARTICLE.getSecondaryOptionalFields()) .withRequiredFields(ARTICLE.getRequiredFields()) .build(); private static final BibEntryType PROCEEDINGS = new BibEntryTypeBuilder() .withType(StandardEntryType.Proceedings) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.EVENTTITLE, StandardField.VOLUME, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.EVENTTITLE, StandardField.EVENTTITLEADDON, StandardField.EVENTDATE, StandardField.VENUE, StandardField.LANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType MVPROCEEDINGS = new BibEntryTypeBuilder() .withType(StandardEntryType.MvProceedings) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.EVENTTITLE, StandardField.VOLUME, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.EVENTTITLE, StandardField.EVENTTITLEADDON, StandardField.EVENTDATE, StandardField.VENUE, StandardField.LANGUAGE, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType INPROCEEDINGS = new BibEntryTypeBuilder() .withType(StandardEntryType.InProceedings) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.EVENTTITLE, StandardField.VOLUME, StandardField.PUBLISHER, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.DATE) .withDetailFields(StandardField.EDITOR, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.MAINTITLE, StandardField.MAINSUBTITLE, StandardField.MAINTITLEADDON, StandardField.BOOKSUBTITLE, StandardField.BOOKTITLEADDON, StandardField.EVENTTITLE, StandardField.EVENTTITLEADDON, StandardField.EVENTDATE, StandardField.VENUE, StandardField.LANGUAGE, StandardField.VOLUME, StandardField.PART, StandardField.VOLUMES, StandardField.SERIES, StandardField.NUMBER, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType REFERENCE = new BibEntryTypeBuilder() .withType(StandardEntryType.Reference) .withImportantFields(COLLECTION.getPrimaryOptionalFields()) .withDetailFields(COLLECTION.getSecondaryOptionalFields()) .withRequiredFields(COLLECTION.getRequiredFields()) .build(); private static final BibEntryType MVREFERENCE = new BibEntryTypeBuilder() .withType(StandardEntryType.MvReference) .withImportantFields(MVCOLLECTION.getPrimaryOptionalFields()) .withDetailFields(MVCOLLECTION.getSecondaryOptionalFields()) .withRequiredFields(MVCOLLECTION.getRequiredFields()) .build(); private static final BibEntryType INREFERENCE = new BibEntryTypeBuilder() .withType(StandardEntryType.InReference) .withImportantFields(INCOLLECTION.getPrimaryOptionalFields()) .withDetailFields(INCOLLECTION.getSecondaryOptionalFields()) .withRequiredFields(INCOLLECTION.getRequiredFields()) .build(); private static final BibEntryType REPORT = new BibEntryTypeBuilder() .withType(StandardEntryType.Report) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.NUMBER, StandardField.ISRN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.TYPE, StandardField.INSTITUTION, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.NUMBER, StandardField.VERSION, StandardField.NOTE, StandardField.LOCATION, StandardField.ISRN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType SET = new BibEntryTypeBuilder() .withType(StandardEntryType.Set) .withRequiredFields(StandardField.ENTRYSET, StandardField.CROSSREF) .build(); private static final BibEntryType THESIS = new BibEntryTypeBuilder() .withType(StandardEntryType.Thesis) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.TYPE, StandardField.INSTITUTION, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.NOTE, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType UNPUBLISHED = new BibEntryTypeBuilder() .withType(StandardEntryType.Unpublished) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.HOWPUBLISHED, StandardField.PUBSTATE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.NOTE, StandardField.LOCATION, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.EVENTTITLE, StandardField.EVENTDATE, StandardField.VENUE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType CONFERENCE = new BibEntryTypeBuilder() .withType(StandardEntryType.Conference) .withImportantFields(INPROCEEDINGS.getPrimaryOptionalFields()) .withDetailFields(INPROCEEDINGS.getSecondaryOptionalFields()) .withRequiredFields(INPROCEEDINGS.getRequiredFields()) .build(); private static final BibEntryType ELECTRONIC = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Electronic) .withImportantFields(ONLINE.getPrimaryOptionalFields()) .withDetailFields(ONLINE.getSecondaryOptionalFields()) .withRequiredFields(ONLINE.getRequiredFields()) .build(); private static final BibEntryType MASTERSTHESIS = new BibEntryTypeBuilder() .withType(StandardEntryType.MastersThesis) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.TYPE, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.INSTITUTION, StandardField.DATE) .withDetailFields(StandardField.TYPE, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.NOTE, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType PHDTHESIS = new BibEntryTypeBuilder() .withType(StandardEntryType.PhdThesis) .withImportantFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.TYPE, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.INSTITUTION, StandardField.DATE) .withDetailFields(StandardField.TYPE, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.NOTE, StandardField.LOCATION, StandardField.ISBN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType TECHREPORT = new BibEntryTypeBuilder() .withType(StandardEntryType.TechReport) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.TYPE, StandardField.NUMBER, StandardField.ISRN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.INSTITUTION, StandardField.DATE) .withDetailFields(StandardField.TYPE, StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.NUMBER, StandardField.VERSION, StandardField.NOTE, StandardField.LOCATION, StandardField.ISRN, StandardField.CHAPTER, StandardField.PAGES, StandardField.PAGETOTAL, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType WWW = new BibEntryTypeBuilder() .withType(StandardEntryType.WWW) .withImportantFields(ONLINE.getPrimaryOptionalFields()) .withDetailFields(ONLINE.getSecondaryOptionalFields()) .withRequiredFields(ONLINE.getRequiredFields()) .build(); private static final BibEntryType SOFTWARE = new BibEntryTypeBuilder() .withType(StandardEntryType.Software) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.HOWPUBLISHED, StandardField.LOCATION, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.TYPE, StandardField.VERSION, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.LOCATION, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); private static final BibEntryType DATASET = new BibEntryTypeBuilder() .withType(StandardEntryType.Dataset) .withImportantFields( StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.HOWPUBLISHED, StandardField.LOCATION, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.DATE) .withDetailFields(StandardField.SUBTITLE, StandardField.TITLEADDON, StandardField.LANGUAGE, StandardField.EDITION, StandardField.HOWPUBLISHED, StandardField.TYPE, StandardField.VERSION, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.LOCATION, StandardField.ADDENDUM, StandardField.PUBSTATE, StandardField.DOI, StandardField.EPRINT, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, StandardField.URL, StandardField.URLDATE) .build(); public static final List<BibEntryType> ALL = Arrays.asList(ARTICLE, BOOK, MVBOOK, INBOOK, BOOKINBOOK, SUPPBOOK, BOOKLET, COLLECTION, MVCOLLECTION, INCOLLECTION, SUPPCOLLECTION, MANUAL, MISC, ONLINE, PATENT, PERIODICAL, SUPPPERIODICAL, PROCEEDINGS, MVPROCEEDINGS, INPROCEEDINGS, REFERENCE, MVREFERENCE, INREFERENCE, REPORT, SET, THESIS, UNPUBLISHED, CONFERENCE, ELECTRONIC, MASTERSTHESIS, PHDTHESIS, TECHREPORT, WWW, SOFTWARE, DATASET); public static final List<BibEntryType> RECOMMENDED = Arrays.asList(ARTICLE, BOOK, INPROCEEDINGS, REPORT, MISC); }
37,572
82.868304
154
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BiblatexSoftwareEntryType.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.Locale; import java.util.Optional; public enum BiblatexSoftwareEntryType implements EntryType { Dataset("Dataset"), SoftwareVersion("SoftwareVersion"), SoftwareModule("SoftwareModule"), CodeFragment("CodeFragment"); private final String displayName; BiblatexSoftwareEntryType(String displayName) { this.displayName = displayName; } public static Optional<BiblatexSoftwareEntryType> fromName(String name) { return Arrays.stream(BiblatexSoftwareEntryType.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public String getName() { return displayName.toLowerCase(Locale.ENGLISH); } @Override public String getDisplayName() { return displayName; } }
909
24.277778
77
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BiblatexSoftwareEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.BiblatexSoftwareField; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; public class BiblatexSoftwareEntryTypeDefinitions { private static final BibEntryType SOFTWARE = new BibEntryTypeBuilder() .withType(StandardEntryType.Software) .withImportantFields(StandardField.DATE, StandardField.DOI, StandardField.EPRINTTYPE, StandardField.EPRINTCLASS, StandardField.EPRINT, StandardField.EDITOR, StandardField.FILE, BiblatexSoftwareField.HALID, BiblatexSoftwareField.HALVERSION, StandardField.INSTITUTION, BiblatexSoftwareField.INTRODUCEDIN, BiblatexSoftwareField.LICENSE, StandardField.MONTH, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.RELATED, BiblatexSoftwareField.RELATEDSTRING, BiblatexSoftwareField.REPOSITORY, BiblatexSoftwareField.SWHID, StandardField.URLDATE, StandardField.VERSION) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.URL, StandardField.VERSION, StandardField.YEAR) .build(); private static final BibEntryType SOFTWAREVERSION = new BibEntryTypeBuilder() .withType(BiblatexSoftwareEntryType.SoftwareVersion) .withImportantFields(StandardField.DATE, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, BiblatexSoftwareField.HALID, BiblatexSoftwareField.HALVERSION, StandardField.INSTITUTION, BiblatexSoftwareField.INTRODUCEDIN, BiblatexSoftwareField.LICENSE, StandardField.MONTH, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.RELATED, BiblatexSoftwareField.RELATEDTYPE, BiblatexSoftwareField.RELATEDSTRING, BiblatexSoftwareField.REPOSITORY, BiblatexSoftwareField.SWHID, StandardField.SUBTITLE, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.URL, StandardField.YEAR, StandardField.VERSION) .withDetailFields(StandardField.DATE, StandardField.EPRINTCLASS, StandardField.EPRINTTYPE, BiblatexSoftwareField.HALID, BiblatexSoftwareField.HALVERSION, StandardField.INSTITUTION, BiblatexSoftwareField.INTRODUCEDIN, BiblatexSoftwareField.LICENSE, StandardField.MONTH, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.RELATED, BiblatexSoftwareField.RELATEDTYPE, BiblatexSoftwareField.RELATEDSTRING, BiblatexSoftwareField.REPOSITORY, BiblatexSoftwareField.SWHID, StandardField.SUBTITLE, StandardField.URLDATE) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.URL, StandardField.YEAR) .build(); private static final BibEntryType SOFTWAREMODULE = new BibEntryTypeBuilder() .withType(BiblatexSoftwareEntryType.SoftwareModule) .withImportantFields(StandardField.DATE, StandardField.DOI, StandardField.EPRINTTYPE, StandardField.EPRINTCLASS, StandardField.EPRINT, StandardField.EDITOR, StandardField.FILE, BiblatexSoftwareField.HALID, BiblatexSoftwareField.HALVERSION, StandardField.INSTITUTION, BiblatexSoftwareField.INTRODUCEDIN, BiblatexSoftwareField.LICENSE, StandardField.MONTH, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.RELATED, BiblatexSoftwareField.RELATEDSTRING, BiblatexSoftwareField.REPOSITORY, BiblatexSoftwareField.SWHID, StandardField.URLDATE, StandardField.VERSION) .withRequiredFields(StandardField.AUTHOR, StandardField.SUBTITLE, StandardField.URL, StandardField.YEAR) .build(); private static final BibEntryType CODEFRAGMENT = new BibEntryTypeBuilder() .withType(BiblatexSoftwareEntryType.CodeFragment) .withImportantFields(StandardField.DATE, StandardField.DOI, StandardField.EPRINTTYPE, StandardField.EPRINTCLASS, StandardField.EPRINT, StandardField.EDITOR, StandardField.FILE, BiblatexSoftwareField.HALID, BiblatexSoftwareField.HALVERSION, StandardField.INSTITUTION, BiblatexSoftwareField.INTRODUCEDIN, BiblatexSoftwareField.LICENSE, StandardField.MONTH, StandardField.NOTE, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.RELATED, BiblatexSoftwareField.RELATEDSTRING, BiblatexSoftwareField.REPOSITORY, BiblatexSoftwareField.SWHID, StandardField.URLDATE, StandardField.VERSION) .withRequiredFields(StandardField.URL) .build(); public static final List<BibEntryType> ALL = Arrays.asList(SOFTWAREVERSION, SOFTWARE, SOFTWAREMODULE, CODEFRAGMENT); }
5,076
91.309091
187
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/BibtexEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; /** * This class represents all supported BibTeX entry types. * The BibLaTeX entry types are defined at {@link BiblatexEntryTypeDefinitions}. */ public class BibtexEntryTypeDefinitions { /** * An article from a journal or magazine. * <p> * Required fields: author, title, journal, year. * Optional fields: volume, number, pages, month, note. */ private static final BibEntryType ARTICLE = new BibEntryTypeBuilder() .withType(StandardEntryType.Article) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.JOURNAL, StandardField.YEAR) .withImportantFields(StandardField.VOLUME, StandardField.NUMBER, StandardField.PAGES, StandardField.MONTH, StandardField.ISSN, StandardField.NOTE) .build(); /** * A book with an explicit publisher. * <p> * Required fields: author or editor, title, publisher, year. * Optional fields: volume or number, series, address, edition, month, note. */ private static final BibEntryType BOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.Book) .withRequiredFields(new OrFields(StandardField.AUTHOR, StandardField.EDITOR), StandardField.TITLE, StandardField.PUBLISHER, StandardField.YEAR) .withImportantFields(StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.ADDRESS, StandardField.EDITION, StandardField.MONTH, StandardField.ISBN, StandardField.NOTE) .build(); /** * A work that is printed and bound, but without a named publisher or sponsoring institution. * <p> * Required field: title. * Optional fields: author, howpublished, address, month, year, note. */ private static final BibEntryType BOOKLET = new BibEntryTypeBuilder() .withType(StandardEntryType.Booklet) .withRequiredFields(StandardField.TITLE) .withImportantFields(StandardField.AUTHOR, StandardField.HOWPUBLISHED, StandardField.ADDRESS, StandardField.MONTH, StandardField.YEAR, StandardField.NOTE) .build(); /** * An article in a conference proceedings. * <p> * Required fields: author, title, booktitle, year. * Optional fields: editor, volume or number, series, pages, address, month, organization, publisher, note. */ private static final BibEntryType CONFERENCE = new BibEntryTypeBuilder() .withType(StandardEntryType.Conference) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.YEAR) .withImportantFields(StandardField.EDITOR, StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.PAGES, StandardField.ADDRESS, StandardField.MONTH, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.NOTE) .build(); /** * A part of a book, which may be a chapter (or section or whatever) and/or a range of pages. * <p> * Required fields: author or editor, title, chapter and/or pages, publisher, year. * Optional fields: volume or number, series, type, address, edition, month, note. */ private static final BibEntryType INBOOK = new BibEntryTypeBuilder() .withType(StandardEntryType.InBook) .withRequiredFields(Arrays.asList(new OrFields(StandardField.CHAPTER, StandardField.PAGES), new OrFields(StandardField.AUTHOR, StandardField.EDITOR)), StandardField.TITLE, StandardField.PUBLISHER, StandardField.YEAR) .withImportantFields(StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.TYPE, StandardField.ADDRESS, StandardField.EDITION, StandardField.MONTH, StandardField.ISBN, StandardField.NOTE) .build(); /** * A part of a book having its own title. * Required fields: author, title, booktitle, publisher, year. * Optional fields: editor, volume or number, series, type, chapter, pages, address, edition, month, note. */ private static final BibEntryType INCOLLECTION = new BibEntryTypeBuilder() .withType(StandardEntryType.InCollection) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.PUBLISHER, StandardField.YEAR) .withImportantFields(StandardField.EDITOR, StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.TYPE, StandardField.CHAPTER, StandardField.PAGES, StandardField.ADDRESS, StandardField.EDITION, StandardField.MONTH, StandardField.ISBN, StandardField.NOTE) .build(); /** * An article in a conference proceedings. * <p> * Required fields: author, title, booktitle, year. * Optional fields: editor, volume or number, series, pages, address, month, organization, publisher, note. */ private static final BibEntryType INPROCEEDINGS = new BibEntryTypeBuilder() .withType(StandardEntryType.InProceedings) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.BOOKTITLE, StandardField.YEAR) .withImportantFields(StandardField.EDITOR, StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.PAGES, StandardField.ADDRESS, StandardField.MONTH, StandardField.ORGANIZATION, StandardField.PUBLISHER, StandardField.NOTE) .build(); /** * Technical documentation. * Required field: title. * Optional fields: author, organization, address, edition, month, year, note. */ private static final BibEntryType MANUAL = new BibEntryTypeBuilder().withRequiredFields(StandardField.TITLE).withImportantFields(StandardField.AUTHOR, StandardField.ORGANIZATION, StandardField.ADDRESS, StandardField.EDITION, StandardField.MONTH, StandardField.YEAR, StandardField.ISBN, StandardField.NOTE).withType(StandardEntryType.Manual) .build(); /** * A Master's thesis. * <p> * Required fields: author, title, school, year. * Optional fields: type, address, month, note. */ private static final BibEntryType MASTERSTHESIS = new BibEntryTypeBuilder() .withType(StandardEntryType.MastersThesis) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.SCHOOL, StandardField.YEAR) .withImportantFields(StandardField.TYPE, StandardField.ADDRESS, StandardField.MONTH, StandardField.NOTE) .build(); /** * Use this type when nothing else fits. * <p> * Required fields: none. * Optional fields: author, title, howpublished, month, year, note. */ private static final BibEntryType MISC = new BibEntryTypeBuilder() .withType(StandardEntryType.Misc) .withImportantFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.HOWPUBLISHED, StandardField.MONTH, StandardField.YEAR, StandardField.NOTE) .build(); /** * A PhD thesis. * <p> * Required fields: author, title, school, year. * Optional fields: type, address, month, note. */ private static final BibEntryType PHDTHESIS = new BibEntryTypeBuilder() .withType(StandardEntryType.PhdThesis) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.SCHOOL, StandardField.YEAR) .withImportantFields(StandardField.TYPE, StandardField.ADDRESS, StandardField.MONTH, StandardField.NOTE) .build(); /** * The proceedings of a conference. * <p> * Required fields: title, year. * Optional fields: editor, volume or number, series, address, month, organization, publisher, note. */ private static final BibEntryType PROCEEDINGS = new BibEntryTypeBuilder() .withType(StandardEntryType.Proceedings) .withRequiredFields(StandardField.TITLE, StandardField.YEAR) .withImportantFields(StandardField.EDITOR, StandardField.VOLUME, StandardField.NUMBER, StandardField.SERIES, StandardField.ADDRESS, StandardField.PUBLISHER, StandardField.MONTH, StandardField.ORGANIZATION, StandardField.ISBN, StandardField.NOTE) .build(); /** * A report published by a school or other institution, usually numbered within a series. * <p> * Required fields: author, title, institution, year. * Optional fields: type, number, address, month, note. */ private static final BibEntryType TECHREPORT = new BibEntryTypeBuilder() .withType(StandardEntryType.TechReport) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.INSTITUTION, StandardField.YEAR) .withImportantFields(StandardField.TYPE, StandardField.NUMBER, StandardField.ADDRESS, StandardField.MONTH, StandardField.NOTE) .build(); /** * A document having an author and title, but not formally published. * <p> * Required fields: author, title, note. * Optional fields: month, year. */ private static final BibEntryType UNPUBLISHED = new BibEntryTypeBuilder() .withType(StandardEntryType.Unpublished) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.NOTE) .withImportantFields(StandardField.MONTH, StandardField.YEAR) .build(); public static final List<BibEntryType> ALL = Arrays.asList(ARTICLE, INBOOK, BOOK, BOOKLET, INCOLLECTION, CONFERENCE, INPROCEEDINGS, PROCEEDINGS, MANUAL, MASTERSTHESIS, PHDTHESIS, TECHREPORT, UNPUBLISHED, MISC); public static final List<BibEntryType> RECOMMENDED = Arrays.asList(ARTICLE, BOOK, INPROCEEDINGS, TECHREPORT, MISC); private BibtexEntryTypeDefinitions() { } }
10,085
53.225806
344
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/EntryType.java
package org.jabref.model.entry.types; public interface EntryType { /** * Returns the tag name of the entry type. */ String getName(); /** * Returns the name presented in the UI */ String getDisplayName(); }
246
15.466667
46
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/EntryTypeFactory.java
package org.jabref.model.entry.types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Objects; import org.jabref.model.entry.BibEntryType; public class EntryTypeFactory { private EntryTypeFactory() { } /** * Checks whether two EntryTypeFactory are equal * based on the equality of the type names and on the equality of the required and optional field lists * * @return returns true if the two compared entry types have the same name and equal required and optional fields */ public static boolean nameAndFieldsAreEqual(BibEntryType type1, BibEntryType type2) { if ((type1 == null) && (type2 == null)) { return true; } else if ((type1 == null) || (type2 == null)) { return false; } else { return Objects.equals(type1.getType(), type2.getType()) && Objects.equals(type1.getRequiredFields(), type2.getRequiredFields()) && Objects.equals(type1.getOptionalFields(), type2.getOptionalFields()) && Objects.equals(type1.getSecondaryOptionalFields(), type2.getSecondaryOptionalFields()); } } public static boolean isExclusiveBiblatex(EntryType type) { return isBiblatex(type) && !isBibtex(type); } private static boolean isBibtex(EntryType type) { return BibtexEntryTypeDefinitions.ALL.stream().anyMatch(bibEntryType -> bibEntryType.getType().equals(type)); } private static boolean isBiblatex(EntryType type) { return BiblatexEntryTypeDefinitions.ALL.stream().anyMatch(bibEntryType -> bibEntryType.getType().equals(type)); } public static EntryType parse(String typeName) { List<EntryType> types = new ArrayList<>(Arrays.<EntryType>asList(StandardEntryType.values())); types.addAll(Arrays.<EntryType>asList(IEEETranEntryType.values())); types.addAll(Arrays.<EntryType>asList(BiblatexSoftwareEntryType.values())); types.addAll(Arrays.<EntryType>asList(BiblatexApaEntryType.values())); types.addAll(Arrays.<EntryType>asList(SystematicLiteratureReviewStudyEntryType.values())); return types.stream().filter(type -> type.getName().equals(typeName.toLowerCase(Locale.ENGLISH))).findFirst().orElse(new UnknownEntryType(typeName)); } }
2,378
40.736842
157
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/IEEETranEntryType.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.Locale; import java.util.Optional; public enum IEEETranEntryType implements EntryType { IEEEtranBSTCTL("IEEEtranBSTCTL"), Electronic("Electronic"), Patent("Patent"), Periodical("Periodical"), Standard("Standard"); private final String displayName; IEEETranEntryType(String displayName) { this.displayName = displayName; } public static Optional<IEEETranEntryType> fromName(String name) { return Arrays.stream(IEEETranEntryType.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public String getName() { return displayName.toLowerCase(Locale.ENGLISH); } @Override public String getDisplayName() { return displayName; } }
886
23.638889
77
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/IEEETranEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.IEEEField; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; /** * This class represents all supported IEEETran entry types. * <p> * See <a href="http://ctan.sharelatex.com/tex-archive/macros/latex/contrib/IEEEtran/bibtex/IEEEtran_bst_HOWTO.pdf">http://ctan.sharelatex.com/tex-archive/macros/latex/contrib/IEEEtran/bibtex/IEEEtran_bst_HOWTO.pdf</a> * <p> * Electronic, IEEETranBSTCTL, Periodical, Patent, Standard */ public class IEEETranEntryTypeDefinitions { /** * Electronic entry type for internet references * <p> * Required fields: * Optional fields: author, month, year, title, language, howpublished, organization, address, note, url */ private static final BibEntryType ELECTRONIC = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Electronic) .withImportantFields(StandardField.AUTHOR, StandardField.MONTH, StandardField.YEAR, StandardField.TITLE, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.ORGANIZATION, StandardField.ADDRESS, StandardField.NOTE, StandardField.URL) .build(); /** * Special entry type that can be used to externally control some aspects of the bibliography style. */ private static final BibEntryType IEEETRANBSTCTL = new BibEntryTypeBuilder() .withType(IEEETranEntryType.IEEEtranBSTCTL) .withImportantFields(IEEEField.CTLUSE_ARTICLE_NUMBER, IEEEField.CTLUSE_PAPER, IEEEField.CTLUSE_FORCED_ETAL, IEEEField.CTLUSE_URL, IEEEField.CTLMAX_NAMES_FORCED_ETAL, IEEEField.CTLNAMES_SHOW_ETAL, IEEEField.CTLUSE_ALT_SPACING, IEEEField.CTLALT_STRETCH_FACTOR, IEEEField.CTLDASH_REPEATED_NAMES, IEEEField.CTLNAME_FORMAT_STRING, IEEEField.CTLNAME_LATEX_CMD, IEEEField.CTLNAME_URL_PREFIX) .build(); /** * The periodical entry type is used for journals and magazines. * <p> * Required fields: title, year * Optional fields: editor, language, series, volume, number, organization, month, note, url */ private static final BibEntryType PERIODICAL = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Periodical) .withRequiredFields(StandardField.TITLE, StandardField.YEAR) .withImportantFields(StandardField.EDITOR, StandardField.LANGUAGE, StandardField.SERIES, StandardField.VOLUME, StandardField.NUMBER, StandardField.ORGANIZATION, StandardField.MONTH, StandardField.NOTE, StandardField.URL) .build(); /** * Entry type for patents. * <p> * Required fields: nationality, number, year or yearfiled * Optional fields: author, title, language, assignee, address, type, number, day, dayfiled, month, monthfiled, note, url */ private static final BibEntryType PATENT = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Patent) .withRequiredFields(new OrFields(StandardField.YEAR, StandardField.YEARFILED), StandardField.NATIONALITY, StandardField.NUMBER) .withImportantFields(StandardField.AUTHOR, StandardField.TITLE, StandardField.LANGUAGE, StandardField.ASSIGNEE, StandardField.ADDRESS, StandardField.TYPE, StandardField.NUMBER, StandardField.DAY, StandardField.DAYFILED, StandardField.MONTH, StandardField.MONTHFILED, StandardField.NOTE, StandardField.URL) .build(); /** * The standard entry type is used for proposed or formally published standards. * <p> * Required fields: title, organization or institution * Optional fields: author, language, howpublished, type, number, revision, address, month, year, note, url */ private static final BibEntryType STANDARD = new BibEntryTypeBuilder() .withType(IEEETranEntryType.Standard) .withRequiredFields(new OrFields(StandardField.ORGANIZATION, StandardField.INSTITUTION), StandardField.TITLE) .withImportantFields(StandardField.AUTHOR, StandardField.LANGUAGE, StandardField.HOWPUBLISHED, StandardField.TYPE, StandardField.NUMBER, StandardField.REVISION, StandardField.ADDRESS, StandardField.MONTH, StandardField.YEAR, StandardField.NOTE, StandardField.URL) .build(); public static final List<BibEntryType> ALL = Arrays.asList(ELECTRONIC, IEEETRANBSTCTL, PERIODICAL, PATENT, STANDARD); private IEEETranEntryTypeDefinitions() { } }
4,737
52.840909
232
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/StandardEntryType.java
package org.jabref.model.entry.types; import java.util.Locale; /** * Defines standard entry types as defined by BibTeX and BibLaTeX. * At {@link BibtexEntryTypeDefinitions}, the required and optional fields for each type (for BibTeX) is defined. * The BibLaTeX entry types are defined at {@link BiblatexEntryTypeDefinitions}. * More reading on BibTeX and its fields is collected at <a href="https://docs.jabref.org/advanced/fields">JabRef's documentation</a>. */ public enum StandardEntryType implements EntryType { // BibTeX Article("Article"), Book("Book"), Booklet("Booklet"), Collection("Collection"), Conference("Conference"), InBook("InBook"), InCollection("InCollection"), InProceedings("InProceedings"), Manual("Manual"), MastersThesis("MastersThesis"), Misc("Misc"), PhdThesis("PhdThesis"), Proceedings("Proceedings"), TechReport("TechReport"), Unpublished("Unpublished"), // BibLaTeX BookInBook("BookInBook"), InReference("InReference"), MvBook("MvBook"), MvCollection("MvCollection"), MvProceedings("MvProceedings"), MvReference("MvReference"), Online("Online"), Reference("Reference"), Report("Report"), Set("Set"), SuppBook("SuppBook"), SuppCollection("SuppCollection"), SuppPeriodical("SuppPeriodical"), Thesis("Thesis"), WWW("WWW"), Software("Software"), Dataset("Dataset"); private final String displayName; StandardEntryType(String displayName) { this.displayName = displayName; } @Override public String getName() { return displayName.toLowerCase(Locale.ENGLISH); } @Override public String getDisplayName() { return displayName; } }
1,758
26.920635
134
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/SystematicLiteratureReviewStudyEntryType.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.Locale; import java.util.Optional; public enum SystematicLiteratureReviewStudyEntryType implements EntryType { STUDY_ENTRY("Study"), SEARCH_QUERY_ENTRY("SearchQuery"), LIBRARY_ENTRY("Library"); private final String displayName; SystematicLiteratureReviewStudyEntryType(String displayName) { this.displayName = displayName; } public static Optional<SystematicLiteratureReviewStudyEntryType> fromName(String name) { return Arrays.stream(SystematicLiteratureReviewStudyEntryType.values()) .filter(field -> field.getName().equalsIgnoreCase(name)) .findAny(); } @Override public String getName() { return displayName.toLowerCase(Locale.ENGLISH); } @Override public String getDisplayName() { return displayName; } }
927
26.294118
92
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/SystematicLiteratureReviewStudyEntryTypeDefinitions.java
package org.jabref.model.entry.types; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; /** * This class represents all supported entry types used in a study definition file */ public class SystematicLiteratureReviewStudyEntryTypeDefinitions { /** * Entry type used for study meta data within a study definition file * * <ul> * <li>Required fields: author, lastsearchdate, name, enabled</li> * <li>Optional fields:</li> * </ul> */ private static final BibEntryType STUDY_ENTRY = new BibEntryTypeBuilder() .withType(SystematicLiteratureReviewStudyEntryType.STUDY_ENTRY) .withRequiredFields(StandardField.AUTHOR, new UnknownField("lastsearchdate"), new UnknownField("name"), new UnknownField("researchquestions")) .build(); /** * Entry type for the queries within the study definition file * * <ul> * <li>Required fields: query</li> * <li>Optional fields:</li> * </ul> */ private static final BibEntryType SEARCH_QUERY_ENTRY = new BibEntryTypeBuilder() .withType(SystematicLiteratureReviewStudyEntryType.SEARCH_QUERY_ENTRY) .withRequiredFields(new UnknownField("query")) .build(); /** * Entry type for the targeted libraries within a study definition file * * <ul> * <li>Required fields: name, enabled</li> * <li>Optional fields: comment</li> * </ul> */ private static final BibEntryType LIBRARY_ENTRY = new BibEntryTypeBuilder() .withType(SystematicLiteratureReviewStudyEntryType.STUDY_ENTRY) .withRequiredFields(new UnknownField("name"), new UnknownField("enabled")) .withImportantFields(StandardField.COMMENT) .build(); public static final List<BibEntryType> ALL = Arrays.asList(STUDY_ENTRY, SEARCH_QUERY_ENTRY, LIBRARY_ENTRY); private SystematicLiteratureReviewStudyEntryTypeDefinitions() { } }
2,162
34.459016
154
java
null
jabref-main/src/main/java/org/jabref/model/entry/types/UnknownEntryType.java
package org.jabref.model.entry.types; import java.util.Locale; import java.util.Objects; import org.jabref.model.strings.StringUtil; public class UnknownEntryType implements EntryType { private final String name; public UnknownEntryType(String name) { this.name = Objects.requireNonNull(name).toLowerCase(Locale.ENGLISH); } @Override public String toString() { return "UnknownEntryType{" + "name='" + name + '\'' + '}'; } @Override public String getName() { return name; } @Override public String getDisplayName() { return StringUtil.capitalizeFirst(name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } UnknownEntryType that = (UnknownEntryType) o; return name.equals(that.name); } @Override public int hashCode() { return Objects.hash(name); } }
1,071
20.877551
77
java
null
jabref-main/src/main/java/org/jabref/model/groups/AbstractGroup.java
package org.jabref.model.groups; import java.util.List; import java.util.Objects; import java.util.Optional; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.paint.Color; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.SearchMatcher; import org.jabref.model.strings.StringUtil; /** * Base class for all groups. */ public abstract class AbstractGroup implements SearchMatcher { /** * The group's name. */ protected final StringProperty name = new SimpleStringProperty(); /** * The hierarchical context of the group. */ protected final GroupHierarchyType context; protected Optional<Color> color = Optional.empty(); protected boolean isExpanded = true; protected Optional<String> description = Optional.empty(); protected Optional<String> iconName = Optional.empty(); protected AbstractGroup(String name, GroupHierarchyType context) { this.name.setValue(name); this.context = Objects.requireNonNull(context); } @Override public String toString() { return "AbstractGroup{" + "name='" + name.getValue() + '\'' + ", context=" + context + ", color=" + color + ", isExpanded=" + isExpanded + ", description=" + description + ", iconName=" + iconName + '}'; } @Override public boolean equals(Object other) { if (this == other) { return true; } if ((other == null) || (getClass() != other.getClass())) { return false; } AbstractGroup that = (AbstractGroup) other; return Objects.equals(this.name.getValue(), that.name.getValue()) && Objects.equals(this.description, that.description) && Objects.equals(this.context, that.context); } @Override public int hashCode() { return Objects.hash(name.getValue(), description, context); } public Optional<Color> getColor() { return color; } public void setColor(Color color) { this.color = Optional.of(color); } public void setColor(String colorString) { if (StringUtil.isBlank(colorString)) { color = Optional.empty(); } else { setColor(Color.valueOf(colorString)); } } public boolean isExpanded() { return isExpanded; } public void setExpanded(boolean expanded) { isExpanded = expanded; } public Optional<String> getDescription() { return description; } public void setDescription(String description) { if (StringUtil.isBlank(description)) { this.description = Optional.empty(); } else { this.description = Optional.of(description); } } public Optional<String> getIconName() { return iconName; } public void setIconName(String iconName) { if (StringUtil.isBlank(iconName)) { this.iconName = Optional.empty(); } else { this.iconName = Optional.of(iconName); } } /** * Returns the way this group relates to its sub- or supergroup. */ public GroupHierarchyType getHierarchicalContext() { return context; } /** * Returns this group's name, e.g. for display in a list/tree. */ public final String getName() { return name.getValue(); } public StringProperty nameProperty() { return name; } /** * @return true if this group contains the specified entry, false otherwise. */ public abstract boolean contains(BibEntry entry); @Override public boolean isMatch(BibEntry entry) { return contains(entry); } /** * @return true if this group contains any of the specified entries, false otherwise. */ public boolean containsAny(List<BibEntry> entries) { for (BibEntry entry : entries) { if (contains(entry)) { return true; } } return false; } /** * @return true if this group contains all of the specified entries, false otherwise. */ public boolean containsAll(List<BibEntry> entries) { for (BibEntry entry : entries) { if (!contains(entry)) { return false; } } return true; } /** * Returns true if this group is dynamic, i.e. uses a search definition or * equiv. that might match new entries, or false if this group contains a * fixed set of entries and thus will never match a new entry that was not * explicitly added to it. */ public abstract boolean isDynamic(); /** * @return A deep copy of this object. */ public abstract AbstractGroup deepCopy(); }
4,924
26.209945
127
java
null
jabref-main/src/main/java/org/jabref/model/groups/AllEntriesGroup.java
package org.jabref.model.groups; import java.util.Objects; import org.jabref.model.entry.BibEntry; /** * This group contains all entries. Always. At any time! */ public class AllEntriesGroup extends AbstractGroup { public AllEntriesGroup(String name) { super(name, GroupHierarchyType.INDEPENDENT); } @Override public AbstractGroup deepCopy() { return new AllEntriesGroup(getName()); } @Override public boolean equals(Object o) { return o instanceof AllEntriesGroup aeg && Objects.equals(aeg.getName(), getName()); } @Override public boolean contains(BibEntry entry) { return true; } @Override public boolean isDynamic() { // this is actually a special case; I define it as non-dynamic return false; } @Override public int hashCode() { return getName().hashCode(); } }
903
20.52381
92
java
null
jabref-main/src/main/java/org/jabref/model/groups/AutomaticGroup.java
package org.jabref.model.groups; import java.util.Set; import javafx.collections.ObservableList; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.TreeCollector; public abstract class AutomaticGroup extends AbstractGroup { public AutomaticGroup(String name, GroupHierarchyType context) { super(name, context); } @Override public boolean contains(BibEntry entry) { return false; } @Override public boolean isDynamic() { return false; } public abstract Set<GroupTreeNode> createSubgroups(BibEntry entry); public ObservableList<GroupTreeNode> createSubgroups(ObservableList<BibEntry> entries) { // TODO: Propagate changes to entry list (however: there is no flatMap and collect as TransformationList) return entries.stream() .flatMap(entry -> createSubgroups(entry).stream()) .collect(TreeCollector.mergeIntoTree(GroupTreeNode::isSameGroupAs)); } }
1,001
28.470588
113
java
null
jabref-main/src/main/java/org/jabref/model/groups/AutomaticKeywordGroup.java
package org.jabref.model.groups; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Keyword; import org.jabref.model.entry.KeywordList; import org.jabref.model.entry.field.Field; import org.jabref.model.strings.StringUtil; public class AutomaticKeywordGroup extends AutomaticGroup { private final Character keywordDelimiter; private final Character keywordHierarchicalDelimiter; private final Field field; public AutomaticKeywordGroup(String name, GroupHierarchyType context, Field field, Character keywordDelimiter, Character keywordHierarchicalDelimiter) { super(name, context); this.field = field; this.keywordDelimiter = keywordDelimiter; this.keywordHierarchicalDelimiter = keywordHierarchicalDelimiter; } public Character getKeywordHierarchicalDelimiter() { return keywordHierarchicalDelimiter; } public Character getKeywordDelimiter() { return keywordDelimiter; } public Field getField() { return field; } @Override public AbstractGroup deepCopy() { return new AutomaticKeywordGroup(this.name.getValue(), this.context, field, this.keywordDelimiter, keywordHierarchicalDelimiter); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AutomaticKeywordGroup that = (AutomaticKeywordGroup) o; return Objects.equals(keywordDelimiter, that.keywordDelimiter) && Objects.equals(field, that.field); } @Override public int hashCode() { return Objects.hash(keywordDelimiter, field); } @Override public Set<GroupTreeNode> createSubgroups(BibEntry entry) { KeywordList keywordList = entry.getFieldAsKeywords(field, keywordDelimiter); return keywordList.stream() .filter(keyword -> StringUtil.isNotBlank(keyword.get())) .map(this::createGroup) .collect(Collectors.toSet()); } private GroupTreeNode createGroup(Keyword keywordChain) { WordKeywordGroup rootGroup = new WordKeywordGroup( keywordChain.get(), GroupHierarchyType.INCLUDING, field, keywordChain.getPathFromRootAsString(keywordHierarchicalDelimiter), true, keywordDelimiter, true); GroupTreeNode root = new GroupTreeNode(rootGroup); keywordChain.getChild() .map(this::createGroup) .ifPresent(root::addChild); return root; } }
2,820
31.802326
156
java
null
jabref-main/src/main/java/org/jabref/model/groups/AutomaticPersonsGroup.java
package org.jabref.model.groups; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; public class AutomaticPersonsGroup extends AutomaticGroup { private final Field field; public AutomaticPersonsGroup(String name, GroupHierarchyType context, Field field) { super(name, context); this.field = field; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AutomaticPersonsGroup that = (AutomaticPersonsGroup) o; return Objects.equals(field, that.field); } @Override public int hashCode() { return Objects.hash(field); } @Override public AbstractGroup deepCopy() { return new AutomaticPersonsGroup(this.name.getValue(), this.context, this.field); } @Override public Set<GroupTreeNode> createSubgroups(BibEntry entry) { return LastNameGroup.getAsLastNamesLatexFree(field, entry) .stream() .map(lastName -> new LastNameGroup(lastName, GroupHierarchyType.INDEPENDENT, field, lastName)) .map(GroupTreeNode::new) .collect(Collectors.toSet()); } public Field getField() { return field; } }
1,492
26.648148
122
java
null
jabref-main/src/main/java/org/jabref/model/groups/ExplicitGroup.java
package org.jabref.model.groups; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.jabref.model.entry.field.StandardField; /** * This group contains entries, which were manually assigned to it. * Assignments are stored in the {@link StandardField#GROUPS} field. * Thus, internally, we represent {@link ExplicitGroup} as a special {@link WordKeywordGroup} operating on * {@link StandardField#GROUPS}. */ public class ExplicitGroup extends WordKeywordGroup { /** * Previous versions of JabRef stored the linked entries directly in the "jabref-meta" comment at the end of the * file. These keys are still parsed and stored in this field. */ private final List<String> legacyEntryKeys = new ArrayList<>(); public ExplicitGroup(String name, GroupHierarchyType context, Character keywordSeparator) { super(name, context, StandardField.GROUPS, name, true, keywordSeparator, true); } public void addLegacyEntryKey(String key) { this.legacyEntryKeys.add(key); } @Override public AbstractGroup deepCopy() { ExplicitGroup copy = new ExplicitGroup(getName(), getHierarchicalContext(), keywordSeparator); copy.legacyEntryKeys.addAll(legacyEntryKeys); return copy; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ExplicitGroup)) { return false; } ExplicitGroup other = (ExplicitGroup) o; return Objects.equals(getName(), other.getName()) && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext()) && Objects.equals(getIconName(), other.getIconName()) && Objects.equals(getDescription(), other.getDescription()) && Objects.equals(getColor(), other.getColor()) && Objects.equals(isExpanded(), other.isExpanded()) && Objects.equals(getLegacyEntryKeys(), other.getLegacyEntryKeys()); } public void clearLegacyEntryKeys() { legacyEntryKeys.clear(); } public List<String> getLegacyEntryKeys() { return Collections.unmodifiableList(legacyEntryKeys); } @Override public int hashCode() { return Objects.hash(name.getValue(), context, legacyEntryKeys, iconName, color, description, isExpanded); } @Override public boolean isDynamic() { return false; } }
2,524
32.666667
116
java
null
jabref-main/src/main/java/org/jabref/model/groups/GroupEntryChanger.java
package org.jabref.model.groups; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; /** * Some groups can change entries so that they match (or no longer match) the group. * This functionality is encoded in this interface. */ public interface GroupEntryChanger { /** * Adds the specified entries to this group. * * @return If this group or one or more entries was/were modified as a * result of this operation, a list of changes is returned. */ List<FieldChange> add(Collection<BibEntry> entriesToAdd); default List<FieldChange> add(BibEntry entryToAdd) { return add(Collections.singletonList(entryToAdd)); } /** * Removes the specified entries from this group. * * @return If this group or one or more entries was/were modified as a * result of this operation, a list of changes is returned. */ List<FieldChange> remove(List<BibEntry> entriesToRemove); default List<FieldChange> remove(BibEntry entryToAdd) { return remove(Collections.singletonList(entryToAdd)); } }
1,184
28.625
84
java
null
jabref-main/src/main/java/org/jabref/model/groups/GroupHierarchyType.java
package org.jabref.model.groups; public enum GroupHierarchyType { /** * Group's contents are independent of its hierarchical position. */ INDEPENDENT("Independent"), /** * Group's content is the intersection of its own content with its supergroup's content. */ REFINING("Intersection"), // INTERSECTION /** * Group's content is the union of its own content with its subgroups' content. */ INCLUDING("Union"); // UNION private final String displayName; GroupHierarchyType(String displayName) { this.displayName = displayName; } /** * Returns the hierarchy type from its position in this enum. * If the specified position is out of the enums bounds, then {@link #INDEPENDENT} is returned. */ public static GroupHierarchyType getByNumberOrDefault(int type) { GroupHierarchyType[] types = values(); if (type >= 0 && type < types.length) { return types[type]; } else { return INDEPENDENT; } } public String getDisplayName() { return displayName; } }
1,126
25.209302
99
java
null
jabref-main/src/main/java/org/jabref/model/groups/GroupTreeNode.java
package org.jabref.model.groups; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.model.FieldChange; import org.jabref.model.TreeNode; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.SearchMatcher; import org.jabref.model.search.matchers.MatcherSet; import org.jabref.model.search.matchers.MatcherSets; /** * A node in the groups tree that holds exactly one AbstractGroup. */ public class GroupTreeNode extends TreeNode<GroupTreeNode> { private static final String PATH_DELIMITER = " > "; private AbstractGroup group; /** * Creates this node and associates the specified group with it. * * @param group the group underlying this node */ public GroupTreeNode(AbstractGroup group) { super(GroupTreeNode.class); setGroup(group, false, false, null); } public static GroupTreeNode fromGroup(AbstractGroup group) { return new GroupTreeNode(group); } /** * Returns the group underlying this node. * * @return the group associated with this node */ public AbstractGroup getGroup() { return group; } /** * Associates the specified group with this node. * * @param newGroup the new group (has to be non-null) * @deprecated use {@link #setGroup(AbstractGroup, boolean, boolean, List)}} instead */ @Deprecated public void setGroup(AbstractGroup newGroup) { this.group = Objects.requireNonNull(newGroup); } /** * Associates the specified group with this node while also providing the possibility to modify previous matched entries so that they are now matched by the new group. * * @param newGroup the new group (has to be non-null) * @param shouldKeepPreviousAssignments specifies whether previous matched entries should be added to the new group * @param shouldRemovePreviousAssignments specifies whether previous matched entries should be removed from the old group * @param entriesInDatabase list of entries in the database */ public List<FieldChange> setGroup(AbstractGroup newGroup, boolean shouldKeepPreviousAssignments, boolean shouldRemovePreviousAssignments, List<BibEntry> entriesInDatabase) { AbstractGroup oldGroup = getGroup(); group = Objects.requireNonNull(newGroup); List<FieldChange> changes = new ArrayList<>(); boolean shouldRemoveFromOldGroup = shouldRemovePreviousAssignments && (oldGroup instanceof GroupEntryChanger); boolean shouldAddToNewGroup = shouldKeepPreviousAssignments && (newGroup instanceof GroupEntryChanger); if (shouldAddToNewGroup || shouldRemoveFromOldGroup) { List<BibEntry> entriesMatchedByOldGroup = entriesInDatabase.stream().filter(oldGroup::isMatch) .collect(Collectors.toList()); if (shouldRemoveFromOldGroup) { GroupEntryChanger entryChanger = (GroupEntryChanger) oldGroup; changes.addAll(entryChanger.remove(entriesMatchedByOldGroup)); } if (shouldAddToNewGroup) { GroupEntryChanger entryChanger = (GroupEntryChanger) newGroup; changes.addAll(entryChanger.add(entriesMatchedByOldGroup)); } } return changes; } /** * Creates a {@link SearchMatcher} that matches entries of this group and that takes the hierarchical information into account. I.e., it finds elements contained in this nodes group, or the union of those elements in its own group and its children's groups (recursively), or the intersection of the elements in its own group and its parent's group (depending on the hierarchical settings stored in the involved groups) */ public SearchMatcher getSearchMatcher() { return getSearchMatcher(group.getHierarchicalContext()); } private SearchMatcher getSearchMatcher(GroupHierarchyType originalContext) { final GroupHierarchyType context = group.getHierarchicalContext(); if (context == GroupHierarchyType.INDEPENDENT) { return group; } MatcherSet searchRule = MatcherSets.build( context == GroupHierarchyType.REFINING ? MatcherSets.MatcherType.AND : MatcherSets.MatcherType.OR); searchRule.addRule(group); if ((context == GroupHierarchyType.INCLUDING) && (originalContext != GroupHierarchyType.REFINING)) { for (GroupTreeNode child : getChildren()) { searchRule.addRule(child.getSearchMatcher(originalContext)); } } else if ((context == GroupHierarchyType.REFINING) && !isRoot() && (originalContext != GroupHierarchyType.INCLUDING)) { // noinspection OptionalGetWithoutIsPresent searchRule.addRule(getParent().get().getSearchMatcher(originalContext)); } return searchRule; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } GroupTreeNode that = (GroupTreeNode) o; return Objects.equals(group, that.group) && Objects.equals(getChildren(), that.getChildren()); } @Override public int hashCode() { return Objects.hash(group); } public List<GroupTreeNode> getContainingGroups(List<BibEntry> entries, boolean requireAll) { List<GroupTreeNode> groups = new ArrayList<>(); // Add myself if I contain the entries if (requireAll) { if (this.group.containsAll(entries)) { groups.add(this); } } else { if (this.group.containsAny(entries)) { groups.add(this); } } // Traverse children for (GroupTreeNode child : getChildren()) { groups.addAll(child.getContainingGroups(entries, requireAll)); } return groups; } /** * Determines all groups in the subtree starting at this node which contain the given entry. */ public List<GroupTreeNode> getMatchingGroups(BibEntry entry) { return getMatchingGroups(Collections.singletonList(entry)); } /** * Determines all groups in the subtree starting at this node which contain at least one of the given entries. */ public List<GroupTreeNode> getMatchingGroups(List<BibEntry> entries) { List<GroupTreeNode> groups = new ArrayList<>(); // Add myself if I contain the entries SearchMatcher matcher = getSearchMatcher(); for (BibEntry entry : entries) { if (matcher.isMatch(entry)) { groups.add(this); break; } } // Traverse children for (GroupTreeNode child : getChildren()) { groups.addAll(child.getMatchingGroups(entries)); } return groups; } public List<BibEntry> getEntriesInGroup(List<BibEntry> entries) { List<BibEntry> result = new ArrayList<>(); for (BibEntry entry : entries) { if (this.group.contains(entry)) { result.add(entry); } } return result; } public String getName() { return group.getName(); } public GroupTreeNode addSubgroup(AbstractGroup subgroup) { GroupTreeNode child = GroupTreeNode.fromGroup(subgroup); addChild(child); return child; } @Override public GroupTreeNode copyNode() { return GroupTreeNode.fromGroup(group); } /** * Determines the entries in the specified list which are matched by this group. * * @param entries list of entries to be searched * @return matched entries */ public List<BibEntry> findMatches(List<BibEntry> entries) { SearchMatcher matcher = getSearchMatcher(); return entries.stream() .filter(matcher::isMatch) .collect(Collectors.toList()); } /** * Determines the entries in the specified database which are matched by this group. * * @param database database to be searched * @return matched entries */ public List<BibEntry> findMatches(BibDatabase database) { return findMatches(database.getEntries()); } /** * Returns whether this group matches the specified {@link BibEntry} while taking the hierarchical information into account. */ public boolean matches(BibEntry entry) { return getSearchMatcher().isMatch(entry); } /** * Get the path from the root of the tree as a string (every group name is separated by {@link #PATH_DELIMITER}. * <p> * The name of the root is not included. */ public String getPath() { return getPathFromRoot().stream() .skip(1) // Skip root .map(GroupTreeNode::getName) .collect(Collectors.joining(PATH_DELIMITER)); } @Override public String toString() { return "GroupTreeNode{" + "group=" + group + '}'; } /** * Finds a children using the given path. Each group name should be separated by {@link #PATH_DELIMITER}. * <p> * The path should be generated using {@link #getPath()}. */ public Optional<GroupTreeNode> getChildByPath(String pathToSource) { GroupTreeNode present = this; for (String groupName : pathToSource.split(PATH_DELIMITER)) { Optional<GroupTreeNode> childWithName = present .getChildren().stream() .filter(group -> Objects.equals(group.getName(), groupName)) .findFirst(); if (childWithName.isPresent()) { present = childWithName.get(); } else { // No child with that name found -> path seems to be invalid return Optional.empty(); } } return Optional.of(present); } /** * Adds the specified entries to this group. If the group does not support explicit adding of entries (i.e., does not implement {@link GroupEntryChanger}), then no action is performed. */ public List<FieldChange> addEntriesToGroup(Collection<BibEntry> entries) { if (getGroup() instanceof GroupEntryChanger) { return ((GroupEntryChanger) getGroup()).add(entries); } else { return Collections.emptyList(); } } /** * Removes the given entries from this group. If the group does not support the explicit removal of entries (i.e., does not implement {@link GroupEntryChanger}), then no action is performed. */ public List<FieldChange> removeEntriesFromGroup(List<BibEntry> entries) { if (getGroup() instanceof GroupEntryChanger) { return ((GroupEntryChanger) getGroup()).remove(entries); } else { return Collections.emptyList(); } } /** * Returns true if the underlying groups of both {@link GroupTreeNode}s is the same. */ public boolean isSameGroupAs(GroupTreeNode other) { return Objects.equals(group, other.group); } }
11,671
35.936709
422
java
null
jabref-main/src/main/java/org/jabref/model/groups/KeywordGroup.java
package org.jabref.model.groups; import java.util.Objects; import org.jabref.model.entry.field.Field; /** * Matches entries based on a search phrase relative to the content in a specified field. */ public abstract class KeywordGroup extends AbstractGroup { protected final Field searchField; protected final String searchExpression; protected final boolean caseSensitive; public KeywordGroup(String name, GroupHierarchyType context, Field searchField, String searchExpression, boolean caseSensitive) { super(name, context); this.caseSensitive = caseSensitive; this.searchField = searchField; this.searchExpression = searchExpression; } public boolean isCaseSensitive() { return caseSensitive; } public String getSearchExpression() { return searchExpression; } public Field getSearchField() { return searchField; } @Override public boolean isDynamic() { return true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } KeywordGroup that = (KeywordGroup) o; return isCaseSensitive() == that.isCaseSensitive() && Objects.equals(getSearchField(), that.getSearchField()) && Objects.equals(getSearchExpression(), that.getSearchExpression()); } @Override public int hashCode() { return Objects.hash(super.hashCode(), getSearchField(), getSearchExpression(), isCaseSensitive()); } }
1,668
27.288136
187
java
null
jabref-main/src/main/java/org/jabref/model/groups/LastNameGroup.java
package org.jabref.model.groups; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; 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.strings.LatexToUnicodeAdapter; /** * Matches based on a latex free last name in a specified field. The field is parsed as an author list and the last names are resolved of latex. */ public class LastNameGroup extends KeywordGroup { public LastNameGroup(String groupName, GroupHierarchyType context, Field searchField, String lastName) { super(groupName, context, searchField, LatexToUnicodeAdapter.format(lastName), true); } static List<String> getAsLastNamesLatexFree(Field field, BibEntry bibEntry) { return bibEntry.getField(field).stream() .map(AuthorList::parse) .map(AuthorList::latexFree) .map(AuthorList::getAuthors) .flatMap(Collection::stream) .map(Author::getLast) .flatMap(Optional::stream) .collect(Collectors.toList()); } @Override public boolean contains(BibEntry entry) { return getAsLastNamesLatexFree(getSearchField(), entry).stream().anyMatch(name -> name.equals(getSearchExpression())); } @Override public AbstractGroup deepCopy() { return new LastNameGroup(getName(), getHierarchicalContext(), getSearchField(), getSearchExpression()); } }
1,637
37.093023
144
java
null
jabref-main/src/main/java/org/jabref/model/groups/RegexKeywordGroup.java
package org.jabref.model.groups; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; /** * Matches entries if the content of a given field is matched by a regular expression. */ public class RegexKeywordGroup extends KeywordGroup { private Pattern pattern; public RegexKeywordGroup(String name, GroupHierarchyType context, Field searchField, String searchExpression, boolean caseSensitive) { super(name, context, searchField, searchExpression, caseSensitive); this.pattern = compilePattern(searchExpression, caseSensitive); } private static Pattern compilePattern(String searchExpression, boolean caseSensitive) { return caseSensitive ? Pattern.compile("\\b" + searchExpression + "\\b") : Pattern.compile( "\\b" + searchExpression + "\\b", Pattern.CASE_INSENSITIVE); } @Override public boolean contains(BibEntry entry) { Optional<String> content = entry.getField(searchField); return content.map(value -> pattern.matcher(value).find()).orElse(false); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof RegexKeywordGroup)) { return false; } RegexKeywordGroup other = (RegexKeywordGroup) o; return getName().equals(other.getName()) && (getHierarchicalContext() == other.getHierarchicalContext()) && searchField.equals(other.searchField) && searchExpression.equals(other.searchExpression) && (caseSensitive == other.caseSensitive); } @Override public AbstractGroup deepCopy() { return new RegexKeywordGroup(getName(), getHierarchicalContext(), searchField, searchExpression, caseSensitive); } @Override public int hashCode() { return Objects.hash(getName(), getHierarchicalContext(), searchField, searchExpression, caseSensitive); } }
2,190
33.234375
104
java
null
jabref-main/src/main/java/org/jabref/model/groups/SearchGroup.java
package org.jabref.model.groups; import java.util.EnumSet; import java.util.Objects; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.GroupSearchQuery; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This group matches entries by a complex search pattern, which might include conditions about the values of * multiple fields. */ public class SearchGroup extends AbstractGroup { private static final Logger LOGGER = LoggerFactory.getLogger(SearchGroup.class); private final GroupSearchQuery query; public SearchGroup(String name, GroupHierarchyType context, String searchExpression, EnumSet<SearchFlags> searchFlags) { super(name, context); this.query = new GroupSearchQuery(searchExpression, searchFlags); } public String getSearchExpression() { return query.getSearchExpression(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SearchGroup)) { return false; } SearchGroup other = (SearchGroup) o; return Objects.equals(getName(), other.getName()) && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext()) && Objects.equals(getSearchExpression(), other.getSearchExpression()) && Objects.equals(getSearchFlags(), other.getSearchFlags()); } @Override public boolean contains(BibEntry entry) { return query.isMatch(entry); } public EnumSet<SearchFlags> getSearchFlags() { return query.getSearchFlags(); } @Override public AbstractGroup deepCopy() { try { return new SearchGroup(getName(), getHierarchicalContext(), getSearchExpression(), getSearchFlags()); } catch (Throwable t) { // this should never happen, because the constructor obviously // succeeded in creating _this_ instance! LOGGER.error("Internal error in SearchGroup.deepCopy(). " + "Please report this on https://github.com/JabRef/jabref/issues", t); return null; } } @Override public String toString() { return "SearchGroup [query=" + query + ", name=" + name + ", searchFlags=" + getSearchFlags() + ", context=" + context + ", color=" + color + ", isExpanded=" + isExpanded + ", description=" + description + ", iconName=" + iconName + "]"; } @Override public boolean isDynamic() { return true; } @Override public int hashCode() { return Objects.hash(getName(), getHierarchicalContext(), getSearchExpression(), getSearchFlags()); } }
2,771
32.39759
246
java
null
jabref-main/src/main/java/org/jabref/model/groups/TexGroup.java
package org.jabref.model.groups; import java.io.IOException; import java.net.InetAddress; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.auxparser.AuxParser; import org.jabref.logic.auxparser.AuxParserResult; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.BibEntry; import org.jabref.model.metadata.MetaData; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateListener; import org.jabref.model.util.FileUpdateMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @AllowedToUseLogic("because it needs access to aux parser") public class TexGroup extends AbstractGroup implements FileUpdateListener { private static final Logger LOGGER = LoggerFactory.getLogger(TexGroup.class); private final Path filePath; private Set<String> keysUsedInAux; private final FileUpdateMonitor fileMonitor; private final AuxParser auxParser; private final MetaData metaData; private final String user; TexGroup(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData, String user) { super(name, context); this.metaData = metaData; this.user = user; this.filePath = expandPath(Objects.requireNonNull(filePath)); this.auxParser = auxParser; this.fileMonitor = fileMonitor; } TexGroup(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData) throws IOException { this(name, context, filePath, auxParser, fileMonitor, metaData, System.getProperty("user.name") + '-' + InetAddress.getLocalHost().getHostName()); } public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData) throws IOException { TexGroup group = new TexGroup(name, context, filePath, auxParser, fileMonitor, metaData); fileMonitor.addListenerForFile(group.getFilePathResolved(), group); return group; } // without FileUpdateMonitor public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, MetaData metaData) throws IOException { return new TexGroup(name, context, filePath, auxParser, new DummyFileUpdateMonitor(), metaData); } public Path getFilePathResolved() { return this.filePath; } @Override public boolean contains(BibEntry entry) { if (keysUsedInAux == null) { AuxParserResult auxResult = auxParser.parse(filePath); keysUsedInAux = auxResult.getUniqueKeys(); } return entry.getCitationKey().map(keysUsedInAux::contains).orElse(false); } @Override public boolean isDynamic() { return false; } @Override public AbstractGroup deepCopy() { try { return new TexGroup(name.getValue(), context, filePath, auxParser, fileMonitor, metaData); } catch (IOException ex) { // This should never happen because we were able to monitor the file just fine until now LOGGER.error("Problem creating copy of group", ex); return null; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } if (!super.equals(o)) { return false; } TexGroup group = (TexGroup) o; return Objects.equals(filePath, group.filePath); } @Override public String toString() { return "TexGroup{" + "filePath=" + filePath + ", keysUsedInAux=" + keysUsedInAux + ", auxParser=" + auxParser + ", fileMonitor=" + fileMonitor + "} " + super.toString(); } @Override public int hashCode() { return Objects.hash(super.hashCode(), filePath); } public Path getFilePath() { return relativize(filePath); } @Override public void fileUpdated() { // Reset previous parse result keysUsedInAux = null; metaData.groupsBinding().invalidate(); } private Path relativize(Path path) { List<Path> fileDirectories = getFileDirectoriesAsPaths(); return FileUtil.relativize(path, fileDirectories); } private Path expandPath(Path path) { List<Path> fileDirectories = getFileDirectoriesAsPaths(); return FileUtil.find(path.toString(), fileDirectories).orElse(path); } private List<Path> getFileDirectoriesAsPaths() { return metaData.getLatexFileDirectory(user) .map(List::of) .orElse(Collections.emptyList()); } }
5,045
33.326531
181
java
null
jabref-main/src/main/java/org/jabref/model/groups/WordKeywordGroup.java
package org.jabref.model.groups; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.KeywordList; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.ListUtil; /** * Matches entries if a given field contains a specified word. */ public class WordKeywordGroup extends KeywordGroup implements GroupEntryChanger { protected final Character keywordSeparator; private final SearchStrategy searchStrategy; private final boolean onlySplitWordsAtSeparator; public WordKeywordGroup(String name, GroupHierarchyType context, Field searchField, String searchExpression, boolean caseSensitive, Character keywordSeparator, boolean onlySplitWordsAtSeparator) { super(name, context, searchField, searchExpression, caseSensitive); this.keywordSeparator = keywordSeparator; this.onlySplitWordsAtSeparator = onlySplitWordsAtSeparator; if (onlySplitWordsAtSeparator) { if (InternalField.TYPE_HEADER == searchField) { searchStrategy = new TypeSearchStrategy(); } else { searchStrategy = new KeywordListSearchStrategy(); } } else { searchStrategy = new StringSearchStrategy(); } } private static boolean containsCaseInsensitive(Set<String> searchIn, Collection<String> searchFor) { for (String searchWord : searchFor) { if (!containsCaseInsensitive(searchIn, searchWord)) { return false; } } return true; } private static boolean containsCaseInsensitive(Set<String> searchIn, String searchFor) { for (String word : searchIn) { if (word.equalsIgnoreCase(searchFor)) { return true; } } return false; } @Override public List<FieldChange> add(Collection<BibEntry> entriesToAdd) { Objects.requireNonNull(entriesToAdd); List<FieldChange> changes = new ArrayList<>(); for (BibEntry entry : new ArrayList<>(entriesToAdd)) { if (!contains(entry)) { String oldContent = entry.getField(searchField).orElse(""); KeywordList wordlist = KeywordList.parse(oldContent, keywordSeparator); wordlist.add(searchExpression); String newContent = wordlist.getAsString(keywordSeparator); entry.setField(searchField, newContent).ifPresent(changes::add); } } return changes; } @Override public List<FieldChange> remove(List<BibEntry> entriesToRemove) { Objects.requireNonNull(entriesToRemove); List<FieldChange> changes = new ArrayList<>(); for (BibEntry entry : new ArrayList<>(entriesToRemove)) { if (contains(entry)) { String oldContent = entry.getField(searchField).orElse(""); KeywordList wordlist = KeywordList.parse(oldContent, keywordSeparator); wordlist.remove(searchExpression); String newContent = wordlist.getAsString(keywordSeparator); entry.setField(searchField, newContent).ifPresent(changes::add); } } return changes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof WordKeywordGroup)) { return false; } WordKeywordGroup other = (WordKeywordGroup) o; return Objects.equals(getName(), other.getName()) && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext()) && Objects.equals(searchField, other.searchField) && Objects.equals(searchExpression, other.searchExpression) && Objects.equals(caseSensitive, other.caseSensitive) && Objects.equals(keywordSeparator, other.keywordSeparator) && Objects.equals(onlySplitWordsAtSeparator, other.onlySplitWordsAtSeparator); } @Override public boolean contains(BibEntry entry) { return searchStrategy.contains(entry); } @Override public AbstractGroup deepCopy() { return new WordKeywordGroup(getName(), getHierarchicalContext(), searchField, searchExpression, caseSensitive, keywordSeparator, onlySplitWordsAtSeparator); } @Override public int hashCode() { return Objects.hash(getName(), getHierarchicalContext(), searchField, searchExpression, caseSensitive, keywordSeparator, onlySplitWordsAtSeparator); } interface SearchStrategy { boolean contains(BibEntry entry); } class StringSearchStrategy implements SearchStrategy { Set<String> searchWords; StringSearchStrategy() { searchWords = new HashSet<>(StringUtil.getStringAsWords(searchExpression)); } @Override public boolean contains(BibEntry entry) { Set<String> content = entry.getFieldAsWords(searchField); if (caseSensitive) { return content.containsAll(searchWords); } else { return containsCaseInsensitive(content, searchWords); } } } class TypeSearchStrategy implements SearchStrategy { Set<EntryType> searchWords; TypeSearchStrategy() { searchWords = KeywordList.parse(searchExpression, keywordSeparator) .stream() .map(word -> EntryTypeFactory.parse(word.get())) .collect(Collectors.toSet()); } @Override public boolean contains(BibEntry entry) { return searchWords.stream() .anyMatch(word -> entry.getType().equals(word)); } } class KeywordListSearchStrategy implements SearchStrategy { private final KeywordList searchWords; KeywordListSearchStrategy() { searchWords = KeywordList.parse(searchExpression, keywordSeparator); } @Override public boolean contains(BibEntry entry) { KeywordList fieldValue = entry.getFieldAsKeywords(searchField, keywordSeparator); return ListUtil.allMatch(searchWords, fieldValue::contains); } } }
6,943
34.610256
104
java
null
jabref-main/src/main/java/org/jabref/model/groups/event/GroupUpdatedEvent.java
package org.jabref.model.groups.event; import org.jabref.model.database.event.BibDatabaseContextChangedEvent; import org.jabref.model.metadata.MetaData; public class GroupUpdatedEvent extends BibDatabaseContextChangedEvent { private final MetaData metaData; /** * @param metaData Affected instance */ public GroupUpdatedEvent(MetaData metaData) { this.metaData = metaData; } public MetaData getMetaData() { return this.metaData; } }
488
22.285714
71
java
null
jabref-main/src/main/java/org/jabref/model/metadata/ContentSelector.java
package org.jabref.model.metadata; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import org.jabref.model.entry.field.Field; public class ContentSelector { private final Field field; private final List<String> values; public ContentSelector(Field field, String... values) { this(field, Arrays.asList(values)); } public ContentSelector(Field field, List<String> values) { this.field = field; this.values = values; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } ContentSelector that = (ContentSelector) o; return Objects.equals(field, that.field) && Objects.equals(values, that.values); } @Override public String toString() { return "ContentSelector [field=" + field + ", values=" + values + "]"; } @Override public int hashCode() { return Objects.hash(field, values); } public Field getField() { return field; } public List<String> getValues() { return Collections.unmodifiableList(values); } }
1,281
21.892857
78
java
null
jabref-main/src/main/java/org/jabref/model/metadata/ContentSelectors.java
package org.jabref.model.metadata; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import org.jabref.model.entry.field.Field; public class ContentSelectors { private final List<ContentSelector> contentSelectors; public ContentSelectors() { contentSelectors = new ArrayList<>(); } public void addContentSelector(ContentSelector contentSelector) { Objects.requireNonNull(contentSelector); this.contentSelectors.add(contentSelector); } public static ContentSelector parse(Field key, String values) { Objects.requireNonNull(key); Objects.requireNonNull(values); List<String> valueList = Arrays.asList(values.split(";")); return new ContentSelector(key, valueList); } public List<String> getSelectorValuesForField(Field field) { for (ContentSelector selector : contentSelectors) { if (selector.getField().equals(field)) { return selector.getValues(); } } return Collections.emptyList(); } public List<ContentSelector> getContentSelectors() { return Collections.unmodifiableList(contentSelectors); } public void removeSelector(Field field) { ContentSelector toRemove = null; for (ContentSelector selector : contentSelectors) { if (selector.getField().equals(field)) { toRemove = selector; break; } } if (toRemove != null) { contentSelectors.remove(toRemove); } } public List<Field> getFieldsWithSelectors() { List<Field> result = new ArrayList<>(contentSelectors.size()); for (ContentSelector selector : contentSelectors) { result.add(selector.getField()); } return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContentSelectors that = (ContentSelectors) o; return Objects.equals(contentSelectors, that.contentSelectors); } @Override public int hashCode() { return Objects.hash(contentSelectors); } }
2,347
25.088889
71
java
null
jabref-main/src/main/java/org/jabref/model/metadata/MetaData.java
package org.jabref.model.metadata; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern; import org.jabref.logic.citationkeypattern.DatabaseCitationKeyPattern; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.event.ChangePropagation; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.types.EntryType; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.groups.event.GroupUpdatedEvent; import org.jabref.model.metadata.event.MetaDataChangedEvent; import com.google.common.eventbus.EventBus; import com.tobiasdiez.easybind.optional.OptionalBinding; import com.tobiasdiez.easybind.optional.OptionalWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @AllowedToUseLogic("because it needs access to citation pattern and cleanups") public class MetaData { public static final String META_FLAG = "jabref-meta: "; public static final String ENTRYTYPE_FLAG = "jabref-entrytype: "; public static final String SAVE_ORDER_CONFIG = "saveOrderConfig"; // ToDo: Rename in next major version to saveOrder, adapt testbibs public static final String SAVE_ACTIONS = "saveActions"; public static final String PREFIX_KEYPATTERN = "keypattern_"; public static final String KEYPATTERNDEFAULT = "keypatterndefault"; public static final String DATABASE_TYPE = "databaseType"; public static final String VERSION_DB_STRUCT = "VersionDBStructure"; public static final String GROUPSTREE = "grouping"; public static final String GROUPSTREE_LEGACY = "groupstree"; public static final String FILE_DIRECTORY = "fileDirectory"; public static final String FILE_DIRECTORY_LATEX = "fileDirectoryLatex"; public static final String PROTECTED_FLAG_META = "protectedFlag"; public static final String SELECTOR_META_PREFIX = "selector_"; public static final char ESCAPE_CHARACTER = '\\'; public static final char SEPARATOR_CHARACTER = ';'; public static final String SEPARATOR_STRING = String.valueOf(SEPARATOR_CHARACTER); private static final Logger LOGGER = LoggerFactory.getLogger(MetaData.class); private final EventBus eventBus = new EventBus(); private final Map<EntryType, String> citeKeyPatterns = new HashMap<>(); // <BibType, Pattern> private final Map<String, String> userFileDirectory = new HashMap<>(); // <User, FilePath> private final Map<String, Path> laTexFileDirectory = new HashMap<>(); // <User, FilePath> private final ObjectProperty<GroupTreeNode> groupsRoot = new SimpleObjectProperty<>(null); private final OptionalBinding<GroupTreeNode> groupsRootBinding = new OptionalWrapper<>(groupsRoot); private Charset encoding; private SaveOrder saveOrder; private String defaultCiteKeyPattern; private FieldFormatterCleanups saveActions; private BibDatabaseMode mode; private boolean isProtected; private String defaultFileDirectory; private final ContentSelectors contentSelectors = new ContentSelectors(); private final Map<String, List<String>> unknownMetaData = new HashMap<>(); private boolean isEventPropagationEnabled = true; private boolean encodingExplicitlySupplied; private String versionDBStructure; /** * Constructs an empty metadata. */ public MetaData() { // Do nothing } public Optional<SaveOrder> getSaveOrderConfig() { return Optional.ofNullable(saveOrder); } public void setSaveOrderConfig(SaveOrder saveOrder) { this.saveOrder = saveOrder; postChange(); } public Optional<GroupTreeNode> getGroups() { return groupsRootBinding.getValue(); } public OptionalBinding<GroupTreeNode> groupsBinding() { return groupsRootBinding; } /** * Sets a new group root node. <b>WARNING </b>: This invalidates everything returned by getGroups() so far!!! */ public void setGroups(GroupTreeNode root) { Objects.requireNonNull(root); groupsRoot.setValue(root); root.subscribeToDescendantChanged(groupTreeNode -> groupsRootBinding.invalidate()); root.subscribeToDescendantChanged(groupTreeNode -> eventBus.post(new GroupUpdatedEvent(this))); eventBus.post(new GroupUpdatedEvent(this)); postChange(); } /** * @return the stored label patterns */ public AbstractCitationKeyPattern getCiteKeyPattern(GlobalCitationKeyPattern globalPattern) { Objects.requireNonNull(globalPattern); AbstractCitationKeyPattern bibtexKeyPattern = new DatabaseCitationKeyPattern(globalPattern); // Add stored key patterns citeKeyPatterns.forEach(bibtexKeyPattern::addCitationKeyPattern); getDefaultCiteKeyPattern().ifPresent(bibtexKeyPattern::setDefaultValue); return bibtexKeyPattern; } /** * Updates the stored key patterns to the given key patterns. * * @param bibtexKeyPattern the key patterns to update to. <br /> A reference to this object is stored internally and is returned at getCiteKeyPattern(); */ public void setCiteKeyPattern(AbstractCitationKeyPattern bibtexKeyPattern) { Objects.requireNonNull(bibtexKeyPattern); List<String> defaultValue = bibtexKeyPattern.getDefaultValue(); Map<EntryType, List<String>> nonDefaultPatterns = bibtexKeyPattern.getPatterns(); setCiteKeyPattern(defaultValue, nonDefaultPatterns); } public void setCiteKeyPattern(List<String> defaultValue, Map<EntryType, List<String>> nonDefaultPatterns) { // Remove all patterns from metadata citeKeyPatterns.clear(); // Set new value if it is not a default value for (Map.Entry<EntryType, List<String>> pattern : nonDefaultPatterns.entrySet()) { citeKeyPatterns.put(pattern.getKey(), pattern.getValue().get(0)); } // Store default pattern if (defaultValue.isEmpty()) { defaultCiteKeyPattern = null; } else { defaultCiteKeyPattern = defaultValue.get(0); } postChange(); } public Optional<FieldFormatterCleanups> getSaveActions() { return Optional.ofNullable(saveActions); } public void setSaveActions(FieldFormatterCleanups saveActions) { this.saveActions = Objects.requireNonNull(saveActions); postChange(); } public Optional<BibDatabaseMode> getMode() { return Optional.ofNullable(mode); } public void setMode(BibDatabaseMode mode) { if (mode == this.mode) { return; } this.mode = Objects.requireNonNull(mode); postChange(); } public boolean isProtected() { return isProtected; } public ContentSelectors getContentSelectors() { return contentSelectors; } public List<ContentSelector> getContentSelectorList() { return contentSelectors.getContentSelectors(); } public void addContentSelector(ContentSelector contentSelector) { this.contentSelectors.addContentSelector(contentSelector); postChange(); } public void clearContentSelectors(Field field) { contentSelectors.removeSelector(field); postChange(); } public List<String> getContentSelectorValuesForField(Field field) { return contentSelectors.getSelectorValuesForField(field); } public Optional<String> getDefaultFileDirectory() { return Optional.ofNullable(defaultFileDirectory); } public void setDefaultFileDirectory(String path) { defaultFileDirectory = Objects.requireNonNull(path).trim(); postChange(); } public Optional<String> getVersionDBStructure() { return Optional.ofNullable(versionDBStructure); } public void setVersionDBStructure(String version) { versionDBStructure = Objects.requireNonNull(version).trim(); postChange(); } public Optional<String> getUserFileDirectory(String user) { return Optional.ofNullable(userFileDirectory.get(user)); } public void markAsProtected() { isProtected = true; postChange(); } public void clearDefaultFileDirectory() { defaultFileDirectory = null; postChange(); } public void setUserFileDirectory(String user, String path) { userFileDirectory.put(Objects.requireNonNull(user), Objects.requireNonNull(path)); postChange(); } public void clearUserFileDirectory(String user) { userFileDirectory.remove(user); postChange(); } public Optional<Path> getLatexFileDirectory(String user) { return Optional.ofNullable(laTexFileDirectory.get(user)); } public void setLatexFileDirectory(String user, Path path) { laTexFileDirectory.put(Objects.requireNonNull(user), Objects.requireNonNull(path)); postChange(); } public void clearLatexFileDirectory(String user) { laTexFileDirectory.remove(user); postChange(); } public void markAsNotProtected() { isProtected = false; postChange(); } public void clearSaveActions() { saveActions = null; postChange(); } public void clearSaveOrderConfig() { saveOrder = null; postChange(); } /** * Posts a new {@link MetaDataChangedEvent} on the {@link EventBus}. */ private void postChange() { if (isEventPropagationEnabled) { eventBus.post(new MetaDataChangedEvent(this)); } } /** * Returns the encoding used during parsing. */ public Optional<Charset> getEncoding() { return Optional.ofNullable(encoding); } public void setEncoding(Charset encoding) { setEncoding(encoding, ChangePropagation.POST_EVENT); } /** * This method (with additional parameter) has been introduced to avoid event loops while saving a database. */ public void setEncoding(Charset encoding, ChangePropagation postChanges) { this.encoding = Objects.requireNonNull(encoding); if (postChanges == ChangePropagation.POST_EVENT) { postChange(); } } public boolean getEncodingExplicitlySupplied() { return encodingExplicitlySupplied; } /** * Sets the indication whether the encoding was set using "% Encoding: ..." or whether it was detected "magically" */ public void setEncodingExplicitlySupplied(boolean encodingExplicitlySupplied) { this.encodingExplicitlySupplied = encodingExplicitlySupplied; } /** * If disabled {@link MetaDataChangedEvent} will not be posted. */ public void setEventPropagation(boolean enabled) { this.isEventPropagationEnabled = enabled; } public void registerListener(Object listener) { this.eventBus.register(listener); } public void unregisterListener(Object listener) { try { this.eventBus.unregister(listener); } catch (IllegalArgumentException e) { // occurs if the event source has not been registered, should not prevent shutdown } } public Optional<String> getDefaultCiteKeyPattern() { return Optional.ofNullable(defaultCiteKeyPattern); } public boolean isEmpty() { return this.equals(new MetaData()); } public Map<String, String> getUserFileDirectories() { return Collections.unmodifiableMap(userFileDirectory); } public Map<String, Path> getLatexFileDirectories() { return Collections.unmodifiableMap(laTexFileDirectory); } public Map<String, List<String>> getUnknownMetaData() { return Collections.unmodifiableMap(unknownMetaData); } public void putUnknownMetaDataItem(String key, List<String> value) { Objects.requireNonNull(key); Objects.requireNonNull(value); unknownMetaData.put(key, value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } MetaData metaData = (MetaData) o; return (isProtected == metaData.isProtected) && Objects.equals(groupsRoot.getValue(), metaData.groupsRoot.getValue()) && Objects.equals(encoding, metaData.encoding) && Objects.equals(encodingExplicitlySupplied, metaData.encodingExplicitlySupplied) && Objects.equals(saveOrder, metaData.saveOrder) && Objects.equals(citeKeyPatterns, metaData.citeKeyPatterns) && Objects.equals(userFileDirectory, metaData.userFileDirectory) && Objects.equals(laTexFileDirectory, metaData.laTexFileDirectory) && Objects.equals(defaultCiteKeyPattern, metaData.defaultCiteKeyPattern) && Objects.equals(saveActions, metaData.saveActions) && (mode == metaData.mode) && Objects.equals(defaultFileDirectory, metaData.defaultFileDirectory) && Objects.equals(contentSelectors, metaData.contentSelectors) && Objects.equals(versionDBStructure, metaData.versionDBStructure); } @Override public int hashCode() { return Objects.hash(isProtected, groupsRoot.getValue(), encoding, encodingExplicitlySupplied, saveOrder, citeKeyPatterns, userFileDirectory, laTexFileDirectory, defaultCiteKeyPattern, saveActions, mode, defaultFileDirectory, contentSelectors, versionDBStructure); } @Override public String toString() { return "MetaData [citeKeyPatterns=" + citeKeyPatterns + ", userFileDirectory=" + userFileDirectory + ", laTexFileDirectory=" + laTexFileDirectory + ", groupsRoot=" + groupsRoot + ", encoding=" + encoding + ", saveOrderConfig=" + saveOrder + ", defaultCiteKeyPattern=" + defaultCiteKeyPattern + ", saveActions=" + saveActions + ", mode=" + mode + ", isProtected=" + isProtected + ", defaultFileDirectory=" + defaultFileDirectory + ", contentSelectors=" + contentSelectors + ", encodingExplicitlySupplied=" + encodingExplicitlySupplied + ", VersionDBStructure=" + versionDBStructure + "]"; } }
14,759
35.80798
595
java
null
jabref-main/src/main/java/org/jabref/model/metadata/SaveOrder.java
package org.jabref.model.metadata; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Stores the save order config from MetaData * <p> * Format: &lt;choice>, pair of field + ascending (boolean) */ public class SaveOrder { public enum OrderType { SPECIFIED("specified"), ORIGINAL("original"), TABLE("table"); private final String name; OrderType(String name) { this.name = name; } @Override public String toString() { return name; } public static SaveOrder.OrderType fromBooleans(boolean saveInSpecifiedOrder, boolean saveInOriginalOrder) { SaveOrder.OrderType orderType = SaveOrder.OrderType.TABLE; if (saveInSpecifiedOrder) { orderType = SaveOrder.OrderType.SPECIFIED; } else if (saveInOriginalOrder) { orderType = SaveOrder.OrderType.ORIGINAL; } return orderType; } } private static final Logger LOGGER = LoggerFactory.getLogger(SaveOrder.class); private final List<SortCriterion> sortCriteria = new ArrayList<>(); private OrderType orderType; private SaveOrder() { } public SaveOrder(OrderType orderType, List<SortCriterion> sortCriteria) { this.orderType = orderType; this.sortCriteria.addAll(sortCriteria); } private SaveOrder(List<String> data) { Objects.requireNonNull(data); if (data.isEmpty()) { throw new IllegalArgumentException(); } try { this.orderType = OrderType.valueOf(data.get(0).toUpperCase()); } catch (IllegalArgumentException ex) { if (data.size() > 1 && data.size() % 2 == 1) { LOGGER.warn("Could not parse sort order: {} - trying to parse the sort criteria", data.get(0)); this.orderType = OrderType.SPECIFIED; } else { LOGGER.warn("Could not parse sort order: {}", data.get(0)); this.orderType = OrderType.ORIGINAL; return; } } for (int index = 1; index < data.size(); index = index + 2) { sortCriteria.add(new SortCriterion(FieldFactory.parseField(data.get(index)), data.get(index + 1))); } } public static SaveOrder parse(List<String> orderedData) { return new SaveOrder(orderedData); } public static SaveOrder getDefaultSaveOrder() { SaveOrder standard = new SaveOrder(); standard.orderType = OrderType.ORIGINAL; return standard; } public OrderType getOrderType() { return orderType; } public List<SortCriterion> getSortCriteria() { return sortCriteria; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof SaveOrder that) { return Objects.equals(sortCriteria, that.sortCriteria) && Objects.equals(orderType, that.orderType); } return false; } @Override public int hashCode() { return Objects.hash(orderType, sortCriteria); } @Override public String toString() { return "SaveOrderConfig{" + "orderType=" + orderType.toString() + ", sortCriteria=" + sortCriteria + '}'; } /** * Outputs the current configuration to be consumed later by the constructor */ public List<String> getAsStringList() { List<String> res = new ArrayList<>(7); if (orderType == OrderType.ORIGINAL) { res.add(OrderType.ORIGINAL.toString()); } else { res.add(OrderType.SPECIFIED.toString()); } for (SortCriterion sortCriterion : sortCriteria) { res.add(sortCriterion.field.getName()); res.add(Boolean.toString(sortCriterion.descending)); } return res; } public static class SortCriterion { public Field field; public boolean descending; /** * * @param field The field * @param descending Must be a boolean value as string, e.g. "true", "false" */ public SortCriterion(Field field, String descending) { this.field = field; this.descending = Boolean.parseBoolean(descending); } public SortCriterion(Field field, boolean descending) { this.field = field; this.descending = descending; } public SortCriterion() { } @Override public String toString() { return "SortCriterion{" + "field='" + field + '\'' + ", descending=" + descending + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } SortCriterion that = (SortCriterion) o; return Objects.equals(descending, that.descending) && Objects.equals(field, that.field); } @Override public int hashCode() { return Objects.hash(field, descending); } } }
5,534
27.096447
115
java
null
jabref-main/src/main/java/org/jabref/model/metadata/event/MetaDataChangedEvent.java
package org.jabref.model.metadata.event; import org.jabref.model.database.event.BibDatabaseContextChangedEvent; import org.jabref.model.metadata.MetaData; /** * {@link MetaDataChangedEvent} is fired when a tuple of metadata has been put or removed. */ public class MetaDataChangedEvent extends BibDatabaseContextChangedEvent { private final MetaData metaData; /** * @param metaData Affected instance */ public MetaDataChangedEvent(MetaData metaData) { super(); this.metaData = metaData; } public MetaData getMetaData() { return this.metaData; } }
612
23.52
90
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/CitationEntry.java
package org.jabref.model.openoffice; import java.util.Objects; import java.util.Optional; public class CitationEntry implements Comparable<CitationEntry> { private final String refMarkName; private final Optional<String> pageInfo; private final String context; public CitationEntry(String refMarkName, String context) { this(refMarkName, context, Optional.empty()); } public CitationEntry(String refMarkName, String context, String pageInfo) { this(refMarkName, context, Optional.ofNullable(pageInfo)); } public CitationEntry(String refMarkName, String context, Optional<String> pageInfo) { this.refMarkName = refMarkName; this.context = context; this.pageInfo = pageInfo; } public Optional<String> getPageInfo() { return pageInfo; } public String getRefMarkName() { return refMarkName; } @Override public int compareTo(CitationEntry other) { return this.refMarkName.compareTo(other.refMarkName); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof CitationEntry other) { return Objects.equals(this.refMarkName, other.refMarkName); } return false; } @Override public int hashCode() { return Objects.hash(refMarkName); } public String getContext() { return context; } }
1,479
24.084746
89
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java
package org.jabref.model.openoffice.backend; import java.util.Optional; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; /** * NamedRange (with NamedRangeManager) attempts to provide a common interface for working with reference mark based and bookmark based text ranges to be used as locations to fill with citation markers. LibreOffice supports name-based lookup and listing names for both (hence the name). * <p> * Note: currently only implemented for refence marks (in NamedRangeReferenceMark and NamedRangeManagerReferenceMark). */ public interface NamedRange { String getRangeName(); /** * @return Optional.empty if the mark is missing from the document. */ Optional<XTextRange> getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException; /** * Cursor for the reference marks as is, not prepared for filling, but does not need cleanFillCursor either. */ Optional<XTextCursor> getRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; /** * Get a cursor for filling in text. * <p> * Must be followed by cleanFillCursor() */ XTextCursor getFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException; /** * Remove brackets, but if the result would become empty, leave them; if the result would be a single character, leave the left bracket. */ void cleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; /** * Note: create is in NamedRangeManager */ void removeFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException; }
2,116
31.569231
285
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java
package org.jabref.model.openoffice.backend; import java.util.List; import java.util.Optional; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; public interface NamedRangeManager { NamedRange createNamedRange(XTextDocument doc, String markName, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) throws CreationException; List<String> getUsedNames(XTextDocument doc) throws NoDocumentException; Optional<NamedRange> getNamedRangeFromDocument(XTextDocument doc, String markName) throws NoDocumentException, WrappedTargetException; }
981
29.6875
86
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java
package org.jabref.model.openoffice.ootext; import org.jabref.model.strings.StringUtil; /** * Helper functions to produce some of the markup as understood by OOTextIntoOO.write * <p> * These do not cover all tags, only those needed to embed markup from Layout and citation marker formatters into citation markers and bibliography. */ public class OOFormat { private OOFormat() { } /** * Mark {@code ootext} as using a character locale known to OO. * * @param locale language[-country[-territory]] * <p> * https://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/Locale.html * <p> * The country part is optional. * <p> * The territory part is not only optional, the allowed "codes are vendor and browser-specific", so probably best to avoid them if possible. */ public static OOText setLocale(OOText ootext, String locale) { return OOText.fromString(String.format("<span lang=\"%s\">", locale) + ootext.toString() + "</span>"); } /** * Mark {@code ootext} as using the character locale "zxx", which means "no language", "no linguistic content". * <p> * Used around citation marks, probably to turn off spellchecking. */ public static OOText setLocaleNone(OOText ootext) { return OOFormat.setLocale(ootext, "zxx"); } /** * Mark {@code ootext} using a character style {@code charStyle} * * @param charStyle Name of a character style known to OO. May be empty for "Standard", which in turn means do not override any properties. */ public static OOText setCharStyle(OOText ootext, String charStyle) { return OOText.fromString(String.format("<span oo:CharStyleName=\"%s\">", charStyle) + ootext.toString() + "</span>"); } /** * Mark {@code ootext} as part of a paragraph with style {@code paraStyle} */ public static OOText paragraph(OOText ootext, String paraStyle) { if (StringUtil.isNullOrEmpty(paraStyle)) { return paragraph(ootext); } String startTag = String.format("<p oo:ParaStyleName=\"%s\">", paraStyle); return OOText.fromString(startTag + ootext.toString() + "</p>"); } /** * Mark {@code ootext} as part of a paragraph. */ public static OOText paragraph(OOText ootext) { return OOText.fromString("<p>" + ootext.toString() + "</p>"); } /** * Format an OO cross-reference showing the target's page number as label to a reference mark. */ public static OOText formatReferenceToPageNumberOfReferenceMark(String referenceMarkName) { String string = String.format("<oo:referenceToPageNumberOfReferenceMark target=\"%s\">", referenceMarkName); return OOText.fromString(string); } }
2,910
37.302632
158
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/ootext/OOText.java
package org.jabref.model.openoffice.ootext; import java.util.Objects; /** * Text with HTML-like markup as understood by OOTextIntoOO.write * <p> * Some of the tags can be added using OOFormat methods. Others come from the layout engine, either by interpreting LaTeX markup or from settings in the jstyle file. */ public class OOText { private final String data; private OOText(String data) { Objects.requireNonNull(data); this.data = data; } /** * @return null for null input, otherwise the argument wrapped into a new OOText */ public static OOText fromString(String string) { if (string == null) { return null; } return new OOText(string); } /** * @return null for null input, otherwise the string inside the argument */ public static String toString(OOText ootext) { if (ootext == null) { return null; } return ootext.data; } @Override public String toString() { return data; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof OOText)) { return false; } OOText other = (OOText) object; return data.equals(other.data); } @Override public int hashCode() { return data.hashCode(); } }
1,430
21.359375
165
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java
package org.jabref.model.openoffice.ootext; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.util.OOPair; import org.jabref.model.strings.StringUtil; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; import com.sun.star.awt.FontUnderline; import com.sun.star.awt.FontWeight; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyAttribute; import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XMultiPropertySet; import com.sun.star.beans.XMultiPropertyStates; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.beans.XPropertyState; import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.CaseMap; import com.sun.star.text.ControlCharacter; import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Interpret OOText into an OpenOffice or LibreOffice writer document. */ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOTextIntoOO { private static final Logger LOGGER = LoggerFactory.getLogger(OOTextIntoOO.class); /** * "ParaStyleName" is an OpenOffice Property name. */ private static final String PARA_STYLE_NAME = "ParaStyleName"; /* * Character property names used in multiple locations below. */ private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; private static final String CHAR_ESCAPEMENT = "CharEscapement"; private static final String CHAR_STYLE_NAME = "CharStyleName"; private static final String CHAR_UNDERLINE = "CharUnderline"; private static final String CHAR_STRIKEOUT = "CharStrikeout"; /* * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height */ private static final short CHAR_ESCAPEMENT_VALUE_DEFAULT = (short) 0; private static final short SUPERSCRIPT_VALUE = (short) 33; private static final short SUBSCRIPT_VALUE = (short) -10; private static final byte CHAR_ESCAPEMENT_HEIGHT_DEFAULT = (byte) 100; private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; private static final byte SUBSCRIPT_HEIGHT = (byte) 58; private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span|oo:referenceToPageNumberOfReferenceMark)"; private static final String ATTRIBUTE_NAME_REGEXP = "(?:oo:ParaStyleName|oo:CharStyleName|lang|style|target)"; private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; private static final Pattern HTML_TAG = Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" + "|" + "<(" + TAG_NAME_REGEXP + ")" + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" + ">"); private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); private OOTextIntoOO() { } /** * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. * <p> * Limitation: understands no entities. It does not receive any either, unless the user provides it. * <p> * To limit the damage {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} explicitly lists the names we care about. * <p> * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: * <p> * - new tags: * <p> * - {@code <span lang="zxx">} - earlier was applied from code * <p> * - {@code <span oo:CharStyleName="CharStylename">} - earlier was applied from code, for "CitationCharacterFormat" * <p> * - {@code <p>} start new paragraph - earlier was applied from code * <p> * - {@code <p oo:ParaStyleName="ParStyleName">} : start new paragraph and apply ParStyleName - earlier was applied from code * <p> * - {@code <tt>} - earlier: known, but ignored - now: equivalent to {@code <span oo:CharStyleName="Example">} - {@code <oo:referenceToPageNumberOfReferenceMark>} (self-closing) * <p> * - closing tags try to properly restore state (in particular, the "not directly set" state) instead of dictating an "off" state. This makes a difference when the value inherited from another level (for example the paragraph) is not the "off" state. * <p> * An example: a style with {@code ReferenceParagraphFormat="JR_bibentry"} Assume JR_bibentry in LibreOffice is a paragraph style that prescribes "bold" font. LAYOUT only prescribes bold around year. Which parts of the bibliography entries should come out as bold? * <p> * - The user can format citation marks (it is enough to format their start) and the properties not (everywhere) dictated by the style are preserved (where they are not). * * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. */ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) throws WrappedTargetException, CreationException { Objects.requireNonNull(doc); Objects.requireNonNull(ootext); Objects.requireNonNull(position); String lText = OOText.toString(ootext); LOGGER.debug(lText); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); cursor.collapseToEnd(); MyPropertyStack formatStack = new MyPropertyStack(cursor); Stack<String> expectEnd = new Stack<>(); // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; Matcher tagMatcher = HTML_TAG.matcher(lText); while (tagMatcher.find()) { String currentSubstring = lText.substring(piv, tagMatcher.start()); if (!currentSubstring.isEmpty()) { cursor.setString(currentSubstring); } formatStack.apply(cursor); cursor.collapseToEnd(); String endTagName = tagMatcher.group(1); String startTagName = tagMatcher.group(2); String attributeListPart = tagMatcher.group(3); boolean isStartTag = StringUtil.isNullOrEmpty(endTagName); String tagName = isStartTag ? startTagName : endTagName; Objects.requireNonNull(tagName); // Attibutes parsed into (name,value) pairs. List<OOPair<String, String>> attributes = parseAttributes(attributeListPart); // Handle tags: switch (tagName) { case "b": formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); expectEnd.push("/" + tagName); break; case "i": case "em": formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); expectEnd.push("/" + tagName); break; case "smallcaps": formatStack.pushLayer(setCharCaseMap(CaseMap.SMALLCAPS)); expectEnd.push("/" + tagName); break; case "sup": formatStack.pushLayer(setSuperScript(formatStack)); expectEnd.push("/" + tagName); break; case "sub": formatStack.pushLayer(setSubScript(formatStack)); expectEnd.push("/" + tagName); break; case "u": formatStack.pushLayer(setCharUnderline(FontUnderline.SINGLE)); expectEnd.push("/" + tagName); break; case "s": formatStack.pushLayer(setCharStrikeout(FontStrikeout.SINGLE)); expectEnd.push("/" + tagName); break; case "/p": // nop break; case "p": insertParagraphBreak(text, cursor); cursor.collapseToEnd(); for (OOPair<String, String> pair : attributes) { String key = pair.a; String value = pair.b; switch (key) { case "oo:ParaStyleName": // <p oo:ParaStyleName="Standard"> if (StringUtil.isNullOrEmpty(value)) { LOGGER.debug("oo:ParaStyleName inherited"); } else { if (setParagraphStyle(cursor, value)) { // Presumably tested already: LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); } } break; default: LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); break; } } break; case "oo:referenceToPageNumberOfReferenceMark": for (OOPair<String, String> pair : attributes) { String key = pair.a; String value = pair.b; switch (key) { case "target" -> UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); default -> LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); } } break; case "tt": // Note: "Example" names a character style in LibreOffice. formatStack.pushLayer(setCharStyleName("Example")); expectEnd.push("/" + tagName); break; case "span": List<OOPair<String, Object>> settings = new ArrayList<>(); for (OOPair<String, String> pair : attributes) { String key = pair.a; String value = pair.b; switch (key) { case "oo:CharStyleName" -> // <span oo:CharStyleName="Standard"> settings.addAll(setCharStyleName(value)); case "lang" -> // <span lang="zxx"> // <span lang="en-US"> settings.addAll(setCharLocale(value)); case "style" -> { // HTML-style small-caps if ("font-variant: small-caps".equals(value)) { settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); break; } LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", value, key, tagName)); } default -> LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); } } formatStack.pushLayer(settings); expectEnd.push("/" + tagName); break; case "/b": case "/i": case "/em": case "/tt": case "/smallcaps": case "/sup": case "/sub": case "/u": case "/s": case "/span": formatStack.popLayer(); String expected = expectEnd.pop(); if (!tagName.equals(expected)) { LOGGER.warn(String.format("expected '<%s>', found '<%s>' after '%s'", expected, tagName, currentSubstring)); } break; default: LOGGER.warn(String.format("ignoring unknown tag '<%s>'", tagName)); break; } piv = tagMatcher.end(); } if (piv < lText.length()) { cursor.setString(lText.substring(piv)); } formatStack.apply(cursor); cursor.collapseToEnd(); if (!expectEnd.empty()) { StringBuilder rest = new StringBuilder(); for (String s : expectEnd) { rest.insert(0, String.format("<%s>", s)); } LOGGER.warn(String.format("OOTextIntoOO.write: expectEnd stack is not empty at the end: %s%n", rest)); } } /** * Purpose: in some cases we do not want to inherit direct formatting from the context. * <p> * In particular, when filling the bibliography title and body. */ public static void removeDirectFormatting(XTextCursor cursor) { XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); XPropertySet propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertyState xPropertyState = UnoCast.cast(XPropertyState.class, cursor).get(); try { // Special handling propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); xPropertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | PropertyVetoException | WrappedTargetException ex) { LOGGER.warn("exception caught", ex); } mpss.setAllPropertiesToDefault(); /* * Now that we have called setAllPropertiesToDefault, check which properties are not set to * default and try to correct what we can and seem necessary. * * Note: tested with LibreOffice : 6.4.6.2 */ // Only report those we do not yet know about final Set<String> knownToFail = Set.of("ListAutoFormat", "ListId", "NumberingIsNumber", "NumberingLevel", "NumberingRules", "NumberingStartValue", "ParaChapterNumberingLevel", "ParaIsNumberingRestart", "ParaStyleName"); // query again, just in case it matters propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); // check the result for (Property p : propertySetInfo.getProperties()) { if ((p.Attributes & PropertyAttribute.READONLY) != 0) { continue; } try { if (isPropertyDefault(cursor, p.Name)) { continue; } } catch (UnknownPropertyException ex) { throw new IllegalStateException("Unexpected UnknownPropertyException", ex); } if (knownToFail.contains(p.Name)) { continue; } LOGGER.warn(String.format("OOTextIntoOO.removeDirectFormatting failed on '%s'", p.Name)); } } static class MyPropertyStack { /* * We only try to control these. Should include all character properties we set, and maybe * their interdependencies. * * For a list of properties see: * https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html * * For interdependencies between properties: * https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting * (at the end, under "Interdependencies between Properties") * */ static final Set<String> CONTROLLED_PROPERTIES = Set.of( /* Used for SuperScript, SubScript. * * These three are interdependent: changing one may change others. */ "CharEscapement", "CharEscapementHeight", "CharAutoEscapement", /* used for Bold */ "CharWeight", /* Used for Italic */ "CharPosture", /* Used for strikeout. These two are interdependent. */ "CharStrikeout", "CharCrossedOut", /* Used for underline. These three are interdependent, but apparently * we can leave out the last two. */ "CharUnderline", // "CharUnderlineColor", "CharUnderlineHasColor", /* Used for lang="zxx", to silence spellchecker. */ "CharLocale", /* Used for CitationCharacterFormat. */ "CharStyleName", /* Used for <smallcaps> and <span style="font-variant: small-caps"> */ "CharCaseMap"); /** * The number of properties actually controlled. */ final int goodSize; /** * From property name to index in goodNames. */ final Map<String, Integer> goodNameToIndex; /** * From index to property name. */ final String[] goodNames; /** * Maintain a stack of layers, each containing a description of the desired state of properties. Each description is an ArrayList of property values, Optional.empty() encoding "not directly set". */ final Stack<ArrayList<Optional<Object>>> layers; MyPropertyStack(XTextCursor cursor) { XPropertySet propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); // On creation, initialize the property name -- index mapping. this.goodNameToIndex = new HashMap<>(); int nextIndex = 0; for (Property p : propertySetInfo.getProperties()) { if ((p.Attributes & PropertyAttribute.READONLY) != 0) { continue; } if (!CONTROLLED_PROPERTIES.contains(p.Name)) { continue; } this.goodNameToIndex.put(p.Name, nextIndex); nextIndex++; } this.goodSize = nextIndex; this.goodNames = new String[goodSize]; for (Map.Entry<String, Integer> entry : goodNameToIndex.entrySet()) { goodNames[entry.getValue()] = entry.getKey(); } // XMultiPropertySet.setPropertyValues() requires alphabetically sorted property names. We adjust here: Arrays.sort(goodNames); for (int i = 0; i < goodSize; i++) { this.goodNameToIndex.put(goodNames[i], i); } // Get the initial state of the properties and add the first layer. XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); PropertyState[] propertyStates; try { propertyStates = mpss.getPropertyStates(goodNames); } catch (UnknownPropertyException ex) { throw new IllegalStateException("Caught unexpected UnknownPropertyException", ex); } XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); Object[] initialValues = mps.getPropertyValues(goodNames); ArrayList<Optional<Object>> initialValuesOpt = new ArrayList<>(goodSize); for (int i = 0; i < goodSize; i++) { if (propertyStates[i] == PropertyState.DIRECT_VALUE) { initialValuesOpt.add(Optional.of(initialValues[i])); } else { initialValuesOpt.add(Optional.empty()); } } this.layers = new Stack<>(); this.layers.push(initialValuesOpt); } /** * Given a list of property name, property value pairs, construct and push a new layer describing the intended state after these have been applied. * <p> * Opening tags usually call this. */ void pushLayer(List<OOPair<String, Object>> settings) { ArrayList<Optional<Object>> oldLayer = layers.peek(); ArrayList<Optional<Object>> newLayer = new ArrayList<>(oldLayer); for (OOPair<String, Object> pair : settings) { String name = pair.a; Integer index = goodNameToIndex.get(name); if (index == null) { LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); continue; } Object newValue = pair.b; newLayer.set(index, Optional.ofNullable(newValue)); } layers.push(newLayer); } /** * Closing tags just pop a layer. */ void popLayer() { if (layers.size() <= 1) { LOGGER.warn("popLayer: underflow"); return; } layers.pop(); } /** * Apply the current desired formatting state to a cursor. * <p> * The idea is to minimize the number of calls to OpenOffice. */ void apply(XTextCursor cursor) { XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); ArrayList<Optional<Object>> topLayer = layers.peek(); try { // select values to be set ArrayList<String> names = new ArrayList<>(goodSize); ArrayList<Object> values = new ArrayList<>(goodSize); // and those to be cleared ArrayList<String> delNames = new ArrayList<>(goodSize); for (int i = 0; i < goodSize; i++) { if (topLayer.get(i).isPresent()) { names.add(goodNames[i]); values.add(topLayer.get(i).get()); } else { delNames.add(goodNames[i]); } } // namesArray must be alphabetically sorted. String[] namesArray = names.toArray(new String[0]); String[] delNamesArray = delNames.toArray(new String[0]); mpss.setPropertiesToDefault(delNamesArray); mps.setPropertyValues(namesArray, values.toArray()); } catch (UnknownPropertyException ex) { LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply", ex); } catch (PropertyVetoException ex) { LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); } catch (WrappedTargetException ex) { LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); } } // Relative CharEscapement needs to know current values. Optional<Object> getPropertyValue(String name) { if (goodNameToIndex.containsKey(name)) { int index = goodNameToIndex.get(name); ArrayList<Optional<Object>> topLayer = layers.peek(); return topLayer.get(index); } return Optional.empty(); } } /** * Parse HTML-like attributes to a list of (name,value) pairs. */ private static List<OOPair<String, String>> parseAttributes(String attributes) { List<OOPair<String, String>> res = new ArrayList<>(); if (attributes == null) { return res; } Matcher attributeMatcher = ATTRIBUTE_PATTERN.matcher(attributes); while (attributeMatcher.find()) { String key = attributeMatcher.group(1); String value = attributeMatcher.group(2); res.add(new OOPair<>(key, value)); } return res; } /** * We rely on property values being either DIRECT_VALUE or DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, or is collapsed, then this is true. */ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { XPropertyState xPropertyState = UnoCast.cast(XPropertyState.class, cursor).get(); PropertyState state = xPropertyState.getPropertyState(propertyName); if (state == PropertyState.AMBIGUOUS_VALUE) { throw new java.lang.IllegalArgumentException("PropertyState.AMBIGUOUS_VALUE" + " (expected properties for a homogeneous cursor)"); } return state == PropertyState.DEFAULT_VALUE; } /* * Various property change requests. Their results are passed to MyPropertyStack.pushLayer() */ private static List<OOPair<String, Object>> setCharWeight(float value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>("CharWeight", value)); return settings; } private static List<OOPair<String, Object>> setCharPosture(FontSlant value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>("CharPosture", value)); return settings; } private static List<OOPair<String, Object>> setCharCaseMap(short value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>("CharCaseMap", value)); return settings; } // com.sun.star.awt.FontUnderline private static List<OOPair<String, Object>> setCharUnderline(short value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>(CHAR_UNDERLINE, value)); return settings; } // com.sun.star.awt.FontStrikeout private static List<OOPair<String, Object>> setCharStrikeout(short value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>(CHAR_STRIKEOUT, value)); return settings; } // CharStyleName private static List<OOPair<String, Object>> setCharStyleName(String value) { List<OOPair<String, Object>> settings = new ArrayList<>(); if (StringUtil.isNullOrEmpty(value)) { LOGGER.warn("setCharStyleName: received null or empty value"); } else { settings.add(new OOPair<>(CHAR_STYLE_NAME, value)); } return settings; } // Locale private static List<OOPair<String, Object>> setCharLocale(Locale value) { List<OOPair<String, Object>> settings = new ArrayList<>(); settings.add(new OOPair<>("CharLocale", value)); return settings; } /** * Locale from string encoding: language, language-country or language-country-variant */ private static List<OOPair<String, Object>> setCharLocale(String value) { if (StringUtil.isNullOrEmpty(value)) { throw new java.lang.IllegalArgumentException("setCharLocale \"\" or null"); } String[] parts = value.split("-"); String language = (parts.length > 0) ? parts[0] : ""; String country = (parts.length > 1) ? parts[1] : ""; String variant = (parts.length > 2) ? parts[2] : ""; return setCharLocale(new Locale(language, country, variant)); } /* * SuperScript and SubScript. * * @param relative If true, calculate the new values relative to the current values. This allows * subscript-in-superscript. */ private static List<OOPair<String, Object>> setCharEscapement(Optional<Short> value, Optional<Byte> height, boolean relative, MyPropertyStack formatStack) { List<OOPair<String, Object>> settings = new ArrayList<>(); Optional<Short> oldValue = formatStack .getPropertyValue(CHAR_ESCAPEMENT) .map(e -> (short) e); Optional<Byte> oldHeight = formatStack .getPropertyValue(CHAR_ESCAPEMENT_HEIGHT) .map(e -> (byte) e); if (relative && (value.isPresent() || height.isPresent())) { double oldHeightFloat = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; double oldValueFloat = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); double heightFloat = height.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT); double valueFloat = value.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); byte newHeight = (byte) Math.round(heightFloat * oldHeightFloat); short newValue = (short) Math.round(valueFloat * oldHeightFloat + oldValueFloat); if (value.isPresent()) { settings.add(new OOPair<>(CHAR_ESCAPEMENT, newValue)); } if (height.isPresent()) { settings.add(new OOPair<>(CHAR_ESCAPEMENT_HEIGHT, newHeight)); } } else { if (value.isPresent()) { settings.add(new OOPair<>(CHAR_ESCAPEMENT, value.get())); } if (height.isPresent()) { settings.add(new OOPair<>(CHAR_ESCAPEMENT_HEIGHT, height.get())); } } return settings; } private static List<OOPair<String, Object>> setSubScript(MyPropertyStack formatStack) { return setCharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true, formatStack); } private static List<OOPair<String, Object>> setSuperScript(MyPropertyStack formatStack) { return setCharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true, formatStack); } /** * @return true on failure */ public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyle) { final boolean FAIL = true; final boolean PASS = false; XParagraphCursor paragraphCursor = UnoCast.cast(XParagraphCursor.class, cursor).get(); XPropertySet propertySet = UnoCast.cast(XPropertySet.class, paragraphCursor).get(); try { propertySet.setPropertyValue(PARA_STYLE_NAME, paragraphStyle); return PASS; } catch (UnknownPropertyException | PropertyVetoException | com.sun.star.lang.IllegalArgumentException | WrappedTargetException ex) { return FAIL; } } private static void insertParagraphBreak(XText text, XTextCursor cursor) { try { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); } catch (com.sun.star.lang.IllegalArgumentException ex) { // Assuming it means wrong code for ControlCharacter. // https://api.libreoffice.org/docs/idl/ref/ does not tell. // If my assumption is correct, we never get here. throw new java.lang.IllegalArgumentException("Caught unexpected com.sun.star.lang.IllegalArgumentException", ex); } } }
32,645
41.507813
268
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java
package org.jabref.model.openoffice.rangesort; import java.util.Arrays; import java.util.Objects; import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoSelection; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.lang.XServiceInfo; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; /* * A problem with XTextViewCursor: if it is not in text, then we get a crippled version that does * not support viewCursor.getStart() or viewCursor.gotoRange(range,false), and will throw an * exception instead. * * Here we manipulate the cursor via XSelectionSupplier.getSelection and XSelectionSupplier.select * to move it to the text. * * Seems to work when the user selected a frame or image. * In these cases restoring the selection works, too. * * When the cursor is in a comment (referred to as "annotation" in OO API) then initialSelection is * null, and select() fails to get a functional viewCursor. * * If FunctionalTextViewCursor.get() reports error, we have to ask the user to move the cursor into * the text part of the document. * * Usage: * * OOResult<FunctionalTextViewCursor, String> fcursor = FunctionalTextViewCursor.get(doc, msg); * if (fcursor.isError()) { * ... * } else { * XTextViewCursor viewCursor = fcursor.get().getViewCursor(); * ... * fc.restore(); * } * */ public class FunctionalTextViewCursor { /* The initial position of the cursor or null. */ private final XTextRange initialPosition; /* The initial selection in the document or null. */ private final XServiceInfo initialSelection; /* The view cursor, potentially moved from its original location. */ private final XTextViewCursor viewCursor; private FunctionalTextViewCursor(XTextRange initialPosition, XServiceInfo initialSelection, XTextViewCursor viewCursor) { this.initialPosition = initialPosition; this.initialSelection = initialSelection; this.viewCursor = viewCursor; } /* * Get a functional XTextViewCursor or an error message. * * The cursor position may differ from the location provided by the user. * * On failure the constructor restores the selection. On success, the caller may want to call * instance.restore() after finished using the cursor. */ public static OOResult<FunctionalTextViewCursor, String> get(XTextDocument doc) { Objects.requireNonNull(doc); XTextRange initialPosition = null; XServiceInfo initialSelection = UnoSelection.getSelectionAsXServiceInfo(doc).orElse(null); XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); if (viewCursor != null) { try { initialPosition = UnoCursor.createTextCursorByRange(viewCursor); viewCursor.getStart(); return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } catch (com.sun.star.uno.RuntimeException ex) { // bad cursor viewCursor = null; initialPosition = null; } } if (initialSelection == null) { String errorMessage = "Selection is not available: cannot provide a functional view cursor"; return OOResult.error(errorMessage); } else if (Arrays.stream(initialSelection.getSupportedServiceNames()) .noneMatch("com.sun.star.text.TextRanges"::equals)) { // initialSelection does not support TextRanges. // We need to change it (and the viewCursor with it). XTextRange newSelection = doc.getText().getStart(); UnoSelection.select(doc, newSelection); viewCursor = UnoCursor.getViewCursor(doc).orElse(null); } if (viewCursor == null) { restore(doc, initialPosition, initialSelection); String errorMessage = "Could not get the view cursor"; return OOResult.error(errorMessage); } try { viewCursor.getStart(); } catch (com.sun.star.uno.RuntimeException ex) { restore(doc, initialPosition, initialSelection); String errorMessage = "The view cursor failed the functionality test"; return OOResult.error(errorMessage); } return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } public XTextViewCursor getViewCursor() { return viewCursor; } private static void restore(XTextDocument doc, XTextRange initialPosition, XServiceInfo initialSelection) { if (initialPosition != null) { XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); if (viewCursor != null) { viewCursor.gotoRange(initialPosition, false); return; } } if (initialSelection != null) { UnoSelection.select(doc, initialSelection); } } /* Restore initial state of viewCursor (possibly by restoring selection) if possible. */ public void restore(XTextDocument doc) { FunctionalTextViewCursor.restore(doc, initialPosition, initialSelection); } }
5,498
37.454545
112
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeHolder.java
package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; public interface RangeHolder { XTextRange getRange(); }
146
17.375
46
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java
package org.jabref.model.openoffice.rangesort; import java.util.List; /** * Used in reporting range overlaps. */ public class RangeOverlap<V> { public final RangeOverlapKind kind; public final List<V> valuesForOverlappingRanges; public RangeOverlap(RangeOverlapKind kind, List<V> valuesForOverlappingRanges) { this.kind = kind; this.valuesForOverlappingRanges = valuesForOverlappingRanges; } }
431
24.411765
84
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java
package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOTuple3; import com.sun.star.text.XText; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextRangeCompare; public class RangeOverlapBetween { private RangeOverlapBetween() { } /** * Check for any overlap between two sets of XTextRange values. * <p> * Assume fewHolders is small (usually a single element, for checking the cursor) * <p> * Returns on first problem found. */ public static <V extends RangeHolder> List<RangeOverlap<V>> findFirst(XTextDocument doc, List<V> fewHolders, List<V> manyHolders, boolean includeTouching) { List<RangeOverlap<V>> result = new ArrayList<>(); if (fewHolders.isEmpty()) { return result; } /* * Cache all we need to know about fewHolders. We are trying to minimize the number of calls * to LO. */ List<OOTuple3<XText, XTextRangeCompare, V>> fewTuples = new ArrayList<>(fewHolders.size()); for (V aHolder : fewHolders) { XText aText = aHolder.getRange().getText(); fewTuples.add(new OOTuple3<>(aText, UnoCast.cast(XTextRangeCompare.class, aText).get(), aHolder)); } /* * We only go through manyHolders once: fewTuples is in the inner loop. */ for (V bHolder : manyHolders) { XTextRange bRange = bHolder.getRange(); XText bText = bRange.getText(); XTextRange bRangeStart = bRange.getStart(); XTextRange bRangeEnd = bRange.getEnd(); for (OOTuple3<XText, XTextRangeCompare, V> tup : fewTuples) { XText aText = tup.a; XTextRangeCompare cmp = tup.b; V aHolder = tup.c; XTextRange aRange = aHolder.getRange(); if (aText != bText) { continue; } int abEndToStart = UnoTextRange.compareStartsUnsafe(cmp, aRange.getEnd(), bRangeStart); if (abEndToStart < 0 || (!includeTouching && (abEndToStart == 0))) { continue; } int baEndToStart = UnoTextRange.compareStartsUnsafe(cmp, bRangeEnd, aRange.getStart()); if (baEndToStart < 0 || (!includeTouching && (baEndToStart == 0))) { continue; } boolean equal = UnoTextRange.compareStartsThenEndsUnsafe(cmp, aRange, bRange) == 0; boolean touching = abEndToStart == 0 || baEndToStart == 0; // In case of two equal collapsed ranges there is an ambiguity : TOUCH or EQUAL_RANGE ? // // We return EQUAL_RANGE RangeOverlapKind kind = equal ? RangeOverlapKind.EQUAL_RANGE : (touching ? RangeOverlapKind.TOUCH : RangeOverlapKind.OVERLAP); List<V> valuesForOverlappingRanges = new ArrayList<>(); valuesForOverlappingRanges.add(aHolder); valuesForOverlappingRanges.add(bHolder); result.add(new RangeOverlap<>(kind, valuesForOverlappingRanges)); return result; } } return result; } }
3,668
36.060606
103
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java
package org.jabref.model.openoffice.rangesort; public enum RangeOverlapKind { /** * The ranges share a boundary */ TOUCH, /** * They share some characters */ OVERLAP, /** * They cover the same XTextRange */ EQUAL_RANGE }
280
12.380952
46
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java
package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextRange; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextRangeCompare; public class RangeOverlapWithin { private RangeOverlapWithin() { } /** * Report identical, overlapping or touching ranges between elements of rangeHolders. * <p> * For overlapping and touching, only report consecutive ranges and only with a single sample of otherwise identical ranges. * * @param rangeHolders represent the ranges to be checked. * <p> * Note: for each rangeHolder, rangeHolder.getRange() is called multiple times. To avoid repeated work, they should keep a copy of the range instead of getting it each time from the document. * @param reportAtMost Limit the number of records returned to atMost. Zero {@code reportAtMost} means no limit. * @param includeTouching Should the result contain ranges sharing only a boundary? */ public static <V extends RangeHolder> List<RangeOverlap<V>> findOverlappingRanges(XTextDocument doc, List<V> rangeHolders, boolean includeTouching, int reportAtMost) { RangeSort.RangePartitions<V> partitions = RangeSort.partitionAndSortRanges(rangeHolders); return findOverlappingRanges(partitions, reportAtMost, includeTouching); } /** * Report identical, overlapping or touching ranges. * <p> * For overlapping and touching, only report consecutive ranges and only with a single sample of otherwise identical ranges. * * @param atMost Limit the number of records returned to atMost. Zero {@code atMost} means no limit. * @param includeTouching Should the result contain ranges sharing only a boundary? */ public static <V extends RangeHolder> List<RangeOverlap<V>> findOverlappingRanges(RangeSort.RangePartitions<V> input, int atMost, boolean includeTouching) { assert atMost >= 0; List<RangeOverlap<V>> result = new ArrayList<>(); for (List<V> partition : input.getPartitions()) { if (partition.isEmpty()) { continue; } XTextRangeCompare cmp = UnoCast.cast(XTextRangeCompare.class, partition.get(0).getRange().getText()).get(); for (int i = 0; i < (partition.size() - 1); i++) { V aHolder = partition.get(i); V bHolder = partition.get(i + 1); XTextRange aRange = aHolder.getRange(); XTextRange bRange = bHolder.getRange(); // check equal values int cmpResult = UnoTextRange.compareStartsThenEndsUnsafe(cmp, aRange, bRange); if (cmpResult == 0) { List<V> aValues = new ArrayList<>(); aValues.add(aHolder); // aValues.add(bHolder); // collect those equal while (i < (partition.size() - 1) && UnoTextRange.compareStartsThenEndsUnsafe( cmp, aRange, partition.get(i + 1).getRange()) == 0) { bHolder = partition.get(i + 1); aValues.add(bHolder); i++; } result.add(new RangeOverlap<>(RangeOverlapKind.EQUAL_RANGE, aValues)); if (atMost > 0 && result.size() >= atMost) { return result; } continue; } // Not equal, and (a <= b) since sorted. // Check if a.end >= b.start cmpResult = UnoTextRange.compareStartsUnsafe(cmp, aRange.getEnd(), bRange.getStart()); if (cmpResult > 0 || (includeTouching && (cmpResult == 0))) { // found overlap or touch List<V> valuesForOverlappingRanges = new ArrayList<>(); valuesForOverlappingRanges.add(aHolder); valuesForOverlappingRanges.add(bHolder); result.add(new RangeOverlap<>((cmpResult == 0) ? RangeOverlapKind.TOUCH : RangeOverlapKind.OVERLAP, valuesForOverlappingRanges)); } if (atMost > 0 && result.size() >= atMost) { return result; } } } return result; } }
5,024
43.469027
218
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java
package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextRange; import com.sun.star.text.XText; import com.sun.star.text.XTextRangeCompare; /** * RangeSort provides sorting based on XTextRangeCompare, which only provides comparison between XTextRange values within the same XText. */ public class RangeSort { private RangeSort() { } /** * Compare two RangeHolders (using RangeHolder.getRange()) within an XText. * <p> * Note: since we only look at the ranges, this comparison is generally not consistent with `equals` on the RangeHolders. Probably should not be used for key comparison in {@code TreeMap<RangeHolder>} or {@code Set<RangeHolder>} */ private static class HolderComparatorWithinPartition implements Comparator<RangeHolder> { private final XTextRangeCompare cmp; HolderComparatorWithinPartition(XText text) { cmp = UnoCast.cast(XTextRangeCompare.class, text) .orElseThrow(java.lang.IllegalArgumentException::new); } /** * Assumes a and b belong to the same XText as cmp. */ @Override public int compare(RangeHolder a, RangeHolder b) { return UnoTextRange.compareStartsThenEndsUnsafe(cmp, a.getRange(), b.getRange()); } } /** * Sort a list of RangeHolder values known to share the same getText(). * <p> * Note: RangeHolder.getRange() is called many times. */ public static <V extends RangeHolder> void sortWithinPartition(List<V> rangeHolders) { if (rangeHolders.isEmpty()) { return; } XText text = rangeHolders.get(0).getRange().getText(); rangeHolders.sort(new HolderComparatorWithinPartition(text)); } /** * Represent a partitioning of RangeHolders by XText */ public static class RangePartitions<V extends RangeHolder> { private final Map<XText, List<V>> partitions; public RangePartitions() { this.partitions = new HashMap<>(); } public void add(V holder) { XText partitionKey = holder.getRange().getText(); List<V> partition = partitions.computeIfAbsent(partitionKey, unused -> new ArrayList<>()); partition.add(holder); } public List<List<V>> getPartitions() { return new ArrayList<>(partitions.values()); } } /** * Partition RangeHolders by the corresponding XText. */ public static <V extends RangeHolder> RangePartitions<V> partitionRanges(List<V> holders) { RangePartitions<V> result = new RangePartitions<>(); for (V holder : holders) { result.add(holder); } return result; } /** * Note: RangeHolder.getRange() is called many times. */ public static <V extends RangeHolder> RangePartitions<V> partitionAndSortRanges(List<V> holders) { RangePartitions<V> result = partitionRanges(holders); for (List<V> partition : result.getPartitions()) { sortWithinPartition(partition); } return result; } }
3,357
31.921569
232
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java
package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; /** * A simple implementation of {@code RangeSortable} */ public class RangeSortEntry<T> implements RangeSortable<T> { private XTextRange range; private int indexInPosition; private final T content; public RangeSortEntry(XTextRange range, int indexInPosition, T content) { this.range = range; this.indexInPosition = indexInPosition; this.content = content; } @Override public XTextRange getRange() { return range; } @Override public int getIndexInPosition() { return indexInPosition; } @Override public T getContent() { return content; } public void setRange(XTextRange range) { this.range = range; } public void setIndexInPosition(int indexInPosition) { this.indexInPosition = indexInPosition; } }
930
20.651163
77
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java
package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; import org.jabref.model.openoffice.uno.UnoScreenRefresh; import com.sun.star.awt.Point; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sort XTextRange values visually (top-down,left-to-right). * <p> * Requires functional XTextViewCursor. * <p> * Problem: for multicolumn layout and when viewing pages side-by-side in LO, the (top-down,left-to-right) order interpreted as-on-the-screen: an XTextRange at the top of the second column or second page is sorted before an XTextRange at the bottom of the first column of the first page. */ public class RangeSortVisual { private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); private RangeSortVisual() { } /** * Sort the input {@code inputs} visually. * <p> * Requires a functional {@code XTextViewCursor}. * * @return The input, sorted by the elements XTextRange and getIndexInPosition. */ public static <T> List<RangeSortable<T>> visualSort(List<RangeSortable<T>> inputs, XTextDocument doc, FunctionalTextViewCursor fcursor) { if (UnoScreenRefresh.hasControllersLocked(doc)) { final String msg = "visualSort: with ControllersLocked, viewCursor.gotoRange is probably useless"; LOGGER.warn(msg); throw new IllegalStateException(msg); } XTextViewCursor viewCursor = fcursor.getViewCursor(); final int inputSize = inputs.size(); // find coordinates List<Point> positions = new ArrayList<>(inputSize); for (RangeSortable<T> v : inputs) { positions.add(findPositionOfTextRange(v.getRange(), viewCursor)); } fcursor.restore(doc); // order by position ArrayList<ComparableMark<RangeSortable<T>>> comparableMarks = new ArrayList<>(inputSize); for (int i = 0; i < inputSize; i++) { RangeSortable<T> input = inputs.get(i); comparableMarks.add(new ComparableMark<>(positions.get(i), input.getIndexInPosition(), input)); } comparableMarks.sort(RangeSortVisual::compareTopToBottomLeftToRight); // collect ordered result List<RangeSortable<T>> result = new ArrayList<>(comparableMarks.size()); for (ComparableMark<RangeSortable<T>> mark : comparableMarks) { result.add(mark.getContent()); } if (result.size() != inputSize) { throw new IllegalStateException("visualSort: result.size() != inputSize"); } return result; } /** * Given a location, return its position: coordinates relative to the top left position of the first page of the document. * <p> * Note: for text layouts with two or more columns, this gives the wrong order: top-down/left-to-right does not match reading order. * <p> * Note: The "relative to the top left position of the first page" is meant "as it appears on the screen". * <p> * In particular: when viewing pages side-by-side, the top half of the right page is higher than the lower half of the left page. Again, top-down/left-to-right does not match reading order. * * @param range Location. * @param cursor To get the position, we need az XTextViewCursor. It will be moved to the range. */ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { cursor.gotoRange(range, false); return cursor.getPosition(); } private static <T> int compareTopToBottomLeftToRight(ComparableMark<T> a, ComparableMark<T> b) { if (a.position.Y != b.position.Y) { return a.position.Y - b.position.Y; } if (a.position.X != b.position.X) { return a.position.X - b.position.X; } return a.indexInPosition - b.indexInPosition; } /** * A reference mark name paired with its visual position. * <p> * Comparison is based on (Y,X,indexInPosition): vertical compared first, horizontal second, indexInPosition third. * <p> * Used for sorting reference marks by their visual positions. */ private static class ComparableMark<T> { private final Point position; private final int indexInPosition; private final T content; public ComparableMark(Point position, int indexInPosition, T content) { this.position = position; this.indexInPosition = indexInPosition; this.content = content; } public T getContent() { return content; } } }
4,948
36.778626
287
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java
package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; /** * This is what {@code visualSort} needs in its input. */ public interface RangeSortable<T> extends RangeHolder { /** * The XTextRange * <p> * For citation marks in footnotes this may be the range of the footnote mark. */ XTextRange getRange(); /** * For citation marks in footnotes this may provide order within the footnote. */ int getIndexInPosition(); T getContent(); }
518
20.625
82
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/Citation.java
package org.jabref.model.openoffice.style; import java.util.List; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.util.OOPair; public class Citation implements ComparableCitation, CitationMarkerEntry, CitationMarkerNumericEntry { /** * key in database */ public final String citationKey; /** * Result from database lookup. Optional.empty() if not found. */ private Optional<CitationLookupResult> db; /** * The number used for numbered citation styles . */ private Optional<Integer> number; /** * Letter that makes the in-text citation unique. */ private Optional<String> uniqueLetter; /** * pageInfo */ private Optional<OOText> pageInfo; /** * isFirstAppearanceOfSource */ private boolean isFirstAppearanceOfSource; public Citation(String citationKey) { this.citationKey = citationKey; this.db = Optional.empty(); this.number = Optional.empty(); this.uniqueLetter = Optional.empty(); this.pageInfo = Optional.empty(); this.isFirstAppearanceOfSource = false; } @Override public String getCitationKey() { return citationKey; } @Override public Optional<OOText> getPageInfo() { return pageInfo; } @Override public boolean getIsFirstAppearanceOfSource() { return isFirstAppearanceOfSource; } @Override public Optional<BibEntry> getBibEntry() { return db.map(citationLookupResult -> citationLookupResult.entry); } public static Optional<CitationLookupResult> lookup(BibDatabase database, String key) { return database .getEntryByCitationKey(key) .map(bibEntry -> new CitationLookupResult(bibEntry, database)); } public static Optional<CitationLookupResult> lookup(List<BibDatabase> databases, String key) { return databases.stream() .map(database -> Citation.lookup(database, key)) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } public void lookupInDatabases(List<BibDatabase> databases) { db = Citation.lookup(databases, citationKey); } public Optional<CitationLookupResult> getLookupResult() { return db; } public void setLookupResult(Optional<CitationLookupResult> db) { this.db = db; } public boolean isUnresolved() { return db.isEmpty(); } @Override public Optional<Integer> getNumber() { return number; } public void setNumber(Optional<Integer> number) { this.number = number; } public int getNumberOrThrow() { return number.get(); } public Optional<String> getUniqueLetter() { return uniqueLetter; } public void setUniqueLetter(Optional<String> uniqueLetter) { this.uniqueLetter = uniqueLetter; } public void setPageInfo(Optional<OOText> pageInfo) { Optional<OOText> normalizedPageInfo = PageInfo.normalizePageInfo(pageInfo); if (!normalizedPageInfo.equals(pageInfo)) { throw new IllegalArgumentException("setPageInfo argument is not normalized"); } this.pageInfo = normalizedPageInfo; } public void setIsFirstAppearanceOfSource(boolean value) { isFirstAppearanceOfSource = value; } /* * Setters for CitationGroups.distribute() */ public static void setLookupResult(OOPair<Citation, Optional<CitationLookupResult>> pair) { Citation citation = pair.a; citation.db = pair.b; } public static void setNumber(OOPair<Citation, Optional<Integer>> pair) { Citation citation = pair.a; citation.number = pair.b; } public static void setUniqueLetter(OOPair<Citation, Optional<String>> pair) { Citation citation = pair.a; citation.uniqueLetter = pair.b; } }
4,156
26.169935
102
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java
package org.jabref.model.openoffice.style; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.util.OOListUtil; /** * A CitationGroup describes a group of citations. */ public class CitationGroup { public final OODataModel dataModel; /* * Identifies this citation group. */ public final CitationGroupId groupId; /* * The core data, stored in the document: * The type of citation and citations in storage order. */ public final CitationType citationType; public final List<Citation> citationsInStorageOrder; /* * A name of a reference mark to link to by formatCitedOnPages. * May be initially empty, if backend does not use reference marks. * * produceCitationMarkers might want fill it to support cross-references to citation groups from * the bibliography. */ private Optional<String> referenceMarkNameForLinking; /* * Indices into citations: citations[localOrder[i]] provides ith citation according to the * currently imposed local order for presentation. * * Initialized to (0..(nCitations-1)) in the constructor. */ private List<Integer> localOrder; /* * "Cited on pages" uses this to sort the cross-references. */ private Optional<Integer> indexInGlobalOrder; /* * Citation marker. */ private Optional<OOText> citationMarker; public CitationGroup(OODataModel dataModel, CitationGroupId groupId, CitationType citationType, List<Citation> citationsInStorageOrder, Optional<String> referenceMarkNameForLinking) { this.dataModel = dataModel; this.groupId = groupId; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); this.localOrder = OOListUtil.makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); this.citationMarker = Optional.empty(); } public int numberOfCitations() { return citationsInStorageOrder.size(); } /* * localOrder */ /** * Sort citations for presentation within a CitationGroup. */ void imposeLocalOrder(Comparator<BibEntry> entryComparator) { // For JabRef52 the single pageInfo is always in the last-in-localorder citation. // We adjust here accordingly by taking it out and adding it back after sorting. final int last = this.numberOfCitations() - 1; Optional<OOText> lastPageInfo = Optional.empty(); if (dataModel == OODataModel.JabRef52) { Citation lastCitation = getCitationsInLocalOrder().get(last); lastPageInfo = lastCitation.getPageInfo(); lastCitation.setPageInfo(Optional.empty()); } this.localOrder = OOListUtil.order(citationsInStorageOrder, new CompareCitation(entryComparator, true)); if (dataModel == OODataModel.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); } } public List<Integer> getLocalOrder() { return Collections.unmodifiableList(localOrder); } /* * citations */ public List<Citation> getCitationsInLocalOrder() { return OOListUtil.map(localOrder, citationsInStorageOrder::get); } /* * indexInGlobalOrder */ public void setIndexInGlobalOrder(Optional<Integer> indexInGlobalOrder) { this.indexInGlobalOrder = indexInGlobalOrder; } public Optional<Integer> getIndexInGlobalOrder() { return this.indexInGlobalOrder; } /* * referenceMarkNameForLinking */ public Optional<String> getReferenceMarkNameForLinking() { return referenceMarkNameForLinking; } public void setReferenceMarkNameForLinking(Optional<String> referenceMarkNameForLinking) { this.referenceMarkNameForLinking = referenceMarkNameForLinking; } /* * citationMarker */ public void setCitationMarker(Optional<OOText> citationMarker) { this.citationMarker = citationMarker; } public Optional<OOText> getCitationMarker() { return this.citationMarker; } }
4,565
29.238411
100
java