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/logic/integrity/BracesCorrector.java
package org.jabref.logic.integrity; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BracesCorrector { private static final Pattern PATTERN_ESCAPED_CURLY_BRACES = Pattern.compile("(\\\\\\{)|(\\\\\\})"); public static String apply(String input) { if (input == null) { return null; } else { Matcher matcher = PATTERN_ESCAPED_CURLY_BRACES.matcher(input); String addedBraces = input; String c = matcher.replaceAll(""); long diff = c.chars().filter(ch -> ch == '{').count() - c.chars().filter(ch -> ch == '}').count(); while (diff != 0) { if (diff < 0) { addedBraces = "{" + addedBraces; diff++; } else { addedBraces = addedBraces + "}"; diff--; } } return addedBraces; } } }
964
29.15625
110
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/BracketChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; public class BracketChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // metaphor: integer-based stack (push + / pop -) int counter = 0; for (char a : value.trim().toCharArray()) { if (a == '{') { counter++; } else if (a == '}') { if (counter == 0) { return Optional.of(Localization.lang("unexpected closing curly bracket")); } else { counter--; } } } if (counter > 0) { return Optional.of(Localization.lang("unexpected opening curly bracket")); } return Optional.empty(); } }
987
25.702703
94
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/CitationKeyChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; /** * Currently only checks the key if there is an author, year, and title present. */ public class CitationKeyChecker implements EntryChecker { @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> author = entry.getField(StandardField.AUTHOR); Optional<String> title = entry.getField(StandardField.TITLE); Optional<String> year = entry.getField(StandardField.YEAR); if (author.isEmpty() || title.isEmpty() || year.isEmpty()) { return Collections.emptyList(); } if (StringUtil.isBlank(entry.getCitationKey())) { String authorTitleYear = entry.getAuthorTitleYear(100); return Collections.singletonList(new IntegrityMessage( Localization.lang("empty citation key") + ": " + authorTitleYear, entry, InternalField.KEY_FIELD)); } return Collections.emptyList(); } }
1,274
34.416667
119
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/CitationKeyDeviationChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; public class CitationKeyDeviationChecker implements EntryChecker { private final BibDatabaseContext bibDatabaseContext; private final CitationKeyPatternPreferences citationKeyPatternPreferences; public CitationKeyDeviationChecker(BibDatabaseContext bibDatabaseContext, CitationKeyPatternPreferences citationKeyPatternPreferences) { this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContext); this.citationKeyPatternPreferences = Objects.requireNonNull(citationKeyPatternPreferences); } @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> valuekey = entry.getCitationKey(); if (valuekey.isEmpty()) { return Collections.emptyList(); } String key = valuekey.get(); // generate new key String generatedKey = new CitationKeyGenerator(bibDatabaseContext, citationKeyPatternPreferences).generateKey(entry); if (!Objects.equals(key, generatedKey)) { return Collections.singletonList(new IntegrityMessage( Localization.lang("Citation key deviates from generated key"), entry, InternalField.KEY_FIELD)); } return Collections.emptyList(); } }
1,709
37
140
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/CitationKeyDuplicationChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; public class CitationKeyDuplicationChecker implements EntryChecker { private final BibDatabase database; public CitationKeyDuplicationChecker(BibDatabase database) { this.database = Objects.requireNonNull(database); } @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> citeKey = entry.getCitationKey(); if (citeKey.isEmpty()) { return Collections.emptyList(); } boolean isDuplicate = database.isDuplicateCitationKeyExisting(citeKey.get()); if (isDuplicate) { return Collections.singletonList( new IntegrityMessage(Localization.lang("Duplicate citation key"), entry, StandardField.KEY)); } return Collections.emptyList(); } }
1,116
30.027778
113
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/DatabaseChecker.java
package org.jabref.logic.integrity; import java.util.List; import org.jabref.model.database.BibDatabase; @FunctionalInterface public interface DatabaseChecker { List<IntegrityMessage> check(BibDatabase database); }
222
19.272727
55
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/DateChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.Date; import org.jabref.model.strings.StringUtil; public class DateChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } Optional<Date> parsedDate = Date.parse(value); if (!parsedDate.isPresent()) { return Optional.of(Localization.lang("incorrect format")); } return Optional.empty(); } }
616
23.68
70
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/DoiDuplicationChecker.java
package org.jabref.logic.integrity; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javafx.collections.ObservableList; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class DoiDuplicationChecker implements DatabaseChecker { @Override public List<IntegrityMessage> check(BibDatabase database) { ObservableList<BibEntry> bibEntries = database.getEntries(); BiMap<DOI, List<BibEntry>> duplicateMap = HashBiMap.create(bibEntries.size()); for (BibEntry bibEntry : bibEntries) { bibEntry.getDOI().ifPresent(doi -> duplicateMap.computeIfAbsent(doi, absentDoi -> new ArrayList<>()).add(bibEntry)); } return duplicateMap.inverse().keySet().stream() .filter(list -> list.size() > 1) .flatMap(list -> list.stream()) .map(item -> new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), item, StandardField.DOI)) .collect(Collectors.toList()); } }
1,370
37.083333
142
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/DoiValidityChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.strings.StringUtil; public class DoiValidityChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (DOI.isValid(value)) { return Optional.empty(); } else { return Optional.of(Localization.lang("DOI %0 is invalid", value)); } } }
600
25.130435
78
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/EditionChecker.java
package org.jabref.logic.integrity; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class EditionChecker implements ValueChecker { private static final Predicate<String> FIRST_LETTER_CAPITALIZED = Pattern.compile("^[A-Z]").asPredicate(); private static final Predicate<String> ONLY_NUMERALS_OR_LITERALS = Pattern.compile("^([0-9]+|[^0-9].+)$") .asPredicate(); private static final Predicate<String> ONLY_NUMERALS = Pattern.compile("[0-9]+").asPredicate(); private static final String FIRST_EDITION = "1"; private final BibDatabaseContext bibDatabaseContextEdition; // Allow integers in 'edition' field in BibTeX mode --> see GeneralTab.fml private final boolean allowIntegerEdition; public EditionChecker(BibDatabaseContext bibDatabaseContext, boolean allowIntegerEdition) { this.bibDatabaseContextEdition = Objects.requireNonNull(bibDatabaseContext); this.allowIntegerEdition = allowIntegerEdition; } /** * Checks, if field contains only an integer or a literal (biblatex mode) Checks, if the first letter is capitalized * (BibTeX mode) biblatex package documentation: The edition of a printed publication. This must be an integer, not * an ordinal. It is also possible to give the edition as a literal string, for example "Third, revised and expanded * edition". Official BibTeX specification: The edition of a book-for example, "Second". This should be an ordinal, * and should have the first letter capitalized. */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (value.equals(FIRST_EDITION)) { return Optional.of(Localization.lang("edition of book reported as just 1")); } if (bibDatabaseContextEdition.isBiblatexMode()) { if (!ONLY_NUMERALS_OR_LITERALS.test(value.trim())) { return Optional.of(Localization.lang("should contain an integer or a literal")); } } else { if (ONLY_NUMERALS.test(value) && (!allowIntegerEdition)) { return Optional.of(Localization.lang("no integer as values for edition allowed")); } } if (!isFirstCharDigit(value) && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } return Optional.empty(); } boolean isFirstCharDigit(String input) { return !StringUtil.isNullOrEmpty(input) && Character.isDigit(input.charAt(0)); } }
2,931
43.424242
120
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/EntryChecker.java
package org.jabref.logic.integrity; import java.util.List; import org.jabref.model.entry.BibEntry; @FunctionalInterface public interface EntryChecker { List<IntegrityMessage> check(BibEntry entry); }
207
17.909091
49
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/EntryLinkChecker.java
package org.jabref.logic.integrity; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; public class EntryLinkChecker implements EntryChecker { private final BibDatabase database; public EntryLinkChecker(BibDatabase database) { this.database = Objects.requireNonNull(database); } @Override public List<IntegrityMessage> check(BibEntry entry) { List<IntegrityMessage> result = new ArrayList<>(); for (Entry<Field, String> field : entry.getFieldMap().entrySet()) { Set<FieldProperty> properties = field.getKey().getProperties(); if (properties.contains(FieldProperty.SINGLE_ENTRY_LINK)) { if (database.getEntryByCitationKey(field.getValue()).isEmpty()) { result.add(new IntegrityMessage(Localization.lang("Referenced citation key does not exist"), entry, field.getKey())); } } else if (properties.contains(FieldProperty.MULTIPLE_ENTRY_LINK)) { List<String> keys = new ArrayList<>(Arrays.asList(field.getValue().split(","))); for (String key : keys) { if (database.getEntryByCitationKey(key).isEmpty()) { result.add(new IntegrityMessage( Localization.lang("Referenced citation key does not exist") + ": " + key, entry, field.getKey())); } } } } return result; } }
1,858
37.729167
119
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/FieldChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.util.OptionalUtil; public class FieldChecker implements EntryChecker { protected final Field field; private final ValueChecker checker; public FieldChecker(Field field, ValueChecker checker) { this.field = field; this.checker = Objects.requireNonNull(checker); } @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> value = entry.getField(field); if (value.isEmpty()) { return Collections.emptyList(); } return OptionalUtil.toList(checker.checkValue(value.get()).map(message -> new IntegrityMessage(message, entry, field))); } }
900
28.064516
128
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/FieldCheckers.java
package org.jabref.logic.integrity; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.FilePreferences; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class FieldCheckers { private final Multimap<Field, ValueChecker> fieldChecker; public FieldCheckers(BibDatabaseContext databaseContext, FilePreferences filePreferences, JournalAbbreviationRepository abbreviationRepository, boolean allowIntegerEdition) { fieldChecker = getAllMap(databaseContext, filePreferences, abbreviationRepository, allowIntegerEdition); } private static Multimap<Field, ValueChecker> getAllMap(BibDatabaseContext databaseContext, FilePreferences filePreferences, JournalAbbreviationRepository abbreviationRepository, boolean allowIntegerEdition) { ArrayListMultimap<Field, ValueChecker> fieldCheckers = ArrayListMultimap.create(50, 10); for (Field field : FieldFactory.getPersonNameFields()) { fieldCheckers.put(field, new PersonNamesChecker(databaseContext)); } fieldCheckers.put(StandardField.BOOKTITLE, new BooktitleChecker()); fieldCheckers.put(StandardField.TITLE, new BracketChecker()); fieldCheckers.put(StandardField.TITLE, new TitleChecker(databaseContext)); fieldCheckers.put(StandardField.DOI, new DoiValidityChecker()); fieldCheckers.put(StandardField.EDITION, new EditionChecker(databaseContext, allowIntegerEdition)); fieldCheckers.put(StandardField.FILE, new FileChecker(databaseContext, filePreferences)); fieldCheckers.put(StandardField.HOWPUBLISHED, new HowPublishedChecker(databaseContext)); fieldCheckers.put(StandardField.ISBN, new ISBNChecker()); fieldCheckers.put(StandardField.ISSN, new ISSNChecker()); fieldCheckers.put(StandardField.MONTH, new MonthChecker(databaseContext)); fieldCheckers.put(StandardField.MONTHFILED, new MonthChecker(databaseContext)); fieldCheckers.put(StandardField.NOTE, new NoteChecker(databaseContext)); fieldCheckers.put(StandardField.PAGES, new PagesChecker(databaseContext)); fieldCheckers.put(StandardField.URL, new UrlChecker()); fieldCheckers.put(StandardField.YEAR, new YearChecker()); fieldCheckers.put(StandardField.KEY, new ValidCitationKeyChecker()); fieldCheckers.put(InternalField.KEY_FIELD, new ValidCitationKeyChecker()); if (databaseContext.isBiblatexMode()) { fieldCheckers.put(StandardField.DATE, new DateChecker()); fieldCheckers.put(StandardField.URLDATE, new DateChecker()); fieldCheckers.put(StandardField.EVENTDATE, new DateChecker()); fieldCheckers.put(StandardField.ORIGDATE, new DateChecker()); } return fieldCheckers; } public List<FieldChecker> getAll() { return fieldChecker .entries() .stream() .map(pair -> new FieldChecker(pair.getKey(), pair.getValue())) .collect(Collectors.toList()); } public Collection<ValueChecker> getForField(Field field) { return fieldChecker .get(field); } }
3,597
47.621622
212
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/FileChecker.java
package org.jabref.logic.integrity; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.model.strings.StringUtil; import org.jabref.preferences.FilePreferences; public class FileChecker implements ValueChecker { private final BibDatabaseContext context; private final FilePreferences filePreferences; public FileChecker(BibDatabaseContext context, FilePreferences filePreferences) { this.context = context; this.filePreferences = filePreferences; } @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } List<LinkedFile> linkedFiles = FileFieldParser .parse(value).stream() .filter(file -> !file.isOnlineLink()) .collect(Collectors.toList()); for (LinkedFile file : linkedFiles) { Optional<Path> linkedFile = file.findIn(context, filePreferences); if ((!linkedFile.isPresent()) || !Files.exists(linkedFile.get())) { return Optional.of(Localization.lang("link should refer to a correct file path")); } } return Optional.empty(); } }
1,511
31.170213
98
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/HTMLCharacterChecker.java
package org.jabref.logic.integrity; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; /** * Checks, if there are any HTML encoded characters in nonverbatim fields. */ public class HTMLCharacterChecker implements EntryChecker { // Detect any HTML encoded character private static final Pattern HTML_CHARACTER_PATTERN = Pattern.compile("&[#\\p{Alnum}]+;"); @Override public List<IntegrityMessage> check(BibEntry entry) { List<IntegrityMessage> results = new ArrayList<>(); for (Map.Entry<Field, String> field : entry.getFieldMap().entrySet()) { // skip verbatim fields if (field.getKey().getProperties().contains(FieldProperty.VERBATIM)) { continue; } Matcher characterMatcher = HTML_CHARACTER_PATTERN.matcher(field.getValue()); if (characterMatcher.find()) { results.add( new IntegrityMessage(Localization.lang("HTML encoded character found"), entry, field.getKey())); } } return results; } }
1,343
33.461538
120
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/HowPublishedChecker.java
package org.jabref.logic.integrity; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class HowPublishedChecker implements ValueChecker { private static final Predicate<String> FIRST_LETTER_CAPITALIZED = Pattern.compile("^[^a-z]").asPredicate(); private final BibDatabaseContext databaseContext; public HowPublishedChecker(BibDatabaseContext databaseContext) { this.databaseContext = Objects.requireNonNull(databaseContext); } /** * Official BibTeX specification: * HowPublished: How something strange has been published. The first word should be capitalized. * biblatex package documentation (Section 4.9.1): * The biblatex package will automatically capitalize the first word when required at the beginning of a sentence. */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // BibTeX if (!databaseContext.isBiblatexMode() && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } return Optional.empty(); } }
1,428
33.02381
119
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/ISBNChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.identifier.ISBN; import org.jabref.model.strings.StringUtil; public class ISBNChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // Check that the ISBN is on the correct form ISBN isbn = new ISBN(value); if (!isbn.isValidFormat()) { return Optional.of(Localization.lang("incorrect format")); } if (!isbn.isValidChecksum()) { return Optional.of(Localization.lang("incorrect control digit")); } return Optional.empty(); } }
790
24.516129
77
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/ISSNChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.identifier.ISSN; import org.jabref.model.strings.StringUtil; public class ISSNChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // Check that the ISSN is on the correct form String issnString = value.trim(); ISSN issn = new ISSN(issnString); if (!issn.isValidFormat()) { return Optional.of(Localization.lang("incorrect format")); } if (issn.isValidChecksum()) { return Optional.empty(); } else { return Optional.of(Localization.lang("incorrect control digit")); } } }
856
25.78125
77
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/IntegrityCheck.java
package org.jabref.logic.integrity; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.FilePreferences; public class IntegrityCheck { private final BibDatabaseContext bibDatabaseContext; private final FieldCheckers fieldCheckers; private final List<EntryChecker> entryCheckers; public IntegrityCheck(BibDatabaseContext bibDatabaseContext, FilePreferences filePreferences, CitationKeyPatternPreferences citationKeyPatternPreferences, JournalAbbreviationRepository journalAbbreviationRepository, boolean allowIntegerEdition) { this.bibDatabaseContext = bibDatabaseContext; fieldCheckers = new FieldCheckers(bibDatabaseContext, filePreferences, journalAbbreviationRepository, allowIntegerEdition); entryCheckers = new ArrayList<>(List.of( new CitationKeyChecker(), new TypeChecker(), new BibStringChecker(), new HTMLCharacterChecker(), new EntryLinkChecker(bibDatabaseContext.getDatabase()), new CitationKeyDeviationChecker(bibDatabaseContext, citationKeyPatternPreferences), new CitationKeyDuplicationChecker(bibDatabaseContext.getDatabase()), new AmpersandChecker() )); if (bibDatabaseContext.isBiblatexMode()) { entryCheckers.addAll(List.of( new JournalInAbbreviationListChecker(StandardField.JOURNALTITLE, journalAbbreviationRepository), new UTF8Checker(bibDatabaseContext.getMetaData().getEncoding().orElse(StandardCharsets.UTF_8)) )); } else { entryCheckers.addAll(List.of( new JournalInAbbreviationListChecker(StandardField.JOURNAL, journalAbbreviationRepository), new ASCIICharacterChecker(), new NoBibtexFieldChecker(), new BibTeXEntryTypeChecker()) ); } } List<IntegrityMessage> check() { List<IntegrityMessage> result = new ArrayList<>(); BibDatabase database = bibDatabaseContext.getDatabase(); for (BibEntry entry : database.getEntries()) { result.addAll(checkEntry(entry)); } result.addAll(checkDatabase(database)); return result; } public List<IntegrityMessage> checkEntry(BibEntry entry) { List<IntegrityMessage> result = new ArrayList<>(); if (entry == null) { return result; } for (FieldChecker fieldChecker : fieldCheckers.getAll()) { result.addAll(fieldChecker.check(entry)); } for (EntryChecker entryChecker : entryCheckers) { result.addAll(entryChecker.check(entry)); } return result; } public List<IntegrityMessage> checkDatabase(BibDatabase database) { return new DoiDuplicationChecker().check(database); } }
3,470
36.728261
116
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/IntegrityMessage.java
package org.jabref.logic.integrity; import java.util.Objects; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; public final class IntegrityMessage implements Cloneable { private final BibEntry entry; private final Field field; private final String message; public IntegrityMessage(String message, BibEntry entry, Field field) { this.message = message; this.entry = entry; this.field = field; } @Override public String toString() { return "[" + getEntry().getCitationKey().orElse("") + "] in " + field.getDisplayName() + ": " + getMessage(); } public String getMessage() { return message; } public BibEntry getEntry() { return entry; } public Field getField() { return field; } @Override public Object clone() { return new IntegrityMessage(message, entry, field); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntegrityMessage that = (IntegrityMessage) o; return Objects.equals(entry, that.entry) && Objects.equals(field, that.field) && Objects.equals(message, that.message); } @Override public int hashCode() { return Objects.hash(entry, field, message); } }
1,467
23.466667
117
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/JournalInAbbreviationListChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; public class JournalInAbbreviationListChecker implements EntryChecker { private final Field field; private final JournalAbbreviationRepository abbreviationRepository; public JournalInAbbreviationListChecker(Field field, JournalAbbreviationRepository abbreviationRepository) { this.field = Objects.requireNonNull(field); this.abbreviationRepository = Objects.requireNonNull(abbreviationRepository); } @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> value = entry.getLatexFreeField(field); if (value.isEmpty()) { return Collections.emptyList(); } final String journal = value.get(); if (!abbreviationRepository.isKnownName(journal)) { return Collections.singletonList(new IntegrityMessage(Localization.lang("journal not found in abbreviation list"), entry, field)); } return Collections.emptyList(); } }
1,299
33.210526
142
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/MonthChecker.java
package org.jabref.logic.integrity; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class MonthChecker implements ValueChecker { private static final Predicate<String> ONLY_AN_INTEGER = Pattern.compile("[1-9]|10|11|12") .asPredicate(); private static final Predicate<String> MONTH_NORMALIZED = Pattern .compile("#jan#|#feb#|#mar#|#apr#|#may#|#jun#|#jul#|#aug#|#sep#|#oct#|#nov#|#dec#") .asPredicate(); private final BibDatabaseContext bibDatabaseContextMonth; public MonthChecker(BibDatabaseContext bibDatabaseContext) { this.bibDatabaseContextMonth = Objects.requireNonNull(bibDatabaseContext); } /** * biblatex package documentation (Section 2.3.9): * The month field is an integer field. * The bibliography style converts the month to a language-dependent string as required. * For backwards compatibility, you may also use the following three-letter abbreviations in the month field: * jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec. * Note that these abbreviations are BibTeX strings which must be given without any braces or quotes. */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // biblatex if (bibDatabaseContextMonth.isBiblatexMode() && !(ONLY_AN_INTEGER.test(value.trim()) || MONTH_NORMALIZED.test(value.trim()))) { return Optional.of(Localization.lang("should be an integer or normalized")); } // BibTeX if (!bibDatabaseContextMonth.isBiblatexMode() && !MONTH_NORMALIZED.test(value.trim())) { return Optional.of(Localization.lang("should be normalized")); } return Optional.empty(); } }
2,113
38.148148
113
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/NoBibtexFieldChecker.java
package org.jabref.logic.integrity; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.BiblatexEntryTypeDefinitions; import org.jabref.model.entry.types.BibtexEntryTypeDefinitions; /** * This checker checks whether the entry does not contain any field appearing only in biblatex (and not in BibTeX) */ public class NoBibtexFieldChecker implements EntryChecker { private Set<Field> getAllBiblatexOnlyFields() { Set<BibField> allBibtexFields = BibtexEntryTypeDefinitions.ALL.stream().flatMap(type -> type.getAllBibFields().stream()).collect(Collectors.toSet()); return BiblatexEntryTypeDefinitions.ALL.stream() .flatMap(type -> type.getAllBibFields().stream()) .filter(field -> !allBibtexFields.contains(field)) .map(BibField::field) // these fields are displayed by JabRef as default .filter(field -> !field.equals(StandardField.ABSTRACT)) .filter(field -> !field.equals(StandardField.COMMENT)) .filter(field -> !field.equals(StandardField.DOI)) .filter(field -> !field.equals(StandardField.URL)) .collect(Collectors.toSet()); } @Override public List<IntegrityMessage> check(BibEntry entry) { final Set<Field> allBiblatexOnlyFields = getAllBiblatexOnlyFields(); return entry.getFields().stream() .filter(allBiblatexOnlyFields::contains) .map(name -> new IntegrityMessage(Localization.lang("biblatex field only"), entry, name)).collect(Collectors.toList()); } }
2,171
50.714286
157
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/NoteChecker.java
package org.jabref.logic.integrity; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class NoteChecker implements ValueChecker { private static final Predicate<String> FIRST_LETTER_CAPITALIZED = Pattern.compile("^[^a-z]").asPredicate(); private final BibDatabaseContext bibDatabaseContextEdition; public NoteChecker(BibDatabaseContext bibDatabaseContext) { this.bibDatabaseContextEdition = Objects.requireNonNull(bibDatabaseContext); } /** * biblatex package documentation (Section 4.9.1): * The biblatex package will automatically capitalize the first word when required at the beginning of a sentence. * Official BibTeX specification: * note: Any additional information that can help the reader. The first word should be capitalized. */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } // BibTeX if (!bibDatabaseContextEdition.isBiblatexMode() && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } return Optional.empty(); } }
1,449
33.52381
118
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/PagesChecker.java
package org.jabref.logic.integrity; import java.util.Arrays; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class PagesChecker implements ValueChecker { private static final String PAGES_EXP_BIBTEX = "" + "\\A" // begin String + "[A-Za-z]?\\d*" // optional prefix and number + "(" + "(\\+|-{2}|\u2013)" // separator, must contain exactly two dashes + "[A-Za-z]?\\d*" // optional prefix and number + ")?" + "\\z"; // end String // See https://packages.oth-regensburg.de/ctan/macros/latex/contrib/biblatex/doc/biblatex.pdf#subsubsection.3.15.3 for valid content private static final String PAGES_EXP_BIBLATEX = "" + "\\A" // begin String + "[A-Za-z]?\\d*" // optional prefix and number + "(" + "(\\+|-{1,2}|\u2013)" // separator + "[A-Za-z]?\\d*" // optional prefix and number + ")?" + "\\z"; // end String private final Predicate<String> isValidPageNumber; public PagesChecker(BibDatabaseContext databaseContext) { if (databaseContext.isBiblatexMode()) { isValidPageNumber = Pattern.compile(PAGES_EXP_BIBLATEX).asPredicate(); } else { isValidPageNumber = Pattern.compile(PAGES_EXP_BIBTEX).asPredicate(); } } /** * From BibTex manual: * One or more page numbers or range of numbers, such as 42--111 or 7,41,73--97 or 43+ * (the '+' in this last example indicates pages following that don't form a simple range). * To make it easier to maintain Scribe-compatible databases, the standard styles convert * a single dash (as in 7-33) to the double dash used in TEX to denote number ranges (as in 7--33). * biblatex: * same as above but allows single dash as well */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (Arrays.stream(value.split(",")) .map(String::trim) .anyMatch(pageRange -> !isValidPageNumber.test(pageRange))) { return Optional.of(Localization.lang("should contain a valid page number range")); } return Optional.empty(); } }
2,594
38.318182
136
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/PersonNamesChecker.java
package org.jabref.logic.integrity; import java.util.Locale; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.format.RemoveBrackets; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.AuthorList; import org.jabref.model.strings.StringUtil; public class PersonNamesChecker implements ValueChecker { private final BibDatabaseMode bibMode; public PersonNamesChecker(BibDatabaseContext databaseContext) { this.bibMode = databaseContext.getMode(); } @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } String valueTrimmedAndLowerCase = value.trim().toLowerCase(Locale.ROOT); if (valueTrimmedAndLowerCase.startsWith("and ") || valueTrimmedAndLowerCase.startsWith(",")) { return Optional.of(Localization.lang("should start with a name")); } else if (valueTrimmedAndLowerCase.endsWith(" and") || valueTrimmedAndLowerCase.endsWith(",")) { return Optional.of(Localization.lang("should end with a name")); } // Remove all brackets to handle corporate names correctly, e.g., {JabRef} value = new RemoveBrackets().format(value); // Check that the value is in one of the two standard BibTeX formats: // Last, First and ... // First Last and ... AuthorList authorList = AuthorList.parse(value); if (!authorList.getAsLastFirstNamesWithAnd(false).equals(value) && !authorList.getAsFirstLastNamesWithAnd().equals(value)) { return Optional.of(Localization.lang("Names are not in the standard %0 format.", bibMode.getFormattedName())); } return Optional.empty(); } }
1,877
38.125
122
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/TitleChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.strings.StringUtil; public class TitleChecker implements ValueChecker { private static final Pattern INSIDE_CURLY_BRAKETS = Pattern.compile("\\{[^}\\{]*\\}"); private static final Pattern DELIMITERS = Pattern.compile("\\.|\\!|\\?|\\;|\\:"); private static final Predicate<String> HAS_CAPITAL_LETTERS = Pattern.compile("[\\p{Lu}\\p{Lt}]").asPredicate(); private final BibDatabaseContext databaseContext; public TitleChecker(BibDatabaseContext databaseContext) { this.databaseContext = databaseContext; } /** * Algorithm: * - remove everything that is in brackets * - split the title into sub titles based on the delimiters * (defined in the local variable DELIMITERS, currently . ! ? ; :) * - for each sub title: * - remove trailing whitespaces * - ignore first letter as this can always be written in caps * - check if at least one capital letter is in the sub title */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (databaseContext.isBiblatexMode()) { return Optional.empty(); } String valueOnlySpacesWithinCurlyBraces = value; while (true) { Matcher matcher = INSIDE_CURLY_BRAKETS.matcher(valueOnlySpacesWithinCurlyBraces); if (!matcher.find()) { break; } valueOnlySpacesWithinCurlyBraces = matcher.replaceAll(""); } String[] splitTitle = DELIMITERS.split(valueOnlySpacesWithinCurlyBraces); for (String subTitle : splitTitle) { subTitle = subTitle.trim(); if (!subTitle.isEmpty()) { subTitle = subTitle.substring(1); if (HAS_CAPITAL_LETTERS.test(subTitle)) { return Optional.of(Localization.lang("capital letters are not masked using curly brackets {}")); } } } return Optional.empty(); } }
2,348
34.059701
116
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/TypeChecker.java
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; public class TypeChecker implements EntryChecker { @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> value = entry.getField(StandardField.PAGES); if (value.isEmpty()) { return Collections.emptyList(); } if (StandardEntryType.Proceedings == entry.getType()) { return Collections.singletonList(new IntegrityMessage( Localization.lang("wrong entry type as proceedings has page numbers"), entry, StandardField.PAGES)); } return Collections.emptyList(); } }
899
30.034483
120
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/UTF8Checker.java
package org.jabref.logic.integrity; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; public class UTF8Checker implements EntryChecker { private final Charset charset; /** * Creates a UTF8Checker that, * <ol> * <li>decode a String into a bytes array</li> * <li>attempts to decode the bytes array to a character array using the UTF-8 Charset</li> * </ol> * * @param charset the charset used to decode BibEntry fields */ public UTF8Checker(Charset charset) { this.charset = charset; } /** * Detect any non UTF-8 encoded field * * @param entry the BibEntry of BibLatex. * @return return the warning of UTF-8 check for BibLatex. */ @Override public List<IntegrityMessage> check(BibEntry entry) { List<IntegrityMessage> results = new ArrayList<>(); for (Map.Entry<Field, String> field : entry.getFieldMap().entrySet()) { boolean utfOnly = UTF8EncodingChecker(field.getValue().getBytes(charset)); if (!utfOnly) { results.add(new IntegrityMessage(Localization.lang("Non-UTF-8 encoded field found"), entry, field.getKey())); } } return results; } /** * Check whether a byte array is encoded in UTF-8 charset * * Use java api decoder and try&catch block to check the charset. * * @param data the byte array used to check the encoding charset * @return true if is encoded in UTF-8 & false is not encoded in UTF-8 */ public static boolean UTF8EncodingChecker(byte[] data) { CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); try { decoder.decode(ByteBuffer.wrap(data)); } catch (CharacterCodingException ex) { return false; } return true; } }
2,215
31.115942
107
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/UrlChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; public class UrlChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (!value.contains("://")) { return Optional.of(Localization.lang("should contain a protocol") + ": http[s]://, file://, ftp://, ..."); } return Optional.empty(); } }
571
23.869565
118
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/ValidCitationKeyChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; /** * Makes sure the key is legal */ public class ValidCitationKeyChecker implements ValueChecker { @Override public Optional<String> checkValue(String value) { if (StringUtil.isNullOrEmpty(value)) { return Optional.of(Localization.lang("empty citation key")); } String cleaned = CitationKeyGenerator.cleanKey(value, ""); if (cleaned.equals(value)) { return Optional.empty(); } else { return Optional.of(Localization.lang("Invalid citation key")); } } }
773
25.689655
74
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/ValueChecker.java
package org.jabref.logic.integrity; import java.util.Optional; public interface ValueChecker { /** * Validates the specified value. * Returns a error massage if the validation failed. Otherwise an empty optional is returned. */ Optional<String> checkValue(String value); }
298
23.916667
97
java
null
jabref-main/src/main/java/org/jabref/logic/integrity/YearChecker.java
package org.jabref.logic.integrity; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; public class YearChecker implements ValueChecker { private static final Predicate<String> CONTAINS_FOUR_DIGIT = Pattern.compile("([^0-9]|^)[0-9]{4}([^0-9]|$)") .asPredicate(); private static final Predicate<String> ENDS_WITH_FOUR_DIGIT = Pattern.compile("[0-9]{4}$").asPredicate(); private static final String PUNCTUATION_MARKS = "[(){},.;!?<>%&$]"; /** * Checks, if the number String contains a four digit year and ends with it. * Official bibtex spec: * Generally it should consist of four numerals, such as 1984, although the standard styles * can handle any year whose last four nonpunctuation characters are numerals, such as ‘(about 1984)’. * Source: http://ftp.fernuni-hagen.de/ftp-dir/pub/mirrors/www.ctan.org/biblio/bibtex/base/btxdoc.pdf */ @Override public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (!CONTAINS_FOUR_DIGIT.test(value.trim())) { return Optional.of(Localization.lang("should contain a four digit number")); } if (!ENDS_WITH_FOUR_DIGIT.test(value.replaceAll(PUNCTUATION_MARKS, ""))) { return Optional.of(Localization.lang("last four nonpunctuation characters should be numerals")); } return Optional.empty(); } }
1,650
39.268293
112
java
null
jabref-main/src/main/java/org/jabref/logic/journals/Abbreviation.java
package org.jabref.logic.journals; import java.io.Serializable; import java.util.Objects; public class Abbreviation implements Comparable<Abbreviation>, Serializable { private static final long serialVersionUID = 1; private transient String name; private final String abbreviation; private transient String dotlessAbbreviation; // Is the empty string if not available private String shortestUniqueAbbreviation; public Abbreviation(String name, String abbreviation) { this(name, abbreviation, ""); } public Abbreviation(String name, String abbreviation, String shortestUniqueAbbreviation) { this(name, abbreviation, // "L. N." becomes "L N ", we need to remove the double spaces inbetween abbreviation.replace(".", " ").replace(" ", " ").trim(), shortestUniqueAbbreviation.trim()); } private Abbreviation(String name, String abbreviation, String dotlessAbbreviation, String shortestUniqueAbbreviation) { this.name = name.intern(); this.abbreviation = abbreviation.intern(); this.dotlessAbbreviation = dotlessAbbreviation.intern(); this.shortestUniqueAbbreviation = shortestUniqueAbbreviation.trim().intern(); } public String getName() { return name; } public String getAbbreviation() { return abbreviation; } public String getShortestUniqueAbbreviation() { if (shortestUniqueAbbreviation.isEmpty()) { shortestUniqueAbbreviation = getAbbreviation(); } return shortestUniqueAbbreviation; } public boolean isDefaultShortestUniqueAbbreviation() { return (shortestUniqueAbbreviation.isEmpty()) || this.shortestUniqueAbbreviation.equals(this.abbreviation); } public String getDotlessAbbreviation() { return this.dotlessAbbreviation; } @Override public int compareTo(Abbreviation toCompare) { int nameComparison = getName().compareTo(toCompare.getName()); if (nameComparison != 0) { return nameComparison; } int abbreviationComparison = getAbbreviation().compareTo(toCompare.getAbbreviation()); if (abbreviationComparison != 0) { return abbreviationComparison; } return getShortestUniqueAbbreviation().compareTo(toCompare.getShortestUniqueAbbreviation()); } public String getNext(String current) { String currentTrimmed = current.trim(); if (getDotlessAbbreviation().equals(currentTrimmed)) { return getShortestUniqueAbbreviation().equals(getAbbreviation()) ? getName() : getShortestUniqueAbbreviation(); } else if (getShortestUniqueAbbreviation().equals(currentTrimmed) && !getShortestUniqueAbbreviation().equals(getAbbreviation())) { return getName(); } else if (getName().equals(currentTrimmed)) { return getAbbreviation(); } else { return getDotlessAbbreviation(); } } @Override public String toString() { return String.format("Abbreviation{name=%s, abbreviation=%s, dotlessAbbreviation=%s, shortestUniqueAbbreviation=%s}", this.name, this.abbreviation, this.dotlessAbbreviation, this.shortestUniqueAbbreviation); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Abbreviation that = (Abbreviation) o; return getName().equals(that.getName()) && getAbbreviation().equals(that.getAbbreviation()) && getShortestUniqueAbbreviation().equals(that.getShortestUniqueAbbreviation()); } @Override public int hashCode() { return Objects.hash(getName(), getAbbreviation(), getShortestUniqueAbbreviation()); } }
3,961
33.754386
180
java
null
jabref-main/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java
package org.jabref.logic.journals; import org.apache.commons.csv.CSVFormat; public final class AbbreviationFormat { public static final char DELIMITER = ';'; public static final char ESCAPE = '\\'; public static final char QUOTE = '"'; private AbbreviationFormat() { } public static CSVFormat getCSVFormat() { return CSVFormat.DEFAULT.builder() .setIgnoreEmptyLines(true) .setDelimiter(DELIMITER) .setEscape(ESCAPE) .setQuote(QUOTE) .setTrim(true) .build(); } }
599
24
45
java
null
jabref-main/src/main/java/org/jabref/logic/journals/AbbreviationParser.java
package org.jabref.logic.journals; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.LinkedHashSet; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Reads abbreviation files (CSV format) into a list of Abbreviations. */ public class AbbreviationParser { private static final Logger LOGGER = LoggerFactory.getLogger(AbbreviationParser.class); // Ensures ordering while preventing duplicates private final LinkedHashSet<Abbreviation> abbreviations = new LinkedHashSet<>(); void readJournalListFromResource(String resourceFileName) { try (InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { readJournalList(reader); } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } } public void readJournalListFromFile(Path file) throws IOException { readJournalListFromFile(file, StandardCharsets.UTF_8); } public void readJournalListFromFile(Path file, Charset encoding) throws IOException { try (BufferedReader reader = Files.newBufferedReader(file, encoding)) { readJournalList(reader); } } /** * Read the given file, which should contain a list of journal names and their abbreviations. Each line should be * formatted as: "Full Journal Name;Abbr. Journal Name;[Shortest Unique Abbreviation]" * * @param reader a given file into a Reader object */ private void readJournalList(Reader reader) throws IOException { try (CSVParser csvParser = new CSVParser(reader, AbbreviationFormat.getCSVFormat())) { for (CSVRecord csvRecord : csvParser) { String name = csvRecord.size() > 0 ? csvRecord.get(0) : ""; String abbreviation = csvRecord.size() > 1 ? csvRecord.get(1) : ""; String shortestUniqueAbbreviation = csvRecord.size() > 2 ? csvRecord.get(2) : ""; // Check name and abbreviation if (name.isEmpty() || abbreviation.isEmpty()) { return; } Abbreviation abbreviationToAdd = new Abbreviation(name, abbreviation, shortestUniqueAbbreviation); abbreviations.add(abbreviationToAdd); } } } public Collection<Abbreviation> getAbbreviations() { return abbreviations; } }
2,919
36.922078
117
java
null
jabref-main/src/main/java/org/jabref/logic/journals/AbbreviationWriter.java
package org.jabref.logic.journals; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.apache.commons.csv.CSVPrinter; /** * This class provides handy static methods to save abbreviations to the file system. */ public final class AbbreviationWriter { private AbbreviationWriter() { } /** * This method will write the list of abbreviations to a file on the file system specified by the given path. If the * file already exists its content will be overridden, otherwise a new file will be created. * * @param path to a file (doesn't have to exist just yet) * @param abbreviations as a list specifying which entries should be written */ public static void writeOrCreate(Path path, List<Abbreviation> abbreviations) throws IOException { try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(path), StandardCharsets.UTF_8); CSVPrinter csvPrinter = new CSVPrinter(writer, AbbreviationFormat.getCSVFormat())) { for (Abbreviation entry : abbreviations) { if (entry.isDefaultShortestUniqueAbbreviation()) { csvPrinter.printRecord(entry.getName(), entry.getAbbreviation()); } else { csvPrinter.printRecord(entry.getName(), entry.getAbbreviation(), entry.getShortestUniqueAbbreviation()); } } } } }
1,560
38.025
124
java
null
jabref-main/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java
package org.jabref.logic.journals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * This class loads abbreviations from a CSV file and stores them into a MV file * </p> * <p> * Abbreviations are available at <a href="https://github.com/JabRef/abbrv.jabref.org/">https://github.com/JabRef/abbrv.jabref.org/</a>. * </p> */ public class JournalAbbreviationLoader { private static final Logger LOGGER = LoggerFactory.getLogger(JournalAbbreviationLoader.class); public static Collection<Abbreviation> readJournalListFromFile(Path file) throws IOException { LOGGER.debug(String.format("Reading journal list from file %s", file)); AbbreviationParser parser = new AbbreviationParser(); parser.readJournalListFromFile(file); return parser.getAbbreviations(); } public static JournalAbbreviationRepository loadRepository(JournalAbbreviationPreferences journalAbbreviationPreferences) { JournalAbbreviationRepository repository; // Initialize with built-in list try { Path tempDir = Files.createTempDirectory("jabref-journal"); Path tempJournalList = tempDir.resolve("journal-list.mv"); Files.copy(JournalAbbreviationRepository.class.getResourceAsStream("/journals/journal-list.mv"), tempJournalList); repository = new JournalAbbreviationRepository(tempJournalList); tempDir.toFile().deleteOnExit(); tempJournalList.toFile().deleteOnExit(); } catch (IOException e) { LOGGER.error("Error while copying journal list", e); return null; } // Read external lists List<String> lists = journalAbbreviationPreferences.getExternalJournalLists(); if (!(lists.isEmpty())) { // reversing ensures that the latest lists overwrites the former one Collections.reverse(lists); for (String filename : lists) { try { repository.addCustomAbbreviations(readJournalListFromFile(Path.of(filename))); } catch (IOException e) { LOGGER.error("Cannot read external journal list file {}", filename, e); } } } return repository; } public static JournalAbbreviationRepository loadBuiltInRepository() { return loadRepository(new JournalAbbreviationPreferences(Collections.emptyList(), true)); } }
2,639
38.402985
138
java
null
jabref-main/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java
package org.jabref.logic.journals; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class JournalAbbreviationPreferences { private final ObservableList<String> externalJournalLists; private final BooleanProperty useFJournalField; public JournalAbbreviationPreferences(List<String> externalJournalLists, boolean useFJournalField) { this.externalJournalLists = FXCollections.observableArrayList(externalJournalLists); this.useFJournalField = new SimpleBooleanProperty(useFJournalField); } public ObservableList<String> getExternalJournalLists() { return externalJournalLists; } public void setExternalJournalLists(List<String> list) { externalJournalLists.clear(); externalJournalLists.addAll(list); } public boolean shouldUseFJournalField() { return useFJournalField.get(); } public BooleanProperty useFJournalFieldProperty() { return useFJournalField; } public void setUseFJournalField(boolean useFJournalField) { this.useFJournalField.set(useFJournalField); } }
1,297
29.904762
92
java
null
jabref-main/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java
package org.jabref.logic.journals; import java.nio.file.Path; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.h2.mvstore.MVMap; import org.h2.mvstore.MVStore; /** * A repository for all journal abbreviations, including add and find methods. */ public class JournalAbbreviationRepository { static final Pattern QUESTION_MARK = Pattern.compile("\\?"); private final Map<String, Abbreviation> fullToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> abbreviationToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> dotlessToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> shortestUniqueToAbbreviationObject = new HashMap<>(); private final TreeSet<Abbreviation> customAbbreviations = new TreeSet<>(); public JournalAbbreviationRepository(Path journalList) { MVStore store = new MVStore.Builder().readOnly().fileName(journalList.toAbsolutePath().toString()).open(); MVMap<String, Abbreviation> mvFullToAbbreviationObject = store.openMap("FullToAbbreviation"); mvFullToAbbreviationObject.forEach((name, abbreviation) -> { String abbrevationString = abbreviation.getAbbreviation(); String shortestUniqueAbbreviation = abbreviation.getShortestUniqueAbbreviation(); Abbreviation newAbbreviation = new Abbreviation( name, abbrevationString, shortestUniqueAbbreviation ); fullToAbbreviationObject.put(name, newAbbreviation); abbreviationToAbbreviationObject.put(abbrevationString, newAbbreviation); dotlessToAbbreviationObject.put(newAbbreviation.getDotlessAbbreviation(), newAbbreviation); shortestUniqueToAbbreviationObject.put(shortestUniqueAbbreviation, newAbbreviation); }); } private static boolean isMatched(String name, Abbreviation abbreviation) { return name.equalsIgnoreCase(abbreviation.getName()) || name.equalsIgnoreCase(abbreviation.getAbbreviation()) || name.equalsIgnoreCase(abbreviation.getDotlessAbbreviation()) || name.equalsIgnoreCase(abbreviation.getShortestUniqueAbbreviation()); } private static boolean isMatchedAbbreviated(String name, Abbreviation abbreviation) { boolean isExpanded = name.equalsIgnoreCase(abbreviation.getName()); if (isExpanded) { return false; } boolean isAbbreviated = name.equalsIgnoreCase(abbreviation.getAbbreviation()) || name.equalsIgnoreCase(abbreviation.getDotlessAbbreviation()) || name.equalsIgnoreCase(abbreviation.getShortestUniqueAbbreviation()); return isAbbreviated; } /** * Returns true if the given journal name is contained in the list either in its full form * (e.g., Physical Review Letters) or its abbreviated form (e.g., Phys. Rev. Lett.). */ public boolean isKnownName(String journalName) { if (QUESTION_MARK.matcher(journalName).find()) { return false; } String journal = journalName.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); return customAbbreviations.stream().anyMatch(abbreviation -> isMatched(journal, abbreviation)) || fullToAbbreviationObject.containsKey(journal) || abbreviationToAbbreviationObject.containsKey(journal) || dotlessToAbbreviationObject.containsKey(journal) || shortestUniqueToAbbreviationObject.containsKey(journal); } /** * Returns true if the given journal name is in its abbreviated form (e.g. Phys. Rev. Lett.). The test is strict, * i.e., journals whose abbreviation is the same as the full name are not considered */ public boolean isAbbreviatedName(String journalName) { if (QUESTION_MARK.matcher(journalName).find()) { return false; } String journal = journalName.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); return customAbbreviations.stream().anyMatch(abbreviation -> isMatchedAbbreviated(journal, abbreviation)) || abbreviationToAbbreviationObject.containsKey(journal) || dotlessToAbbreviationObject.containsKey(journal) || shortestUniqueToAbbreviationObject.containsKey(journal); } /** * Attempts to get the abbreviation of the journal given. * * @param input The journal name (either full name or abbreviated name). */ public Optional<Abbreviation> get(String input) { // Clean up input: trim and unescape ampersand String journal = input.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); Optional<Abbreviation> customAbbreviation = customAbbreviations.stream() .filter(abbreviation -> isMatched(journal, abbreviation)) .findFirst(); if (customAbbreviation.isPresent()) { return customAbbreviation; } return Optional.ofNullable(fullToAbbreviationObject.get(journal)) .or(() -> Optional.ofNullable(abbreviationToAbbreviationObject.get(journal))) .or(() -> Optional.ofNullable(dotlessToAbbreviationObject.get(journal))) .or(() -> Optional.ofNullable(shortestUniqueToAbbreviationObject.get(journal))); } public void addCustomAbbreviation(Abbreviation abbreviation) { Objects.requireNonNull(abbreviation); // We do NOT want to keep duplicates // The set automatically "removes" duplicates // What is a duplicate? An abbreviation is NOT the same if any field is NOT equal (e.g., if the shortest unique differs, the abbreviation is NOT the same) customAbbreviations.add(abbreviation); } public Collection<Abbreviation> getCustomAbbreviations() { return customAbbreviations; } public void addCustomAbbreviations(Collection<Abbreviation> abbreviationsToAdd) { abbreviationsToAdd.forEach(this::addCustomAbbreviation); } public Optional<String> getNextAbbreviation(String text) { return get(text).map(abbreviation -> abbreviation.getNext(text)); } public Optional<String> getDefaultAbbreviation(String text) { return get(text).map(Abbreviation::getAbbreviation); } public Optional<String> getDotless(String text) { return get(text).map(Abbreviation::getDotlessAbbreviation); } public Optional<String> getShortestUniqueAbbreviation(String text) { return get(text).map(Abbreviation::getShortestUniqueAbbreviation); } public Set<String> getFullNames() { return fullToAbbreviationObject.keySet(); } public Collection<Abbreviation> getAllLoaded() { return fullToAbbreviationObject.values(); } }
7,212
44.08125
162
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/Encodings.java
package org.jabref.logic.l10n; import java.nio.charset.Charset; import java.util.List; import java.util.stream.Collectors; public class Encodings { public static final Charset[] ENCODINGS; public static final String[] ENCODINGS_DISPLAYNAMES; private static List<Charset> encodingsList = Charset.availableCharsets().values().stream().distinct() .collect(Collectors.toList()); private Encodings() { } static { List<String> encodingsStringList = encodingsList.stream().map(Charset::displayName).distinct() .collect(Collectors.toList()); ENCODINGS = encodingsList.toArray(new Charset[encodingsList.size()]); ENCODINGS_DISPLAYNAMES = encodingsStringList.toArray(new String[encodingsStringList.size()]); } public static List<Charset> getCharsets() { return encodingsList; } }
956
33.178571
105
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/Language.java
package org.jabref.logic.l10n; import java.util.Locale; import java.util.Objects; import java.util.Optional; /** * Contains all supported languages. */ public enum Language { ARABIC("العربية (Arabic)", "ar"), BAHASA_INDONESIA("Bahasa Indonesia", "id"), BRAZILIAN_PORTUGUESE("Brazilian Portuguese", "pt_BR"), DANISH("Dansk", "da"), DUTCH("Nederlands", "nl"), ENGLISH("English", "en"), FRENCH("Français", "fr"), GERMAN("Deutsch", "de"), GREEK("ελληνικά (Greek)", "el"), ITALIAN("Italiano", "it"), JAPANESE("Japanese", "ja"), KOREAN("한국어 (Korean)", "ko"), NORWEGIAN("Norsk", "no"), PERSIAN("فارسی (Farsi)", "fa"), POLISH("Polish", "pl"), PORTUGUESE("Português", "pt"), RUSSIAN("Russian", "ru"), SIMPLIFIED_CHINESE("Chinese (Simplified)", "zh_CN"), SPANISH("Español", "es"), SWEDISH("Svenska", "sv"), TAGALOG("Tagalog/Filipino", "tl"), TRADITIONAL_CHINESE("Chinese (Traditional)", "zh_TW"), TURKISH("Turkish", "tr"), UKRAINIAN("украї́нська (Ukrainian)", "uk"), VIETNAMESE("Vietnamese", "vi"); private final String displayName; private final String id; /** * @param id Typically as 639-1 code */ Language(String displayName, String id) { this.displayName = displayName; this.id = id; } public static Optional<Locale> convertToSupportedLocale(Language language) { Objects.requireNonNull(language); // Very important to split languages like pt_BR into two parts, because otherwise the country would be treated lowercase and create problems in loading String[] languageParts = language.getId().split("_"); Locale locale; if (languageParts.length == 1) { locale = Locale.of(languageParts[0]); } else if (languageParts.length == 2) { locale = Locale.of(languageParts[0], languageParts[1]); } else { locale = Locale.ENGLISH; } return Optional.of(locale); } public String getDisplayName() { return displayName; } public String getId() { return id; } }
2,145
28.39726
159
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/Localization.java
package org.jabref.logic.l10n; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides handling for messages and menu entries in the preferred language of the user. * <p> * Notes: All messages and menu-entries in JabRef are stored in escaped form like "This_is_a_message". This message * serves as key inside the {@link l10n} properties files that hold the translation for many languages. When a message * is accessed, it needs to be unescaped and possible parameters that can appear in a message need to be filled with * values. * <p> * This implementation loads the appropriate language by importing all keys/values from the correct bundle and stores * them in unescaped form inside a {@link LocalizationBundle} which provides fast access because it caches the key-value * pairs. * <p> * The access to this is given by the functions {@link Localization#lang(String, String...)} and * that developers should use whenever they use strings for the e.g. GUI that need to be translatable. */ public class Localization { static final String RESOURCE_PREFIX = "l10n/JabRef"; private static final Logger LOGGER = LoggerFactory.getLogger(Localization.class); private static Locale locale; private static LocalizationBundle localizedMessages; private Localization() { } /** * Public access to all messages that are not menu-entries * * @param key The key of the message in unescaped form like "All fields" * @param params Replacement strings for parameters %0, %1, etc. * @return The message with replaced parameters */ public static String lang(String key, Object... params) { if (localizedMessages == null) { // I'm logging this because it should never happen LOGGER.error("Messages are not initialized before accessing key: {}", key); setLanguage(Language.ENGLISH); } var stringParams = Arrays.stream(params).map(Object::toString).toArray(String[]::new); return lookup(localizedMessages, key, stringParams); } /** * Sets the language and loads the appropriate translations. Note, that this function should be called before any * other function of this class. * * @param language Language identifier like "en", "de", etc. */ public static void setLanguage(Language language) { Optional<Locale> knownLanguage = Language.convertToSupportedLocale(language); final Locale defaultLocale = Locale.getDefault(); if (knownLanguage.isEmpty()) { LOGGER.warn("Language {} is not supported by JabRef (Default: {})", language, defaultLocale); setLanguage(Language.ENGLISH); return; } // avoid reinitialization of the language bundles final Locale langLocale = knownLanguage.get(); if ((locale != null) && locale.equals(langLocale) && locale.equals(defaultLocale)) { return; } locale = langLocale; Locale.setDefault(locale); try { createResourceBundles(locale); } catch (MissingResourceException ex) { // should not happen as we have scripts to enforce this LOGGER.warn("Could not find bundles for language " + locale + ", switching to full english language", ex); setLanguage(Language.ENGLISH); } } /** * Returns the messages bundle, e.g. to load FXML files correctly translated. * * @return The internally cashed bundle. */ public static LocalizationBundle getMessages() { // avoid situations where this function is called before any language was set if (locale == null) { setLanguage(Language.ENGLISH); } return localizedMessages; } /** * Creates and caches the language bundles used in JabRef for a particular language. This function first loads * correct version of the "escaped" bundles that are given in {@link l10n}. After that, it stores the unescaped * version in a cached {@link LocalizationBundle} for fast access. * * @param locale Localization to use. */ private static void createResourceBundles(Locale locale) { ResourceBundle messages = ResourceBundle.getBundle(RESOURCE_PREFIX, locale); Objects.requireNonNull(messages, "Could not load " + RESOURCE_PREFIX + " resource."); localizedMessages = new LocalizationBundle(createLookupMap(messages)); } /** * Helper function to create a Map from the key/value pairs of a bundle. * * @param baseBundle JabRef language bundle with keys and values for translations. * @return Lookup map for the baseBundle. */ private static Map<String, String> createLookupMap(ResourceBundle baseBundle) { final ArrayList<String> baseKeys = Collections.list(baseBundle.getKeys()); return new HashMap<>(baseKeys.stream().collect( Collectors.toMap( // not required to unescape content, because that is already done by the ResourceBundle itself key -> key, baseBundle::getString) )); } /** * This looks up a key in the bundle and replaces parameters %0, ..., %9 with the respective params given. Note that * the keys are the "unescaped" strings from the bundle property files. * * @param bundle The {@link LocalizationBundle} which is usually {@link Localization#localizedMessages}. * @param key The lookup key. * @param params The parameters that should be inserted into the message * @return The final message with replaced parameters. */ private static String lookup(LocalizationBundle bundle, String key, String... params) { Objects.requireNonNull(key); String translation = bundle.containsKey(key) ? bundle.getString(key) : ""; if (translation.isEmpty()) { LOGGER.warn("Warning: could not get translation for \"{}\" for locale {}", key, Locale.getDefault()); translation = key; } return new LocalizationKeyParams(translation, params).replacePlaceholders(); } /** * A bundle for caching localized strings. Needed to support JavaFX inline binding. */ private static class LocalizationBundle extends ResourceBundle { private final Map<String, String> lookup; LocalizationBundle(Map<String, String> lookupMap) { lookup = lookupMap; } @Override public final Object handleGetObject(String key) { Objects.requireNonNull(key); return Optional.ofNullable(lookup.get(key)) .orElse(key); } @Override public Enumeration<String> getKeys() { return Collections.enumeration(lookup.keySet()); } @Override protected Set<String> handleKeySet() { return lookup.keySet(); } @Override public boolean containsKey(String key) { // Pretend we have every key return true; } } }
7,540
38.072539
120
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/LocalizationKey.java
package org.jabref.logic.l10n; import java.util.Objects; /** * Model for a localization to translate. The key is the English text. */ public class LocalizationKey { private final String key; private final String escapedPropertyKey; /** * @param key plain key - no escaping. E.g., "Copy \cite{key}" or "Newline follows\nsecond line" are valid parameters. */ private LocalizationKey(String key) { this.key = key; // space, #, !, = and : are not allowed in properties file keys // # and ! are only disallowed at the beginning of the key but easier to escape every instance this.escapedPropertyKey = key .replace("\n", "\\n") .replace(" ", "\\ ") .replace("#", "\\#") .replace("!", "\\!") .replace("=", "\\=") .replace(":", "\\:"); } /** * @param key plain key - no escaping. E.g., "Copy \cite{key}" or "Newline follows\nsecond line" are valid parameters. */ public static LocalizationKey fromKey(String key) { return new LocalizationKey(Objects.requireNonNull(key)); } public static LocalizationKey fromEscapedJavaString(String key) { // "\n" in the string is an escaped newline. That needs to be kept. // "\\" in the string can stay --> needs to be kept return new LocalizationKey(Objects.requireNonNull(key)); } /* public static LocalizationKey fromPropertyKey(String key) { String propertyKey = key; // we ne need to unescape the escaped characters (see org.jabref.logic.l10n.LocalizationKey.LocalizationKey) String javaCodeKey = key.replaceAll("\\\\([ #!=:])", "$1"); return new LocalizationKey(javaCodeKey, propertyKey); } */ public String getEscapedPropertiesKey() { return this.escapedPropertyKey; } public String getValueForEnglishPropertiesFile() { // Newline needs to be escaped return this.key.replace("\n", "\\n"); } public String getKey() { return this.key; } }
2,107
32.460317
122
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/LocalizationKeyParams.java
package org.jabref.logic.l10n; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; public class LocalizationKeyParams { private final LocalizationKey key; private final List<String> params; public LocalizationKeyParams(String key, String... params) { this.key = LocalizationKey.fromKey(key); this.params = Arrays.asList(params); if (this.params.size() > 10) { throw new IllegalStateException("Translations can only have at most 10 parameters"); } } public String replacePlaceholders() { String translation = key.getKey(); for (int i = 0; i < params.size(); i++) { String param = params.get(i); translation = translation.replaceAll("%" + i, Matcher.quoteReplacement(param)); } return translation; } }
859
26.741935
96
java
null
jabref-main/src/main/java/org/jabref/logic/l10n/LocalizationLocator.java
package org.jabref.logic.l10n; import java.util.ResourceBundle; import com.airhacks.afterburner.views.ResourceLocator; public class LocalizationLocator implements ResourceLocator { @Override public ResourceBundle getResourceBundle(String s) { return Localization.getMessages(); } }
305
22.538462
61
java
null
jabref-main/src/main/java/org/jabref/logic/layout/AbstractParamLayoutFormatter.java
package org.jabref.logic.layout; import java.util.ArrayList; import java.util.List; /** * This is an abstract implementation of ParamLayoutFormatter, which provides some * functionality for the handling of argument strings. */ public abstract class AbstractParamLayoutFormatter implements ParamLayoutFormatter { private static final char SEPARATOR = ','; protected AbstractParamLayoutFormatter() { } /** * Parse an argument string and return the parts of the argument. The parts are * separated by commas, and escaped commas are reduced to literal commas. * * @param arg The argument string. * @return A list of strings representing the parts of the argument. */ protected static List<String> parseArgument(String arg) { List<String> parts = new ArrayList<>(); StringBuilder current = new StringBuilder(); boolean escaped = false; for (int i = 0; i < arg.length(); i++) { if ((arg.charAt(i) == AbstractParamLayoutFormatter.SEPARATOR) && !escaped) { parts.add(current.toString()); current = new StringBuilder(); } else if (arg.charAt(i) == '\\') { if (escaped) { escaped = false; current.append(arg.charAt(i)); } else { escaped = true; } } else if (escaped) { // Handle newline and tab: if (arg.charAt(i) == 'n') { current.append('\n'); } else if (arg.charAt(i) == 't') { current.append('\t'); } else { if ((arg.charAt(i) != ',') && (arg.charAt(i) != '"')) { current.append('\\'); } current.append(arg.charAt(i)); } escaped = false; } else { current.append(arg.charAt(i)); } } parts.add(current.toString()); return parts; } }
2,079
33.666667
88
java
null
jabref-main/src/main/java/org/jabref/logic/layout/Layout.java
package org.jabref.logic.layout; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Layout { private static final Logger LOGGER = LoggerFactory.getLogger(Layout.class); private final List<LayoutEntry> layoutEntries; private final List<String> missingFormatters = new ArrayList<>(); public Layout(List<StringInt> parsedEntries, List<Path> fileDirForDatabase, LayoutFormatterPreferences layoutPreferences, JournalAbbreviationRepository abbreviationRepository) { List<LayoutEntry> tmpEntries = new ArrayList<>(parsedEntries.size()); List<StringInt> blockEntries = null; LayoutEntry le; String blockStart = null; for (StringInt parsedEntry : parsedEntries) { switch (parsedEntry.i) { case LayoutHelper.IS_LAYOUT_TEXT: case LayoutHelper.IS_SIMPLE_COMMAND: case LayoutHelper.IS_OPTION_FIELD: // Do nothing break; case LayoutHelper.IS_FIELD_START: case LayoutHelper.IS_GROUP_START: blockEntries = new ArrayList<>(); blockStart = parsedEntry.s; break; case LayoutHelper.IS_FIELD_END: case LayoutHelper.IS_GROUP_END: if ((blockStart != null) && (blockEntries != null)) { if (blockStart.equals(parsedEntry.s)) { blockEntries.add(parsedEntry); le = new LayoutEntry(blockEntries, parsedEntry.i == LayoutHelper.IS_FIELD_END ? LayoutHelper.IS_FIELD_START : LayoutHelper.IS_GROUP_START, fileDirForDatabase, layoutPreferences, abbreviationRepository); tmpEntries.add(le); blockEntries = null; } else { LOGGER.debug(blockStart + '\n' + parsedEntry.s); LOGGER.warn("Nested field/group entries are not implemented!"); Thread.dumpStack(); } } break; default: break; } if (blockEntries == null) { tmpEntries.add(new LayoutEntry(parsedEntry, fileDirForDatabase, layoutPreferences, abbreviationRepository)); } else { blockEntries.add(parsedEntry); } } layoutEntries = new ArrayList<>(tmpEntries); for (LayoutEntry layoutEntry : layoutEntries) { missingFormatters.addAll(layoutEntry.getInvalidFormatters()); } } public void setPostFormatter(LayoutFormatter formatter) { for (LayoutEntry layoutEntry : layoutEntries) { layoutEntry.setPostFormatter(formatter); } } public String getText() { return layoutEntries.stream().map(LayoutEntry::getText).collect(Collectors.joining("\n")); } /** * Returns the processed bibtex entry. If the database argument is * null, no string references will be resolved. Otherwise all valid * string references will be replaced by the strings' contents. Even * recursive string references are resolved. */ public String doLayout(BibEntry bibtex, BibDatabase database) { StringBuilder builder = new StringBuilder(100); for (LayoutEntry layoutEntry : layoutEntries) { String fieldText = layoutEntry.doLayout(bibtex, database); // The following change means we treat null fields as "". This is to fix the // problem of whitespace disappearing after missing fields. if (fieldText == null) { fieldText = ""; } builder.append(fieldText); } return builder.toString(); } /** * Returns the processed text. If the database argument is * null, no string references will be resolved. Otherwise all valid * string references will be replaced by the strings' contents. Even * recursive string references are resolved. */ public String doLayout(BibDatabaseContext databaseContext, Charset encoding) { StringBuilder sb = new StringBuilder(100); String fieldText; for (LayoutEntry layoutEntry : layoutEntries) { fieldText = layoutEntry.doLayout(databaseContext, encoding); if (fieldText == null) { fieldText = ""; } sb.append(fieldText); } return sb.toString(); } public List<String> getMissingFormatters() { return new ArrayList<>(missingFormatters); } }
5,274
35.37931
139
java
null
jabref-main/src/main/java/org/jabref/logic/layout/LayoutEntry.java
package org.jabref.logic.layout; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.formatter.bibtexfields.UnicodeToLatexFormatter; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.layout.format.AuthorAbbreviator; import org.jabref.logic.layout.format.AuthorAndToSemicolonReplacer; import org.jabref.logic.layout.format.AuthorAndsCommaReplacer; import org.jabref.logic.layout.format.AuthorAndsReplacer; import org.jabref.logic.layout.format.AuthorFirstAbbrLastCommas; import org.jabref.logic.layout.format.AuthorFirstAbbrLastOxfordCommas; import org.jabref.logic.layout.format.AuthorFirstFirst; import org.jabref.logic.layout.format.AuthorFirstFirstCommas; import org.jabref.logic.layout.format.AuthorFirstLastCommas; import org.jabref.logic.layout.format.AuthorFirstLastOxfordCommas; import org.jabref.logic.layout.format.AuthorLF_FF; import org.jabref.logic.layout.format.AuthorLF_FFAbbr; import org.jabref.logic.layout.format.AuthorLastFirst; import org.jabref.logic.layout.format.AuthorLastFirstAbbrCommas; import org.jabref.logic.layout.format.AuthorLastFirstAbbrOxfordCommas; import org.jabref.logic.layout.format.AuthorLastFirstAbbreviator; import org.jabref.logic.layout.format.AuthorLastFirstCommas; import org.jabref.logic.layout.format.AuthorLastFirstOxfordCommas; import org.jabref.logic.layout.format.AuthorNatBib; import org.jabref.logic.layout.format.AuthorOrgSci; import org.jabref.logic.layout.format.Authors; import org.jabref.logic.layout.format.CSLType; import org.jabref.logic.layout.format.CompositeFormat; import org.jabref.logic.layout.format.CreateBibORDFAuthors; import org.jabref.logic.layout.format.CreateDocBook4Authors; import org.jabref.logic.layout.format.CreateDocBook4Editors; import org.jabref.logic.layout.format.CreateDocBook5Authors; import org.jabref.logic.layout.format.CreateDocBook5Editors; import org.jabref.logic.layout.format.CurrentDate; import org.jabref.logic.layout.format.DOICheck; import org.jabref.logic.layout.format.DOIStrip; import org.jabref.logic.layout.format.DateFormatter; import org.jabref.logic.layout.format.Default; import org.jabref.logic.layout.format.EntryTypeFormatter; import org.jabref.logic.layout.format.FileLink; import org.jabref.logic.layout.format.FirstPage; import org.jabref.logic.layout.format.FormatPagesForHTML; import org.jabref.logic.layout.format.FormatPagesForXML; import org.jabref.logic.layout.format.GetOpenOfficeType; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.HTMLParagraphs; import org.jabref.logic.layout.format.IfPlural; import org.jabref.logic.layout.format.Iso690FormatDate; import org.jabref.logic.layout.format.Iso690NamesAuthors; import org.jabref.logic.layout.format.JournalAbbreviator; import org.jabref.logic.layout.format.LastPage; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.layout.format.MarkdownFormatter; import org.jabref.logic.layout.format.NameFormatter; import org.jabref.logic.layout.format.NoSpaceBetweenAbbreviations; import org.jabref.logic.layout.format.NotFoundFormatter; import org.jabref.logic.layout.format.Number; import org.jabref.logic.layout.format.Ordinal; import org.jabref.logic.layout.format.RTFChars; import org.jabref.logic.layout.format.RemoveBrackets; import org.jabref.logic.layout.format.RemoveBracketsAddComma; import org.jabref.logic.layout.format.RemoveLatexCommandsFormatter; import org.jabref.logic.layout.format.RemoveTilde; import org.jabref.logic.layout.format.RemoveWhitespace; import org.jabref.logic.layout.format.Replace; import org.jabref.logic.layout.format.ReplaceWithEscapedDoubleQuotes; import org.jabref.logic.layout.format.RisAuthors; import org.jabref.logic.layout.format.RisKeywords; import org.jabref.logic.layout.format.RisMonth; import org.jabref.logic.layout.format.ShortMonthFormatter; import org.jabref.logic.layout.format.ToLowerCase; import org.jabref.logic.layout.format.ToUpperCase; import org.jabref.logic.layout.format.WrapContent; import org.jabref.logic.layout.format.WrapFileLinks; import org.jabref.logic.layout.format.XMLChars; import org.jabref.logic.openoffice.style.OOPreFormatter; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class LayoutEntry { private static final Logger LOGGER = LoggerFactory.getLogger(LayoutEntry.class); private List<LayoutFormatter> option; // Formatter to be run after other formatters: private LayoutFormatter postFormatter; private String text; private List<LayoutEntry> layoutEntries; private final int type; private final List<String> invalidFormatter = new ArrayList<>(); private final List<Path> fileDirForDatabase; private final LayoutFormatterPreferences preferences; private final JournalAbbreviationRepository abbreviationRepository; public LayoutEntry(StringInt si, List<Path> fileDirForDatabase, LayoutFormatterPreferences preferences, JournalAbbreviationRepository abbreviationRepository) { this.preferences = preferences; this.abbreviationRepository = abbreviationRepository; this.fileDirForDatabase = Objects.requireNonNullElse(fileDirForDatabase, Collections.emptyList()); type = si.i; switch (type) { case LayoutHelper.IS_LAYOUT_TEXT -> text = si.s; case LayoutHelper.IS_SIMPLE_COMMAND -> text = si.s.trim(); case LayoutHelper.IS_OPTION_FIELD -> doOptionField(si.s); default -> { // IS_FIELD_START and IS_FIELD_END } } } public LayoutEntry(List<StringInt> parsedEntries, int layoutType, List<Path> fileDirForDatabase, LayoutFormatterPreferences preferences, JournalAbbreviationRepository abbreviationRepository) { this.preferences = preferences; this.abbreviationRepository = abbreviationRepository; this.fileDirForDatabase = Objects.requireNonNullElse(fileDirForDatabase, Collections.emptyList()); List<LayoutEntry> tmpEntries = new ArrayList<>(); String blockStart = parsedEntries.get(0).s; String blockEnd = parsedEntries.get(parsedEntries.size() - 1).s; if (!blockStart.equals(blockEnd)) { LOGGER.warn("Field start and end entry must be equal."); } type = layoutType; text = blockEnd; List<StringInt> blockEntries = null; for (StringInt parsedEntry : parsedEntries.subList(1, parsedEntries.size() - 1)) { switch (parsedEntry.i) { case LayoutHelper.IS_FIELD_START: case LayoutHelper.IS_GROUP_START: blockEntries = new ArrayList<>(); blockStart = parsedEntry.s; break; case LayoutHelper.IS_FIELD_END: case LayoutHelper.IS_GROUP_END: if (blockStart.equals(parsedEntry.s)) { blockEntries.add(parsedEntry); int groupType = parsedEntry.i == LayoutHelper.IS_GROUP_END ? LayoutHelper.IS_GROUP_START : LayoutHelper.IS_FIELD_START; LayoutEntry le = new LayoutEntry(blockEntries, groupType, fileDirForDatabase, preferences, abbreviationRepository); tmpEntries.add(le); blockEntries = null; } else { LOGGER.warn("Nested field entries are not implemented!"); } break; case LayoutHelper.IS_LAYOUT_TEXT: case LayoutHelper.IS_SIMPLE_COMMAND: case LayoutHelper.IS_OPTION_FIELD: default: // Do nothing break; } if (blockEntries == null) { tmpEntries.add(new LayoutEntry(parsedEntry, fileDirForDatabase, preferences, abbreviationRepository)); } else { blockEntries.add(parsedEntry); } } layoutEntries = new ArrayList<>(tmpEntries); for (LayoutEntry layoutEntry : layoutEntries) { invalidFormatter.addAll(layoutEntry.getInvalidFormatters()); } } public void setPostFormatter(LayoutFormatter formatter) { this.postFormatter = formatter; } public String doLayout(BibEntry bibtex, BibDatabase database) { switch (type) { case LayoutHelper.IS_LAYOUT_TEXT: return text; case LayoutHelper.IS_SIMPLE_COMMAND: String value = bibtex.getResolvedFieldOrAlias(FieldFactory.parseField(text), database).orElse(""); // If a post formatter has been set, call it: if (postFormatter != null) { value = postFormatter.format(value); } return value; case LayoutHelper.IS_FIELD_START: case LayoutHelper.IS_GROUP_START: return handleFieldOrGroupStart(bibtex, database); case LayoutHelper.IS_FIELD_END: case LayoutHelper.IS_GROUP_END: return ""; case LayoutHelper.IS_OPTION_FIELD: return handleOptionField(bibtex, database); case LayoutHelper.IS_ENCODING_NAME: // Printing the encoding name is not supported in entry layouts, only // in begin/end layouts. This prevents breakage if some users depend // on a field called "encoding". We simply return this field instead: return bibtex.getResolvedFieldOrAlias(new UnknownField("encoding"), database).orElse(null); default: return ""; } } private String handleOptionField(BibEntry bibtex, BibDatabase database) { String fieldEntry; if (InternalField.TYPE_HEADER.getName().equals(text)) { fieldEntry = bibtex.getType().getDisplayName(); } else if (InternalField.OBSOLETE_TYPE_HEADER.getName().equals(text)) { LOGGER.warn("'" + InternalField.OBSOLETE_TYPE_HEADER + "' is an obsolete name for the entry type. Please update your layout to use '" + InternalField.TYPE_HEADER + "' instead."); fieldEntry = bibtex.getType().getDisplayName(); } else { // changed section begin - arudert // resolve field (recognized by leading backslash) or text fieldEntry = text.startsWith("\\") ? bibtex .getResolvedFieldOrAlias(FieldFactory.parseField(text.substring(1)), database) .orElse("") : BibDatabase.getText(text, database); // changed section end - arudert } if (option != null) { for (LayoutFormatter anOption : option) { fieldEntry = anOption.format(fieldEntry); } } // If a post formatter has been set, call it: if (postFormatter != null) { fieldEntry = postFormatter.format(fieldEntry); } return fieldEntry; } private String handleFieldOrGroupStart(BibEntry bibtex, BibDatabase database) { Optional<String> field; boolean negated = false; if (type == LayoutHelper.IS_GROUP_START) { field = bibtex.getResolvedFieldOrAlias(FieldFactory.parseField(text), database); } else if (text.matches(".*(;|(\\&+)).*")) { // split the strings along &, && or ; for AND formatter String[] parts = text.split("\\s*(;|(\\&+))\\s*"); field = Optional.empty(); for (String part : parts) { negated = part.startsWith("!"); field = bibtex.getResolvedFieldOrAlias(FieldFactory.parseField(negated ? part.substring(1).trim() : part), database); if (field.isPresent() == negated) { break; } } } else { // split the strings along |, || for OR formatter String[] parts = text.split("\\s*(\\|+)\\s*"); field = Optional.empty(); for (String part : parts) { negated = part.startsWith("!"); field = bibtex.getResolvedFieldOrAlias(FieldFactory.parseField(negated ? part.substring(1).trim() : part), database); if (field.isPresent() ^ negated) { break; } } } if ((field.isPresent() == negated) || ((type == LayoutHelper.IS_GROUP_START) && field.get().equalsIgnoreCase(LayoutHelper.getCurrentGroup()))) { return null; } else { if (type == LayoutHelper.IS_GROUP_START) { LayoutHelper.setCurrentGroup(field.get()); } StringBuilder sb = new StringBuilder(100); String fieldText; boolean previousSkipped = false; for (int i = 0; i < layoutEntries.size(); i++) { fieldText = layoutEntries.get(i).doLayout(bibtex, database); if (fieldText == null) { if ((i + 1) < layoutEntries.size()) { if (layoutEntries.get(i + 1).doLayout(bibtex, database).trim().isEmpty()) { i++; previousSkipped = true; continue; } } } else { // if previous was skipped --> remove leading line // breaks if (previousSkipped) { int eol = 0; while ((eol < fieldText.length()) && ((fieldText.charAt(eol) == '\n') || (fieldText.charAt(eol) == '\r'))) { eol++; } if (eol < fieldText.length()) { sb.append(fieldText.substring(eol)); } } else { sb.append(fieldText); } } previousSkipped = false; } return sb.toString(); } } /** * Do layout for general formatters (no bibtex-entry fields). * * @param databaseContext Bibtex Database */ public String doLayout(BibDatabaseContext databaseContext, Charset encoding) { switch (type) { case LayoutHelper.IS_LAYOUT_TEXT: return text; case LayoutHelper.IS_SIMPLE_COMMAND: throw new UnsupportedOperationException("bibtex entry fields not allowed in begin or end layout"); case LayoutHelper.IS_FIELD_START: case LayoutHelper.IS_GROUP_START: throw new UnsupportedOperationException("field and group starts not allowed in begin or end layout"); case LayoutHelper.IS_FIELD_END: case LayoutHelper.IS_GROUP_END: throw new UnsupportedOperationException("field and group ends not allowed in begin or end layout"); case LayoutHelper.IS_OPTION_FIELD: String field = BibDatabase.getText(text, databaseContext.getDatabase()); if (option != null) { for (LayoutFormatter anOption : option) { field = anOption.format(field); } } // If a post formatter has been set, call it: if (postFormatter != null) { field = postFormatter.format(field); } return field; case LayoutHelper.IS_ENCODING_NAME: return encoding.displayName(); case LayoutHelper.IS_FILENAME: case LayoutHelper.IS_FILEPATH: return databaseContext.getDatabasePath().map(Path::toAbsolutePath).map(Path::toString).orElse(""); default: break; } return ""; } private void doOptionField(String s) { List<String> v = StringUtil.tokenizeToList(s, "\n"); if (v.size() == 1) { text = v.get(0); } else { text = v.get(0).trim(); option = getOptionalLayout(v.get(1)); // See if there was an undefined formatter: for (LayoutFormatter anOption : option) { if (anOption instanceof NotFoundFormatter formatter) { String notFound = formatter.getNotFound(); invalidFormatter.add(notFound); } } } } private LayoutFormatter getLayoutFormatterByName(String name) { return switch (name) { // For backward compatibility case "HTMLToLatexFormatter", "HtmlToLatex" -> new HtmlToLatexFormatter(); // For backward compatibility case "UnicodeToLatexFormatter", "UnicodeToLatex" -> new UnicodeToLatexFormatter(); case "OOPreFormatter" -> new OOPreFormatter(); case "AuthorAbbreviator" -> new AuthorAbbreviator(); case "AuthorAndToSemicolonReplacer" -> new AuthorAndToSemicolonReplacer(); case "AuthorAndsCommaReplacer" -> new AuthorAndsCommaReplacer(); case "AuthorAndsReplacer" -> new AuthorAndsReplacer(); case "AuthorFirstAbbrLastCommas" -> new AuthorFirstAbbrLastCommas(); case "AuthorFirstAbbrLastOxfordCommas" -> new AuthorFirstAbbrLastOxfordCommas(); case "AuthorFirstFirst" -> new AuthorFirstFirst(); case "AuthorFirstFirstCommas" -> new AuthorFirstFirstCommas(); case "AuthorFirstLastCommas" -> new AuthorFirstLastCommas(); case "AuthorFirstLastOxfordCommas" -> new AuthorFirstLastOxfordCommas(); case "AuthorLastFirst" -> new AuthorLastFirst(); case "AuthorLastFirstAbbrCommas" -> new AuthorLastFirstAbbrCommas(); case "AuthorLastFirstAbbreviator" -> new AuthorLastFirstAbbreviator(); case "AuthorLastFirstAbbrOxfordCommas" -> new AuthorLastFirstAbbrOxfordCommas(); case "AuthorLastFirstCommas" -> new AuthorLastFirstCommas(); case "AuthorLastFirstOxfordCommas" -> new AuthorLastFirstOxfordCommas(); case "AuthorLF_FF" -> new AuthorLF_FF(); case "AuthorLF_FFAbbr" -> new AuthorLF_FFAbbr(); case "AuthorNatBib" -> new AuthorNatBib(); case "AuthorOrgSci" -> new AuthorOrgSci(); case "CompositeFormat" -> new CompositeFormat(); case "CreateBibORDFAuthors" -> new CreateBibORDFAuthors(); case "CreateDocBook4Authors" -> new CreateDocBook4Authors(); case "CreateDocBook4Editors" -> new CreateDocBook4Editors(); case "CreateDocBook5Authors" -> new CreateDocBook5Authors(); case "CreateDocBook5Editors" -> new CreateDocBook5Editors(); case "CurrentDate" -> new CurrentDate(); case "DateFormatter" -> new DateFormatter(); case "DOICheck" -> new DOICheck(); case "DOIStrip" -> new DOIStrip(); case "EntryTypeFormatter" -> new EntryTypeFormatter(); case "FirstPage" -> new FirstPage(); case "FormatPagesForHTML" -> new FormatPagesForHTML(); case "FormatPagesForXML" -> new FormatPagesForXML(); case "GetOpenOfficeType" -> new GetOpenOfficeType(); case "HTMLChars" -> new HTMLChars(); case "HTMLParagraphs" -> new HTMLParagraphs(); case "Iso690FormatDate" -> new Iso690FormatDate(); case "Iso690NamesAuthors" -> new Iso690NamesAuthors(); case "JournalAbbreviator" -> new JournalAbbreviator(abbreviationRepository); case "LastPage" -> new LastPage(); // For backward compatibility case "FormatChars", "LatexToUnicode" -> new LatexToUnicodeFormatter(); case "NameFormatter" -> new NameFormatter(); case "NoSpaceBetweenAbbreviations" -> new NoSpaceBetweenAbbreviations(); case "Ordinal" -> new Ordinal(); case "RemoveBrackets" -> new RemoveBrackets(); case "RemoveBracketsAddComma" -> new RemoveBracketsAddComma(); case "RemoveLatexCommands" -> new RemoveLatexCommandsFormatter(); case "RemoveTilde" -> new RemoveTilde(); case "RemoveWhitespace" -> new RemoveWhitespace(); case "RisKeywords" -> new RisKeywords(); case "RisMonth" -> new RisMonth(); case "RTFChars" -> new RTFChars(); case "ToLowerCase" -> new ToLowerCase(); case "ToUpperCase" -> new ToUpperCase(); case "XMLChars" -> new XMLChars(); case "Default" -> new Default(); case "FileLink" -> new FileLink(fileDirForDatabase, preferences.getMainFileDirectory()); case "Number" -> new Number(); case "RisAuthors" -> new RisAuthors(); case "Authors" -> new Authors(); case "IfPlural" -> new IfPlural(); case "Replace" -> new Replace(); case "WrapContent" -> new WrapContent(); case "WrapFileLinks" -> new WrapFileLinks(fileDirForDatabase, preferences.getMainFileDirectory()); case "Markdown" -> new MarkdownFormatter(); case "CSLType" -> new CSLType(); case "ShortMonth" -> new ShortMonthFormatter(); case "ReplaceWithEscapedDoubleQuotes" -> new ReplaceWithEscapedDoubleQuotes(); default -> null; }; } /** * Return an array of LayoutFormatters found in the given formatterName string (in order of appearance). */ private List<LayoutFormatter> getOptionalLayout(String formatterName) { List<List<String>> formatterStrings = parseMethodsCalls(formatterName); List<LayoutFormatter> results = new ArrayList<>(formatterStrings.size()); Map<String, String> userNameFormatter = NameFormatter.getNameFormatters(preferences.getNameFormatterPreferences()); for (List<String> strings : formatterStrings) { String nameFormatterName = strings.get(0).trim(); // Check if this is a name formatter defined by this export filter: Optional<String> contents = preferences.getCustomExportNameFormatter(nameFormatterName); if (contents.isPresent()) { NameFormatter nf = new NameFormatter(); nf.setParameter(contents.get()); results.add(nf); continue; } // Try to load from formatters in formatter folder LayoutFormatter formatter = getLayoutFormatterByName(nameFormatterName); if (formatter != null) { // If this formatter accepts an argument, check if we have one, and set it if so if ((formatter instanceof ParamLayoutFormatter layoutFormatter) && (strings.size() >= 2)) { layoutFormatter.setArgument(strings.get(1)); } results.add(formatter); continue; } // Then check whether this is a user defined formatter String formatterParameter = userNameFormatter.get(nameFormatterName); if (formatterParameter != null) { NameFormatter nf = new NameFormatter(); nf.setParameter(formatterParameter); results.add(nf); continue; } results.add(new NotFoundFormatter(nameFormatterName)); } return results; } public List<String> getInvalidFormatters() { return invalidFormatter; } public static List<List<String>> parseMethodsCalls(String calls) { List<List<String>> result = new ArrayList<>(); char[] c = calls.toCharArray(); int i = 0; while (i < c.length) { int start = i; if (Character.isJavaIdentifierStart(c[i])) { i++; while ((i < c.length) && (Character.isJavaIdentifierPart(c[i]) || (c[i] == '.'))) { i++; } if ((i < c.length) && (c[i] == '(')) { String method = calls.substring(start, i); // Skip the brace i++; int bracelevel = 0; if (i < c.length) { if (c[i] == '"') { // Parameter is in format "xxx" // Skip " i++; int startParam = i; i++; boolean escaped = false; while (((i + 1) < c.length) && !(!escaped && (c[i] == '"') && (c[i + 1] == ')') && (bracelevel == 0))) { if (c[i] == '\\') { escaped = !escaped; } else if (c[i] == '(') { bracelevel++; } else if (c[i] == ')') { bracelevel--; } else { escaped = false; } i++; } String param = calls.substring(startParam, i); result.add(Arrays.asList(method, param)); } else { // Parameter is in format xxx int startParam = i; while ((i < c.length) && (!((c[i] == ')') && (bracelevel == 0)))) { if (c[i] == '(') { bracelevel++; } else if (c[i] == ')') { bracelevel--; } i++; } String param = calls.substring(startParam, i); result.add(Arrays.asList(method, param)); } } else { // Incorrectly terminated open brace result.add(Collections.singletonList(method)); } } else { String method = calls.substring(start, i); result.add(Collections.singletonList(method)); } } i++; } return result; } public String getText() { return text; } }
27,719
43.423077
139
java
null
jabref-main/src/main/java/org/jabref/logic/layout/LayoutFormatter.java
package org.jabref.logic.layout; /** * The LayoutFormatter is used for a Filter design-pattern. * <p> * Implementing classes have to accept a String and returned a formatted version of it. * <p> * Example: * <p> * "John von Neumann" => "von Neumann, John" */ @FunctionalInterface public interface LayoutFormatter { /** * Failure Mode: * <p> * Formatters should be robust in the sense that they always return some relevant string. * <p> * If the formatter can detect an invalid input it should return the original string otherwise it may simply return * a wrong output. * * @param fieldText The text to layout. * @return The layouted text. */ String format(String fieldText); }
745
25.642857
119
java
null
jabref-main/src/main/java/org/jabref/logic/layout/LayoutFormatterBasedFormatter.java
package org.jabref.logic.layout; import org.jabref.logic.cleanup.Formatter; /** * When having to use a LayoutFormatter as Formatter, this class is helpful. One usecase is {@link org.jabref.logic.cleanup.FieldFormatterCleanup} */ public class LayoutFormatterBasedFormatter extends Formatter { private final LayoutFormatter layoutFormatter; public LayoutFormatterBasedFormatter(LayoutFormatter layoutFormatter) { this.layoutFormatter = layoutFormatter; } @Override public String getName() { return layoutFormatter.getClass().getName(); } @Override public String getKey() { return layoutFormatter.getClass().getName(); } @Override public String format(String value) { return layoutFormatter.format(value); } @Override public String getDescription() { return layoutFormatter.getClass().getName(); } @Override public String getExampleInput() { return layoutFormatter.getClass().getName(); } }
1,019
23.878049
146
java
null
jabref-main/src/main/java/org/jabref/logic/layout/LayoutFormatterPreferences.java
package org.jabref.logic.layout; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javafx.beans.property.StringProperty; import org.jabref.logic.layout.format.NameFormatterPreferences; public class LayoutFormatterPreferences { private final NameFormatterPreferences nameFormatterPreferences; private final StringProperty mainFileDirectoryProperty; private final Map<String, String> customExportNameFormatters = new HashMap<>(); public LayoutFormatterPreferences(NameFormatterPreferences nameFormatterPreferences, StringProperty mainFileDirectoryProperty) { this.nameFormatterPreferences = nameFormatterPreferences; this.mainFileDirectoryProperty = mainFileDirectoryProperty; } public NameFormatterPreferences getNameFormatterPreferences() { return nameFormatterPreferences; } public String getMainFileDirectory() { return mainFileDirectoryProperty.get(); } public Optional<String> getCustomExportNameFormatter(String formatterName) { return Optional.ofNullable(customExportNameFormatters.get(formatterName)); } public void clearCustomExportNameFormatters() { customExportNameFormatters.clear(); } public void putCustomExportNameFormatter(String formatterName, String contents) { customExportNameFormatters.put(formatterName, contents); } }
1,437
32.44186
88
java
null
jabref-main/src/main/java/org/jabref/logic/layout/LayoutHelper.java
package org.jabref.logic.layout; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import org.jabref.logic.journals.JournalAbbreviationRepository; /** * Helper class to get a Layout object. * * <pre> * <code> * LayoutHelper helper = new LayoutHelper(...a reader...); * Layout layout = helper.getLayoutFromText(); * </code> * </pre> */ public class LayoutHelper { public static final int IS_LAYOUT_TEXT = 1; public static final int IS_SIMPLE_COMMAND = 2; public static final int IS_FIELD_START = 3; public static final int IS_FIELD_END = 4; public static final int IS_OPTION_FIELD = 5; public static final int IS_GROUP_START = 6; public static final int IS_GROUP_END = 7; public static final int IS_ENCODING_NAME = 8; public static final int IS_FILENAME = 9; public static final int IS_FILEPATH = 10; private static String currentGroup; private final PushbackReader in; private final List<StringInt> parsedEntries = new ArrayList<>(); private final List<Path> fileDirForDatabase; private final LayoutFormatterPreferences preferences; private final JournalAbbreviationRepository abbreviationRepository; private boolean endOfFile; public LayoutHelper(Reader in, List<Path> fileDirForDatabase, LayoutFormatterPreferences preferences, JournalAbbreviationRepository abbreviationRepository) { this.in = new PushbackReader(Objects.requireNonNull(in)); this.preferences = Objects.requireNonNull(preferences); this.abbreviationRepository = abbreviationRepository; this.fileDirForDatabase = fileDirForDatabase; } public LayoutHelper(Reader in, LayoutFormatterPreferences preferences, JournalAbbreviationRepository abbreviationRepository) { this(in, Collections.emptyList(), preferences, abbreviationRepository); } public Layout getLayoutFromText() throws IOException { parse(); for (StringInt parsedEntry : parsedEntries) { if ((parsedEntry.i == LayoutHelper.IS_SIMPLE_COMMAND) || (parsedEntry.i == LayoutHelper.IS_FIELD_START) || (parsedEntry.i == LayoutHelper.IS_FIELD_END) || (parsedEntry.i == LayoutHelper.IS_GROUP_START) || (parsedEntry.i == LayoutHelper.IS_GROUP_END)) { parsedEntry.s = parsedEntry.s.trim().toLowerCase(Locale.ROOT); } } return new Layout(parsedEntries, fileDirForDatabase, preferences, abbreviationRepository); } public static String getCurrentGroup() { return LayoutHelper.currentGroup; } public static void setCurrentGroup(String newGroup) { LayoutHelper.currentGroup = newGroup; } private void doBracketedField(final int field) throws IOException { StringBuilder buffer = null; int currentCharacter; boolean start = false; while (!endOfFile) { currentCharacter = read(); if (currentCharacter == -1) { endOfFile = true; if (buffer != null) { parsedEntries.add(new StringInt(buffer.toString(), field)); } return; } if ((currentCharacter == '{') || (currentCharacter == '}')) { if (currentCharacter == '}') { if (buffer != null) { parsedEntries.add(new StringInt(buffer.toString(), field)); return; } } else { start = true; } } else { if (buffer == null) { buffer = new StringBuilder(100); } if (start && (currentCharacter != '}')) { buffer.append((char) currentCharacter); } } } } private void doBracketedOptionField() throws IOException { StringBuilder buffer = null; int c; boolean start = false; boolean inQuotes = false; boolean doneWithOptions = false; String option = null; String tmp; while (!endOfFile) { c = read(); if (c == -1) { endOfFile = true; if (buffer != null) { if (option == null) { tmp = buffer.toString(); } else { tmp = buffer.toString() + '\n' + option; } parsedEntries.add(new StringInt(tmp, LayoutHelper.IS_OPTION_FIELD)); } return; } if (!inQuotes && ((c == ']') || (c == '[') || (doneWithOptions && ((c == '{') || (c == '}'))))) { if ((c == ']') || (doneWithOptions && (c == '}'))) { // changed section start - arudert // buffer may be null for parameters if ((c == ']') && (buffer != null)) { // changed section end - arudert option = buffer.toString(); buffer = null; start = false; doneWithOptions = true; } else if (c == '}') { // changed section begin - arudert // bracketed option must be followed by an (optionally empty) parameter // if empty, the parameter is set to " " (whitespace to avoid that the tokenizer that // splits the string later on ignores the empty parameter) String parameter = buffer == null ? " " : buffer.toString(); if (option == null) { tmp = parameter; } else { tmp = parameter + '\n' + option; } parsedEntries.add(new StringInt(tmp, LayoutHelper.IS_OPTION_FIELD)); return; } // changed section end - arudert // changed section start - arudert // } // changed section end - arudert } else { start = true; } } else if (c == '"') { inQuotes = !inQuotes; if (buffer == null) { buffer = new StringBuilder(100); } buffer.append('"'); } else { if (buffer == null) { buffer = new StringBuilder(100); } if (start) { // changed section begin - arudert // keep the backslash so we know wether this is a fieldname or an ordinary parameter // if (c != '\\') { buffer.append((char) c); // } // changed section end - arudert } } } } private void parse() throws IOException { skipWhitespace(); int c; StringBuilder buffer = null; boolean escaped = false; while (!endOfFile) { c = read(); if (c == -1) { endOfFile = true; // Check for null, otherwise a Layout that finishes with a curly brace throws a NPE if (buffer != null) { parsedEntries.add(new StringInt(buffer.toString(), LayoutHelper.IS_LAYOUT_TEXT)); } return; } if ((c == '\\') && (peek() != '\\') && !escaped) { if (buffer != null) { parsedEntries.add(new StringInt(buffer.toString(), LayoutHelper.IS_LAYOUT_TEXT)); buffer = null; } parseField(); // To make sure the next character, if it is a backslash, // doesn't get ignored, since "previous" now holds a backslash: escaped = false; } else { if (buffer == null) { buffer = new StringBuilder(100); } if ((c != '\\') || escaped) /* (previous == '\\'))) */ { buffer.append((char) c); } escaped = (c == '\\') && !escaped; } } } private void parseField() throws IOException { int c; StringBuilder buffer = null; String name; while (!endOfFile) { c = read(); if (c == -1) { endOfFile = true; } if (!Character.isLetter((char) c) && (c != '_')) { unread(c); name = buffer == null ? "" : buffer.toString(); if (name.isEmpty()) { StringBuilder lastFive = new StringBuilder(10); if (parsedEntries.isEmpty()) { lastFive.append("unknown"); } else { for (StringInt entry : parsedEntries.subList(Math.max(0, parsedEntries.size() - 6), parsedEntries.size() - 1)) { lastFive.append(entry.s); } } throw new IOException( "Backslash parsing error near \'" + lastFive.toString().replace("\n", " ") + '\''); } if ("begin".equalsIgnoreCase(name)) { // get field name doBracketedField(LayoutHelper.IS_FIELD_START); return; } else if ("begingroup".equalsIgnoreCase(name)) { // get field name doBracketedField(LayoutHelper.IS_GROUP_START); return; } else if ("format".equalsIgnoreCase(name)) { if (c == '[') { // get format parameter // get field name doBracketedOptionField(); return; } else { // get field name doBracketedField(LayoutHelper.IS_OPTION_FIELD); return; } } else if ("filename".equalsIgnoreCase(name)) { // Print the name of the database BIB file. // This is only supported in begin/end layouts, not in // entry layouts. parsedEntries.add(new StringInt(name, LayoutHelper.IS_FILENAME)); return; } else if ("filepath".equalsIgnoreCase(name)) { // Print the full path of the database BIB file. // This is only supported in begin/end layouts, not in // entry layouts. parsedEntries.add(new StringInt(name, LayoutHelper.IS_FILEPATH)); return; } else if ("end".equalsIgnoreCase(name)) { // get field name doBracketedField(LayoutHelper.IS_FIELD_END); return; } else if ("endgroup".equalsIgnoreCase(name)) { // get field name doBracketedField(LayoutHelper.IS_GROUP_END); return; } else if ("encoding".equalsIgnoreCase(name)) { // Print the name of the current encoding used for export. // This is only supported in begin/end layouts, not in // entry layouts. parsedEntries.add(new StringInt(name, LayoutHelper.IS_ENCODING_NAME)); return; } // for all other cases -> simple command parsedEntries.add(new StringInt(name, LayoutHelper.IS_SIMPLE_COMMAND)); return; } else { if (buffer == null) { buffer = new StringBuilder(100); } buffer.append((char) c); } } } private int peek() throws IOException { int c = read(); unread(c); return c; } private int read() throws IOException { return in.read(); } private void skipWhitespace() throws IOException { int c; while (true) { c = read(); if ((c == -1) || (c == 65535)) { endOfFile = true; return; } if (!Character.isWhitespace((char) c)) { unread(c); break; } } } private void unread(int c) throws IOException { in.unread(c); } }
13,248
33.683246
117
java
null
jabref-main/src/main/java/org/jabref/logic/layout/ParamLayoutFormatter.java
package org.jabref.logic.layout; /** * This interface extends LayoutFormatter, adding the capability of taking * and additional parameter. Such a parameter is specified in the layout file * by the following construct: \format[MyFormatter(argument){\field} * If and only if MyFormatter is a class that implements ParamLayoutFormatter, * it will be set up with the argument given in the parenthesis by way of the * method setArgument(String). If no argument is given, the formatter will be * invoked without the setArgument() method being called first. */ public interface ParamLayoutFormatter extends LayoutFormatter { /** * Method for setting the argument of this formatter. * * @param arg A String argument. */ void setArgument(String arg); }
782
36.285714
78
java
null
jabref-main/src/main/java/org/jabref/logic/layout/StringInt.java
package org.jabref.logic.layout; /** * String and integer value. */ public class StringInt implements java.io.Serializable { /** * Description of the Field */ public String s; /** * Description of the Field */ public final int i; /** * Constructor for the StringInt object */ public StringInt(final String s, final int i) { this.s = s; this.i = i; } }
432
15.653846
56
java
null
jabref-main/src/main/java/org/jabref/logic/layout/TextBasedPreviewLayout.java
package org.jabref.logic.layout; import java.io.IOException; import java.io.StringReader; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; import org.jabref.logic.preview.PreviewLayout; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements the preview based JabRef's <a href="https://docs.jabref.org/import-export/export/customexports">Custom export filters</a>. */ public class TextBasedPreviewLayout implements PreviewLayout { public static final String NAME = "PREVIEW"; private static final Logger LOGGER = LoggerFactory.getLogger(TextBasedPreviewLayout.class); private Layout layout; private String text; private LayoutFormatterPreferences layoutFormatterPreferences; private JournalAbbreviationRepository abbreviationRepository; public TextBasedPreviewLayout(String text, LayoutFormatterPreferences layoutFormatterPreferences, JournalAbbreviationRepository abbreviationRepository) { this.layoutFormatterPreferences = layoutFormatterPreferences; this.abbreviationRepository = abbreviationRepository; setText(text); } public TextBasedPreviewLayout(Layout layout) { this.layout = layout; this.text = layout.getText(); } public void setText(String text) { this.text = text; StringReader sr = new StringReader(text.replace("__NEWLINE__", "\n")); try { layout = new LayoutHelper(sr, layoutFormatterPreferences, abbreviationRepository).getLayoutFromText(); } catch (IOException e) { LOGGER.error("Could not generate layout", e); } } @Override public String generatePreview(BibEntry entry, BibDatabaseContext databaseContext) { if (layout != null) { return layout.doLayout(entry, databaseContext.getDatabase()); } else { return ""; } } public String getText() { return text; } @Override public String getName() { return NAME; } @Override public String getDisplayName() { return Localization.lang("Customized preview style"); } }
2,280
31.126761
157
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorAbbreviator.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * Duplicate of AuthorLastFirstAbbreviator. * * @see AuthorLastFirstAbbreviator */ public class AuthorAbbreviator implements LayoutFormatter { /* * (non-Javadoc) * * @see org.jabref.export.layout.LayoutFormatter#format(java.lang.String) */ @Override public String format(String fieldText) { AuthorList list = AuthorList.parse(fieldText); return list.getAsLastFirstNamesWithAnd(true); } }
580
23.208333
77
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacer.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; public class AuthorAndToSemicolonReplacer implements LayoutFormatter { @Override public String format(String fieldText) { return fieldText.replaceAll(" and ", "; "); } }
281
22.5
70
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacer.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; /** * Replaces and's for & (in case of two authors) and , (in case of more than two authors). */ public class AuthorAndsCommaReplacer implements LayoutFormatter { @Override public String format(String fieldText) { String[] authors = fieldText.split(" and "); String s; switch (authors.length) { case 1: // Does nothing s = authors[0]; break; case 2: s = authors[0] + " & " + authors[1]; break; default: int i; int x = authors.length; StringBuilder sb = new StringBuilder(); for (i = 0; i < (x - 2); i++) { sb.append(authors[i]).append(", "); } sb.append(authors[i]).append(" & ").append(authors[i + 1]); s = sb.toString(); break; } return s; } }
1,058
26.153846
90
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorAndsReplacer.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; /** * Replaces and's for & (in case of two authors) and ; (in case * of more than two authors). */ public class AuthorAndsReplacer implements LayoutFormatter { /* (non-Javadoc) * @see org.jabref.export.layout.LayoutFormatter#format(java.lang.String) */ @Override public String format(String fieldText) { if (fieldText == null) { return null; } String[] authors = fieldText.split(" and "); // CHECKSTYLE:OFF String s = switch (authors.length) { case 1 -> authors[0]; // just no action case 2 -> authors[0] + " & " + authors[1]; default -> { int i; int x = authors.length; StringBuilder sb = new StringBuilder(); for (i = 0; i < (x - 2); i++) { sb.append(authors[i]).append("; "); } sb.append(authors[i]).append(" & ").append(authors[i + 1]); yield sb.toString(); } }; // CHECKSTYLE:ON return s; } }
1,175
28.4
77
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>First names will be abbreviated.</li> * <li>Individual authors separated by comma.</li> * <li>There is no command in front the and of a list of three or more authors.</li> * </ul> */ public class AuthorFirstAbbrLastCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, true, false); } }
617
28.428571
84
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>First names will be abbreviated.</li> * <li>Individual authors separated by comma.</li> * <li>The and of a list of three or more authors is preceeded by a comma * (Oxford comma)</li> * </ul> */ public class AuthorFirstAbbrLastOxfordCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, true, true); } }
634
27.863636
79
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstFirst.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * Author First First prints .... */ public class AuthorFirstFirst implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirst(fieldText); } }
363
21.75
61
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstFirstCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given in order: first von last, jr.</li> * <li>First names will NOT be abbreviated.</li> * <li>Individual authors are separated by commas.</li> * <li>There is no comma before the 'and' at the end of a list of three or more authors</li> * </ul> */ public class AuthorFirstFirstCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, false, false); } }
628
28.952381
92
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstLastCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>First names will not be abbreviated.</li> * <li>Individual authors separated by comma.</li> * <li>There is no comma before the and of a list of three or more authors.</li> * </ul> */ public class AuthorFirstLastCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, false, false); } }
614
28.285714
81
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>Individual authors separated by comma.</li> * <li>The and of a list of three or more authors is preceeded by a comma * (Oxford comma)</li> * </ul> */ public class AuthorFirstLastOxfordCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, false, true); } }
586
26.952381
80
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLF_FF.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; public class AuthorLF_FF implements LayoutFormatter { @Override public String format(String fieldText) { AuthorList al = AuthorList.parse(fieldText); return al.getAsLastFirstFirstLastNamesWithAnd(false); } }
370
23.733333
61
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLF_FFAbbr.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; public class AuthorLF_FFAbbr implements LayoutFormatter { @Override public String format(String fieldText) { AuthorList al = AuthorList.parse(fieldText); return al.getAsLastFirstFirstLastNamesWithAnd(true); } }
373
23.933333
60
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirst.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; public class AuthorLastFirst implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorLastNameFirst(fieldText); } }
319
23.615385
60
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given in order: von last, jr, first.</li> * <li>First names will be abbreviated.</li> * <li>Individual authors are separated by commas.</li> * <li>There is no comma before the 'and' at the end of a list of three or more authors</li> * </ul> */ public class AuthorLastFirstAbbrCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorLastNameFirstCommas(fieldText, true, false); } }
626
28.857143
92
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given in order: von last, jr, first.</li> * <li>First names will be abbreviated.</li> * <li>Individual authors are separated by commas.</li> * <li>The 'and' of a list of three or more authors is preceeded by a comma * (Oxford comma)</li> * </ul> */ public class AuthorLastFirstAbbrOxfordCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorLastNameFirstCommas(fieldText, true, true); } }
637
28
78
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviator.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; /** * Uses as input the fields (author or editor) in the LastFirst format. * <p> * This formater enables to abbreviate the authors name in the following way: * <p> * Ex: Someone, Van Something will be abbreviated as Someone, V.S. */ public class AuthorLastFirstAbbreviator implements LayoutFormatter { /** * @see org.jabref.logic.layout.LayoutFormatter#format(java.lang.String) */ @Override public String format(String fieldText) { // This formatter is a duplicate of AuthorAbbreviator, so we simply call that one. return new AuthorAbbreviator().format(fieldText); } }
708
29.826087
90
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirstCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given in order: von last, jr, first.</li> * <li>First names will NOT be abbreviated.</li> * <li>Individual authors are separated by commas.</li> * <li>There is no comma before the 'and' at the end of a list of three or more authors</li> * </ul> */ public class AuthorLastFirstCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorLastNameFirstCommas(fieldText, false, false); } }
627
28.904762
92
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommas.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given in order: von last, jr, first.</li> * <li>First names will NOT be abbreviated.</li> * <li>Individual authors are separated by commas.</li> * <li>The 'and' of a list of three or more authors is preceded by a comma * (Oxford comma) * </ul> */ public class AuthorLastFirstOxfordCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorLastNameFirstCommas(fieldText, false, true); } }
632
27.772727
79
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorNatBib.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * Natbib style: Last names only. Two authors are separated by "and", three or more authors are given as "Smith et al." */ public class AuthorNatBib implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorNatbib(fieldText); } }
437
26.375
119
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/AuthorOrgSci.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; /** * Will return the Authors to match the OrgSci format: * * <ul> * <li>That is the first author is LastFirst, but all others are FirstLast.</li> * <li>First names are abbreviated</li> * <li>Spaces between abbreviated first names are NOT removed. Use * NoSpaceBetweenAbbreviations to achieve this.</li> * </ul> * <p> * See the testcase for examples. * </p> * <p> * Idea from: http://stuermer.ch/blog/bibliography-reference-management-with-jabref.html * </p> */ public class AuthorOrgSci implements LayoutFormatter { @Override public String format(String fieldText) { AuthorList a = AuthorList.parse(fieldText); if (a.isEmpty()) { return fieldText; } Author first = a.getAuthor(0); StringBuilder sb = new StringBuilder(); sb.append(first.getLastFirst(true)); for (int i = 1; i < a.getNumberOfAuthors(); i++) { sb.append(", ").append(a.getAuthor(i).getFirstLast(true)); } return sb.toString(); } }
1,191
28.8
88
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/Authors.java
package org.jabref.logic.layout.format; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import org.jabref.logic.layout.AbstractParamLayoutFormatter; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; /** * Versatile author name formatter that takes arguments to control the formatting style. */ public class Authors extends AbstractParamLayoutFormatter { /* AuthorSort = [FirstFirst | LastFirst | LastFirstFirstFirst] AuthorAbbr = [FullName | Initials | FirstInitial | MiddleInitial | InitialsNoSpace | LastName] AuthorSep = [Comma | And | Colon | Semicolon | Sep=<string>] AuthorLastSep = [And | Comma | Colon | Semicolon | Amp | Oxford | LastSep=<string>] AuthorPunc = [FullPunc | NoPunc | NoComma | NoPeriod] AuthorNumber = [inf | <number>] AuthorNumberEtAl = [ {1} | <number>] EtAlString = [ et al. | EtAl=<string>] */ private static final List<String> AUTHOR_ORDER = new ArrayList<>(); private static final List<String> AUTHOR_ABRV = new ArrayList<>(); private static final List<String> AUTHOR_PUNC = new ArrayList<>(); private static final List<String> SEPARATORS = new ArrayList<>(); private static final List<String> LAST_SEPARATORS = new ArrayList<>(); private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+"); static { Authors.AUTHOR_ORDER.add("firstfirst"); Authors.AUTHOR_ORDER.add("lastfirst"); Authors.AUTHOR_ORDER.add("lastfirstfirstfirst"); Authors.AUTHOR_ABRV.add("fullname"); Authors.AUTHOR_ABRV.add("initials"); Authors.AUTHOR_ABRV.add("firstinitial"); Authors.AUTHOR_ABRV.add("middleinitial"); Authors.AUTHOR_ABRV.add("lastname"); Authors.AUTHOR_ABRV.add("initialsnospace"); Authors.AUTHOR_PUNC.add("fullpunc"); Authors.AUTHOR_PUNC.add("nopunc"); Authors.AUTHOR_PUNC.add("nocomma"); Authors.AUTHOR_PUNC.add("noperiod"); Authors.SEPARATORS.add("comma"); Authors.SEPARATORS.add("and"); Authors.SEPARATORS.add("colon"); Authors.SEPARATORS.add("semicolon"); Authors.SEPARATORS.add("sep"); Authors.LAST_SEPARATORS.add("and"); Authors.LAST_SEPARATORS.add("colon"); Authors.LAST_SEPARATORS.add("semicolon"); Authors.LAST_SEPARATORS.add("amp"); Authors.LAST_SEPARATORS.add("oxford"); Authors.LAST_SEPARATORS.add("lastsep"); } private static final int FIRST_FIRST = 0; private static final int LAST_FIRST = 1; private static final int LF_FF = 2; private static final String COMMA = ", "; private static final String AMP = " & "; private static final String COLON = ": "; private static final String SEMICOLON = "; "; private static final String AND = " and "; private static final String OXFORD = ", and "; private int flMode; private boolean abbreviate = true; private boolean firstInitialOnly; private boolean middleInitial; private boolean lastNameOnly; private boolean abbrDots = true; private boolean abbrSpaces = true; private boolean setSep; private boolean setMaxAuthors; private int maxAuthors = -1; private int authorNumberEtAl = 1; private String lastFirstSeparator = ", "; private String separator = Authors.COMMA; private String lastSeparator = Authors.AND; private String etAlString = " et al."; @Override public void setArgument(String arg) { List<String> parts = AbstractParamLayoutFormatter.parseArgument(arg); for (String part : parts) { int index = part.indexOf('='); if (index > 0) { String key = part.substring(0, index); String value = part.substring(index + 1); handleArgument(key, value); } else { handleArgument(part, ""); } } } private void handleArgument(String key, String value) { if (Authors.AUTHOR_ORDER.contains(key.trim().toLowerCase(Locale.ROOT))) { if (comp(key, "FirstFirst")) { flMode = Authors.FIRST_FIRST; } else if (comp(key, "LastFirst")) { flMode = Authors.LAST_FIRST; } else if (comp(key, "LastFirstFirstFirst")) { flMode = Authors.LF_FF; } } else if (Authors.AUTHOR_ABRV.contains(key.trim().toLowerCase(Locale.ROOT))) { if (comp(key, "FullName")) { abbreviate = false; } else if (comp(key, "Initials")) { abbreviate = true; firstInitialOnly = false; } else if (comp(key, "FirstInitial")) { abbreviate = true; firstInitialOnly = true; } else if (comp(key, "MiddleInitial")) { abbreviate = true; middleInitial = true; } else if (comp(key, "LastName")) { lastNameOnly = true; } else if (comp(key, "InitialsNoSpace")) { abbreviate = true; abbrSpaces = false; } } else if (Authors.AUTHOR_PUNC.contains(key.trim().toLowerCase(Locale.ROOT))) { if (comp(key, "FullPunc")) { abbrDots = true; lastFirstSeparator = ", "; } else if (comp(key, "NoPunc")) { abbrDots = false; lastFirstSeparator = " "; } else if (comp(key, "NoComma")) { abbrDots = true; lastFirstSeparator = " "; } else if (comp(key, "NoPeriod")) { abbrDots = false; lastFirstSeparator = ", "; } } else if (Authors.SEPARATORS.contains(key.trim().toLowerCase(Locale.ROOT)) || Authors.LAST_SEPARATORS.contains(key.trim().toLowerCase(Locale.ROOT))) { // AuthorSep = [Comma | And | Colon | Semicolon | sep=<string>] // AuthorLastSep = [And | Comma | Colon | Semicolon | Amp | Oxford | lastsep=<string>] if (comp(key, "Comma")) { if (setSep) { lastSeparator = Authors.COMMA; } else { separator = Authors.COMMA; setSep = true; } } else if (comp(key, "And")) { if (setSep) { lastSeparator = Authors.AND; } else { separator = Authors.AND; setSep = true; } } else if (comp(key, "Colon")) { if (setSep) { lastSeparator = Authors.COLON; } else { separator = Authors.COLON; setSep = true; } } else if (comp(key, "Semicolon")) { if (setSep) { lastSeparator = Authors.SEMICOLON; } else { separator = Authors.SEMICOLON; setSep = true; } } else if (comp(key, "Oxford")) { lastSeparator = Authors.OXFORD; } else if (comp(key, "Amp")) { lastSeparator = Authors.AMP; } else if (comp(key, "Sep") && !value.isEmpty()) { separator = value; setSep = true; } else if (comp(key, "LastSep") && !value.isEmpty()) { lastSeparator = value; } } else if ("etal".equalsIgnoreCase(key.trim())) { etAlString = value; } else if (Authors.NUMBER_PATTERN.matcher(key.trim()).matches()) { // Just a number: int num = Integer.parseInt(key.trim()); if (setMaxAuthors) { authorNumberEtAl = num; } else { maxAuthors = num; setMaxAuthors = true; } } } /** * Check for case-insensitive equality between two strings after removing * white space at the beginning and end of the first string. * * @param one The first string - whitespace is trimmed * @param two The second string * @return true if the strings are deemed equal */ private static boolean comp(String one, String two) { return one.trim().equalsIgnoreCase(two); } @Override public String format(String fieldText) { if (fieldText == null) { return ""; } StringBuilder sb = new StringBuilder(); AuthorList al = AuthorList.parse(fieldText); if ((maxAuthors < 0) || (al.getNumberOfAuthors() <= maxAuthors)) { for (int i = 0; i < al.getNumberOfAuthors(); i++) { Author a = al.getAuthor(i); addSingleName(sb, a, (flMode == Authors.FIRST_FIRST) || ((flMode == Authors.LF_FF) && (i > 0))); if (i < (al.getNumberOfAuthors() - 2)) { sb.append(separator); } else if (i < (al.getNumberOfAuthors() - 1)) { sb.append(lastSeparator); } } } else { for (int i = 0; i < Math.min(al.getNumberOfAuthors() - 1, authorNumberEtAl); i++) { if (i > 0) { sb.append(separator); } addSingleName(sb, al.getAuthor(i), flMode == Authors.FIRST_FIRST); } sb.append(etAlString); } return sb.toString(); } private void addSingleName(StringBuilder sb, Author a, boolean firstFirst) { StringBuilder lastNameSB = new StringBuilder(); a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> lastNameSB.append(von).append(' ')); a.getLast().ifPresent(lastNameSB::append); String jrSeparator = " "; a.getJr().filter(jr -> !jr.isEmpty()).ifPresent(jr -> lastNameSB.append(jrSeparator).append(jr)); String firstNameResult = ""; if (a.getFirst().isPresent()) { if (abbreviate) { firstNameResult = a.getFirstAbbr().orElse(""); if (firstInitialOnly && (firstNameResult.length() > 2)) { firstNameResult = firstNameResult.substring(0, 2); } else if (middleInitial) { String abbr = firstNameResult; firstNameResult = a.getFirst().get(); int index = firstNameResult.indexOf(' '); if (index >= 0) { firstNameResult = firstNameResult.substring(0, index + 1); if (abbr.length() > 3) { firstNameResult = firstNameResult + abbr.substring(3); } } } if (!abbrDots) { firstNameResult = firstNameResult.replace(".", ""); } if (!abbrSpaces) { firstNameResult = firstNameResult.replace(" ", ""); } } else { firstNameResult = a.getFirst().get(); } } if (lastNameOnly || (firstNameResult.isEmpty())) { sb.append(lastNameSB); } else if (firstFirst) { String firstFirstSeparator = " "; sb.append(firstNameResult).append(firstFirstSeparator); sb.append(lastNameSB); } else { sb.append(lastNameSB).append(lastFirstSeparator).append(firstNameResult); } } }
11,611
37.450331
159
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CSLType.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.types.StandardEntryType; public class CSLType implements LayoutFormatter { @Override public String format(String value) { return switch (StandardEntryType.valueOf(value)) { case Article -> "article"; case Book -> "book"; case Conference -> "paper-conference"; case Report, TechReport -> "report"; case Thesis, MastersThesis, PhdThesis -> "thesis"; case WWW, Online -> "webpage"; default -> "no-type"; }; } }
642
28.227273
62
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CompositeFormat.java
package org.jabref.logic.layout.format; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.jabref.logic.layout.LayoutFormatter; /** * A layout formatter that is the composite of the given Formatters executed in order. */ public class CompositeFormat implements LayoutFormatter { private final List<LayoutFormatter> formatters; /** * If called with this constructor, this formatter does nothing. */ public CompositeFormat() { formatters = Collections.emptyList(); } public CompositeFormat(LayoutFormatter first, LayoutFormatter second) { formatters = Arrays.asList(first, second); } public CompositeFormat(LayoutFormatter[] formatters) { this.formatters = Arrays.asList(formatters); } @Override public String format(String fieldText) { String result = fieldText; for (LayoutFormatter formatter : formatters) { result = formatter.format(result); } return result; } }
1,035
24.9
86
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CreateBibORDFAuthors.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; public class CreateBibORDFAuthors implements LayoutFormatter { @Override public String format(String fieldText) { // Yeah, the format is quite verbose... sorry about that :) // <bibo:contribution> // <bibo:Contribution> // <bibo:role rdf:resource="http://purl.org/ontology/bibo/roles/author" /> // <bibo:contributor><foaf:Person foaf:name="Ola Spjuth"/></bibo:contributor> // <bibo:position>1</bibo:position> // </bibo:Contribution> // </bibo:contribution> StringBuilder sb = new StringBuilder(100); if (!fieldText.contains(" and ")) { singleAuthor(sb, fieldText, 1); } else { String[] names = fieldText.split(" and "); for (int i = 0; i < names.length; i++) { singleAuthor(sb, names[i], i + 1); if (i < (names.length - 1)) { sb.append('\n'); } } } return sb.toString(); } private static void singleAuthor(StringBuilder sb, String author, int position) { sb.append("<bibo:contribution>\n"); sb.append(" <bibo:Contribution>\n"); sb.append(" <bibo:role rdf:resource=\"http://purl.org/ontology/bibo/roles/author\" />\n"); sb.append(" <bibo:contributor><foaf:Person foaf:name=\"").append(author).append("\"/></bibo:contributor>\n"); sb.append(" <bibo:position>").append(position).append("</bibo:position>\n"); sb.append(" </bibo:Contribution>\n"); sb.append("</bibo:contribution>\n"); } }
1,739
36.826087
120
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CreateDocBook4Authors.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.field.StandardField; /** * Create DocBook authors formatter. */ public class CreateDocBook4Authors implements LayoutFormatter { @Override public String format(String fieldText) { StringBuilder sb = new StringBuilder(100); AuthorList al = AuthorList.parse(fieldText); DocBookAuthorFormatter formatter = new DocBookAuthorFormatter(); formatter.addBody(sb, al, StandardField.AUTHOR.getName(), DocBookVersion.DOCBOOK_4); return sb.toString(); } }
660
30.47619
92
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CreateDocBook4Editors.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.field.StandardField; /** * Create DocBook4 editors formatter. */ public class CreateDocBook4Editors implements LayoutFormatter { @Override public String format(String fieldText) { // <editor><firstname>L.</firstname><surname>Xue</surname></editor> StringBuilder sb = new StringBuilder(100); AuthorList al = AuthorList.parse(fieldText); DocBookAuthorFormatter formatter = new DocBookAuthorFormatter(); formatter.addBody(sb, al, StandardField.EDITOR.getName(), DocBookVersion.DOCBOOK_4); return sb.toString(); } }
737
32.545455
92
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CreateDocBook5Authors.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.field.StandardField; /** * Create DocBook5 authors formatter */ public class CreateDocBook5Authors implements LayoutFormatter { @Override public String format(String fieldText) { StringBuilder sb = new StringBuilder(100); AuthorList al = AuthorList.parse(fieldText); DocBookAuthorFormatter authorFormatter = new DocBookAuthorFormatter(); authorFormatter.addBody(sb, al, StandardField.AUTHOR.getName(), DocBookVersion.DOCBOOK_5); return sb.toString(); } }
673
29.636364
98
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CreateDocBook5Editors.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.field.StandardField; /** * Create DocBook editors formatter. */ public class CreateDocBook5Editors implements LayoutFormatter { @Override public String format(String fieldText) { // <editor><personname><firstname>L.</firstname><surname>Xue</surname></personname></editor> StringBuilder sb = new StringBuilder(100); AuthorList al = AuthorList.parse(fieldText); DocBookAuthorFormatter formatter = new DocBookAuthorFormatter(); formatter.addBody(sb, al, StandardField.EDITOR.getName(), DocBookVersion.DOCBOOK_5); return sb.toString(); } }
761
33.636364
100
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/CurrentDate.java
package org.jabref.logic.layout.format; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.jabref.logic.layout.LayoutFormatter; /** * Inserts the current date (the time a database is being exported). * * <p>If a fieldText is given, it must be a valid {@link DateTimeFormatter} pattern. * If none is given, the format pattern will be <code>yyyy-MM-dd hh:mm:ss z</code>. * This follows ISO-8601. Reason: <a href="https://xkcd.com/1179/">https://xkcd.com/1179/</a>.</p> */ public class CurrentDate implements LayoutFormatter { // default time stamp follows ISO-8601. Reason: https://xkcd.com/1179/ private static final String DEFAULT_FORMAT = "yyyy-MM-dd hh:mm:ss z"; @Override public String format(String fieldText) { String format = CurrentDate.DEFAULT_FORMAT; if ((fieldText != null) && !fieldText.trim().isEmpty()) { format = fieldText; } return ZonedDateTime.now().format(DateTimeFormatter.ofPattern(format)); } }
1,026
34.413793
98
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/DOICheck.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.identifier.DOI; /** * Used to fix [ 1588028 ] export HTML table DOI URL. * <p> * Will prepend "http://doi.org/" if only DOI and not an URL is given. */ public class DOICheck implements LayoutFormatter { @Override public String format(String fieldText) { if (fieldText == null) { return null; } String result = fieldText; if (result.startsWith("/")) { result = result.substring(1); } return DOI.parse(result).map(DOI::getURIAsASCIIString).orElse(result); } }
666
26.791667
78
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/DOIStrip.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.identifier.DOI; /** * Will strip any prefixes from the Doi field, in order to output only the Doi number */ public class DOIStrip implements LayoutFormatter { @Override public String format(String fieldText) { if (fieldText == null) { return null; } return DOI.parse(fieldText).map(DOI::getDOI).orElse(fieldText); } }
489
24.789474
85
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/DateFormatter.java
package org.jabref.logic.layout.format; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import org.jabref.logic.layout.ParamLayoutFormatter; public class DateFormatter implements ParamLayoutFormatter { private String formatString = "yyyy-MM-dd"; // Use ISO-format as default @Override public String format(String fieldText) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatString); LocalDate date = LocalDate.parse(fieldText, DateTimeFormatter.ISO_LOCAL_DATE); return date.format(formatter); } @Override public void setArgument(String arg) { formatString = arg; } }
672
27.041667
86
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/Default.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.ParamLayoutFormatter; /** * Layout formatter that puts in a default value (given as argument) if the field is empty. * Empty means null or an empty string. */ public class Default implements ParamLayoutFormatter { private String defValue = ""; @Override public void setArgument(String arg) { this.defValue = arg; } @Override public String format(String fieldText) { return ((fieldText == null) || fieldText.isEmpty()) ? defValue : fieldText; } }
569
23.782609
91
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/DocBookAuthorFormatter.java
package org.jabref.logic.layout.format; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; /** * DocBook author formatter for both version 4 and 5 */ public class DocBookAuthorFormatter { private static final XMLChars XML_CHARS = new XMLChars(); /** * @param tagName Editor or author field/tag */ public void addBody(StringBuilder sb, AuthorList al, String tagName, DocBookVersion version) { for (int i = 0; i < al.getNumberOfAuthors(); i++) { sb.append('<').append(tagName).append('>'); if (version == DocBookVersion.DOCBOOK_5) { sb.append("<personname>"); } Author a = al.getAuthor(i); a.getFirst().filter(first -> !first.isEmpty()).ifPresent(first -> sb.append("<firstname>") .append(XML_CHARS.format(first)).append("</firstname>")); a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append("<othername>") .append(XML_CHARS.format(von)).append("</othername>")); a.getLast().filter(last -> !last.isEmpty()).ifPresent(last -> { sb.append("<surname>").append(XML_CHARS.format(last)); a.getJr().filter(jr -> !jr.isEmpty()) .ifPresent(jr -> sb.append(' ').append(XML_CHARS.format(jr))); sb.append("</surname>"); if (version == DocBookVersion.DOCBOOK_5) { sb.append("</personname>"); } }); if (i < (al.getNumberOfAuthors() - 1)) { sb.append("</").append(tagName).append(">\n "); } else { sb.append("</").append(tagName).append('>'); } } } }
1,882
40.844444
137
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/DocBookVersion.java
package org.jabref.logic.layout.format; public enum DocBookVersion { DOCBOOK_4, DOCBOOK_5 }
101
13.571429
39
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/EntryTypeFormatter.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.types.EntryTypeFactory; /* * Camel casing of entry type string, unknown entry types gets a leading capital * * Example (known): inbook -> InBook * Example (unknown): banana -> Banana */ public class EntryTypeFormatter implements LayoutFormatter { /** * Input: entry type as a string */ @Override public String format(String entryType) { return EntryTypeFactory.parse(entryType).getDisplayName(); } }
560
24.5
80
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/FileLink.java
package org.jabref.logic.layout.format; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.layout.ParamLayoutFormatter; import org.jabref.model.entry.LinkedFile; /** * Export formatter that handles the file link list of JabRef 2.3 and later, by * selecting the first file link, if any, specified by the field. */ public class FileLink implements ParamLayoutFormatter { private final List<Path> fileDirectories; private final String mainFileDirectory; private String fileType; public FileLink(List<Path> fileDirectories, String mainFileDirectory) { this.fileDirectories = fileDirectories; this.mainFileDirectory = mainFileDirectory; } @Override public String format(String field) { if (field == null) { return ""; } List<LinkedFile> fileList = FileFieldParser.parse(field); LinkedFile link = null; if (fileType == null) { // No file type specified. Simply take the first link. if (!(fileList.isEmpty())) { link = fileList.get(0); } } else { // A file type is specified: for (LinkedFile flEntry : fileList) { if (flEntry.getFileType().equalsIgnoreCase(fileType)) { link = flEntry; break; } } } if (link == null) { return ""; } List<Path> dirs; if (fileDirectories.isEmpty()) { dirs = Collections.singletonList(Path.of(mainFileDirectory)); } else { dirs = fileDirectories; } return link.findIn(dirs) .map(path -> path.normalize().toString()) .orElse(link.getLink()); } /** * This method is called if the layout file specifies an argument for this * formatter. We use it as an indicator of which file type we should look for. * * @param arg The file type. */ @Override public void setArgument(String arg) { fileType = arg; } }
2,201
27.597403
82
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/FirstPage.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; /** * Formatter that returns the first page from the "pages" field, if set. * * For instance, if the pages field is set to "345-360" or "345--360", * this formatter will return "345". */ public class FirstPage implements LayoutFormatter { @Override public String format(String s) { if (s == null) { return ""; } String[] pageParts = s.split("[ \\-]+"); if (pageParts.length == 2) { return pageParts[0]; } else { return s; } } }
620
22.884615
72
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/FormatPagesForHTML.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; public class FormatPagesForHTML implements LayoutFormatter { @Override public String format(String field) { return field.replace("--", "-"); } }
256
20.416667
60
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/FormatPagesForXML.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; public class FormatPagesForXML implements LayoutFormatter { @Override public String format(String field) { return field.replace("--", "&#x2013;"); } }
262
20.916667
59
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/GetOpenOfficeType.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; /** * Change type of record to match the one used by OpenOffice formatter. */ public class GetOpenOfficeType implements LayoutFormatter { @Override public String format(String fieldText) { if ("Article".equalsIgnoreCase(fieldText)) { return "7"; } if ("Book".equalsIgnoreCase(fieldText)) { return "1"; } if ("Booklet".equalsIgnoreCase(fieldText)) { return "2"; } if ("Inbook".equalsIgnoreCase(fieldText)) { return "5"; } if ("Incollection".equalsIgnoreCase(fieldText)) { return "5"; } if ("Inproceedings".equalsIgnoreCase(fieldText)) { return "6"; } if ("Manual".equalsIgnoreCase(fieldText)) { return "8"; } if ("Mastersthesis".equalsIgnoreCase(fieldText)) { return "9"; } if ("Misc".equalsIgnoreCase(fieldText)) { return "10"; } if ("Other".equalsIgnoreCase(fieldText)) { return "10"; } if ("Phdthesis".equalsIgnoreCase(fieldText)) { return "9"; } if ("Proceedings".equalsIgnoreCase(fieldText)) { return "3"; } if ("Techreport".equalsIgnoreCase(fieldText)) { return "13"; } if ("Unpublished".equalsIgnoreCase(fieldText)) { return "14"; } // Default, Miscelaneous return "10"; } }
1,594
26.5
71
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/HTMLChars.java
package org.jabref.logic.layout.format; import java.util.Map; import java.util.Objects; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.util.strings.HTMLUnicodeConversionMaps; import org.jabref.model.strings.StringUtil; /** * This formatter escapes characters so they are suitable for HTML. */ public class HTMLChars implements LayoutFormatter { private static final Map<String, String> HTML_CHARS = HTMLUnicodeConversionMaps.LATEX_HTML_CONVERSION_MAP; @Override public String format(String inField) { int i; String field = inField.replaceAll("&|\\\\&", "&amp;") // Replace & and \& with &amp; .replaceAll("[\\n]{2,}", "<p>") // Replace double line breaks with <p> .replace("\n", "<br>") // Replace single line breaks with <br> .replace("\\$", "&dollar;") // Replace \$ with &dollar; .replaceAll("\\$([^$]*)\\$", "\\{$1\\}"); // Replace $...$ with {...} to simplify conversion StringBuilder sb = new StringBuilder(); StringBuilder currentCommand = null; char c; boolean escaped = false; boolean incommand = false; for (i = 0; i < field.length(); i++) { c = field.charAt(i); if (escaped && (c == '\\')) { sb.append('\\'); escaped = false; } else if (c == '\\') { if (incommand) { /* Close Command */ String command = currentCommand.toString(); String result = HTML_CHARS.get(command); sb.append(Objects.requireNonNullElse(result, command)); } escaped = true; incommand = true; currentCommand = new StringBuilder(); } else if (!incommand && ((c == '{') || (c == '}'))) { // Swallow the brace. } else if (Character.isLetter(c) || StringUtil.SPECIAL_COMMAND_CHARS.contains(String.valueOf(c))) { escaped = false; if (!incommand) { sb.append(c); } else { currentCommand.append(c); testCharCom: if ((currentCommand.length() == 1) && StringUtil.SPECIAL_COMMAND_CHARS.contains(currentCommand.toString())) { // This indicates that we are in a command of the type // \^o or \~{n} if (i >= (field.length() - 1)) { break testCharCom; } String command = currentCommand.toString(); i++; c = field.charAt(i); String commandBody; if (c == '{') { String part = StringUtil.getPart(field, i, false); i += part.length(); commandBody = part; } else { commandBody = field.substring(i, i + 1); } String result = HTML_CHARS.get(command + commandBody); sb.append(Objects.requireNonNullElse(result, commandBody)); incommand = false; escaped = false; } else { // Are we already at the end of the string? if ((i + 1) == field.length()) { String command = currentCommand.toString(); String result = HTML_CHARS.get(command); /* If found, then use translated version. If not, * then keep * the text of the parameter intact. */ sb.append(Objects.requireNonNullElse(result, command)); } } } } else { if (!incommand) { sb.append(c); } else if (Character.isWhitespace(c) || (c == '{') || (c == '}')) { String command = currentCommand.toString(); // Test if we are dealing with a formatting // command. // If so, handle. String tag = getHTMLTag(command); if (!tag.isEmpty()) { String part = StringUtil.getPart(field, i, true); i += part.length(); sb.append('<').append(tag).append('>').append(part).append("</").append(tag).append('>'); } else if (c == '{') { String argument = StringUtil.getPart(field, i, true); i += argument.length(); // handle common case of general latex command String result = HTML_CHARS.get(command + argument); // If found, then use translated version. If not, then keep // the text of the parameter intact. if (result == null) { if (argument.isEmpty()) { // Maybe a separator, such as in \LaTeX{}, so use command sb.append(command); } else { // Otherwise, use argument sb.append(argument); } } else { sb.append(result); } } else if (c == '}') { // This end brace terminates a command. This can be the case in // constructs like {\aa}. The correct behaviour should be to // substitute the evaluated command and swallow the brace: String result = HTML_CHARS.get(command); // If the command is unknown, just print it: sb.append(Objects.requireNonNullElse(result, command)); } else { String result = HTML_CHARS.get(command); sb.append(Objects.requireNonNullElse(result, command)); sb.append(' '); } } else { sb.append(c); /* * TODO: this point is reached, apparently, if a command is * terminated in a strange way, such as with "$\omega$". * Also, the command "\&" causes us to get here. The former * issue is maybe a little difficult to address, since it * involves the LaTeX math mode. We don't have a complete * LaTeX parser, so maybe it's better to ignore these * commands? */ } incommand = false; escaped = false; } } return sb.toString().replace("~", "&nbsp;"); // Replace any remaining ~ with &nbsp; (non-breaking spaces) } private String getHTMLTag(String latexCommand) { String result = ""; switch (latexCommand) { // Italic case "textit": case "it": result = "i"; break; // Emphasize case "emph": case "em": result = "em"; break; // Bold font case "textbf": case "bf": result = "b"; break; // Underline case "underline": result = "u"; break; // Strikeout, sout is the "standard" command, although it is actually based on the package ulem case "sout": result = "s"; break; // Monospace font case "texttt": result = "tt"; break; // Superscript case "textsuperscript": result = "sup"; break; // Subscript case "textsubscript": result = "sub"; break; default: break; } return result; } }
8,634
40.917476
122
java
null
jabref-main/src/main/java/org/jabref/logic/layout/format/HTMLParagraphs.java
package org.jabref.logic.layout.format; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.logic.layout.LayoutFormatter; /** * Will interpret two consecutive newlines as the start of a new paragraph and thus * wrap the paragraph in HTML-p-tags. */ public class HTMLParagraphs implements LayoutFormatter { private static final Pattern BEFORE_NEW_LINES_PATTERN = Pattern.compile("(.*?)\\n\\s*\\n"); @Override public String format(String fieldText) { if (fieldText == null) { return fieldText; } String trimmedFieldText = fieldText.trim(); if (trimmedFieldText.isEmpty()) { return trimmedFieldText; } Matcher m = HTMLParagraphs.BEFORE_NEW_LINES_PATTERN.matcher(trimmedFieldText); StringBuilder s = new StringBuilder(); while (m.find()) { String middle = m.group(1).trim(); if (!middle.isEmpty()) { s.append("<p>\n"); m.appendReplacement(s, m.group(1)); s.append("\n</p>\n"); } } s.append("<p>\n"); m.appendTail(s); s.append("\n</p>"); return s.toString(); } }
1,228
26.311111
95
java