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/layout/format/IfPlural.java | package org.jabref.logic.layout.format;
import java.util.List;
import org.jabref.logic.layout.AbstractParamLayoutFormatter;
/**
* This formatter takes two arguments and examines the field text.
* If the field text represents multiple individuals, that is it contains the string "and"
* then the field text is replaced with the first argument, otherwise it is replaced with the second.
* For example:
*
* <p>
* \format[IfPlural(Eds.,Ed.)]{\editor}
* <p>
* Should expand to 'Eds.' if the document has more than one editor and 'Ed.' if it only has one.
*/
public class IfPlural extends AbstractParamLayoutFormatter {
private String pluralText;
private String singularText;
@Override
public void setArgument(String arg) {
List<String> parts = AbstractParamLayoutFormatter.parseArgument(arg);
if (parts.size() < 2) {
return; // TODO: too few arguments. Print an error message here?
}
pluralText = parts.get(0);
singularText = parts.get(1);
}
@Override
public String format(String fieldText) {
if ((fieldText == null) || fieldText.isEmpty() || (pluralText == null)) {
return ""; // TODO: argument missing or invalid. Print an error message here?
}
if (fieldText.matches(".*\\sand\\s.*")) {
return pluralText;
} else {
return singularText;
}
}
}
| 1,416 | 29.804348 | 101 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/Iso690FormatDate.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.strings.StringUtil;
public class Iso690FormatDate implements LayoutFormatter {
@Override
public String format(String s) {
if (StringUtil.isBlank(s)) {
return "";
}
StringBuilder sb = new StringBuilder();
String[] date = s.split("de");
// parte el string en los distintos campos de la fecha
if (date.length == 1) { // sólo pone el año
sb.append(date[0].trim());
} else if (date.length == 2) { // primer campo mes, segundo campo año
// cambiamos al formato año - mes
sb.append(date[1].trim()).append('-').append(date[0].trim());
} else if (date.length == 3) {
// primer campo día, segundo campo mes y tercer campo año
// cambiamos al formato año-mes-día
sb.append(date[2].trim()).append('-').append(date[1].trim()).append('-').append(date[0].trim());
}
return sb.toString(); // retorna el string creado con la fecha.
}
}
| 1,110 | 37.310345 | 108 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/Iso690NamesAuthors.java | package org.jabref.logic.layout.format;
import java.util.Locale;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.strings.StringUtil;
public class Iso690NamesAuthors implements LayoutFormatter {
@Override
public String format(String s) {
if (StringUtil.isBlank(s)) {
return "";
}
StringBuilder sb = new StringBuilder();
String[] authors = s.split("and");
// parte el string en los distintos autores
for (int i = 0; i < authors.length; i++) {
// parte el string author en varios campos, según el separador ","
String[] author = authors[i].split(",");
// No separa apellidos y nombre con coma (,)
if (author.length < 2) { // Caso 1: Nombre Apellidos
// parte el string author en varios campos, según el separador " "
author = authors[i].split(" ");
// declaramos y damos un valor para evitar problemas
String name;
String surname;
if (author.length == 1) { // Caso 1.0: Sólo un campo
sb.append(author[0].trim().toUpperCase(Locale.ROOT));
} else if (author.length == 2) { // Caso 1.1: Nombre Apellido
// primer campo Nombre
name = author[0].trim();
// Segundo campo Apellido
surname = author[1].trim().toUpperCase(Locale.ROOT);
// añadimos los campos modificados al string final
sb.append(surname);
sb.append(", ");
sb.append(name);
} else if (author.length == 3) { // Caso 1.2: Nombre Apellido1 Apellido2
// primer campo Nombre
name = author[0].trim();
// Segundo y tercer campo Apellido1 Apellido2
surname = author[1].trim().toUpperCase(Locale.ROOT) + ' ' + author[2].trim().toUpperCase(Locale.ROOT);
// añadimos los campos modificados al string final
sb.append(surname);
sb.append(", ");
sb.append(name);
} else if (author.length == 4) { // Caso 1.3: Nombre SegundoNombre Apellido1 Apellido2
// primer y segundo campo Nombre SegundoNombre
name = author[0].trim() + ' ' + author[1].trim();
// tercer y cuarto campo Apellido1 Apellido2
surname = author[2].trim().toUpperCase(Locale.ROOT) + ' ' + author[3].trim().toUpperCase(Locale.ROOT);
// añadimos los campos modificados al string final
sb.append(surname);
sb.append(", ");
sb.append(name);
}
} else { // Caso 2: Apellidos, Nombre
// Campo 1 apellidos, lo pasamos a mayusculas
String surname = author[0].trim().toUpperCase(Locale.ROOT);
// campo 2 nombre
String name = author[1].trim();
// añadimos los campos modificados al string final
sb.append(surname);
sb.append(", ");
sb.append(name);
}
if (i < authors.length - 2) { // si hay mas de 2 autores, lo separamos por ", "
sb.append(", ");
} else if (i == authors.length - 2) { // si hay 2 autores, lo separamos por " y "
sb.append(" y ");
}
}
return sb.toString(); // retorna el string creado de autores.
}
}
| 3,662 | 42.607143 | 122 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/JournalAbbreviator.java | package org.jabref.logic.layout.format;
import java.util.Objects;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.layout.LayoutFormatter;
/**
* JournalAbbreviator formats the given text in an abbreviated form according to the journal abbreviation lists.
*
* The given input text is abbreviated according to the journal abbreviation lists. If no abbreviation for input is
* found (e.g. not in list or already abbreviated), the input will be returned unmodified.
*
* Usage: \format[JournalAbbreviator]{\journal} Example result: "Phys. Rev. Lett." instead of "Physical Review Letters"
*/
public class JournalAbbreviator implements LayoutFormatter {
private final JournalAbbreviationRepository repository;
public JournalAbbreviator(JournalAbbreviationRepository repository) {
this.repository = Objects.requireNonNull(repository);
}
@Override
public String format(String fieldText) {
return repository.getDefaultAbbreviation(fieldText).orElse(fieldText);
}
}
| 1,047 | 35.137931 | 119 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/LastPage.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Formatter that returns the last 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 "360".
*/
public class LastPage implements LayoutFormatter {
@Override
public String format(String s) {
if (s == null) {
return "";
}
String[] pageParts = s.split("[\\-]+");
if (pageParts.length == 2) {
return pageParts[1];
} else if (pageParts.length >= 1) {
return pageParts[0];
} else {
return "";
}
}
}
| 695 | 23.857143 | 71 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/LatexToUnicodeFormatter.java | package org.jabref.logic.layout.format;
import org.jabref.logic.cleanup.Formatter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.strings.LatexToUnicodeAdapter;
/**
* This formatter converts LaTeX character sequences their equivalent unicode characters,
* and removes other LaTeX commands without handling them.
*/
public class LatexToUnicodeFormatter extends Formatter implements LayoutFormatter {
@Override
public String getName() {
return Localization.lang("LaTeX to Unicode");
}
@Override
public String getKey() {
return "latex_to_unicode";
}
@Override
public String format(String inField) {
return LatexToUnicodeAdapter.format(inField);
}
@Override
public String getDescription() {
return Localization.lang("Converts LaTeX encoding to Unicode characters.");
}
@Override
public String getExampleInput() {
return "M{\\\"{o}}nch";
}
}
| 1,015 | 25.051282 | 89 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/MarkdownFormatter.java | package org.jabref.logic.layout.format;
import java.util.Objects;
import org.jabref.logic.layout.LayoutFormatter;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;
public class MarkdownFormatter implements LayoutFormatter {
private final Parser parser;
private final HtmlRenderer renderer;
public MarkdownFormatter() {
MutableDataSet options = new MutableDataSet();
parser = Parser.builder(options).build();
renderer = HtmlRenderer.builder(options).build();
}
@Override
public String format(final String fieldText) {
Objects.requireNonNull(fieldText, "Field Text should not be null, when handed to formatter");
Node document = parser.parse(fieldText);
String html = renderer.render(document);
// workaround HTMLChars transforming "\n" into <br> by returning a one liner
return html.replaceAll("\\r\\n|\\r|\\n", " ").trim();
}
}
| 1,066 | 30.382353 | 101 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/NameFormatter.java | package org.jabref.logic.layout.format;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jabref.logic.bst.util.BstNameFormatter;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.entry.AuthorList;
/**
* This layout formatter uses the Bibtex name.format$ method and provides ultimate flexibility:
*
* The formatter needs a parameter to be passed in that follows the following format:
*
* <code><case1>@<range11>@"<format>"@<range12>@"<format>"@<range13>...@@
*
* <case2>@<range21>@...</code> and so on.
*
* Individual cases are separated by @@ and items in a case by @.
*
* Cases are just integers or the character * and will tell the formatter to apply the following formats if there are
* less or equal authors given to it. The cases must be in strict increasing order with the * in the last position.
*
* For instance:
*
* case1 = 2
* case2 = 3
* case3 = *
*
* Ranges are either <integer>..<integer>, <integer> or the character * using a 1 based index for indexing
* authors from the given authorlist. Integer indexes can be negative to denote them to start from
* the end of the list where -1 is the last author.
*
* For instance with an authorlist of "Joe Doe and Mary Jane and Bruce Bar and Arthur Kay":
*
* 1..3 will affect Joe, Mary and Bruce
*
* 4..4 will affect Arthur
*
* * will affect all of them
*
* 2..-1 will affect Mary, Bruce and Arthur
*
* The <format> uses the Bibtex formatter format:
*
* The four letter v, f, l, j indicate the name parts von, first, last, jr which
* are used within curly braces. A single letter v, f, l, j indicates that the name should be abbreviated.
* To put a quote in the format string quote it using \" (mh. this doesn't work yet)
*
* I give some examples but would rather point you to the bibtex documentation.
*
* "{ll}, {f}." Will turn "Joe Doe" into "Doe, J."
*
* Complete example:
*
* To turn:
*
* "Joe Doe and Mary Jane and Bruce Bar and Arthur Kay"
*
* into
*
* "Doe, J., Jane, M., Bar, B. and Kay, A."
*
* you would use
*
* 1@*@{ll}, {f}.@@2@1@{ll}, {f}.@2@ and {ll}, {f}.@@*@1..-3@{ll}, {f}., @-2@{ll}, {f}.@-1@ and {ll}, {f}.
*
* Yeah this is trouble-some to write, but should work.
*
* For more examples see the test-cases.
*
*/
public class NameFormatter implements LayoutFormatter {
public static final String DEFAULT_FORMAT = "1@*@{ff }{vv }{ll}{, jj}@@*@1@{ff }{vv }{ll}{, jj}@*@, {ff }{vv }{ll}{, jj}";
private String parameter = NameFormatter.DEFAULT_FORMAT;
private static String format(String toFormat, AuthorList al, String[] formats) {
StringBuilder sb = new StringBuilder();
int n = al.getNumberOfAuthors();
for (int i = 1; i <= al.getNumberOfAuthors(); i++) {
for (int j = 1; j < formats.length; j += 2) {
if ("*".equals(formats[j])) {
sb.append(BstNameFormatter.formatName(toFormat, i, formats[j + 1]));
break;
} else {
String[] range = formats[j].split("\\.\\.");
int s;
int e;
if (range.length == 2) {
s = Integer.parseInt(range[0]);
e = Integer.parseInt(range[1]);
} else {
s = e = Integer.parseInt(range[0]);
}
if (s < 0) {
s += n + 1;
}
if (e < 0) {
e += n + 1;
}
if (e < s) {
int temp = e;
e = s;
s = temp;
}
if ((s <= i) && (i <= e)) {
sb.append(BstNameFormatter.formatName(toFormat, i, formats[j + 1]));
break;
}
}
}
}
return sb.toString();
}
public String format(String toFormat, String inParameters) {
AuthorList al = AuthorList.parse(toFormat);
String parameters;
if ((inParameters == null) || inParameters.isEmpty()) {
parameters = "*:*:\"{ff}{vv}{ll}{,jj} \"";
} else {
parameters = inParameters;
}
String[] cases = parameters.split("@@");
for (String aCase : cases) {
String[] formatString = aCase.split("@");
if (formatString.length < 3) {
// Error
return toFormat;
}
if ("*".equals(formatString[0])) {
return format(toFormat, al, formatString);
} else {
if (al.getNumberOfAuthors() <= Integer.parseInt(formatString[0])) {
return format(toFormat, al, formatString);
}
}
}
return toFormat;
}
@Override
public String format(String fieldText) {
return format(fieldText, parameter);
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public static Map<String, String> getNameFormatters(NameFormatterPreferences prefs) {
Objects.requireNonNull(prefs);
Map<String, String> result = new HashMap<>();
List<String> names = prefs.getNameFormatterKey();
List<String> formats = prefs.getNameFormatterValue();
for (int i = 0; i < names.size(); i++) {
if (i < formats.size()) {
result.put(names.get(i), formats.get(i));
} else {
result.put(names.get(i), DEFAULT_FORMAT);
}
}
return result;
}
}
| 5,823 | 31 | 126 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/NameFormatterPreferences.java | package org.jabref.logic.layout.format;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class NameFormatterPreferences {
private final ObservableList<String> nameFormatterKey;
private final ObservableList<String> nameFormatterValue;
public NameFormatterPreferences(List<String> nameFormatterKey, List<String> nameFormatterValue) {
this.nameFormatterKey = FXCollections.observableArrayList(nameFormatterKey);
this.nameFormatterValue = FXCollections.observableArrayList(nameFormatterValue);
}
public ObservableList<String> getNameFormatterKey() {
return nameFormatterKey;
}
public ObservableList<String> getNameFormatterValue() {
return nameFormatterValue;
}
public void setNameFormatterKey(List<String> list) {
nameFormatterKey.clear();
nameFormatterKey.addAll(list);
}
public void setNameFormatterValue(List<String> list) {
nameFormatterValue.clear();
nameFormatterValue.addAll(list);
}
}
| 1,075 | 28.888889 | 101 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviations.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* <p>
* LayoutFormatter that removes the space between abbreviated First names
* </p>
* <p>
* What out that this regular expression might also remove other spaces that fit the pattern.
* </p>
* <p>
* Example: J. R. R. Tolkien becomes J.R.R. Tolkien.
* </p>
* <p>
* See Testcase for more examples.
* <p>
*/
public class NoSpaceBetweenAbbreviations implements LayoutFormatter {
/*
* Match '.' followed by spaces followed by uppercase char followed by '.'
* but don't include the last dot into the capturing group.
*
* Replace the match by removing the spaces.
*
* @see org.jabref.export.layout.LayoutFormatter#format(java.lang.String)
*/
@Override
public String format(String fieldText) {
return fieldText.replaceAll("\\.\\s+(\\p{Lu})(?=\\.)", "\\.$1");
}
}
| 923 | 26.176471 | 93 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/NotFoundFormatter.java | package org.jabref.logic.layout.format;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Formatter used to signal that a formatter hasn't been found. This can be
* used for graceful degradation if a layout uses an undefined format.
*/
public class NotFoundFormatter implements LayoutFormatter {
private final String notFound;
public NotFoundFormatter(String notFound) {
this.notFound = notFound;
}
public String getNotFound() {
return notFound;
}
@Override
public String format(String fieldText) {
return '[' + Localization.lang("Formatter not found: %0", notFound) + "] " + fieldText;
}
}
| 703 | 25.074074 | 95 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/Number.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.ParamLayoutFormatter;
/**
* Formatter that outputs a sequence number for the current entry. The sequence number is
* tied to the entry's position in the order, not to the number of calls to this formatter.
*/
public class Number implements ParamLayoutFormatter {
public static int serialExportNumber;
@Override
public void setArgument(String arg) {
// No effect currently.
}
@Override
public String format(String fieldText) {
return String.valueOf(serialExportNumber);
}
}
| 596 | 24.956522 | 91 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/Ordinal.java | package org.jabref.logic.layout.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Converts number to ordinal
*/
public class Ordinal implements LayoutFormatter {
// Detect last digit in number not directly followed by a letter plus the number 11
private static final Pattern NUMBER_PATTERN = Pattern.compile("(1?\\d\\b)");
@Override
public String format(String fieldText) {
if (fieldText == null) {
return null;
}
Matcher m = NUMBER_PATTERN.matcher(fieldText);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String result = m.group(1);
int value = Integer.parseInt(result);
// CHECKSTYLE:OFF
String ordinalString = switch (value) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
// CHECKSTYLE:ON
m.appendReplacement(sb, result + ordinalString);
}
m.appendTail(sb);
return sb.toString();
}
}
| 1,151 | 27.8 | 87 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RTFChars.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.logic.layout.StringInt;
import org.jabref.logic.util.strings.RtfCharMap;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Transform a LaTeX-String to RTF.
*
* This method will:
*
* 1.) Remove LaTeX-Command sequences.
*
* 2.) Replace LaTeX-Special chars with RTF equivalents.
*
* 3.) Replace emph and textit and textbf with their RTF replacements.
*
* 4.) Take special care to save all unicode characters correctly.
*
* 5.) Replace --- by \emdash and -- by \endash.
*/
public class RTFChars implements LayoutFormatter {
private static final Logger LOGGER = LoggerFactory.getLogger(LayoutFormatter.class);
private static final RtfCharMap RTF_CHARS = new RtfCharMap();
@Override
public String format(String field) {
StringBuilder sb = new StringBuilder();
StringBuilder currentCommand = null;
boolean escaped = false;
boolean incommand = false;
for (int i = 0; i < field.length(); i++) {
char c = field.charAt(i);
if (escaped && (c == '\\')) {
sb.append('\\');
escaped = false;
} else if (c == '\\') {
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) {
// Else we are in a command, and should not keep the letter.
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 combody;
if (c == '{') {
StringInt part = getPart(field, i, true);
i += part.i;
combody = part.s;
} else {
combody = field.substring(i, i + 1);
}
String result = RTF_CHARS.get(command + combody);
if (result != null) {
sb.append(result);
}
incommand = false;
escaped = false;
}
} else {
sb.append(c);
}
} else {
testContent:
if (!incommand || (!Character.isWhitespace(c) && (c != '{') && (c != '}'))) {
sb.append(c);
} else {
assert incommand;
// First test for braces that may be part of a LaTeX command:
if ((c == '{') && (currentCommand.length() == 0)) {
// We have seen something like \{, which is probably the start
// of a command like \{aa}. Swallow the brace.
continue;
} else if ((c == '}') && (currentCommand.length() > 0)) {
// Seems to be the end of a command like \{aa}. Look it up:
String command = currentCommand.toString();
String result = RTF_CHARS.get(command);
if (result != null) {
sb.append(result);
}
incommand = false;
escaped = false;
continue;
}
// Then look for italics etc.,
// but first check if we are already at the end of the string.
if (i >= (field.length() - 1)) {
break testContent;
}
if (((c == '{') || (c == ' ')) && (currentCommand.length() > 0)) {
String command = currentCommand.toString();
// Then test if we are dealing with a italics or bold
// command. If so, handle.
if ("em".equals(command) || "emph".equals(command) || "textit".equals(command)
|| "it".equals(command)) {
StringInt part = getPart(field, i, c == '{');
i += part.i;
sb.append("{\\i ").append(part.s).append('}');
} else if ("textbf".equals(command) || "bf".equals(command)) {
StringInt part = getPart(field, i, c == '{');
i += part.i;
sb.append("{\\b ").append(part.s).append('}');
} else {
LOGGER.info("Unknown command " + command);
}
if (c == ' ') {
// command was separated with the content by ' '
// We have to add the space a
}
} else {
sb.append(c);
}
}
incommand = false;
escaped = false;
}
}
char[] chars = sb.toString().toCharArray();
sb = new StringBuilder();
for (char c : chars) {
if (c < 128) {
sb.append(c);
} else {
sb.append("\\u").append((long) c).append(transformSpecialCharacter(c));
}
}
return sb.toString().replace("---", "{\\emdash}").replace("--", "{\\endash}").replace("``", "{\\ldblquote}")
.replace("''", "{\\rdblquote}");
}
/**
* @param text the text to extract the part from
* @param i the position to start
* @param commandNestedInBraces true if the command is nested in braces (\emph{xy}), false if spaces are sued (\emph xy)
* @return a tuple of number of added characters and the extracted part
*/
private StringInt getPart(String text, int i, boolean commandNestedInBraces) {
char c;
int count = 0;
int icount = i;
StringBuilder part = new StringBuilder();
loop:
while ((count >= 0) && (icount < text.length())) {
icount++;
c = text.charAt(icount);
switch (c) {
case '}':
count--;
break;
case '{':
count++;
break;
case ' ':
if (!commandNestedInBraces) {
// in any case, a space terminates the loop
break loop;
}
break;
default:
break;
}
part.append(c);
}
String res = part.toString();
// the wrong "}" at the end is removed by "format(res)"
return new StringInt(format(res), part.length());
}
/**
* This method transforms the unicode of a special character into its base character: 233 (é) - > e
*
* @param c long
* @return returns the basic character of the given unicode
*/
private String transformSpecialCharacter(long c) {
if (((192 <= c) && (c <= 197)) || (c == 256) || (c == 258) || (c == 260)) {
return "A";
}
if (((224 <= c) && (c <= 229)) || (c == 257) || (c == 259) || (c == 261)) {
return "a";
}
if ((199 == c) || (262 == c) || (264 == c) || (266 == c) || (268 == c)) {
return "C";
}
if ((231 == c) || (263 == c) || (265 == c) || (267 == c) || (269 == c)) {
return "c";
}
if ((208 == c) || (272 == c)) {
return "D";
}
if ((240 == c) || (273 == c)) {
return "d";
}
if (((200 <= c) && (c <= 203)) || (274 == c) || (276 == c) || (278 == c) || (280 == c) || (282 == c)) {
return "E";
}
if (((232 <= c) && (c <= 235)) || (275 == c) || (277 == c) || (279 == c) || (281 == c) || (283 == c)) {
return "e";
}
if (((284 == c) || (286 == c)) || (288 == c) || (290 == c) || (330 == c)) {
return "G";
}
if ((285 == c) || (287 == c) || (289 == c) || (291 == c) || (331 == c)) {
return "g";
}
if ((292 == c) || (294 == c)) {
return "H";
}
if ((293 == c) || (295 == c)) {
return "h";
}
if (((204 <= c) && (c <= 207)) || (296 == c) || (298 == c) || (300 == c) || (302 == c) || (304 == c)) {
return "I";
}
if (((236 <= c) && (c <= 239)) || (297 == c) || (299 == c) || (301 == c) || (303 == c)) {
return "i";
}
if (308 == c) {
return "J";
}
if (309 == c) {
return "j";
}
if (310 == c) {
return "K";
}
if (311 == c) {
return "k";
}
if ((313 == c) || (315 == c) || (319 == c)) {
return "L";
}
if ((314 == c) || (316 == c) || (320 == c) || (322 == c)) {
return "l";
}
if ((209 == c) || (323 == c) || (325 == c) || (327 == c)) {
return "N";
}
if ((241 == c) || (324 == c) || (326 == c) || (328 == c)) {
return "n";
}
if (((210 <= c) && (c <= 214)) || (c == 216) || (332 == c) || (334 == c)) {
return "O";
}
if (((242 <= c) && (c <= 248) && (247 != c)) || (333 == c) || (335 == c)) {
return "o";
}
if ((340 == c) || (342 == c) || (344 == c)) {
return "R";
}
if ((341 == c) || (343 == c) || (345 == c)) {
return "r";
}
if ((346 == c) || (348 == c) || (350 == c) || (352 == c)) {
return "S";
}
if ((347 == c) || (349 == c) || (351 == c) || (353 == c)) {
return "s";
}
if ((354 == c) || (356 == c) || (358 == c)) {
return "T";
}
if ((355 == c) || (359 == c)) {
return "t";
}
if (((217 <= c) && (c <= 220)) || (360 == c) || (362 == c) || (364 == c) || (366 == c) || (370 == c)) {
return "U";
}
if (((249 <= c) && (c <= 251)) || (361 == c) || (363 == c) || (365 == c) || (367 == c) || (371 == c)) {
return "u";
}
if (372 == c) {
return "W";
}
if (373 == c) {
return "w";
}
if ((374 == c) || (376 == c) || (221 == c)) {
return "Y";
}
if ((375 == c) || (255 == c)) {
return "y";
}
if ((377 == c) || (379 == c) || (381 == c)) {
return "Z";
}
if ((378 == c) || (380 == c) || (382 == c)) {
return "z";
}
if (198 == c) {
return "AE";
}
if (230 == c) {
return "ae";
}
if (338 == c) {
return "OE";
}
if (339 == c) {
return "oe";
}
if (222 == c) {
return "TH";
}
if (223 == c) {
return "ss";
}
if (161 == c) {
return "!";
}
return "?";
}
}
| 12,300 | 34.552023 | 124 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RemoveBrackets.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Remove brackets formatter.
*
* <example>
* "{Stefan Kolb}" -> "Stefan Kolb"
* </example>
*/
public class RemoveBrackets implements LayoutFormatter {
@Override
public String format(String fieldText) {
StringBuilder builder = new StringBuilder(fieldText.length());
for (char c : fieldText.toCharArray()) {
if ((c != '{') && (c != '}')) {
builder.append(c);
}
}
return builder.toString();
}
}
| 581 | 22.28 | 70 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RemoveBracketsAddComma.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Remove brackets formatter.
*/
public class RemoveBracketsAddComma implements LayoutFormatter {
@Override
public String format(String fieldText) {
StringBuilder builder = new StringBuilder(fieldText.length());
for (char c : fieldText.toCharArray()) {
if (c == '}') {
builder.append(',');
} else if (c != '{') {
builder.append(c);
}
}
return builder.toString();
}
}
| 575 | 24.043478 | 70 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RemoveLatexCommandsFormatter.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.strings.StringUtil;
public class RemoveLatexCommandsFormatter implements LayoutFormatter {
@Override
public String format(String field) {
StringBuilder cleanedField = new StringBuilder();
StringBuilder currentCommand = null;
char currentCharacter;
boolean escaped = false;
boolean incommand = false;
int currentFieldPosition;
for (currentFieldPosition = 0; currentFieldPosition < field.length(); currentFieldPosition++) {
currentCharacter = field.charAt(currentFieldPosition);
if (escaped && (currentCharacter == '\\')) {
cleanedField.append('\\');
escaped = false;
// \\ --> first \ begins the command, second \ ends the command
// \latexommand\\ -> \latexcommand is the command, terminated by \, which begins a new command
incommand = false;
} else if (currentCharacter == '\\') {
escaped = true;
incommand = true;
currentCommand = new StringBuilder();
} else if (!incommand && ((currentCharacter == '{') || (currentCharacter == '}'))) {
// Swallow the brace.
} else if (Character.isLetter(currentCharacter) || StringUtil.SPECIAL_COMMAND_CHARS.contains(String.valueOf(currentCharacter))) {
escaped = false;
if (incommand) {
currentCommand.append(currentCharacter);
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}
incommand = false;
escaped = false;
}
} else {
cleanedField.append(currentCharacter);
}
} else if (Character.isLetter(currentCharacter)) {
escaped = false;
if (incommand) {
// We are in a command, and should not keep the letter.
currentCommand.append(currentCharacter);
} else {
cleanedField.append(currentCharacter);
}
} else {
if (!incommand || (!Character.isWhitespace(currentCharacter) && (currentCharacter != '{'))) {
cleanedField.append(currentCharacter);
} else {
if (!Character.isWhitespace(currentCharacter) && (currentCharacter != '{')) {
// do not append the opening brace of a command parameter
// do not append the whitespace character
cleanedField.append(currentCharacter);
}
if (incommand) {
// eat up all whitespace characters
while (currentFieldPosition + 1 < field.length() && Character.isWhitespace(field.charAt(currentFieldPosition + 1))) {
currentFieldPosition++;
}
}
}
incommand = false;
escaped = false;
}
}
return cleanedField.toString();
}
}
| 3,472 | 45.306667 | 141 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RemoveTilde.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Replace a non-command tilde ~ by a space.
* <p>
* Useful for formatting Latex code.
*/
public class RemoveTilde implements LayoutFormatter {
@Override
public String format(String fieldText) {
StringBuilder result = new StringBuilder(fieldText.length());
char[] c = fieldText.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '~') {
result.append(' ');
} else {
result.append(c[i]);
// Skip the next character if the current one is a backslash
if ((c[i] == '\\') && ((i + 1) < c.length)) {
i++;
result.append(c[i]);
}
}
}
return result.toString();
}
}
| 875 | 26.375 | 76 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RemoveWhitespace.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Remove non-printable character formatter.
*/
public class RemoveWhitespace implements LayoutFormatter {
@Override
public String format(String fieldEntry) {
if (fieldEntry == null) {
return null;
}
StringBuilder sb = new StringBuilder(fieldEntry.length());
for (char c : fieldEntry.toCharArray()) {
if (!Character.isWhitespace(c) || Character.isSpaceChar(c)) {
sb.append(c);
}
}
return sb.toString();
}
}
| 618 | 21.925926 | 73 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/Replace.java | package org.jabref.logic.layout.format;
import java.util.List;
import org.jabref.logic.layout.AbstractParamLayoutFormatter;
/**
* Formatter that does regexp replacement.
*
* To use this formatter, a two-part argument must be given. The parts are
* separated by a comma. To indicate the comma character, use an escape
* sequence: \,
* For inserting newlines and tabs in arguments, use \n and \t, respectively.
*
* The first part is the regular expression to search for. Remember that any commma
* character must be preceded by a backslash, and consequently a literal backslash must
* be written as a pair of backslashes. A description of Java regular expressions can be
* found at:
* http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
*
* The second part is the text to replace all matches with.
*
* For instance:
* \format[Replace(and,&)]{\author} :
* will output the "author" field after replacing all occurences of "and"
* by "&"
*
* \format[Replace(\s,_)]{\author} :
* will output the "author" field after replacing all whitespace
* by underscores.
*
* \format[Replace(\,,;)]{\author} :
* will output the "author" field after replacing all commas by semicolons.
*
*/
public class Replace extends AbstractParamLayoutFormatter {
private String regex;
private String replaceWith;
@Override
public void setArgument(String arg) {
List<String> parts = AbstractParamLayoutFormatter.parseArgument(arg);
if (parts.size() < 2) {
return; // TODO: too few arguments. Print an error message here?
}
regex = parts.get(0);
replaceWith = parts.get(1);
}
@Override
public String format(String fieldText) {
if ((fieldText == null) || (regex == null)) {
return fieldText; // TODO: argument missing or invalid. Print an error message here?
}
return fieldText.replaceAll(regex, replaceWith);
}
}
| 1,981 | 32.033333 | 96 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/ReplaceUnicodeLigaturesFormatter.java | package org.jabref.logic.layout.format;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.jabref.logic.cleanup.Formatter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.logic.util.strings.UnicodeLigaturesMap;
public class ReplaceUnicodeLigaturesFormatter extends Formatter implements LayoutFormatter {
private final Map<Pattern, String> ligaturesMap;
public ReplaceUnicodeLigaturesFormatter() {
ligaturesMap = new HashMap<>();
UnicodeLigaturesMap stringMap = new UnicodeLigaturesMap();
for (String key : stringMap.keySet()) {
ligaturesMap.put(Pattern.compile(key), stringMap.get(key));
}
}
@Override
public String getName() {
return Localization.lang("Replace Unicode ligatures");
}
@Override
public String getKey() {
return "replace_unicode_ligatures";
}
@Override
public String format(String fieldText) {
String result = fieldText;
for (Pattern key : ligaturesMap.keySet()) {
result = key.matcher(result).replaceAll(ligaturesMap.get(key));
}
return result;
}
@Override
public String getDescription() {
return Localization.lang("Replaces Unicode ligatures with their expanded form");
}
@Override
public String getExampleInput() {
return "Æneas";
}
}
| 1,456 | 26.490566 | 92 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/ReplaceWithEscapedDoubleQuotes.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
public class ReplaceWithEscapedDoubleQuotes implements LayoutFormatter {
@Override
public String format(String fieldText) {
StringBuilder builder = new StringBuilder(fieldText.length());
for (char c : fieldText.toCharArray()) {
if (c == '\"') {
builder.append("\"\"");
} else {
builder.append(c);
}
}
return builder.toString();
}
}
| 535 | 25.8 | 72 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RisAuthors.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.AuthorList;
public class RisAuthors implements ParamLayoutFormatter {
private String arg = "";
@Override
public String format(String s) {
if (s == null) {
return "";
}
StringBuilder sb = new StringBuilder();
String[] authors = AuthorList.fixAuthorLastNameFirst(s).split(" and ");
for (int i = 0; i < authors.length; i++) {
sb.append(arg);
sb.append(" - ");
sb.append(authors[i]);
if (i < authors.length - 1) {
sb.append(OS.NEWLINE);
}
}
return sb.toString();
}
@Override
public void setArgument(String arg) {
this.arg = arg;
}
}
| 871 | 24.647059 | 79 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RisKeywords.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.Keyword;
import org.jabref.model.entry.KeywordList;
public class RisKeywords implements LayoutFormatter {
@Override
public String format(String s) {
if (s == null) {
return "";
}
StringBuilder sb = new StringBuilder();
KeywordList keywords = KeywordList.parse(s, ',');
int i = 0;
for (Keyword keyword : keywords) {
sb.append("KW - ");
sb.append(keyword.toString());
if (i < (keywords.size() - 1)) {
sb.append(OS.NEWLINE);
}
i++;
}
return sb.toString();
}
}
| 776 | 25.793103 | 57 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/RisMonth.java | package org.jabref.logic.layout.format;
import java.util.Locale;
import java.util.Optional;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.entry.Month;
public class RisMonth implements LayoutFormatter {
@Override
public String format(String month) {
if (month == null) {
return "";
}
Optional<Month> parsedMonth = Month.getMonthByShortName(month);
return parsedMonth.map(Month::getTwoDigitNumber).orElse(month.toLowerCase(Locale.ROOT));
}
}
| 527 | 24.142857 | 96 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/ShortMonthFormatter.java | package org.jabref.logic.layout.format;
import java.util.Optional;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.entry.Month;
public class ShortMonthFormatter implements LayoutFormatter {
@Override
public String format(String fieldText) {
Optional<Month> month = Month.parse(fieldText);
return month.map(Month::getShortName).orElse("");
}
}
| 399 | 24 | 61 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/ToLowerCase.java | package org.jabref.logic.layout.format;
import java.util.Locale;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Convert the contents to lower case.
*/
public class ToLowerCase implements LayoutFormatter {
@Override
public String format(String fieldText) {
if (fieldText == null) {
return null;
}
return fieldText.toLowerCase(Locale.ROOT);
}
}
| 404 | 19.25 | 53 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/ToUpperCase.java | package org.jabref.logic.layout.format;
import java.util.Locale;
import org.jabref.logic.layout.LayoutFormatter;
/**
* Convert the contents to upper case.
*/
public class ToUpperCase implements LayoutFormatter {
@Override
public String format(String fieldText) {
if (fieldText == null) {
return null;
}
return fieldText.toUpperCase(Locale.ROOT);
}
}
| 405 | 18.333333 | 53 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/WrapContent.java | package org.jabref.logic.layout.format;
import java.util.List;
import org.jabref.logic.layout.AbstractParamLayoutFormatter;
/**
* This formatter outputs the input value after adding a prefix and a postfix,
* as long as the input value is non-empty. If the input value is empty, an
* empty string is output (the prefix and postfix are not output in this case).
*
* The formatter requires an argument containing the prefix and postix separated
* by a comma. To include a the comma character in either, use an escape sequence
* (\,).
*/
public class WrapContent extends AbstractParamLayoutFormatter {
private String before;
private String after;
@Override
public void setArgument(String arg) {
List<String> parts = AbstractParamLayoutFormatter.parseArgument(arg);
if (parts.size() < 2) {
return;
}
before = parts.get(0);
after = parts.get(1);
}
@Override
public String format(String fieldText) {
if (fieldText == null) {
return null;
}
if (before == null) {
return fieldText;
}
if (fieldText.isEmpty()) {
return "";
} else {
return before + fieldText + after;
}
}
}
| 1,265 | 26.521739 | 81 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/WrapFileLinks.java | package org.jabref.logic.layout.format;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jabref.logic.importer.util.FileFieldParser;
import org.jabref.logic.layout.AbstractParamLayoutFormatter;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.entry.LinkedFile;
/**
* This formatter iterates over all file links, or all file links of a specified
* type, outputting a format string given as the first argument. The format string
* can contain a number of escape sequences indicating file link information to
* be inserted into the string.
* <p/>
* This formatter can take an optional second argument specifying the name of a file
* type. If specified, the iteration will only include those files with a file type
* matching the given name (case-insensitively). If specified as an empty argument,
* all file links will be included.
* <p/>
* After the second argument, pairs of additional arguments can be added in order to
* specify regular expression replacements to be done upon the inserted link information
* before insertion into the output string. A non-paired argument will be ignored.
* In order to specify replacements without filtering on file types, use an empty second
* argument.
* <p/>
* <p/>
* <p/>
* The escape sequences for embedding information are as follows:
* <p/>
* \i : This inserts the iteration index (starting from 1), and can be useful if
* the output list of files should be enumerated.
* \p : This inserts the file path of the file link. Relative links below your file directory
* will be expanded to their absolute path.
* \r : This inserts the file path without expanding relative links.
* \f : This inserts the name of the file link's type.
* \x : This inserts the file's extension, if any.
* \d : This inserts the file link's description, if any.
* <p/>
* For instance, an entry could contain a file link to the file "/home/john/report.pdf"
* of the "PDF" type with description "John's final report".
* <p/>
* Using the WrapFileLinks formatter with the following argument:
* <p/>
* \format[WrapFileLinks(\i. \d (\p))]{\file}
* <p/>
* would give the following output:
* 1. John's final report (/home/john/report.pdf)
* <p/>
* If the entry contained a second file link to the file "/home/john/draft.txt" of the
* "Text file" type with description 'An early "draft"', the output would be as follows:
* 1. John's final report (/home/john/report.pdf)
* 2. An early "draft" (/home/john/draft.txt)
* <p/>
* If the formatter was called with a second argument, the list would be filtered.
* For instance:
* \format[WrapFileLinks(\i. \d (\p),text file)]{\file}
* <p/>
* would show only the text file:
* 1. An early "draft" (/home/john/draft.txt)
* <p/>
* If we wanted this output to be part of an XML styled output, the quotes in the
* file description could cause problems. Adding two additional arguments to translate
* the quotes into XML characters solves this:
* \format[WrapFileLinks(\i. \d (\p),text file,",")]{\file}
* <p/>
* would give the following output:
* 1. An early "draft" (/home/john/draft.txt)
* <p/>
* Additional pairs of replacements can be added.
*/
public class WrapFileLinks extends AbstractParamLayoutFormatter {
private static final int STRING = 0;
private static final int ITERATION_COUNT = 1;
private static final int FILE_PATH = 2;
private static final int FILE_TYPE = 3;
private static final int FILE_EXTENSION = 4;
private static final int FILE_DESCRIPTION = 5;
private static final int RELATIVE_FILE_PATH = 6;
// Define which escape sequences give what results:
private static final Map<Character, Integer> ESCAPE_SEQ = new HashMap<>();
static {
WrapFileLinks.ESCAPE_SEQ.put('i', WrapFileLinks.ITERATION_COUNT);
WrapFileLinks.ESCAPE_SEQ.put('p', WrapFileLinks.FILE_PATH);
WrapFileLinks.ESCAPE_SEQ.put('r', WrapFileLinks.RELATIVE_FILE_PATH);
WrapFileLinks.ESCAPE_SEQ.put('f', WrapFileLinks.FILE_TYPE);
WrapFileLinks.ESCAPE_SEQ.put('x', WrapFileLinks.FILE_EXTENSION);
WrapFileLinks.ESCAPE_SEQ.put('d', WrapFileLinks.FILE_DESCRIPTION);
}
private final Map<String, String> replacements = new HashMap<>();
private final List<Path> fileDirectories;
private final String mainFileDirectory;
private String fileType;
private List<FormatEntry> format;
public WrapFileLinks(List<Path> fileDirectories, String mainFileDirectory) {
this.fileDirectories = fileDirectories;
this.mainFileDirectory = mainFileDirectory;
}
/**
* Parse a format string and return a list of FormatEntry objects. The format
* string is basically marked up with "\i" marking that the iteration number should
* be inserted, and with "\p" marking that the file path of the current iteration
* should be inserted, plus additional markers.
*
* @param format The marked-up string.
* @return the resulting format entries.
*/
private static List<FormatEntry> parseFormatString(String format) {
List<FormatEntry> l = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean escaped = false;
for (int i = 0; i < format.length(); i++) {
char c = format.charAt(i);
if (escaped) {
escaped = false; // we know we'll be out of escape mode after this
// Check if this escape sequence is meaningful:
if (c == '\\') {
// Escaped backslash: means that we add a backslash:
sb.append('\\');
} else if (WrapFileLinks.ESCAPE_SEQ.containsKey(c)) {
// Ok, we have the code. Add the previous string (if any) and
// the entry indicated by the escape sequence:
if (sb.length() > 0) {
l.add(new FormatEntry(sb.toString()));
// Clear the buffer:
sb = new StringBuilder();
}
l.add(new FormatEntry(WrapFileLinks.ESCAPE_SEQ.get(c)));
} else {
// Unknown escape sequence.
sb.append('\\');
sb.append(c);
}
} else {
// Check if we are at the start of an escape sequence:
if (c == '\\') {
escaped = true;
} else {
sb.append(c);
}
}
}
// Finished scanning the string. If we collected text at the end, add an entry for it:
if (sb.length() > 0) {
l.add(new FormatEntry(sb.toString()));
}
return l;
}
@Override
public void setArgument(String arg) {
List<String> parts = AbstractParamLayoutFormatter.parseArgument(arg);
format = parseFormatString(parts.get(0));
if ((parts.size() > 1) && !parts.get(1).trim().isEmpty()) {
fileType = parts.get(1);
}
if (parts.size() > 2) {
for (int i = 2; i < (parts.size() - 1); i += 2) {
replacements.put(parts.get(i), parts.get(i + 1));
}
}
}
@Override
public String format(String field) {
if (field == null) {
return "";
}
StringBuilder sb = new StringBuilder();
// Build the list containing the links:
List<LinkedFile> fileList = FileFieldParser.parse(field);
int piv = 1; // counter for relevant iterations
for (LinkedFile flEntry : fileList) {
// Use this entry if we don't discriminate on types, or if the type fits:
if ((fileType == null) || flEntry.getFileType().equalsIgnoreCase(fileType)) {
for (FormatEntry entry : format) {
switch (entry.getType()) {
case STRING:
sb.append(entry.getString());
break;
case ITERATION_COUNT:
sb.append(piv);
break;
case FILE_PATH:
List<Path> dirs;
if (fileDirectories.isEmpty()) {
dirs = Collections.singletonList(Path.of(mainFileDirectory));
} else {
dirs = fileDirectories;
}
String pathString = flEntry.findIn(dirs)
.map(path -> path.toAbsolutePath().toString())
.orElse(flEntry.getLink());
sb.append(replaceStrings(pathString));
break;
case RELATIVE_FILE_PATH:
/*
* Stumbled over this while investigating
*
* https://sourceforge.net/tracker/index.php?func=detail&aid=1469903&group_id=92314&atid=600306
*/
sb.append(replaceStrings(flEntry.getLink())); // f.toURI().toString();
break;
case FILE_EXTENSION:
FileUtil.getFileExtension(flEntry.getLink())
.ifPresent(extension -> sb.append(replaceStrings(extension)));
break;
case FILE_TYPE:
sb.append(replaceStrings(flEntry.getFileType()));
break;
case FILE_DESCRIPTION:
sb.append(replaceStrings(flEntry.getDescription()));
break;
default:
break;
}
}
piv++; // update counter
}
}
return sb.toString();
}
private String replaceStrings(String text) {
String result = text;
for (Map.Entry<String, String> stringStringEntry : replacements.entrySet()) {
String to = stringStringEntry.getValue();
result = result.replaceAll(stringStringEntry.getKey(), to);
}
return result;
}
/**
* This class defines the building blocks of a parsed format strings. Each FormatEntry
* represents either a literal string or a piece of information pertaining to the file
* link to be exported or to the iteration through a series of file links. For literal
* strings this class encapsulates the literal itself, while for other types of information,
* only a type code is provided, and the subclass needs to fill in the proper information
* based on the file link to be exported or the iteration status.
*/
static class FormatEntry {
private final int type;
private String string;
public FormatEntry(int type) {
this.type = type;
}
public FormatEntry(String value) {
this.type = WrapFileLinks.STRING;
this.string = value;
}
public int getType() {
return type;
}
public String getString() {
return string;
}
}
}
| 11,631 | 40.102473 | 123 | java |
null | jabref-main/src/main/java/org/jabref/logic/layout/format/XMLChars.java | package org.jabref.logic.layout.format;
import java.util.HashMap;
import java.util.Map;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.logic.util.strings.XmlCharsMap;
/**
* Changes {\^o} or {\^{o}} to ?
*/
public class XMLChars implements LayoutFormatter {
private static final XmlCharsMap XML_CHARS = new XmlCharsMap();
private static final Map<String, String> ASCII_TO_XML_CHARS = new HashMap<>();
private boolean[] forceReplace;
static {
ASCII_TO_XML_CHARS.put("<", "<");
ASCII_TO_XML_CHARS.put("\"", """);
ASCII_TO_XML_CHARS.put(">", ">");
}
@Override
public String format(String fieldText) {
if (fieldText == null) {
return fieldText;
}
String latexCommandFree = removeLatexCommands(fieldText);
String formattedFieldText = firstFormat(latexCommandFree);
for (Map.Entry<String, String> entry : XML_CHARS.entrySet()) {
String s = entry.getKey();
String repl = entry.getValue();
if (repl != null) {
formattedFieldText = formattedFieldText.replaceAll(s, repl);
}
}
return restFormat(formattedFieldText);
}
private String removeLatexCommands(String fieldText) {
LatexToUnicodeFormatter latexToUnicode = new LatexToUnicodeFormatter();
return latexToUnicode.format(fieldText);
}
private static String firstFormat(String s) {
return s.replaceAll("&|\\\\&", "&").replace("--", "–");
}
private String restFormat(String toFormat) {
String fieldText = toFormat.replace("}", "").replace("{", "");
// now some copy-paste problems most often occuring in abstracts when
// copied from PDF
// AND: this is accepted in the abstract of bibtex files, so are forced
// to catch those cases
if (forceReplace == null) {
forceReplace = new boolean[126];
for (int i = 0; i < 40; i++) {
forceReplace[i] = true;
}
forceReplace[32] = false;
for (int i : new int[] {44, 45, 63, 64, 94, 95, 96, 124}) {
forceReplace[i] = true;
}
}
StringBuilder buffer = new StringBuilder(fieldText.length() * 2);
for (int i = 0; i < fieldText.length(); i++) {
int code = fieldText.charAt(i);
// Checking the case when the character is already escaped
// Just push "&#" to the buffer and keep going from the next char
if ((code == 38) && (fieldText.charAt(i + 1) == 35)) {
i += 2;
buffer.append("&#");
code = fieldText.charAt(i);
}
// TODO: Check whether > 125 is correct here or whether it should rather be >=
if ((code > 125) || forceReplace[code]) {
buffer.append("&#").append(code).append(';');
} else {
buffer.append((char) code);
}
}
fieldText = buffer.toString();
// use common abbreviations for <, > instead of code
for (Map.Entry<String, String> entry : ASCII_TO_XML_CHARS.entrySet()) {
fieldText = fieldText.replace(entry.getKey(), entry.getValue());
}
return fieldText;
}
}
| 3,370 | 31.728155 | 90 | java |
null | jabref-main/src/main/java/org/jabref/logic/logging/LogMessages.java | package org.jabref.logic.logging;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.tinylog.core.LogEntry;
/**
* This class is used for storing and archiving all message output of JabRef as log events.
* To listen to changes on the stored logs one can bind to the {@code messagesProperty}.
*/
public class LogMessages {
private static LogMessages instance = new LogMessages();
private final ObservableList<LogEntry> messages = FXCollections.observableArrayList();
private LogMessages() {
}
public static LogMessages getInstance() {
return instance;
}
public ObservableList<LogEntry> getMessages() {
return FXCollections.unmodifiableObservableList(messages);
}
public void add(LogEntry event) {
messages.add(event);
}
public void clear() {
messages.clear();
}
}
| 898 | 23.297297 | 91 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/BibTeXConverter.java | package org.jabref.logic.msbib;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Month;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.EntryType;
public class BibTeXConverter {
private static final String MSBIB_PREFIX = "msbib-";
private BibTeXConverter() {
}
/**
* Converts an {@link MSBibEntry} to a {@link BibEntry} for import
*
* @param entry The MsBibEntry to convert
* @return The bib entry
*/
public static BibEntry convert(MSBibEntry entry) {
BibEntry result;
Map<Field, String> fieldValues = new HashMap<>();
EntryType bibTexEntryType = MSBibMapping.getBiblatexEntryType(entry.getType());
result = new BibEntry(bibTexEntryType);
// add String fields
for (Map.Entry<String, String> field : entry.fields.entrySet()) {
String msField = field.getKey();
String value = field.getValue();
if ((value != null) && (MSBibMapping.getBibTeXField(msField) != null)) {
fieldValues.put(MSBibMapping.getBibTeXField(msField), value);
}
}
// Value must be converted
if (fieldValues.containsKey(StandardField.LANGUAGE)) {
int lcid = Integer.valueOf(fieldValues.get(StandardField.LANGUAGE));
fieldValues.put(StandardField.LANGUAGE, MSBibMapping.getLanguage(lcid));
}
addAuthor(fieldValues, StandardField.AUTHOR, entry.authors);
addAuthor(fieldValues, StandardField.BOOKAUTHOR, entry.bookAuthors);
addAuthor(fieldValues, StandardField.EDITOR, entry.editors);
addAuthor(fieldValues, StandardField.TRANSLATOR, entry.translators);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "producername"), entry.producerNames);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "composer"), entry.composers);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "conductor"), entry.conductors);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "performer"), entry.performers);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "writer"), entry.writers);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "director"), entry.directors);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "compiler"), entry.compilers);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "interviewer"), entry.interviewers);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "interviewee"), entry.interviewees);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "inventor"), entry.inventors);
addAuthor(fieldValues, new UnknownField(MSBIB_PREFIX + "counsel"), entry.counsels);
if (entry.pages != null) {
fieldValues.put(StandardField.PAGES, entry.pages.toString("--"));
}
parseStandardNumber(entry.standardNumber, fieldValues);
if (entry.address != null) {
fieldValues.put(StandardField.LOCATION, entry.address);
}
// TODO: ConferenceName is saved as booktitle when converting from MSBIB to BibTeX
if (entry.conferenceName != null) {
fieldValues.put(StandardField.ORGANIZATION, entry.conferenceName);
}
if (entry.dateAccessed != null) {
fieldValues.put(new UnknownField(MSBIB_PREFIX + "accessed"), entry.dateAccessed);
}
if (entry.journalName != null) {
fieldValues.put(StandardField.JOURNAL, entry.journalName);
}
if (entry.month != null) {
Optional<Month> month = Month.parse(entry.month);
month.ifPresent(result::setMonth);
}
if (entry.number != null) {
fieldValues.put(StandardField.NUMBER, entry.number);
}
// set all fields
result.setField(fieldValues);
return result;
}
private static void addAuthor(Map<Field, String> map, Field field, List<MsBibAuthor> authors) {
if (authors == null) {
return;
}
String allAuthors = authors.stream().map(MsBibAuthor::getLastFirst).collect(Collectors.joining(" and "));
map.put(field, allAuthors);
}
private static void parseSingleStandardNumber(String type, Field field, String standardNum, Map<Field, String> map) {
Pattern pattern = Pattern.compile(':' + type + ":(.[^:]+)");
Matcher matcher = pattern.matcher(standardNum);
if (matcher.matches()) {
map.put(field, matcher.group(1));
}
}
private static void parseStandardNumber(String standardNum, Map<Field, String> map) {
if (standardNum == null) {
return;
}
parseSingleStandardNumber("ISBN", StandardField.ISBN, standardNum, map);
parseSingleStandardNumber("ISSN", StandardField.ISSN, standardNum, map);
parseSingleStandardNumber("LCCN", new UnknownField("lccn"), standardNum, map);
parseSingleStandardNumber("MRN", StandardField.MR_NUMBER, standardNum, map);
parseSingleStandardNumber("DOI", StandardField.DOI, standardNum, map);
}
}
| 5,474 | 40.165414 | 121 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MSBibConverter.java | package org.jabref.logic.msbib;
import java.util.ArrayList;
import java.util.List;
import org.jabref.model.entry.Author;
import org.jabref.model.entry.AuthorList;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Month;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.IEEETranEntryType;
import org.jabref.model.entry.types.StandardEntryType;
public class MSBibConverter {
private static final String MSBIB_PREFIX = "msbib-";
private static final String BIBTEX_PREFIX = "BIBTEX_";
private MSBibConverter() {
}
public static MSBibEntry convert(BibEntry entry) {
MSBibEntry result = new MSBibEntry();
// memorize original type
result.fields.put(BIBTEX_PREFIX + "Entry", entry.getType().getName());
// define new type
String msBibType = MSBibMapping.getMSBibEntryType(entry.getType()).name();
result.fields.put("SourceType", msBibType);
for (Field field : entry.getFields()) {
String msBibField = MSBibMapping.getMSBibField(field);
if (msBibField != null) {
String value = entry.getLatexFreeField(field).orElse("");
result.fields.put(msBibField, value);
}
}
// Duplicate: also added as BookTitle
entry.getLatexFreeField(StandardField.BOOKTITLE).ifPresent(booktitle -> result.conferenceName = booktitle);
entry.getLatexFreeField(StandardField.PAGES).ifPresent(pages -> result.pages = new PageNumbers(pages));
entry.getLatexFreeField(new UnknownField(MSBIB_PREFIX + "accessed")).ifPresent(accesed -> result.dateAccessed = accesed);
entry.getLatexFreeField(StandardField.URLDATE).ifPresent(acessed -> result.dateAccessed = acessed);
// TODO: currently this can never happen
if ("SoundRecording".equals(msBibType)) {
result.albumTitle = entry.getLatexFreeField(StandardField.TITLE).orElse(null);
}
// TODO: currently this can never happen
if ("Interview".equals(msBibType)) {
result.broadcastTitle = entry.getLatexFreeField(StandardField.TITLE).orElse(null);
}
result.number = entry.getLatexFreeField(StandardField.NUMBER).orElse(null);
if (entry.getType().equals(IEEETranEntryType.Patent)) {
result.patentNumber = entry.getLatexFreeField(StandardField.NUMBER).orElse(null);
result.number = null;
}
result.day = entry.getFieldOrAliasLatexFree(StandardField.DAY).orElse(null);
result.month = entry.getMonth().map(Month::getFullName).orElse(null);
if (!entry.getLatexFreeField(StandardField.YEAR).isPresent()) {
result.year = entry.getFieldOrAliasLatexFree(StandardField.YEAR).orElse(null);
}
result.journalName = entry.getFieldOrAliasLatexFree(StandardField.JOURNAL).orElse(null);
// Value must be converted
entry.getLatexFreeField(StandardField.LANGUAGE)
.ifPresent(lang -> result.fields.put("LCID", String.valueOf(MSBibMapping.getLCID(lang))));
StringBuilder sbNumber = new StringBuilder();
entry.getLatexFreeField(StandardField.ISBN).ifPresent(isbn -> sbNumber.append(" ISBN: ").append(isbn));
entry.getLatexFreeField(StandardField.ISSN).ifPresent(issn -> sbNumber.append(" ISSN: ").append(issn));
entry.getLatexFreeField(new UnknownField("lccn")).ifPresent(lccn -> sbNumber.append("LCCN: ").append(lccn));
entry.getLatexFreeField(StandardField.MR_NUMBER).ifPresent(mrnumber -> sbNumber.append(" MRN: ").append(mrnumber));
result.standardNumber = sbNumber.toString();
if (result.standardNumber.isEmpty()) {
result.standardNumber = null;
}
result.address = entry.getFieldOrAliasLatexFree(StandardField.ADDRESS).orElse(null);
if (entry.getLatexFreeField(StandardField.TYPE).isPresent()) {
result.thesisType = entry.getLatexFreeField(StandardField.TYPE).get();
} else {
if (entry.getType().equals(StandardEntryType.TechReport)) {
result.thesisType = "Tech. rep.";
} else if (entry.getType().equals(StandardEntryType.MastersThesis)) {
result.thesisType = "Master's thesis";
} else if (entry.getType().equals(StandardEntryType.PhdThesis)) {
result.thesisType = "Ph.D. dissertation";
} else if (entry.getType().equals(StandardEntryType.Unpublished)) {
result.thesisType = "unpublished";
}
}
// TODO: currently this can never happen
if ("InternetSite".equals(msBibType) || "DocumentFromInternetSite".equals(msBibType)) {
result.internetSiteTitle = entry.getLatexFreeField(StandardField.TITLE).orElse(null);
}
// TODO: currently only Misc can happen
if ("ElectronicSource".equals(msBibType) || "Art".equals(msBibType) || "Misc".equals(msBibType)) {
result.publicationTitle = entry.getLatexFreeField(StandardField.TITLE).orElse(null);
}
if (entry.getType().equals(IEEETranEntryType.Patent)) {
entry.getField(StandardField.AUTHOR).ifPresent(authors -> result.inventors = getAuthors(entry, authors, StandardField.AUTHOR));
} else {
entry.getField(StandardField.AUTHOR).ifPresent(authors -> result.authors = getAuthors(entry, authors, StandardField.AUTHOR));
}
entry.getField(StandardField.EDITOR).ifPresent(editors -> result.editors = getAuthors(entry, editors, StandardField.EDITOR));
entry.getField(StandardField.TRANSLATOR).ifPresent(translator -> result.translators = getAuthors(entry, translator, StandardField.EDITOR));
return result;
}
private static List<MsBibAuthor> getAuthors(BibEntry entry, String authors, Field field) {
List<MsBibAuthor> result = new ArrayList<>();
boolean corporate = false;
// Only one corporate author is supported
// We have the possible rare case that are multiple authors which start and end with latex , this is currently not considered
if (authors.startsWith("{") && authors.endsWith("}")) {
corporate = true;
}
// FIXME: #4152 This is an ugly hack because the latex2unicode formatter kills of all curly braces, so no more corporate author parsing possible
String authorLatexFree = entry.getLatexFreeField(field).orElse("");
if (corporate) {
authorLatexFree = "{" + authorLatexFree + "}";
}
AuthorList authorList = AuthorList.parse(authorLatexFree);
for (Author author : authorList.getAuthors()) {
result.add(new MsBibAuthor(author, corporate));
}
return result;
}
}
| 6,910 | 46.013605 | 152 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MSBibDatabase.java | package org.jabref.logic.msbib;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Microsoft Word bibliography.
* The class is uesed both for import and export
* See http://www.ecma-international.org/publications/standards/Ecma-376.htm
*/
public class MSBibDatabase {
public static final String NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography";
public static final String PREFIX = "b:";
private static final Logger LOGGER = LoggerFactory.getLogger(MSBibDatabase.class);
private Set<MSBibEntry> entries;
/**
* Creates a {@link MSBibDatabase} for <b>import</b>
*/
public MSBibDatabase() {
entries = new HashSet<>();
}
// TODO: why an additonal entry list? entries are included inside database!
/**
* Creates a new {@link MSBibDatabase} for <b>export</b>
*
* @param database The bib database
* @param entries List of {@link BibEntry}
*/
public MSBibDatabase(BibDatabase database, List<BibEntry> entries) {
if (entries == null) {
var resolvedEntries = database.resolveForStrings(database.getEntries(), false);
addEntriesForExport(resolvedEntries);
} else {
var resolvedEntries = database.resolveForStrings(entries, false);
addEntriesForExport(resolvedEntries);
}
}
/**
* Imports entries from an office xml file
*
* @return List of {@link BibEntry}
*/
public List<BibEntry> importEntriesFromXml(BufferedReader reader) {
entries = new HashSet<>();
Document inputDocument;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
inputDocument = documentBuilder.parse(new InputSource(reader));
} catch (ParserConfigurationException | SAXException | IOException e) {
LOGGER.warn("Could not parse document", e);
return Collections.emptyList();
}
NodeList rootList = inputDocument.getElementsByTagNameNS("*", "Sources");
if (rootList.getLength() == 0) {
rootList = inputDocument.getElementsByTagNameNS("*", "Sources");
}
List<BibEntry> bibitems = new ArrayList<>();
if (rootList.getLength() == 0) {
return bibitems;
}
NodeList sourceList = ((Element) rootList.item(0)).getElementsByTagNameNS("*", "Source");
for (int i = 0; i < sourceList.getLength(); i++) {
MSBibEntry entry = new MSBibEntry((Element) sourceList.item(i));
entries.add(entry);
bibitems.add(BibTeXConverter.convert(entry));
}
return bibitems;
}
private void addEntriesForExport(List<BibEntry> entriesToAdd) {
entries = new HashSet<>();
for (BibEntry entry : entriesToAdd) {
MSBibEntry newMods = MSBibConverter.convert(entry);
entries.add(newMods);
}
}
/**
* Gets the assembled dom for export
*
* @return XML Document
*/
public Document getDomForExport() {
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
document = documentBuilder.newDocument();
Element rootNode = document.createElementNS(NAMESPACE, PREFIX + "Sources");
rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", NAMESPACE);
rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:" + PREFIX.substring(0, PREFIX.length() - 1), NAMESPACE);
rootNode.setAttribute("SelectedStyle", "");
for (MSBibEntry entry : entries) {
Node node = entry.getEntryDom(document);
rootNode.appendChild(node);
}
document.appendChild(rootNode);
} catch (ParserConfigurationException e) {
LOGGER.warn("Could not build XML document", e);
}
return document;
}
}
| 4,873 | 33.814286 | 112 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MSBibEntry.java | package org.jabref.logic.msbib;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jabref.model.entry.Author;
import org.jabref.model.entry.AuthorList;
import org.jabref.model.entry.Date;
import org.jabref.model.entry.Month;
import org.jabref.model.strings.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* MSBib entry representation
*
* @see <a href="http://mahbub.wordpress.com/2007/03/24/details-of-microsoft-office-2007-bibliographic-format-compared-to-bibtex/">ms office 2007 bibliography format compared to bibtex</a>
* @see <a href="http://mahbub.wordpress.com/2007/03/22/deciphering-microsoft-office-2007-bibliography-format/">deciphering ms office 2007 bibliography format</a>
* @see <a href="http://www.ecma-international.org/publications/standards/Ecma-376.htm">ECMA Standard</a>
*/
class MSBibEntry {
// MSBib fields and values
public Map<String, String> fields = new HashMap<>();
public List<MsBibAuthor> authors;
public List<MsBibAuthor> bookAuthors;
public List<MsBibAuthor> editors;
public List<MsBibAuthor> translators;
public List<MsBibAuthor> producerNames;
public List<MsBibAuthor> composers;
public List<MsBibAuthor> conductors;
public List<MsBibAuthor> performers;
public List<MsBibAuthor> writers;
public List<MsBibAuthor> directors;
public List<MsBibAuthor> compilers;
public List<MsBibAuthor> interviewers;
public List<MsBibAuthor> interviewees;
public List<MsBibAuthor> inventors;
public List<MsBibAuthor> counsels;
public PageNumbers pages;
public String standardNumber;
public String address;
public String conferenceName;
public String thesisType;
public String internetSiteTitle;
public String dateAccessed;
public String publicationTitle;
public String albumTitle;
public String broadcastTitle;
public String year;
public String month;
public String day;
public String number;
public String patentNumber;
public String journalName;
private String bibtexEntryType;
/**
* reduced subset, supports only "CITY , STATE, COUNTRY" <br>
* <b>\b(\w+)\s?[,]?\s?(\w+)\s?[,]?\s?(\w*)\b</b> <br>
* WORD SPACE , SPACE WORD SPACE (Can be zero or more) , SPACE WORD (Can be zero or more) <br>
* Matches both single locations (only city) like Berlin and full locations like Stroudsburg, PA, USA <br>
* tested using http://www.regexpal.com/
*/
private final Pattern ADDRESS_PATTERN = Pattern.compile("\\b(\\w+)\\s?[,]?\\s?(\\w*)\\s?[,]?\\s?(\\w*)\\b");
public MSBibEntry() {
// empty
}
/**
* Create a new {@link MsBibEntry} to import from an xml element
*/
public MSBibEntry(Element entry) {
populateFromXml(entry);
}
public String getType() {
return fields.get("SourceType");
}
public String getCiteKey() {
return fields.get("Tag");
}
private String getXmlElementTextContent(String name, Element entry) {
String value = null;
NodeList nodeLst = entry.getElementsByTagNameNS("*", name);
if (nodeLst.getLength() > 0) {
value = nodeLst.item(0).getTextContent();
}
return value;
}
private void populateFromXml(Element entry) {
for (int i = 0; i < entry.getChildNodes().getLength(); i++) {
Node node = entry.getChildNodes().item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String key = node.getLocalName();
String value = node.getTextContent();
if ("SourceType".equals(key)) {
this.bibtexEntryType = value;
}
fields.put(key, value);
}
}
String temp = getXmlElementTextContent("Pages", entry);
if (temp != null) {
pages = new PageNumbers(temp);
}
standardNumber = getXmlElementTextContent("StandardNumber", entry);
conferenceName = getXmlElementTextContent("ConferenceName", entry);
String city = getXmlElementTextContent("City", entry);
String state = getXmlElementTextContent("StateProvince", entry);
String country = getXmlElementTextContent("CountryRegion", entry);
StringBuilder addressBuffer = new StringBuilder();
if (city != null) {
addressBuffer.append(city);
}
if (((state != null) && !state.isEmpty()) && ((city != null) && !city.isEmpty())) {
addressBuffer.append(",").append(' ');
addressBuffer.append(state);
}
if ((country != null) && !country.isEmpty()) {
addressBuffer.append(",").append(' ');
addressBuffer.append(country);
}
address = addressBuffer.toString().trim();
if (address.isEmpty() || ",".equals(address)) {
address = null;
}
if ("Patent".equalsIgnoreCase(bibtexEntryType)) {
number = getXmlElementTextContent("PatentNumber", entry);
}
journalName = getXmlElementTextContent("JournalName", entry);
month = getXmlElementTextContent("Month", entry);
internetSiteTitle = getXmlElementTextContent("InternetSiteTitle", entry);
String monthAccessed = getXmlElementTextContent("MonthAccessed", entry);
String dayAccessed = getXmlElementTextContent("DayAccessed", entry);
String yearAccessed = getXmlElementTextContent("YearAccessed", entry);
Optional<Date> parsedDateAcessed = Date.parse(Optional.ofNullable(yearAccessed),
Optional.ofNullable(monthAccessed),
Optional.ofNullable(dayAccessed));
parsedDateAcessed.map(Date::getNormalized).ifPresent(date -> dateAccessed = date);
NodeList nodeLst = entry.getElementsByTagNameNS("*", "Author");
if (nodeLst.getLength() > 0) {
getAuthors((Element) nodeLst.item(0));
}
}
private void getAuthors(Element authorsElem) {
authors = getSpecificAuthors("Author", authorsElem);
bookAuthors = getSpecificAuthors("BookAuthor", authorsElem);
editors = getSpecificAuthors("Editor", authorsElem);
translators = getSpecificAuthors("Translator", authorsElem);
producerNames = getSpecificAuthors("ProducerName", authorsElem);
composers = getSpecificAuthors("Composer", authorsElem);
conductors = getSpecificAuthors("Conductor", authorsElem);
performers = getSpecificAuthors("Performer", authorsElem);
writers = getSpecificAuthors("Writer", authorsElem);
directors = getSpecificAuthors("Director", authorsElem);
compilers = getSpecificAuthors("Compiler", authorsElem);
interviewers = getSpecificAuthors("Interviewer", authorsElem);
interviewees = getSpecificAuthors("Interviewee", authorsElem);
inventors = getSpecificAuthors("Inventor", authorsElem);
counsels = getSpecificAuthors("Counsel", authorsElem);
}
private List<MsBibAuthor> getSpecificAuthors(String type, Element authors) {
List<MsBibAuthor> result = null;
NodeList nodeLst = authors.getElementsByTagNameNS("*", type);
if (nodeLst.getLength() <= 0) {
return result;
}
nodeLst = ((Element) nodeLst.item(0)).getElementsByTagNameNS("*", "NameList");
if (nodeLst.getLength() <= 0) {
return result;
}
NodeList person = ((Element) nodeLst.item(0)).getElementsByTagNameNS("*", "Person");
if (person.getLength() <= 0) {
return result;
}
result = new LinkedList<>();
for (int i = 0; i < person.getLength(); i++) {
NodeList firstName = ((Element) person.item(i)).getElementsByTagNameNS("*", "First");
NodeList lastName = ((Element) person.item(i)).getElementsByTagNameNS("*", "Last");
NodeList middleName = ((Element) person.item(i)).getElementsByTagNameNS("*", "Middle");
StringBuilder sb = new StringBuilder();
if (firstName.getLength() > 0) {
sb.append(firstName.item(0).getTextContent());
sb.append(" ");
}
if (middleName.getLength() > 0) {
sb.append(middleName.item(0).getTextContent());
sb.append(" ");
}
if (lastName.getLength() > 0) {
sb.append(lastName.item(0).getTextContent());
}
AuthorList authorList = AuthorList.parse(sb.toString());
for (Author author : authorList.getAuthors()) {
result.add(new MsBibAuthor(author));
}
}
return result;
}
/**
* Gets the dom representation for one entry, used for export
*
* @param document XmlDocument
* @return XmlElement represenation of one entry
*/
public Element getEntryDom(Document document) {
Element rootNode = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + "Source");
for (Map.Entry<String, String> entry : fields.entrySet()) {
addField(document, rootNode, entry.getKey(), entry.getValue());
}
Optional.ofNullable(dateAccessed).ifPresent(field -> addDateAcessedFields(document, rootNode));
Element allAuthors = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + "Author");
addAuthor(document, allAuthors, "Author", authors);
addAuthor(document, allAuthors, "BookAuthor", bookAuthors);
addAuthor(document, allAuthors, "Editor", editors);
addAuthor(document, allAuthors, "Translator", translators);
addAuthor(document, allAuthors, "ProducerName", producerNames);
addAuthor(document, allAuthors, "Composer", composers);
addAuthor(document, allAuthors, "Conductor", conductors);
addAuthor(document, allAuthors, "Performer", performers);
addAuthor(document, allAuthors, "Writer", writers);
addAuthor(document, allAuthors, "Director", directors);
addAuthor(document, allAuthors, "Compiler", compilers);
addAuthor(document, allAuthors, "Interviewer", interviewers);
addAuthor(document, allAuthors, "Interviewee", interviewees);
addAuthor(document, allAuthors, "Inventor", inventors);
addAuthor(document, allAuthors, "Counsel", counsels);
rootNode.appendChild(allAuthors);
if (pages != null) {
addField(document, rootNode, "Pages", pages.toString("-"));
}
addField(document, rootNode, "Year", year);
addField(document, rootNode, "Month", month);
addField(document, rootNode, "Day", day);
addField(document, rootNode, "JournalName", journalName);
addField(document, rootNode, "PatentNumber", patentNumber);
addField(document, rootNode, "Number", number);
addField(document, rootNode, "StandardNumber", standardNumber);
addField(document, rootNode, "ConferenceName", conferenceName);
addAddress(document, rootNode, address);
addField(document, rootNode, "ThesisType", thesisType);
addField(document, rootNode, "InternetSiteTitle", internetSiteTitle);
addField(document, rootNode, "PublicationTitle", publicationTitle);
addField(document, rootNode, "AlbumTitle", albumTitle);
addField(document, rootNode, "BroadcastTitle", broadcastTitle);
return rootNode;
}
private void addField(Document document, Element parent, String name, String value) {
if (value == null) {
return;
}
Element elem = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + name);
elem.appendChild(document.createTextNode(StringUtil.stripNonValidXMLCharacters(value)));
parent.appendChild(elem);
}
// Add authors for export
private void addAuthor(Document document, Element allAuthors, String entryName, List<MsBibAuthor> authorsLst) {
if (authorsLst == null) {
return;
}
Element authorTop = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + entryName);
Optional<MsBibAuthor> personName = authorsLst.stream().filter(MsBibAuthor::isCorporate)
.findFirst();
if (personName.isPresent()) {
MsBibAuthor person = personName.get();
Element corporate = document.createElementNS(MSBibDatabase.NAMESPACE,
MSBibDatabase.PREFIX + "Corporate");
corporate.setTextContent(person.getFirstLast());
authorTop.appendChild(corporate);
} else {
Element nameList = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + "NameList");
for (MsBibAuthor name : authorsLst) {
Element person = document.createElementNS(MSBibDatabase.NAMESPACE, MSBibDatabase.PREFIX + "Person");
addField(document, person, "Last", name.getLastName());
addField(document, person, "Middle", name.getMiddleName());
addField(document, person, "First", name.getFirstName());
nameList.appendChild(person);
}
authorTop.appendChild(nameList);
}
allAuthors.appendChild(authorTop);
}
private void addDateAcessedFields(Document document, Element rootNode) {
Optional<Date> parsedDateAcesseField = Date.parse(dateAccessed);
parsedDateAcesseField.flatMap(Date::getYear).map(Object::toString).ifPresent(yearAccessed -> {
addField(document, rootNode, "Year" + "Accessed", yearAccessed);
});
parsedDateAcesseField.flatMap(Date::getMonth)
.map(Month::getFullName).ifPresent(monthAcessed -> {
addField(document, rootNode, "Month" + "Accessed", monthAcessed);
});
parsedDateAcesseField.flatMap(Date::getDay).map(Object::toString).ifPresent(dayAccessed -> {
addField(document, rootNode, "Day" + "Accessed", dayAccessed);
});
}
private void addAddress(Document document, Element parent, String addressToSplit) {
if (addressToSplit == null) {
return;
}
Matcher matcher = ADDRESS_PATTERN.matcher(addressToSplit);
if (addressToSplit.contains(",") && matcher.matches() && (matcher.groupCount() >= 3)) {
addField(document, parent, "City", matcher.group(1));
addField(document, parent, "StateProvince", matcher.group(2));
addField(document, parent, "CountryRegion", matcher.group(3));
} else {
addField(document, parent, "City", addressToSplit);
}
}
}
| 15,021 | 39.820652 | 188 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MSBibEntryType.java | package org.jabref.logic.msbib;
/**
* This class represents all supported MSBib entry types.
* <p>
* Book, BookSection, JournalArticle, ArticleInAPeriodical, ConferenceProceedings, Report,
* InternetSite, DocumentFromInternetSite, ElectronicSource, Art, SoundRecording, Performance,
* Film, Interview, Patent, Case, Misc
*
* See BIBFORM.XML, shared-bibliography.xsd (ECMA standard)
*/
public enum MSBibEntryType {
ArticleInAPeriodical,
Book,
BookSection,
JournalArticle,
ConferenceProceedings,
Report,
SoundRecording,
Performance,
Art,
DocumentFromInternetSite,
InternetSite,
Film,
Interview,
Patent,
ElectronicSource,
Case,
Misc
}
| 709 | 21.903226 | 94 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MSBibMapping.java | package org.jabref.logic.msbib;
import java.util.HashMap;
import java.util.Map;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.IEEETranEntryType;
import org.jabref.model.entry.types.StandardEntryType;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* Mapping between Msbib and biblatex All Fields: <a href = "https://msdn.microsoft.com/de-de/library/office/documentformat.openxml.bibliography">List
* of all MSBib fields</a>
*/
public class MSBibMapping {
private static final String BIBTEX_PREFIX = "BIBTEX_";
private static final String MSBIB_PREFIX = "msbib-";
private static final BiMap<Field, String> BIBLATEX_TO_MS_BIB = HashBiMap.create();
// see https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a
private static final BiMap<String, Integer> LANG_TO_LCID = HashBiMap.create();
static {
LANG_TO_LCID.put("basque", 1609);
LANG_TO_LCID.put("bulgarian", 1026);
LANG_TO_LCID.put("catalan", 1027);
LANG_TO_LCID.put("croatian", 1050);
LANG_TO_LCID.put("czech", 1029);
LANG_TO_LCID.put("danish", 1030);
LANG_TO_LCID.put("dutch", 1043);
LANG_TO_LCID.put("english", 1033); // american english
LANG_TO_LCID.put("finnish", 1035);
LANG_TO_LCID.put("french", 1036);
LANG_TO_LCID.put("german", 1031);
LANG_TO_LCID.put("austrian", 3079);
LANG_TO_LCID.put("swissgerman", 2055);
LANG_TO_LCID.put("greek", 1032);
LANG_TO_LCID.put("hungarian", 1038);
LANG_TO_LCID.put("icelandic", 1039);
LANG_TO_LCID.put("italian", 1040);
LANG_TO_LCID.put("latvian", 1062);
LANG_TO_LCID.put("lithuanian", 1063);
LANG_TO_LCID.put("marathi", 1102);
LANG_TO_LCID.put("nynorsk", 2068);
LANG_TO_LCID.put("polish", 1045);
LANG_TO_LCID.put("brazil", 1046);
LANG_TO_LCID.put("portuguese", 2070);
LANG_TO_LCID.put("romanian", 1048);
LANG_TO_LCID.put("russian", 1049);
LANG_TO_LCID.put("serbian", 2074);
LANG_TO_LCID.put("serbianc", 3098);
LANG_TO_LCID.put("slovak", 1051);
LANG_TO_LCID.put("slovene", 1060);
LANG_TO_LCID.put("spanish", 3082);
LANG_TO_LCID.put("swedish", 1053);
LANG_TO_LCID.put("turkish", 1055);
LANG_TO_LCID.put("ukrainian", 1058);
}
static {
BIBLATEX_TO_MS_BIB.put(InternalField.KEY_FIELD, "Tag");
BIBLATEX_TO_MS_BIB.put(StandardField.TITLE, "Title");
BIBLATEX_TO_MS_BIB.put(StandardField.YEAR, "Year");
BIBLATEX_TO_MS_BIB.put(StandardField.VOLUME, "Volume");
BIBLATEX_TO_MS_BIB.put(StandardField.LANGUAGE, "LCID");
BIBLATEX_TO_MS_BIB.put(StandardField.EDITION, "Edition");
BIBLATEX_TO_MS_BIB.put(StandardField.PUBLISHER, "Publisher");
BIBLATEX_TO_MS_BIB.put(StandardField.BOOKTITLE, "BookTitle");
BIBLATEX_TO_MS_BIB.put(StandardField.SHORTTITLE, "ShortTitle");
BIBLATEX_TO_MS_BIB.put(StandardField.NOTE, "Comments");
BIBLATEX_TO_MS_BIB.put(StandardField.VOLUMES, "NumberVolumes");
BIBLATEX_TO_MS_BIB.put(StandardField.CHAPTER, "ChapterNumber");
BIBLATEX_TO_MS_BIB.put(StandardField.ISSUE, "Issue");
BIBLATEX_TO_MS_BIB.put(StandardField.SCHOOL, "Department");
BIBLATEX_TO_MS_BIB.put(StandardField.INSTITUTION, "Institution");
BIBLATEX_TO_MS_BIB.put(StandardField.DOI, "DOI");
BIBLATEX_TO_MS_BIB.put(StandardField.URL, "URL");
// BibTeX/Biblatex only fields
BIBLATEX_TO_MS_BIB.put(StandardField.SERIES, BIBTEX_PREFIX + "Series");
BIBLATEX_TO_MS_BIB.put(StandardField.ABSTRACT, BIBTEX_PREFIX + "Abstract");
BIBLATEX_TO_MS_BIB.put(StandardField.KEYWORDS, BIBTEX_PREFIX + "KeyWords");
BIBLATEX_TO_MS_BIB.put(StandardField.CROSSREF, BIBTEX_PREFIX + "CrossRef");
BIBLATEX_TO_MS_BIB.put(StandardField.HOWPUBLISHED, BIBTEX_PREFIX + "HowPublished");
BIBLATEX_TO_MS_BIB.put(StandardField.PUBSTATE, BIBTEX_PREFIX + "Pubstate");
BIBLATEX_TO_MS_BIB.put(new UnknownField("affiliation"), BIBTEX_PREFIX + "Affiliation");
BIBLATEX_TO_MS_BIB.put(new UnknownField("contents"), BIBTEX_PREFIX + "Contents");
BIBLATEX_TO_MS_BIB.put(new UnknownField("copyright"), BIBTEX_PREFIX + "Copyright");
BIBLATEX_TO_MS_BIB.put(new UnknownField("price"), BIBTEX_PREFIX + "Price");
BIBLATEX_TO_MS_BIB.put(new UnknownField("size"), BIBTEX_PREFIX + "Size");
BIBLATEX_TO_MS_BIB.put(new UnknownField("intype"), BIBTEX_PREFIX + "InType");
BIBLATEX_TO_MS_BIB.put(new UnknownField("paper"), BIBTEX_PREFIX + "Paper");
BIBLATEX_TO_MS_BIB.put(StandardField.KEY, BIBTEX_PREFIX + "Key");
// MSBib only fields
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "periodical"), "PeriodicalTitle");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + StandardField.DAY), "Day");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "accessed"), "Accessed");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "medium"), "Medium");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "recordingnumber"), "RecordingNumber");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "theater"), "Theater");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "distributor"), "Distributor");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "broadcaster"), "Broadcaster");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "station"), "Station");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + StandardField.TYPE), "Type");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "court"), "Court");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "reporter"), "Reporter");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "casenumber"), "CaseNumber");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "abbreviatedcasenumber"), "AbbreviatedCaseNumber");
BIBLATEX_TO_MS_BIB.put(new UnknownField(MSBIB_PREFIX + "productioncompany"), "ProductionCompany");
}
private MSBibMapping() {
}
public static EntryType getBiblatexEntryType(String msbibType) {
Map<String, EntryType> entryTypeMapping = new HashMap<>();
entryTypeMapping.put("Book", StandardEntryType.Book);
entryTypeMapping.put("BookSection", StandardEntryType.Book);
entryTypeMapping.put("JournalArticle", StandardEntryType.Article);
entryTypeMapping.put("ArticleInAPeriodical", IEEETranEntryType.Periodical);
entryTypeMapping.put("ConferenceProceedings", StandardEntryType.InProceedings);
entryTypeMapping.put("Report", StandardEntryType.TechReport);
entryTypeMapping.put("Patent", IEEETranEntryType.Patent);
entryTypeMapping.put("InternetSite", StandardEntryType.Online);
return entryTypeMapping.getOrDefault(msbibType, StandardEntryType.Misc);
}
public static MSBibEntryType getMSBibEntryType(EntryType bibtexType) {
Map<EntryType, MSBibEntryType> entryTypeMapping = new HashMap<>();
entryTypeMapping.put(StandardEntryType.Book, MSBibEntryType.Book);
entryTypeMapping.put(StandardEntryType.InBook, MSBibEntryType.BookSection);
entryTypeMapping.put(StandardEntryType.Booklet, MSBibEntryType.BookSection);
entryTypeMapping.put(StandardEntryType.InCollection, MSBibEntryType.BookSection);
entryTypeMapping.put(StandardEntryType.Article, MSBibEntryType.JournalArticle);
entryTypeMapping.put(StandardEntryType.InProceedings, MSBibEntryType.ConferenceProceedings);
entryTypeMapping.put(StandardEntryType.Conference, MSBibEntryType.ConferenceProceedings);
entryTypeMapping.put(StandardEntryType.Proceedings, MSBibEntryType.ConferenceProceedings);
entryTypeMapping.put(StandardEntryType.Collection, MSBibEntryType.ConferenceProceedings);
entryTypeMapping.put(StandardEntryType.TechReport, MSBibEntryType.Report);
entryTypeMapping.put(StandardEntryType.Manual, MSBibEntryType.Report);
entryTypeMapping.put(StandardEntryType.MastersThesis, MSBibEntryType.Report);
entryTypeMapping.put(StandardEntryType.PhdThesis, MSBibEntryType.Report);
entryTypeMapping.put(StandardEntryType.Unpublished, MSBibEntryType.Report);
entryTypeMapping.put(IEEETranEntryType.Patent, MSBibEntryType.Patent);
entryTypeMapping.put(StandardEntryType.Misc, MSBibEntryType.Misc);
entryTypeMapping.put(IEEETranEntryType.Electronic, MSBibEntryType.ElectronicSource);
entryTypeMapping.put(StandardEntryType.Online, MSBibEntryType.InternetSite);
return entryTypeMapping.getOrDefault(bibtexType, MSBibEntryType.Misc);
}
/**
* <a href="http://www.microsoft.com/globaldev/reference/lcid-all.mspx">All LCID codes</a>
*
* @param language The language to transform
* @return 1033 (american english) as default. LCID otherwise.
*/
public static int getLCID(String language) {
return LANG_TO_LCID.getOrDefault(language, 1033);
}
/**
* <a href="http://www.microsoft.com/globaldev/reference/lcid-all.mspx">All LCID codes</a>
*
* @param LCID The LCID to transform
* @return "english" as default. Corresponding language from BiMap otherwise.
*/
public static String getLanguage(int LCID) {
return LANG_TO_LCID.inverse().getOrDefault(LCID, "english");
}
public static String getMSBibField(Field field) {
return BIBLATEX_TO_MS_BIB.get(field);
}
public static Field getBibTeXField(String msbibFieldName) {
return BIBLATEX_TO_MS_BIB.inverse().get(msbibFieldName);
}
}
| 10,080 | 50.963918 | 150 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/MsBibAuthor.java | package org.jabref.logic.msbib;
import org.jabref.model.entry.Author;
public class MsBibAuthor {
private String firstName;
private String middleName;
private final Author author;
private boolean isCorporate;
public MsBibAuthor(Author author) {
this.author = author;
StringBuilder sb = new StringBuilder();
author.getFirst().ifPresent(firstNames -> {
String[] names = firstNames.split(" ");
for (int i = 1; i < names.length; i++) {
sb.append(names[i]);
sb.append(" ");
}
this.middleName = sb.toString().trim();
this.firstName = names[0];
});
}
public MsBibAuthor(Author author, boolean isCorporate) {
this(author);
this.isCorporate = isCorporate;
}
public String getFirstName() {
if (!"".equals(firstName)) {
return firstName;
}
return author.getFirst().orElse(null);
}
public String getMiddleName() {
if ("".equals(middleName)) {
return null;
}
return middleName;
}
public String getLastName() {
return author.getLastOnly();
}
public String getFirstLast() {
return author.getFirstLast(false);
}
public String getLastFirst() {
return author.getLastFirst(false);
}
public boolean isCorporate() {
return isCorporate;
}
}
| 1,455 | 22.111111 | 60 | java |
null | jabref-main/src/main/java/org/jabref/logic/msbib/PageNumbers.java | package org.jabref.logic.msbib;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class PageNumbers {
private static final Pattern PAGE_PATTERN = Pattern.compile("\\s*(\\d+)\\s*-{1,2}\\s*(\\d+)\\s*");
private String freeform;
private int start;
private int end;
public PageNumbers(String pages) {
parsePageNums(pages);
}
private void parsePageNums(String pages) {
Matcher matcher = PAGE_PATTERN.matcher(pages);
if (matcher.matches()) {
start = Integer.parseInt(matcher.group(1));
end = Integer.parseInt(matcher.group(2));
} else {
freeform = pages;
}
}
public Element getDOMrepresentation(Document document) {
Element result = document.createElement("extent");
result.setAttribute("unit", "page");
if (freeform == null) {
Element tmpStart = document.createElement("start");
Element tmpEnd = document.createElement("end");
tmpStart.appendChild(document.createTextNode(String.valueOf(this.start)));
tmpEnd.appendChild(document.createTextNode(String.valueOf(this.end)));
result.appendChild(tmpStart);
result.appendChild(tmpEnd);
} else {
Node textNode = document.createTextNode(freeform);
result.appendChild(textNode);
}
return result;
}
public String toString(String separator) {
if (freeform != null) {
return freeform;
}
return start + separator + end;
}
@Override
public String toString() {
return toString("-");
}
}
| 1,754 | 28.25 | 102 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ProgressInputStream.java | package org.jabref.logic.net;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
/**
* An input stream that keeps track of the amount of bytes already read.
* Code based on http://stackoverflow.com/a/1339589/873661, but converted to use JavaFX properties instead of listeners
*/
public class ProgressInputStream extends FilterInputStream {
private final long maxNumBytes;
private final LongProperty totalNumBytesRead;
private final LongProperty progress;
public ProgressInputStream(InputStream in, long maxNumBytes) {
super(in);
this.totalNumBytesRead = new SimpleLongProperty(0);
this.progress = new SimpleLongProperty(0);
this.maxNumBytes = maxNumBytes <= 0 ? 1 : maxNumBytes;
this.progress.bind(totalNumBytesRead.divide(this.maxNumBytes));
}
public long getTotalNumBytesRead() {
return totalNumBytesRead.get();
}
public LongProperty totalNumBytesReadProperty() {
return totalNumBytesRead;
}
public long getProgress() {
return progress.get();
}
public LongProperty progressProperty() {
return progress;
}
public long getMaxNumBytes() {
return maxNumBytes;
}
@Override
public int read() throws IOException {
int b = super.read();
updateProgress(1);
return b;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return (int) updateProgress(super.read(b, off, len));
}
@Override
public long skip(long n) throws IOException {
return updateProgress(super.skip(n));
}
@Override
public void mark(int readlimit) {
throw new UnsupportedOperationException();
}
@Override
public void reset() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public boolean markSupported() {
return false;
}
private long updateProgress(long numBytesRead) {
if (numBytesRead > 0) {
totalNumBytesRead.set(totalNumBytesRead.get() + numBytesRead);
}
return numBytesRead;
}
}
| 2,269 | 24.505618 | 119 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ProxyAuthenticator.java | package org.jabref.logic.net;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.Locale;
public class ProxyAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
String prot = getRequestingProtocol().toLowerCase(Locale.ROOT);
String host = System.getProperty(prot + ".proxyHost", "");
String port = System.getProperty(prot + ".proxyPort", "80");
String user = System.getProperty(prot + ".proxyUser", "");
String password = System.getProperty(prot + ".proxyPassword", "");
if (getRequestingHost().equalsIgnoreCase(host) && (Integer.parseInt(port) == getRequestingPort())) {
return new PasswordAuthentication(user, password.toCharArray());
}
}
return null;
}
}
| 940 | 38.208333 | 112 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ProxyPreferences.java | package org.jabref.logic.net;
import java.util.Objects;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ProxyPreferences {
private final BooleanProperty useProxy;
private final StringProperty hostname;
private final StringProperty port;
private final BooleanProperty useAuthentication;
private final StringProperty username;
private final StringProperty password;
private final BooleanProperty persistPassword;
public ProxyPreferences(Boolean useProxy,
String hostname,
String port,
Boolean useAuthentication,
String username,
String password,
boolean persistPassword) {
this.useProxy = new SimpleBooleanProperty(useProxy);
this.hostname = new SimpleStringProperty(hostname);
this.port = new SimpleStringProperty(port);
this.useAuthentication = new SimpleBooleanProperty(useAuthentication);
this.username = new SimpleStringProperty(username);
this.password = new SimpleStringProperty(password);
this.persistPassword = new SimpleBooleanProperty(persistPassword);
}
public final boolean shouldUseProxy() {
return useProxy.getValue();
}
public BooleanProperty useProxyProperty() {
return useProxy;
}
public void setUseProxy(boolean useProxy) {
this.useProxy.set(useProxy);
}
public final String getHostname() {
return hostname.getValue();
}
public StringProperty hostnameProperty() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname.set(hostname);
}
public final String getPort() {
return port.getValue();
}
public StringProperty portProperty() {
return port;
}
public void setPort(String port) {
this.port.set(port);
}
public final boolean shouldUseAuthentication() {
return useAuthentication.get();
}
public BooleanProperty useAuthenticationProperty() {
return useAuthentication;
}
public void setUseAuthentication(boolean useAuthentication) {
this.useAuthentication.set(useAuthentication);
}
public final String getUsername() {
return username.getValue();
}
public StringProperty usernameProperty() {
return username;
}
public void setUsername(String username) {
this.username.set(username);
}
public final String getPassword() {
return password.getValue();
}
public StringProperty passwordProperty() {
return password;
}
public void setPassword(String password) {
this.password.set(password);
}
public boolean shouldPersistPassword() {
return persistPassword.get();
}
public BooleanProperty persistPasswordProperty() {
return persistPassword;
}
public void setPersistPassword(boolean persistPassword) {
this.persistPassword.set(persistPassword);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProxyPreferences other = (ProxyPreferences) o;
return Objects.equals(useProxy.getValue(), other.useProxy.getValue())
&& Objects.equals(hostname.getValue(), other.hostname.getValue())
&& Objects.equals(port.getValue(), other.port.getValue())
&& Objects.equals(useAuthentication.getValue(), other.useAuthentication.getValue())
&& Objects.equals(username.getValue(), other.username.getValue())
&& Objects.equals(password.getValue(), other.password.getValue())
&& Objects.equals(persistPassword.getValue(), other.persistPassword.getValue());
}
@Override
public int hashCode() {
return Objects.hash(
useProxy.getValue(),
hostname.getValue(),
port.getValue(),
useAuthentication.getValue(),
username.getValue(),
password.getValue(),
persistPassword.getValue());
}
}
| 4,471 | 28.421053 | 99 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ProxyRegisterer.java | package org.jabref.logic.net;
public class ProxyRegisterer {
private ProxyRegisterer() {
}
public static void register(ProxyPreferences proxyPrefs) {
if (proxyPrefs.shouldUseProxy()) {
// NetworkTabView.java ensures that proxyHostname and proxyPort are not null
System.setProperty("http.proxyHost", proxyPrefs.getHostname());
System.setProperty("http.proxyPort", proxyPrefs.getPort());
System.setProperty("https.proxyHost", proxyPrefs.getHostname());
System.setProperty("https.proxyPort", proxyPrefs.getPort());
// NetworkTabView.java ensures that proxyUsername and proxyPassword are neither null nor empty
if (proxyPrefs.shouldUseAuthentication()) {
System.setProperty("http.proxyUser", proxyPrefs.getUsername());
System.setProperty("http.proxyPassword", proxyPrefs.getPassword());
System.setProperty("https.proxyUser", proxyPrefs.getUsername());
System.setProperty("https.proxyPassword", proxyPrefs.getPassword());
} else {
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
} else {
// The following two lines signal that the system proxy settings should be used:
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("proxySet", "true");
}
}
}
| 1,610 | 41.394737 | 106 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/URLDownload.java | package org.jabref.logic.net;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.jabref.logic.importer.FetcherClientException;
import org.jabref.logic.importer.FetcherServerException;
import org.jabref.logic.util.io.FileUtil;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import kong.unirest.apache.ApacheClient;
import org.apache.http.client.config.RequestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* URL download to a string.
* <p>
* Example:
* <code>
* URLDownload dl = new URLDownload(URL);
* String content = dl.asString(ENCODING);
* dl.toFile(Path); // available in FILE
* String contentType = dl.getMimeType();
* </code>
* <br/><br/>
* Almost each call to a public method creates a new HTTP connection (except for {@link #asString(Charset, URLConnection) asString},
* which uses an already opened connection). Nothing is cached.
*/
public class URLDownload {
public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36";
private static final Logger LOGGER = LoggerFactory.getLogger(URLDownload.class);
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(30);
private final URL source;
private final Map<String, String> parameters = new HashMap<>();
private String postData = "";
private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT;
/**
* @param source the URL to download from
* @throws MalformedURLException if no protocol is specified in the source, or an unknown protocol is found
*/
public URLDownload(String source) throws MalformedURLException {
this(new URL(source));
}
/**
* @param source The URL to download.
*/
public URLDownload(URL source) {
this.source = source;
this.addHeader("User-Agent", URLDownload.USER_AGENT);
}
/**
* Older java VMs does not automatically trust the zbMATH certificate. In this case the following exception is
* thrown: sun.security.validator.ValidatorException: PKIX path building failed:
* sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested
* target JM > 8u101 may trust the certificate by default according to http://stackoverflow.com/a/34111150/873661
* <p>
* We will fix this issue by accepting all (!) certificates. This is ugly; but as JabRef does not rely on
* security-relevant information this is kind of OK (no, actually it is not...).
* <p>
* Taken from http://stackoverflow.com/a/6055903/873661 and https://stackoverflow.com/a/19542614/873661
*
* @deprecated
*/
@Deprecated
public static void bypassSSLVerification() {
LOGGER.warn("Fix SSL exceptions by accepting ALL certificates");
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = {new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
try {
// Install all-trusting trust manager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// Install all-trusting host verifier
HostnameVerifier allHostsValid = (hostname, session) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
LOGGER.error("A problem occurred when bypassing SSL verification", e);
}
}
/**
*
* @param socketFactory trust manager
* @param verifier host verifier
*/
public static void setSSLVerification(SSLSocketFactory socketFactory, HostnameVerifier verifier) {
try {
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
} catch (Exception e) {
LOGGER.error("A problem occurred when reset SSL verification", e);
}
}
public URL getSource() {
return source;
}
public String getMimeType() {
Unirest.config().setDefaultHeader("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
String contentType;
// Try to use HEAD request to avoid downloading the whole file
try {
contentType = Unirest.head(source.toString()).asString().getHeaders().get("Content-Type").get(0);
if ((contentType != null) && !contentType.isEmpty()) {
return contentType;
}
} catch (Exception e) {
LOGGER.debug("Error getting MIME type of URL via HEAD request", e);
}
// Use GET request as alternative if no HEAD request is available
try {
contentType = Unirest.get(source.toString()).asString().getHeaders().get("Content-Type").get(0);
if ((contentType != null) && !contentType.isEmpty()) {
return contentType;
}
} catch (Exception e) {
LOGGER.debug("Error getting MIME type of URL via GET request", e);
}
// Try to resolve local URIs
try {
URLConnection connection = new URL(source.toString()).openConnection();
contentType = connection.getContentType();
if ((contentType != null) && !contentType.isEmpty()) {
return contentType;
}
} catch (IOException e) {
LOGGER.debug("Error trying to get MIME type of local URI", e);
}
return "";
}
/**
* Check the connection by using the HEAD request.
* UnirestException can be thrown for invalid request.
*
* @return the status code of the response
*/
public boolean canBeReached() throws UnirestException {
// Set a custom Apache Client Builder to be able to allow circular redirects, otherwise downloads from springer might not work
Unirest.config().httpClient(new ApacheClient.Builder()
.withRequestConfig((c, r) -> RequestConfig.custom()
.setCircularRedirectsAllowed(true)
.build()));
Unirest.config().setDefaultHeader("User-Agent", USER_AGENT);
int statusCode = Unirest.head(source.toString()).asString().getStatus();
return (statusCode >= 200) && (statusCode < 300);
}
public boolean isMimeType(String type) {
String mime = getMimeType();
if (mime.isEmpty()) {
return false;
}
return mime.startsWith(type);
}
public boolean isPdf() {
return isMimeType("application/pdf");
}
public void addHeader(String key, String value) {
this.parameters.put(key, value);
}
public void setPostData(String postData) {
if (postData != null) {
this.postData = postData;
}
}
/**
* Downloads the web resource to a String. Uses UTF-8 as encoding.
*
* @return the downloaded string
*/
public String asString() throws IOException {
return asString(StandardCharsets.UTF_8, this.openConnection());
}
/**
* Downloads the web resource to a String.
*
* @param encoding the desired String encoding
* @return the downloaded string
*/
public String asString(Charset encoding) throws IOException {
return asString(encoding, this.openConnection());
}
/**
* Downloads the web resource to a String from an existing connection. Uses UTF-8 as encoding.
*
* @param existingConnection an existing connection
* @return the downloaded string
*/
public static String asString(URLConnection existingConnection) throws IOException {
return asString(StandardCharsets.UTF_8, existingConnection);
}
/**
* Downloads the web resource to a String.
*
* @param encoding the desired String encoding
* @param connection an existing connection
* @return the downloaded string
*/
public static String asString(Charset encoding, URLConnection connection) throws IOException {
try (InputStream input = new BufferedInputStream(connection.getInputStream());
Writer output = new StringWriter()) {
copy(input, output, encoding);
return output.toString();
}
}
public List<HttpCookie> getCookieFromUrl() throws IOException {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
URLConnection con = this.openConnection();
con.getHeaderFields(); // must be read to store the cookie
try {
return cookieManager.getCookieStore().get(this.source.toURI());
} catch (URISyntaxException e) {
LOGGER.error("Unable to convert download URL to URI", e);
return Collections.emptyList();
}
}
/**
* Downloads the web resource to a file.
*
* @param destination the destination file path.
*/
public void toFile(Path destination) throws IOException {
try (InputStream input = new BufferedInputStream(this.openConnection().getInputStream())) {
Files.copy(input, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.warn("Could not copy input", e);
throw e;
}
}
/**
* Takes the web resource as the source for a monitored input stream.
*/
public ProgressInputStream asInputStream() throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) this.openConnection();
if ((urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) || (urlConnection.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST)) {
LOGGER.error("Response message {} returned for url {}", urlConnection.getResponseMessage(), urlConnection.getURL());
return new ProgressInputStream(new ByteArrayInputStream(new byte[0]), 0);
}
long fileSize = urlConnection.getContentLengthLong();
return new ProgressInputStream(new BufferedInputStream(urlConnection.getInputStream()), fileSize);
}
/**
* Downloads the web resource to a temporary file.
*
* @return the path of the temporary file.
*/
public Path toTemporaryFile() throws IOException {
// Determine file name and extension from source url
String sourcePath = source.getPath();
// Take everything after the last '/' as name + extension
String fileNameWithExtension = sourcePath.substring(sourcePath.lastIndexOf('/') + 1);
String fileName = "jabref-" + FileUtil.getBaseName(fileNameWithExtension);
String extension = "." + FileUtil.getFileExtension(fileNameWithExtension).orElse("tmp");
// Create temporary file and download to it
Path file = Files.createTempFile(fileName, extension);
file.toFile().deleteOnExit();
toFile(file);
return file;
}
@Override
public String toString() {
return "URLDownload{" + "source=" + this.source + '}';
}
private static void copy(InputStream in, Writer out, Charset encoding) throws IOException {
Reader r = new InputStreamReader(in, encoding);
try (BufferedReader read = new BufferedReader(r)) {
String line;
while ((line = read.readLine()) != null) {
out.write(line);
out.write("\n");
}
}
}
/**
* Open a connection to this object's URL (with specified settings). If accessing an HTTP URL, don't forget
* to close the resulting connection after usage.
*
* @return an open connection
*/
public URLConnection openConnection() throws IOException {
URLConnection connection = this.source.openConnection();
connection.setConnectTimeout((int) connectTimeout.toMillis());
for (Entry<String, String> entry : this.parameters.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
if (!this.postData.isEmpty()) {
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(this.postData);
}
}
if (connection instanceof HttpURLConnection lConnection) {
// normally, 3xx is redirect
int status = lConnection.getResponseCode();
if ((status == HttpURLConnection.HTTP_MOVED_TEMP)
|| (status == HttpURLConnection.HTTP_MOVED_PERM)
|| (status == HttpURLConnection.HTTP_SEE_OTHER)) {
// get redirect url from "location" header field
String newUrl = connection.getHeaderField("location");
// open the new connection again
connection = new URLDownload(newUrl).openConnection();
}
if ((status >= 400) && (status < 500)) {
throw new IOException(new FetcherClientException("Encountered HTTP Status code " + status));
}
if (status >= 500) {
throw new IOException(new FetcherServerException("Encountered HTTP Status Code " + status));
}
}
// this does network i/o: GET + read returned headers
return connection;
}
public void setConnectTimeout(Duration connectTimeout) {
if (connectTimeout != null) {
this.connectTimeout = connectTimeout;
}
}
public Duration getConnectTimeout() {
return connectTimeout;
}
}
| 15,578 | 35.917062 | 159 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ssl/SSLCertificate.java | package org.jabref.logic.net.ssl;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Objects;
import java.util.Optional;
import com.google.common.hash.Hashing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SSLCertificate {
private static final Logger LOGGER = LoggerFactory.getLogger(SSLCertificate.class);
private final String sha256Thumbprint;
private final String serialNumber;
private final String issuer;
private final LocalDate validFrom;
private final LocalDate validTo;
private final String signatureAlgorithm;
private final Integer version;
public SSLCertificate(byte[] encoded, String serialNumber, String issuer, LocalDate validFrom, LocalDate validTo, String signatureAlgorithm, Integer version) {
this.serialNumber = serialNumber;
this.issuer = issuer;
this.validFrom = validFrom;
this.validTo = validTo;
this.signatureAlgorithm = signatureAlgorithm;
this.version = version;
this.sha256Thumbprint = Hashing.sha256().hashBytes(encoded).toString();
}
public String getSerialNumber() {
return serialNumber;
}
public String getIssuer() {
return issuer;
}
public LocalDate getValidFrom() {
return validFrom;
}
public LocalDate getValidTo() {
return validTo;
}
public String getSignatureAlgorithm() {
return signatureAlgorithm;
}
public Integer getVersion() {
return version;
}
/**
* @return the SHA-256 of the <a href="https://en.wikipedia.org/wiki/X.690#DER_encoding">DER encoding</a>
*/
public String getSHA256Thumbprint() {
return sha256Thumbprint;
}
public static Optional<SSLCertificate> fromX509(X509Certificate x509Certificate) {
Objects.requireNonNull(x509Certificate);
try {
return Optional.of(new SSLCertificate(x509Certificate.getEncoded(), x509Certificate.getSerialNumber().toString(),
x509Certificate.getIssuerX500Principal().getName(),
LocalDate.ofInstant(x509Certificate.getNotBefore().toInstant(), ZoneId.systemDefault()),
LocalDate.ofInstant(x509Certificate.getNotAfter().toInstant(), ZoneId.systemDefault()),
x509Certificate.getSigAlgName(),
x509Certificate.getVersion()));
} catch (CertificateEncodingException e) {
LOGGER.warn("Error while encoding certificate", e);
}
return Optional.empty();
}
public static Optional<SSLCertificate> fromPath(Path certPath) {
Objects.requireNonNull(certPath);
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
return fromX509((X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certPath.toFile())));
} catch (CertificateException e) {
LOGGER.warn("Certificate doesn't follow X.509 format", e);
} catch (FileNotFoundException e) {
LOGGER.warn("Bad Certificate path: {}", certPath, e);
}
return Optional.empty();
}
}
| 3,484 | 34.20202 | 163 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ssl/SSLPreferences.java | package org.jabref.logic.net.ssl;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class SSLPreferences {
private final StringProperty truststorePath;
public SSLPreferences(String truststorePath) {
this.truststorePath = new SimpleStringProperty(truststorePath);
}
public StringProperty truststorePathProperty() {
return truststorePath;
}
public String getTruststorePath() {
return truststorePath.getValue();
}
}
| 523 | 23.952381 | 71 | java |
null | jabref-main/src/main/java/org/jabref/logic/net/ssl/TrustStoreManager.java | package org.jabref.logic.net.ssl;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TrustStoreManager {
private static final Logger LOGGER = LoggerFactory.getLogger(TrustStoreManager.class);
private static final String STORE_PASSWORD = "changeit";
private final Path storePath;
private KeyStore store;
public TrustStoreManager(Path storePath) {
this.storePath = storePath;
createTruststoreFileIfNotExist(storePath);
try {
store = KeyStore.getInstance(KeyStore.getDefaultType());
store.load(new FileInputStream(storePath.toFile()), STORE_PASSWORD.toCharArray());
} catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.warn("Error while loading trust store from: {}", storePath.toAbsolutePath(), e);
}
}
public void addCertificate(String alias, Path certPath) {
Objects.requireNonNull(alias);
Objects.requireNonNull(certPath);
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
store.setCertificateEntry(alias, certificateFactory.generateCertificate(new FileInputStream(certPath.toFile())));
} catch (KeyStoreException | CertificateException | IOException e) {
LOGGER.warn("Error while adding a new certificate to the truststore: {}", alias, e);
}
}
public void deleteCertificate(String alias) {
Objects.requireNonNull(alias);
try {
store.deleteEntry(alias);
} catch (KeyStoreException e) {
LOGGER.warn("Error while deleting certificate entry with alias: {}", alias, e);
}
}
public boolean certificateExists(String alias) {
Objects.requireNonNull(alias);
try {
return store.isCertificateEntry(alias);
} catch (KeyStoreException e) {
LOGGER.warn("Error while checking certificate existence: {}", alias, e);
}
return false;
}
public List<String> aliases() {
try {
return Collections.list(store.aliases());
} catch (KeyStoreException e) {
LOGGER.warn("Error while reading aliases", e);
}
return Collections.emptyList();
}
public int certsCount() {
try {
return store.size();
} catch (KeyStoreException e) {
LOGGER.warn("Can't count certificates", e);
}
return 0;
}
public void flush() {
try {
store.store(new FileOutputStream(storePath.toFile()), STORE_PASSWORD.toCharArray());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.warn("Error while flushing trust store", e);
}
}
/**
* Custom certificates are certificates with alias that ends with {@code [custom]}
*/
private Boolean isCustomCertificate(String alias) {
return alias.endsWith("[custom]");
}
/**
* Deletes all custom certificates, Custom certificates are certificates with alias that ends with {@code [custom]}
*/
public void clearCustomCertificates() {
aliases().stream().filter(this::isCustomCertificate).forEach(this::deleteCertificate);
flush();
}
public List<SSLCertificate> getCustomCertificates() {
return aliases().stream()
.filter(this::isCustomCertificate)
.map(this::getCertificate)
.map(SSLCertificate::fromX509)
.flatMap(Optional::stream)
.collect(Collectors.toList());
}
public X509Certificate getCertificate(String alias) {
try {
return (X509Certificate) store.getCertificate(alias);
} catch (KeyStoreException e) {
LOGGER.warn("Error while getting certificate of alias: {}", alias, e);
}
return null;
}
/**
* This method checks to see if the truststore is present in {@code storePath},
* and if it isn't, it copies the default JDK truststore to the specified location.
*
* @param storePath path of the truststore
*/
public static void createTruststoreFileIfNotExist(Path storePath) {
try {
LOGGER.debug("Trust store path: {}", storePath.toAbsolutePath());
Path storeResourcePath = Path.of(TrustStoreManager.class.getResource("/ssl/truststore.jks").toURI());
Files.createDirectories(storePath.getParent());
if (Files.notExists(storePath)) {
Files.copy(storeResourcePath, storePath);
}
} catch (IOException e) {
LOGGER.warn("Bad truststore path", e);
} catch (URISyntaxException e) {
LOGGER.warn("Bad resource path", e);
}
}
}
| 5,495 | 34.688312 | 125 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/NoDocumentFoundException.java | package org.jabref.logic.openoffice;
public class NoDocumentFoundException extends Exception {
public NoDocumentFoundException(String message) {
super(message);
}
public NoDocumentFoundException() {
super("No Writer documents found");
}
}
| 274 | 20.153846 | 57 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/OpenOfficeFileSearch.java | package org.jabref.logic.openoffice;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jabref.logic.util.OS;
import org.jabref.logic.util.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OpenOfficeFileSearch {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenOfficeFileSearch.class);
/**
* Detects existing installation of OpenOffice and LibreOffice.
*
* @return a list of detected installation paths
*/
public static List<Path> detectInstallations() {
if (OS.WINDOWS) {
List<Path> programDirs = findWindowsOpenOfficeDirs();
return programDirs.stream().filter(dir -> FileUtil.find(OpenOfficePreferences.WINDOWS_EXECUTABLE, dir).isPresent()).collect(Collectors.toList());
} else if (OS.OS_X) {
List<Path> programDirs = findOSXOpenOfficeDirs();
return programDirs.stream().filter(dir -> FileUtil.find(OpenOfficePreferences.OSX_EXECUTABLE, dir).isPresent()).collect(Collectors.toList());
} else if (OS.LINUX) {
List<Path> programDirs = findLinuxOpenOfficeDirs();
return programDirs.stream().filter(dir -> FileUtil.find(OpenOfficePreferences.LINUX_EXECUTABLE, dir).isPresent()).collect(Collectors.toList());
}
return new ArrayList<>(0);
}
private static List<Path> findOpenOfficeDirectories(List<Path> programDirectories) {
BiPredicate<Path, BasicFileAttributes> filePredicate = (path, attr) ->
attr.isDirectory() && (path.toString().toLowerCase(Locale.ROOT).contains("openoffice")
|| path.toString().toLowerCase(Locale.ROOT).contains("libreoffice"));
return programDirectories.stream().flatMap(dirs -> {
try {
return Files.find(dirs, 1, filePredicate);
} catch (IOException e) {
LOGGER.error("Problem searching for openoffice/libreoffice install directory", e);
return Stream.empty();
}
}).collect(Collectors.toList());
}
private static List<Path> findWindowsOpenOfficeDirs() {
List<Path> sourceList = new ArrayList<>();
// 64-bit program directory
String progFiles = System.getenv("ProgramFiles");
if (progFiles != null) {
sourceList.add(Path.of(progFiles));
}
// 32-bit program directory
progFiles = System.getenv("ProgramFiles(x86)");
if (progFiles != null) {
sourceList.add(Path.of(progFiles));
}
return findOpenOfficeDirectories(sourceList);
}
private static List<Path> findOSXOpenOfficeDirs() {
List<Path> sourceList = Collections.singletonList(Path.of("/Applications"));
return findOpenOfficeDirectories(sourceList);
}
private static List<Path> findLinuxOpenOfficeDirs() {
List<Path> sourceList = Arrays.asList(Path.of("/usr/lib"), Path.of("/usr/lib64"), Path.of("/opt"));
return findOpenOfficeDirectories(sourceList);
}
}
| 3,390 | 37.101124 | 157 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java | package org.jabref.logic.openoffice;
import java.util.List;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class OpenOfficePreferences {
public static final String DEFAULT_WIN_EXEC_PATH = "C:\\Program Files\\LibreOffice 5\\program";
public static final String WINDOWS_EXECUTABLE = "soffice.exe";
public static final String DEFAULT_OSX_EXEC_PATH = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
public static final String OSX_EXECUTABLE = "soffice";
public static final String DEFAULT_LINUX_EXEC_PATH = "/usr/lib/libreoffice/program/soffice";
public static final String DEFAULT_LINUX_FLATPAK_EXEC_PATH = "/app/bin/soffice";
public static final String LINUX_EXECUTABLE = "soffice";
private final StringProperty executablePath;
private final BooleanProperty useAllDatabases;
private final BooleanProperty syncWhenCiting;
private final ObservableList<String> externalStyles;
private final StringProperty currentStyle;
public OpenOfficePreferences(String executablePath,
boolean useAllDatabases,
boolean syncWhenCiting,
List<String> externalStyles,
String currentStyle) {
this.executablePath = new SimpleStringProperty(executablePath);
this.useAllDatabases = new SimpleBooleanProperty(useAllDatabases);
this.syncWhenCiting = new SimpleBooleanProperty(syncWhenCiting);
this.externalStyles = FXCollections.observableArrayList(externalStyles);
this.currentStyle = new SimpleStringProperty(currentStyle);
}
public void clearConnectionSettings() {
this.executablePath.set("");
}
public void clearCurrentStyle() {
this.currentStyle.set("");
}
/**
* path to soffice-file
*/
public String getExecutablePath() {
return executablePath.get();
}
public StringProperty executablePathProperty() {
return executablePath;
}
public void setExecutablePath(String executablePath) {
this.executablePath.setValue(executablePath);
}
/**
* true if all databases should be used when citing
*/
public boolean getUseAllDatabases() {
return useAllDatabases.get();
}
public BooleanProperty useAllDatabasesProperty() {
return useAllDatabases;
}
public void setUseAllDatabases(boolean useAllDatabases) {
this.useAllDatabases.set(useAllDatabases);
}
/**
* true if the reference list is updated when adding a new citation
*/
public boolean getSyncWhenCiting() {
return syncWhenCiting.get();
}
public BooleanProperty syncWhenCitingProperty() {
return syncWhenCiting;
}
public void setSyncWhenCiting(boolean syncWhenCiting) {
this.syncWhenCiting.setValue(syncWhenCiting);
}
/**
* list with paths to external style files
*/
public ObservableList<String> getExternalStyles() {
return externalStyles;
}
public void setExternalStyles(List<String> list) {
externalStyles.clear();
externalStyles.addAll(list);
}
/**
* path to the used style file
*/
public String getCurrentStyle() {
return currentStyle.get();
}
public StringProperty currentStyleProperty() {
return currentStyle;
}
public void setCurrentStyle(String currentStyle) {
this.currentStyle.set(currentStyle);
}
}
| 3,761 | 29.836066 | 110 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java | package org.jabref.logic.openoffice.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationMarkerEntry;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.style.NonUniqueCitationMarker;
import org.jabref.model.openoffice.style.OODataModel;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoScreenRefresh;
import org.jabref.model.openoffice.util.OOListUtil;
import org.jabref.model.strings.StringUtil;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
public class EditInsert {
private EditInsert() {
}
/**
* In insertEntry we receive BibEntry values from the GUI.
* <p>
* In the document we store citations by their citation key.
* <p>
* If the citation key is missing, the best we can do is to notify the user. Or the programmer, that we cannot accept such input.
*/
private static String insertEntryGetCitationKey(BibEntry entry) {
Optional<String> key = entry.getCitationKey();
if (key.isEmpty()) {
throw new IllegalArgumentException("insertEntryGetCitationKey: cannot cite entries without citation key");
}
return key.get();
}
/**
* @param cursor Where to insert.
* @param pageInfo A single pageInfo for a list of entries. This is what we get from the GUI.
*/
public static void insertCitationGroup(XTextDocument doc,
OOFrontend frontend,
XTextCursor cursor,
List<BibEntry> entries,
BibDatabase database,
OOBibStyle style,
CitationType citationType,
String pageInfo)
throws
NoDocumentException,
NotRemoveableException,
WrappedTargetException,
PropertyVetoException,
CreationException,
IllegalTypeException {
List<String> citationKeys = OOListUtil.map(entries, EditInsert::insertEntryGetCitationKey);
final int totalEntries = entries.size();
List<Optional<OOText>> pageInfos = OODataModel.fakePageInfos(pageInfo, totalEntries);
List<CitationMarkerEntry> citations = new ArrayList<>(totalEntries);
for (int i = 0; i < totalEntries; i++) {
Citation cit = new Citation(citationKeys.get(i));
cit.lookupInDatabases(Collections.singletonList(database));
cit.setPageInfo(pageInfos.get(i));
citations.add(cit);
}
// The text we insert
OOText citeText;
if (style.isNumberEntries()) {
citeText = OOText.fromString("[-]"); // A dash only. Only refresh later.
} else {
citeText = style.createCitationMarker(citations,
citationType.inParenthesis(),
NonUniqueCitationMarker.FORGIVEN);
}
if (StringUtil.isBlank(OOText.toString(citeText))) {
citeText = OOText.fromString("[?]");
}
try {
UnoScreenRefresh.lockControllers(doc);
UpdateCitationMarkers.createAndFillCitationGroup(frontend,
doc,
citationKeys,
pageInfos,
citationType,
citeText,
cursor,
style,
true /* insertSpaceAfter */);
} finally {
UnoScreenRefresh.unlockControllers(doc);
}
}
}
| 4,445 | 37.66087 | 133 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java | package org.jabref.logic.openoffice.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoScreenRefresh;
import org.jabref.model.openoffice.uno.UnoTextRange;
import org.jabref.model.openoffice.util.OOListUtil;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EditMerge {
private static final Logger LOGGER = LoggerFactory.getLogger(EditMerge.class);
private EditMerge() {
}
/**
* @return true if modified document
*/
public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend frontend, OOBibStyle style)
throws
CreationException,
IllegalArgumentException,
IllegalTypeException,
NoDocumentException,
NotRemoveableException,
PropertyVetoException,
WrappedTargetException {
boolean madeModifications;
try {
UnoScreenRefresh.lockControllers(doc);
List<JoinableGroupData> joinableGroups = EditMerge.scan(doc, frontend);
for (JoinableGroupData joinableGroupData : joinableGroups) {
List<CitationGroup> groups = joinableGroupData.group;
List<Citation> newCitations = groups.stream()
.flatMap(group -> group.citationsInStorageOrder.stream())
.collect(Collectors.toList());
CitationType citationType = groups.get(0).citationType;
List<Optional<OOText>> pageInfos = frontend.backend.combinePageInfos(groups);
frontend.removeCitationGroups(groups, doc);
XTextCursor textCursor = joinableGroupData.groupCursor;
textCursor.setString(""); // Also remove the spaces between.
List<String> citationKeys = OOListUtil.map(newCitations, Citation::getCitationKey);
/* insertSpaceAfter: no, it is already there (or could be) */
boolean insertSpaceAfter = false;
UpdateCitationMarkers.createAndFillCitationGroup(frontend,
doc,
citationKeys,
pageInfos,
citationType,
OOText.fromString("tmp"),
textCursor,
style,
insertSpaceAfter);
}
madeModifications = !joinableGroups.isEmpty();
} finally {
UnoScreenRefresh.unlockControllers(doc);
}
return madeModifications;
}
private static class JoinableGroupData {
/**
* A list of consecutive citation groups only separated by spaces.
*/
List<CitationGroup> group;
/**
* A cursor covering the XTextRange of each entry in group (and the spaces between them)
*/
XTextCursor groupCursor;
JoinableGroupData(List<CitationGroup> group, XTextCursor groupCursor) {
this.group = group;
this.groupCursor = groupCursor;
}
}
private static class ScanState {
// Citation groups in the current group
List<CitationGroup> currentGroup;
// A cursor that covers the Citation groups in currentGroup, including the space between
// them.
// null if currentGroup.isEmpty()
XTextCursor currentGroupCursor;
// A cursor starting at the end of the last CitationGroup in currentGroup.
// null if currentGroup.isEmpty()
XTextCursor cursorBetween;
// The last element of currentGroup.
// null if currentGroup.isEmpty()
CitationGroup prev;
// The XTextRange for prev.
// null if currentGroup.isEmpty()
XTextRange prevRange;
ScanState() {
reset();
}
void reset() {
currentGroup = new ArrayList<>();
currentGroupCursor = null;
cursorBetween = null;
prev = null;
prevRange = null;
}
}
/**
* Decide if group could be added to state.currentGroup
*
* @param group The CitationGroup to test
* @param currentRange The XTextRange corresponding to group.
* @return false if cannot add, true if can. If returned true, then state.cursorBetween and state.currentGroupCursor are expanded to end at the start of currentRange.
*/
private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTextRange currentRange) {
if (state.currentGroup.isEmpty()) {
return false;
}
Objects.requireNonNull(state.currentGroupCursor);
Objects.requireNonNull(state.cursorBetween);
Objects.requireNonNull(state.prev);
Objects.requireNonNull(state.prevRange);
// Only combine (Author 2000) type citations
if (group.citationType != CitationType.AUTHORYEAR_PAR) {
return false;
}
if (state.prev != null) {
// Even if we combine AUTHORYEAR_INTEXT citations, we would not mix them with AUTHORYEAR_PAR
if (group.citationType != state.prev.citationType) {
return false;
}
if (!UnoTextRange.comparables(state.prevRange, currentRange)) {
return false;
}
// Sanity check: the current range should start later than the previous.
int textOrder = UnoTextRange.compareStarts(state.prevRange, currentRange);
if (textOrder != -1) {
String msg =
String.format("MergeCitationGroups:"
+ " \"%s\" supposed to be followed by \"%s\","
+ " but %s",
state.prevRange.getString(),
currentRange.getString(),
((textOrder == 0)
? "they start at the same position"
: "the start of the latter precedes the start of the first"));
LOGGER.warn(msg);
return false;
}
}
if (state.cursorBetween == null) {
return false;
}
Objects.requireNonNull(state.cursorBetween);
Objects.requireNonNull(state.currentGroupCursor);
// assume: currentGroupCursor.getEnd() == cursorBetween.getEnd()
if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {
LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end");
throw new IllegalStateException("MergeCitationGroups failed");
}
/*
* Try to expand state.currentGroupCursor and state.cursorBetween by going right to reach
* rangeStart.
*/
XTextRange rangeStart = currentRange.getStart();
boolean couldExpand = true;
XTextCursor thisCharCursor =
currentRange.getText().createTextCursorByRange(state.cursorBetween.getEnd());
while (couldExpand && (UnoTextRange.compareEnds(state.cursorBetween, rangeStart) < 0)) {
//
// Check that we only walk through inline whitespace.
//
couldExpand = thisCharCursor.goRight((short) 1, true);
String thisChar = thisCharCursor.getString();
thisCharCursor.collapseToEnd();
if (thisChar.isEmpty() || "\n".equals(thisChar) || !thisChar.trim().isEmpty()) {
couldExpand = false;
if (!thisChar.isEmpty()) {
thisCharCursor.goLeft((short) 1, false);
}
break;
}
state.cursorBetween.goRight((short) 1, true);
state.currentGroupCursor.goRight((short) 1, true);
// These two should move in sync:
if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {
LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)");
throw new IllegalStateException("MergeCitationGroups failed");
}
}
return couldExpand;
}
/**
* Add group to state.currentGroup Set state.cursorBetween to start at currentRange.getEnd() Expand state.currentGroupCursor to also cover currentRange Set state.prev to group, state.prevRange to currentRange
*/
private static void addToCurrentGroup(ScanState state, CitationGroup group, XTextRange currentRange) {
final boolean isNewGroup = state.currentGroup.isEmpty();
if (!isNewGroup) {
Objects.requireNonNull(state.currentGroupCursor);
Objects.requireNonNull(state.cursorBetween);
Objects.requireNonNull(state.prev);
Objects.requireNonNull(state.prevRange);
}
// Add the current entry to a group.
state.currentGroup.add(group);
// Set up cursorBetween to start at currentRange.getEnd()
XTextRange rangeEnd = currentRange.getEnd();
state.cursorBetween = currentRange.getText().createTextCursorByRange(rangeEnd);
// If new group, create currentGroupCursor
if (isNewGroup) {
state.currentGroupCursor = currentRange.getText()
.createTextCursorByRange(currentRange.getStart());
}
// include currentRange in currentGroupCursor
state.currentGroupCursor.goRight((short) (currentRange.getString().length()), true);
if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {
LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end");
throw new IllegalStateException("MergeCitationGroups failed");
}
/* Store data about last entry in currentGroup */
state.prev = group;
state.prevRange = currentRange;
}
/**
* Scan the document for joinable groups. Return those found.
*/
private static List<JoinableGroupData> scan(XTextDocument doc, OOFrontend frontend)
throws
NoDocumentException,
WrappedTargetException {
List<JoinableGroupData> result = new ArrayList<>();
List<CitationGroup> groups = frontend.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */);
if (groups.isEmpty()) {
return result;
}
ScanState state = new ScanState();
for (CitationGroup group : groups) {
XTextRange currentRange = frontend.getMarkRange(doc, group)
.orElseThrow(IllegalStateException::new);
/*
* Decide if we add group to the group. False when the group is empty.
*/
boolean addToGroup = checkAddToGroup(state, group, currentRange);
/*
* Even if we do not add it to an existing group, we might use it to start a new group.
*
* Can it start a new group?
*/
boolean canStartGroup = group.citationType == CitationType.AUTHORYEAR_PAR;
if (!addToGroup) {
// close currentGroup
if (state.currentGroup.size() > 1) {
result.add(new JoinableGroupData(state.currentGroup, state.currentGroupCursor));
}
// Start a new, empty group
state.reset();
}
if (addToGroup || canStartGroup) {
addToCurrentGroup(state, group, currentRange);
}
}
// close currentGroup
if (state.currentGroup.size() > 1) {
result.add(new JoinableGroupData(state.currentGroup, state.currentGroupCursor));
}
return result;
}
}
| 12,962 | 37.465875 | 212 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java | package org.jabref.logic.openoffice.action;
import java.util.List;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.logic.openoffice.style.OOProcess;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoScreenRefresh;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
public class EditSeparate {
private EditSeparate() {
}
public static boolean separateCitations(XTextDocument doc,
OOFrontend frontend,
List<BibDatabase> databases,
OOBibStyle style)
throws
CreationException,
IllegalTypeException,
NoDocumentException,
NotRemoveableException,
PropertyVetoException,
WrappedTargetException,
com.sun.star.lang.IllegalArgumentException {
boolean madeModifications = false;
// To reduce surprises in JabRef52 mode, impose localOrder to
// decide the visually last Citation in the group. Unless the
// style changed since refresh this is the last on the screen
// as well.
frontend.citationGroups.lookupCitations(databases);
frontend.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style));
List<CitationGroup> groups = frontend.citationGroups.getCitationGroupsUnordered();
try {
UnoScreenRefresh.lockControllers(doc);
for (CitationGroup group : groups) {
XTextRange range1 = frontend
.getMarkRange(doc, group)
.orElseThrow(IllegalStateException::new);
XTextCursor textCursor = range1.getText().createTextCursorByRange(range1);
List<Citation> citations = group.citationsInStorageOrder;
if (citations.size() <= 1) {
continue;
}
frontend.removeCitationGroup(group, doc);
// Now we own the content of citations
// Create a citation group for each citation.
final int last = citations.size() - 1;
for (int i = 0; i < citations.size(); i++) {
boolean insertSpaceAfter = i != last;
Citation citation = citations.get(i);
UpdateCitationMarkers.createAndFillCitationGroup(frontend,
doc,
List.of(citation.citationKey),
List.of(citation.getPageInfo()),
group.citationType,
OOText.fromString(citation.citationKey),
textCursor,
style,
insertSpaceAfter);
textCursor.collapseToEnd();
}
madeModifications = true;
}
} finally {
UnoScreenRefresh.unlockControllers(doc);
}
return madeModifications;
}
}
| 3,781 | 37.591837 | 90 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java | package org.jabref.logic.openoffice.action;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.openoffice.style.CitedKey;
import org.jabref.model.openoffice.style.CitedKeys;
import org.jabref.model.openoffice.uno.NoDocumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextDocument;
public class ExportCited {
private ExportCited() {
}
public static class GenerateDatabaseResult {
/**
* null: not done; isEmpty: no unresolved
*/
public final List<String> unresolvedKeys;
public final BibDatabase newDatabase;
GenerateDatabaseResult(List<String> unresolvedKeys, BibDatabase newDatabase) {
this.unresolvedKeys = unresolvedKeys;
this.newDatabase = newDatabase;
}
}
/**
* @param databases The databases to look up the citation keys in the document from.
* @return A new database, with cloned entries.
* If a key is not found, it is added to result.unresolvedKeys
* <p>
* Cross references (in StandardField.CROSSREF) are followed (not recursively): If the referenced entry is found, it is included in the result. If it is not found, it is silently ignored.
*/
public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List<BibDatabase> databases)
throws
NoDocumentException,
WrappedTargetException {
OOFrontend frontend = new OOFrontend(doc);
CitedKeys citationKeys = frontend.citationGroups.getCitedKeysUnordered();
citationKeys.lookupInDatabases(databases);
List<String> unresolvedKeys = new ArrayList<>();
BibDatabase resultDatabase = new BibDatabase();
List<BibEntry> entriesToInsert = new ArrayList<>();
Set<String> seen = new HashSet<>(); // Only add crossReference once.
for (CitedKey citation : citationKeys.values()) {
if (citation.getLookupResult().isEmpty()) {
unresolvedKeys.add(citation.citationKey);
} else {
BibEntry entry = citation.getLookupResult().get().entry;
BibDatabase loopDatabase = citation.getLookupResult().get().database;
// If entry found
BibEntry clonedEntry = (BibEntry) entry.clone();
// Insert a copy of the entry
entriesToInsert.add(clonedEntry);
// Check if the cloned entry has a cross-reference field
clonedEntry
.getField(StandardField.CROSSREF)
.ifPresent(crossReference -> {
boolean isNew = !seen.contains(crossReference);
if (isNew) {
// Add it if it is in the current library
loopDatabase
.getEntryByCitationKey(crossReference)
.ifPresent(entriesToInsert::add);
seen.add(crossReference);
}
});
}
}
resultDatabase.insertEntries(entriesToInsert);
return new GenerateDatabaseResult(unresolvedKeys, resultDatabase);
}
}
| 3,565 | 37.76087 | 191 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java | package org.jabref.logic.openoffice.action;
import java.util.List;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.model.openoffice.CitationEntry;
import org.jabref.model.openoffice.uno.NoDocumentException;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextDocument;
public class ManageCitations {
private ManageCitations() {
}
public static List<CitationEntry> getCitationEntries(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
OOFrontend frontend = new OOFrontend(doc);
return frontend.getCitationEntries(doc);
}
public static void applyCitationEntries(XTextDocument doc, List<CitationEntry> citationEntries)
throws
NoDocumentException,
PropertyVetoException,
IllegalTypeException,
WrappedTargetException,
IllegalArgumentException {
OOFrontend frontend = new OOFrontend(doc);
frontend.applyCitationEntries(doc, citationEntries);
}
}
| 1,182 | 30.131579 | 99 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/action/Update.java | package org.jabref.logic.openoffice.action;
import java.util.List;
import org.jabref.logic.openoffice.frontend.OOFrontend;
import org.jabref.logic.openoffice.frontend.UpdateBibliography;
import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.logic.openoffice.style.OOProcess;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoScreenRefresh;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextDocument;
/**
* Update document: citation marks and bibliography
*/
public class Update {
private Update() {
}
/**
* @return the list of unresolved citation keys
*/
private static List<String> updateDocument(XTextDocument doc,
OOFrontend frontend,
List<BibDatabase> databases,
OOBibStyle style,
FunctionalTextViewCursor fcursor,
boolean doUpdateBibliography,
boolean alwaysAddCitedOnPages)
throws
CreationException,
NoDocumentException,
WrappedTargetException,
com.sun.star.lang.IllegalArgumentException {
final boolean useLockControllers = true;
frontend.imposeGlobalOrder(doc, fcursor);
OOProcess.produceCitationMarkers(frontend.citationGroups, databases, style);
try {
if (useLockControllers) {
UnoScreenRefresh.lockControllers(doc);
}
UpdateCitationMarkers.applyNewCitationMarkers(doc, frontend, style);
if (doUpdateBibliography) {
UpdateBibliography.rebuildBibTextSection(doc,
frontend,
frontend.citationGroups.getBibliography().get(),
style,
alwaysAddCitedOnPages);
}
return frontend.citationGroups.getUnresolvedKeys();
} finally {
if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) {
UnoScreenRefresh.unlockControllers(doc);
}
}
}
public static class SyncOptions {
public final List<BibDatabase> databases;
boolean updateBibliography;
boolean alwaysAddCitedOnPages;
public SyncOptions(List<BibDatabase> databases) {
this.databases = databases;
this.updateBibliography = false;
this.alwaysAddCitedOnPages = false;
}
public SyncOptions setUpdateBibliography(boolean value) {
this.updateBibliography = value;
return this;
}
public SyncOptions setAlwaysAddCitedOnPages(boolean value) {
this.alwaysAddCitedOnPages = value;
return this;
}
}
public static List<String> synchronizeDocument(XTextDocument doc,
OOFrontend frontend,
OOBibStyle style,
FunctionalTextViewCursor fcursor,
SyncOptions syncOptions)
throws
CreationException,
NoDocumentException,
WrappedTargetException,
com.sun.star.lang.IllegalArgumentException {
return Update.updateDocument(doc,
frontend,
syncOptions.databases,
style,
fcursor,
syncOptions.updateBibliography,
syncOptions.alwaysAddCitedOnPages);
}
/**
* Reread document before sync
*/
public static List<String> resyncDocument(XTextDocument doc,
OOBibStyle style,
FunctionalTextViewCursor fcursor,
SyncOptions syncOptions)
throws
CreationException,
NoDocumentException,
WrappedTargetException,
com.sun.star.lang.IllegalArgumentException {
OOFrontend frontend = new OOFrontend(doc);
return Update.synchronizeDocument(doc, frontend, style, fcursor, syncOptions);
}
}
| 4,701 | 34.621212 | 86 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java | package org.jabref.logic.openoffice.backend;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.jabref.model.openoffice.CitationEntry;
import org.jabref.model.openoffice.backend.NamedRange;
import org.jabref.model.openoffice.backend.NamedRangeManager;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroupId;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.style.OODataModel;
import org.jabref.model.openoffice.style.PageInfo;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoUserDefinedProperty;
import org.jabref.model.openoffice.util.OOListUtil;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Backend52, Codec52 and OODataModel.JabRef52 refer to the mode of storage, encoding and what-is-stored in the document under JabRef version 5.2. These basically did not change up to JabRef 5.4.
*/
public class Backend52 {
private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class);
public final OODataModel dataModel;
private final NamedRangeManager citationStorageManager;
private final Map<CitationGroupId, NamedRange> cgidToNamedRange;
// uses: Codec52
public Backend52() {
this.dataModel = OODataModel.JabRef52;
this.citationStorageManager = new NamedRangeManagerReferenceMark();
this.cgidToNamedRange = new HashMap<>();
}
/**
* Get reference mark names from the document matching the pattern used for JabRef reference mark names.
* <p>
* Note: the names returned are in arbitrary order.
*/
public List<String> getJabRefReferenceMarkNames(XTextDocument doc)
throws
NoDocumentException {
List<String> allNames = this.citationStorageManager.getUsedNames(doc);
return Codec52.filterIsJabRefReferenceMarkName(allNames);
}
/**
* Names of custom properties belonging to us, but without a corresponding reference mark. These can be deleted.
*
* @param citationGroupNames These are the names that are used.
*/
private List<String> findUnusedJabrefPropertyNames(XTextDocument doc,
List<String> citationGroupNames) {
Set<String> citationGroupNamesSet = new HashSet<>(citationGroupNames);
List<String> pageInfoThrash = new ArrayList<>();
List<String> jabrefPropertyNames =
UnoUserDefinedProperty.getListOfNames(doc)
.stream()
.filter(Codec52::isJabRefReferenceMarkName)
.toList();
for (String pn : jabrefPropertyNames) {
if (!citationGroupNamesSet.contains(pn)) {
pageInfoThrash.add(pn);
}
}
return pageInfoThrash;
}
/**
* @return Optional.empty if all is OK, message text otherwise.
*/
public Optional<String> healthReport(XTextDocument doc)
throws
NoDocumentException {
List<String> pageInfoThrash =
this.findUnusedJabrefPropertyNames(doc, this.getJabRefReferenceMarkNames(doc));
if (pageInfoThrash.isEmpty()) {
return Optional.empty();
}
String msg = "Backend52: found unused pageInfo data, with names listed below.\n"
+ "In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n"
+ String.join("\n", pageInfoThrash);
return Optional.of(msg);
}
private static void setPageInfoInDataInitial(List<Citation> citations, Optional<OOText> pageInfo) {
// attribute to last citation (initially localOrder == storageOrder)
if (!citations.isEmpty()) {
citations.get(citations.size() - 1).setPageInfo(pageInfo);
}
}
private static Optional<OOText> getPageInfoFromData(CitationGroup group) {
List<Citation> citations = group.getCitationsInLocalOrder();
if (citations.isEmpty()) {
return Optional.empty();
}
return citations.get(citations.size() - 1).getPageInfo();
}
/**
* @param markName Reference mark name
*/
public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, String markName)
throws
WrappedTargetException,
NoDocumentException {
Codec52.ParsedMarkName parsed = Codec52.parseMarkName(markName).orElseThrow(IllegalArgumentException::new);
List<Citation> citations = parsed.citationKeys.stream()
.map(Citation::new)
.collect(Collectors.toList());
Optional<OOText> pageInfo = UnoUserDefinedProperty.getStringValue(doc, markName)
.map(OOText::fromString);
pageInfo = PageInfo.normalizePageInfo(pageInfo);
setPageInfoInDataInitial(citations, pageInfo);
NamedRange namedRange = citationStorageManager.getNamedRangeFromDocument(doc, markName)
.orElseThrow(IllegalArgumentException::new);
CitationGroupId groupId = new CitationGroupId(markName);
CitationGroup group = new CitationGroup(OODataModel.JabRef52,
groupId,
parsed.citationType,
citations,
Optional.of(markName));
this.cgidToNamedRange.put(groupId, namedRange);
return group;
}
/**
* Create a reference mark at the end of {@code position} in the document.
* <p>
* On return {@code position} is collapsed, and is after the inserted space, or at the end of the reference mark.
*
* @param citationKeys Keys to be cited.
* @param pageInfos An optional pageInfo for each citation key. Backend52 only uses and stores the last pageInfo, all others should be Optional.empty()
* @param position Collapsed to its end.
* @param insertSpaceAfter We insert a space after the mark, that carries on format of characters from the original position.
*/
public CitationGroup createCitationGroup(XTextDocument doc,
List<String> citationKeys,
List<Optional<OOText>> pageInfos,
CitationType citationType,
XTextCursor position,
boolean insertSpaceAfter)
throws
CreationException,
NoDocumentException,
WrappedTargetException,
NotRemoveableException,
PropertyVetoException,
IllegalTypeException {
Objects.requireNonNull(pageInfos);
if (pageInfos.size() != citationKeys.size()) {
throw new IllegalArgumentException();
}
final int numberOfCitations = citationKeys.size();
final int last = numberOfCitations - 1;
// Build citations, add pageInfo to each citation
List<Citation> citations = new ArrayList<>(numberOfCitations);
for (int i = 0; i < numberOfCitations; i++) {
Citation cit = new Citation(citationKeys.get(i));
citations.add(cit);
Optional<OOText> pageInfo = PageInfo.normalizePageInfo(pageInfos.get(i));
switch (dataModel) {
case JabRef52:
if (i == last) {
cit.setPageInfo(pageInfo);
} else {
if (pageInfo.isPresent()) {
LOGGER.warn("dataModel JabRef52"
+ " only supports pageInfo for the last citation of a group");
}
}
break;
case JabRef60:
cit.setPageInfo(pageInfo);
break;
default:
throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup");
}
}
/*
* Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode
* the citation keys and citation type in the name of the reference mark. The name of the reference mark
* has to be unique in the document.
*/
final String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)),
citationKeys,
citationType);
final CitationGroupId groupId = new CitationGroupId(markName);
/*
* Apply to document
*/
boolean withoutBrackets = citationType == CitationType.INVISIBLE_CIT;
NamedRange namedRange = this.citationStorageManager.createNamedRange(doc,
markName,
position,
insertSpaceAfter,
withoutBrackets);
switch (dataModel) {
case JabRef52:
Optional<OOText> pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last));
if (pageInfo.isPresent()) {
String pageInfoString = OOText.toString(pageInfo.get());
UnoUserDefinedProperty.setStringProperty(doc, markName, pageInfoString);
} else {
// do not inherit from trash
UnoUserDefinedProperty.removeIfExists(doc, markName);
}
CitationGroup group = new CitationGroup(OODataModel.JabRef52,
groupId,
citationType, citations,
Optional.of(markName));
this.cgidToNamedRange.put(groupId, namedRange);
return group;
case JabRef60:
throw new IllegalStateException("createCitationGroup for JabRef60 is not implemented yet");
default:
throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup");
}
}
/**
* @return A list with a nullable pageInfo entry for each citation in joinableGroups.
* TODO: JabRef52 combinePageInfos is not reversible. Should warn user to check the result. Or
* ask what to do.
*/
public static List<Optional<OOText>>
combinePageInfosCommon(OODataModel dataModel, List<CitationGroup> joinableGroup) {
switch (dataModel) {
case JabRef52:
// collect to pageInfos
List<Optional<OOText>> pageInfos = OOListUtil.map(joinableGroup,
Backend52::getPageInfoFromData);
// Try to do something of the pageInfos.
String singlePageInfo = pageInfos.stream()
.filter(Optional::isPresent)
.map(pi -> OOText.toString(pi.get()))
.distinct()
.collect(Collectors.joining("; "));
int totalCitations = joinableGroup.stream()
.map(CitationGroup::numberOfCitations)
.mapToInt(Integer::intValue).sum();
if ("".equals(singlePageInfo)) {
singlePageInfo = null;
}
return OODataModel.fakePageInfos(singlePageInfo, totalCitations);
case JabRef60:
return joinableGroup.stream()
.flatMap(group -> (group.citationsInStorageOrder.stream()
.map(Citation::getPageInfo)))
.collect(Collectors.toList());
default:
throw new IllegalArgumentException("unhandled dataModel here");
}
}
public List<Optional<OOText>> combinePageInfos(List<CitationGroup> joinableGroup) {
return combinePageInfosCommon(this.dataModel, joinableGroup);
}
private NamedRange getNamedRangeOrThrow(CitationGroup group) {
NamedRange namedRange = this.cgidToNamedRange.get(group.groupId);
if (namedRange == null) {
throw new IllegalStateException("getNamedRange: could not lookup namedRange");
}
return namedRange;
}
public void removeCitationGroup(CitationGroup group, XTextDocument doc)
throws
WrappedTargetException,
NoDocumentException,
NotRemoveableException {
NamedRange namedRange = getNamedRangeOrThrow(group);
String refMarkName = namedRange.getRangeName();
namedRange.removeFromDocument(doc);
UnoUserDefinedProperty.removeIfExists(doc, refMarkName);
this.cgidToNamedRange.remove(group.groupId);
}
/**
* @return Optional.empty if the reference mark is missing.
*/
public Optional<XTextRange> getMarkRange(CitationGroup group, XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
NamedRange namedRange = getNamedRangeOrThrow(group);
return namedRange.getMarkRange(doc);
}
/**
* Cursor for the reference marks as is: not prepared for filling, but does not need cleanFillCursorForCitationGroup either.
*/
public Optional<XTextCursor> getRawCursorForCitationGroup(CitationGroup group, XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
NamedRange namedRange = getNamedRangeOrThrow(group);
return namedRange.getRawCursor(doc);
}
/**
* Must be followed by call to cleanFillCursorForCitationGroup
*/
public XTextCursor getFillCursorForCitationGroup(CitationGroup group, XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException,
CreationException {
NamedRange namedRange = getNamedRangeOrThrow(group);
return namedRange.getFillCursor(doc);
}
/**
* To be called after getFillCursorForCitationGroup
*/
public void cleanFillCursorForCitationGroup(CitationGroup group, XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
NamedRange namedRange = getNamedRangeOrThrow(group);
namedRange.cleanFillCursor(doc);
}
public List<CitationEntry> getCitationEntries(XTextDocument doc, CitationGroups citationGroups)
throws
WrappedTargetException,
NoDocumentException {
switch (dataModel) {
case JabRef52:
// One context per CitationGroup: Backend52 (DataModel.JabRef52)
// For DataModel.JabRef60 (Backend60) we need one context per Citation
List<CitationEntry> citations = new ArrayList<>(citationGroups.numberOfCitationGroups());
for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) {
String name = group.groupId.citationGroupIdAsString();
XTextCursor cursor = this
.getRawCursorForCitationGroup(group, doc)
.orElseThrow(IllegalStateException::new);
String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true);
Optional<String> pageInfo = group.numberOfCitations() > 0
? (getPageInfoFromData(group)
.map(e -> OOText.toString(e)))
: Optional.empty();
CitationEntry entry = new CitationEntry(name, context, pageInfo);
citations.add(entry);
}
return citations;
case JabRef60:
// xx
throw new IllegalStateException("getCitationEntries for JabRef60 is not implemented yet");
default:
throw new IllegalStateException("getCitationEntries: unhandled dataModel ");
}
}
/**
* Only applies to storage. Citation markers are not changed.
*/
public void applyCitationEntries(XTextDocument doc, List<CitationEntry> citationEntries)
throws
PropertyVetoException,
IllegalTypeException,
IllegalArgumentException,
WrappedTargetException {
switch (dataModel) {
case JabRef52:
for (CitationEntry entry : citationEntries) {
Optional<OOText> pageInfo = entry.getPageInfo().map(OOText::fromString);
pageInfo = PageInfo.normalizePageInfo(pageInfo);
if (pageInfo.isPresent()) {
String name = entry.getRefMarkName();
UnoUserDefinedProperty.setStringProperty(doc, name, pageInfo.get().toString());
}
}
break;
case JabRef60:
// ToDo: Implement
throw new IllegalStateException("applyCitationEntries for JabRef60 is not implemented yet");
default:
throw new IllegalStateException("applyCitationEntries: unhandled dataModel ");
}
}
}
| 18,374 | 41.633411 | 195 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java | package org.jabref.logic.openoffice.backend;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jabref.model.openoffice.style.CitationType;
/**
* How and what is encoded in reference mark names under JabRef 5.2.
* <p>
* - pageInfo does not appear here. It is not encoded in the mark name.
*/
class Codec52 {
private static final String BIB_CITATION = "JR_cite";
private static final Pattern CITE_PATTERN =
// Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)");
// citationType is always "1" "2" or "3"
Pattern.compile(BIB_CITATION + "(\\d*)_([123])_(.*)");
private Codec52() {
}
/**
* This is what we get back from parsing a refMarkName.
*/
public static class ParsedMarkName {
/**
* "", "0", "1" ...
*/
public final String index;
/**
* in-text-citation type
*/
public final CitationType citationType;
/**
* Citation keys embedded in the reference mark.
*/
public final List<String> citationKeys;
ParsedMarkName(String index, CitationType citationType, List<String> citationKeys) {
Objects.requireNonNull(index);
Objects.requireNonNull(citationKeys);
this.index = index;
this.citationType = citationType;
this.citationKeys = citationKeys;
}
}
/**
* Integer representation was written into the document in JabRef52, keep it for compatibility.
*/
private static CitationType citationTypeFromInt(int code) {
return switch (code) {
case 1 -> CitationType.AUTHORYEAR_PAR;
case 2 -> CitationType.AUTHORYEAR_INTEXT;
case 3 -> CitationType.INVISIBLE_CIT;
default -> throw new IllegalArgumentException("Invalid CitationType code");
};
}
private static int citationTypeToInt(CitationType type) {
return switch (type) {
case AUTHORYEAR_PAR -> 1;
case AUTHORYEAR_INTEXT -> 2;
case INVISIBLE_CIT -> 3;
};
}
/**
* Produce a reference mark name for JabRef for the given citationType and list citation keys that does not yet appear among the reference marks of the document.
*
* @param usedNames Reference mark names already in use.
* @param citationKeys Identifies the cited sources.
* @param citationType Encodes the effect of withText and inParenthesis options.
* <p>
* The first occurrence of citationKeys gets no serial number, the second gets 0, the third 1 ...
* <p>
* Or the first unused in this series, after removals.
*/
public static String getUniqueMarkName(Set<String> usedNames,
List<String> citationKeys,
CitationType citationType) {
String citationKeysPart = String.join(",", citationKeys);
int index = 0;
int citTypeCode = citationTypeToInt(citationType);
String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart;
while (usedNames.contains(name)) {
name = BIB_CITATION + index + '_' + citTypeCode + '_' + citationKeysPart;
index++;
}
return name;
}
/**
* Parse a JabRef (reference) mark name.
*
* @return Optional.empty() on failure.
*/
public static Optional<ParsedMarkName> parseMarkName(String refMarkName) {
Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName);
if (!citeMatcher.find()) {
return Optional.empty();
}
List<String> keys = Arrays.asList(citeMatcher.group(3).split(","));
String index = citeMatcher.group(1);
int citTypeCode = Integer.parseInt(citeMatcher.group(2));
CitationType citationType = citationTypeFromInt(citTypeCode);
return Optional.of(new Codec52.ParsedMarkName(index, citationType, keys));
}
/**
* @return true if name matches the pattern used for JabRef reference mark names.
*/
public static boolean isJabRefReferenceMarkName(String name) {
return CITE_PATTERN.matcher(name).find();
}
/**
* Filter a list of reference mark names by `isJabRefReferenceMarkName`
*
* @param names The list to be filtered.
*/
public static List<String> filterIsJabRefReferenceMarkName(List<String> names) {
return names.stream()
.filter(Codec52::isJabRefReferenceMarkName)
.collect(Collectors.toList());
}
}
| 4,871 | 34.304348 | 165 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java | package org.jabref.logic.openoffice.backend;
import com.sun.star.text.XTextCursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility methods for processing OO Writer documents.
*/
public class GetContext {
private static final Logger LOGGER = LoggerFactory.getLogger(GetContext.class);
private GetContext() {
}
/**
* Get the text belonging to cursor with up to charBefore and charAfter characters of context.
* <p>
* The actual context may be smaller than requested.
*
* @param charBefore Number of characters requested.
* @param charAfter Number of characters requested.
* @param htmlMarkup If true, the text belonging to the reference mark is surrounded by bold html tag.
*/
public static String getCursorStringWithContext(XTextCursor cursor,
int charBefore,
int charAfter,
boolean htmlMarkup) {
String citPart = cursor.getString();
// extend cursor range left
int flex = 8;
for (int i = 0; i < charBefore; i++) {
try {
cursor.goLeft((short) 1, true);
// If we are close to charBefore and see a space, then cut here. Might avoid cutting
// a word in half.
if ((i >= (charBefore - flex))
&& Character.isWhitespace(cursor.getString().charAt(0))) {
break;
}
} catch (IndexOutOfBoundsException ex) {
LOGGER.warn("Problem going left", ex);
}
}
int lengthWithBefore = cursor.getString().length();
int addedBefore = lengthWithBefore - citPart.length();
cursor.collapseToStart();
for (int i = 0; i < (charAfter + lengthWithBefore); i++) {
try {
cursor.goRight((short) 1, true);
if (i >= ((charAfter + lengthWithBefore) - flex)) {
String strNow = cursor.getString();
if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) {
break;
}
}
} catch (IndexOutOfBoundsException ex) {
LOGGER.warn("Problem going right", ex);
}
}
String result = cursor.getString();
if (htmlMarkup) {
result = result.substring(0, addedBefore)
+ "<b>" + citPart + "</b>"
+ result.substring(lengthWithBefore);
}
return result.trim();
}
}
| 2,689 | 34.394737 | 106 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java | package org.jabref.logic.openoffice.backend;
import java.util.List;
import java.util.Optional;
import org.jabref.model.openoffice.backend.NamedRange;
import org.jabref.model.openoffice.backend.NamedRangeManager;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoReferenceMark;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
public class NamedRangeManagerReferenceMark implements NamedRangeManager {
@Override
public NamedRange createNamedRange(XTextDocument doc,
String refMarkName,
XTextCursor position,
boolean insertSpaceAfter,
boolean withoutBrackets)
throws
CreationException {
return NamedRangeReferenceMark.create(doc, refMarkName, position, insertSpaceAfter, withoutBrackets);
}
@Override
public List<String> getUsedNames(XTextDocument doc)
throws
NoDocumentException {
return UnoReferenceMark.getListOfNames(doc);
}
@Override
public Optional<NamedRange> getNamedRangeFromDocument(XTextDocument doc, String refMarkName)
throws
NoDocumentException,
WrappedTargetException {
return NamedRangeReferenceMark
.getFromDocument(doc, refMarkName)
.map(x -> x);
}
}
| 1,595 | 32.957447 | 109 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java | package org.jabref.logic.openoffice.backend;
import java.util.Optional;
import org.jabref.model.openoffice.backend.NamedRange;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoCursor;
import org.jabref.model.openoffice.uno.UnoReferenceMark;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class NamedRangeReferenceMark implements NamedRange {
private static final String ZERO_WIDTH_SPACE = "\u200b";
// for debugging we may want visible bracket
private static final boolean
REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug;
public static final String
REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<";
public static final String
REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">";
private static final Logger LOGGER = LoggerFactory.getLogger(NamedRangeReferenceMark.class);
/**
* reference mark name
*/
private final String rangeId;
private NamedRangeReferenceMark(String rangeId) {
this.rangeId = rangeId;
}
String getId() {
return rangeId;
}
/**
* Insert {@code n} spaces in a way that reference marks just before or just after the cursor are not affected.
* <p>
* This is based on the observation, that starting two new paragraphs separates us from reference marks on either side.
* <p>
* The pattern used is: {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete}
*
* @param position Where to insert (at position.getStart())
* @param numSpaces Number of spaces to insert.
* @return a new cursor, covering the just-inserted spaces.
*/
private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange position, int numSpaces) {
// Start with an empty cursor at position.getStart();
XText text = position.getText();
XTextCursor cursor = text.createTextCursorByRange(position.getStart());
text.insertString(cursor, "\r\r", false); // para, para
cursor.goLeft((short) 1, false); // left
text.insertString(cursor, " ".repeat(numSpaces), false); // space(numSpaces)
cursor.goRight((short) 1, true);
cursor.setString(""); // right-delete
cursor.goLeft((short) numSpaces, false); // left(numSpaces)
cursor.goLeft((short) 1, true);
cursor.setString(""); // left-delete
cursor.goRight((short) numSpaces, true); // select the newly inserted spaces
return cursor;
}
private static void createReprInDocument(XTextDocument doc,
String refMarkName,
XTextCursor position,
boolean insertSpaceAfter,
boolean withoutBrackets)
throws
CreationException {
// The cursor we received: we push it before us.
position.collapseToEnd();
XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2);
// cursors before the first and after the last space
XTextCursor cursorBefore = cursor.getText().createTextCursorByRange(cursor.getStart());
XTextCursor cursorAfter = cursor.getText().createTextCursorByRange(cursor.getEnd());
cursor.collapseToStart();
cursor.goRight((short) 1, false);
// now we are between two spaces
final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET;
final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET;
String bracketedContent = withoutBrackets
? ""
: left + right;
cursor.getText().insertString(cursor, bracketedContent, true);
UnoReferenceMark.create(doc, refMarkName, cursor, true /* absorb */);
// eat the first inserted space
cursorBefore.goRight((short) 1, true);
cursorBefore.setString("");
if (!insertSpaceAfter) {
// eat the second inserted space
cursorAfter.goLeft((short) 1, true);
cursorAfter.setString("");
}
}
static NamedRangeReferenceMark create(XTextDocument doc,
String refMarkName,
XTextCursor position,
boolean insertSpaceAfter,
boolean withoutBrackets)
throws
CreationException {
createReprInDocument(doc, refMarkName, position, insertSpaceAfter, withoutBrackets);
return new NamedRangeReferenceMark(refMarkName);
}
/**
* @return Optional.empty if there is no corresponding range.
*/
static Optional<NamedRangeReferenceMark> getFromDocument(XTextDocument doc, String refMarkName)
throws
NoDocumentException,
WrappedTargetException {
return UnoReferenceMark.getAnchor(doc, refMarkName)
.map(e -> new NamedRangeReferenceMark(refMarkName));
}
/**
* Remove it from the document.
* <p>
* See: removeCitationGroups
*/
@Override
public void removeFromDocument(XTextDocument doc)
throws
WrappedTargetException,
NoDocumentException {
UnoReferenceMark.removeIfExists(doc, this.getRangeName());
}
@Override
public String getRangeName() {
return rangeId;
}
/**
* @return Optional.empty if the reference mark is missing. See: UnoReferenceMark.getAnchor
*/
@Override
public Optional<XTextRange> getMarkRange(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
String name = this.getRangeName();
return UnoReferenceMark.getAnchor(doc, name);
}
/**
* Cursor for the reference marks as is, not prepared for filling, but does not need cleanFillCursor either.
*
* @return Optional.empty() if reference mark is missing from the document, otherwise an XTextCursor for getMarkRange See: getRawCursorForCitationGroup
*/
@Override
public Optional<XTextCursor> getRawCursor(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
String name = this.getRangeName();
Optional<XTextContent> markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name);
if (markAsTextContent.isEmpty()) {
LOGGER.warn("getRawCursor: markAsTextContent({}).isEmpty()", name);
}
Optional<XTextCursor> full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get());
if (full.isEmpty()) {
LOGGER.warn("getRawCursor: full.isEmpty()");
return Optional.empty();
}
return full;
}
/**
* See: getFillCursorForCitationGroup
*/
@Override
public XTextCursor getFillCursor(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException,
CreationException {
String name = this.getRangeName();
final boolean debugThisFun = false;
XTextCursor full = null;
String fullText = null;
for (int i = 1; i <= 2; i++) {
Optional<XTextContent> markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name);
if (markAsTextContent.isEmpty()) {
String msg = String.format("getFillCursor: markAsTextContent(%s).isEmpty (attempt %d)", name, i);
throw new IllegalStateException(msg);
}
full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()).orElse(null);
if (full == null) {
String msg = String.format("getFillCursor: full == null (attempt %d)", i);
throw new IllegalStateException(msg);
}
fullText = full.getString();
LOGGER.debug("getFillCursor: fulltext = '{}'", fullText);
if (fullText.length() >= 2) {
LOGGER.debug("getFillCursor: (attempt: {}) fulltext.length() >= 2, break loop%n", i);
break;
} else {
// (fullText.length() < 2)
if (i == 2) {
String msg = String.format("getFillCursor: (fullText.length() < 2) (attempt %d)", i);
throw new IllegalStateException(msg);
}
// too short, recreate
LOGGER.warn("getFillCursor: too short, recreate");
full.setString("");
UnoReferenceMark.removeIfExists(doc, name);
final boolean insertSpaceAfter = false;
final boolean withoutBrackets = false;
createReprInDocument(doc, name, full, insertSpaceAfter, withoutBrackets);
}
}
if (full == null) {
throw new IllegalStateException("getFillCursorFor: full == null (after loop)");
}
if (fullText == null) {
throw new IllegalStateException("getFillCursor: fullText == null (after loop)");
}
fullText = full.getString();
if (fullText.length() < 2) {
throw new IllegalStateException("getFillCursor: fullText.length() < 2 (after loop)'%n");
}
XTextCursor beta = full.getText().createTextCursorByRange(full);
beta.collapseToStart();
beta.goRight((short) 1, false);
beta.goRight((short) (fullText.length() - 2), true);
LOGGER.debug("getFillCursor: beta(1) covers '{}'", beta.getString());
final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET;
final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET;
final short rightLength = (short) right.length();
if (fullText.startsWith(left) && fullText.endsWith(right)) {
beta.setString("");
} else {
LOGGER.debug("getFillCursor: recreating brackets for '{}'", fullText);
// we have at least two characters inside
XTextCursor alpha = full.getText().createTextCursorByRange(full);
alpha.collapseToStart();
XTextCursor omega = full.getText().createTextCursorByRange(full);
omega.collapseToEnd();
// beta now covers everything except first and last character
// Replace its content with brackets
String paddingx = "x";
String paddingy = "y";
String paddingz = "z";
beta.setString(paddingx + left + paddingy + right + paddingz);
LOGGER.debug("getFillCursor: beta(2) covers '{}'", beta.getString());
// move beta to before the right bracket
beta.collapseToEnd();
beta.goLeft((short) (rightLength + 1), false);
// remove middle padding
beta.goLeft((short) 1, true);
LOGGER.debug("getFillCursor: beta(3) covers '{}'", beta.getString());
// only drop paddingy later: beta.setString("");
// drop the initial character and paddingx
alpha.collapseToStart();
alpha.goRight((short) (1 + 1), true);
LOGGER.debug("getFillCursor: alpha(4) covers '{}'", alpha.getString());
alpha.setString("");
// drop the last character and paddingz
omega.collapseToEnd();
omega.goLeft((short) (1 + 1), true);
LOGGER.debug("getFillCursor: omega(5) covers '{}'", omega.getString());
omega.setString("");
// drop paddingy now
LOGGER.debug("getFillCursor: beta(6) covers '{}'", beta.getString());
beta.setString("");
// should be OK now.
if (debugThisFun) {
final short leftLength = (short) left.length();
alpha.goRight(leftLength, true);
LOGGER.debug("getFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left);
omega.goLeft(rightLength, true);
LOGGER.debug("getFillCursor: omega(8) covers '{}', should be '{}'", omega.getString(), right);
}
}
// NamedRangeReferenceMark.checkFillCursor(beta);
return beta;
}
/*
* Throw IllegalStateException if the brackets are not there.
*/
public static void checkFillCursor(XTextCursor cursor) {
final String left = REFERENCE_MARK_LEFT_BRACKET;
XTextCursor alpha = cursor.getText().createTextCursorByRange(cursor);
alpha.collapseToStart();
XTextCursor omega = cursor.getText().createTextCursorByRange(cursor);
omega.collapseToEnd();
final short leftLength = (short) left.length();
if (leftLength > 0) {
alpha.goLeft(leftLength, true);
if (!left.equals(alpha.getString())) {
String msg = String.format("checkFillCursor:"
+ " ('%s') is not prefixed with REFERENCE_MARK_LEFT_BRACKET, has '%s'",
cursor.getString(), alpha.getString());
throw new IllegalStateException(msg);
}
}
final String right = REFERENCE_MARK_RIGHT_BRACKET;
final short rightLength = (short) right.length();
if (rightLength > 0) {
omega.goRight(rightLength, true);
if (!right.equals(omega.getString())) {
String msg = String.format("checkFillCursor:"
+ " ('%s') is not followed by REFERENCE_MARK_RIGHT_BRACKET, has '%s'",
cursor.getString(), omega.getString());
throw new IllegalStateException(msg);
}
}
}
/**
* Remove brackets, but if the result would become empty, leave them; if the result would be a single characer, leave the left bracket.
* <p>
* See: cleanFillCursorForCitationGroup
*/
@Override
public void cleanFillCursor(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
// alwaysRemoveBrackets : full compatibility with JabRef 5.2: brackets are temporary, only
// exist between getFillCursor and cleanFillCursor.
final boolean alwaysRemoveBrackets = false;
// removeBracketsFromEmpty is intended to force removal if we are working on an "Empty citation" (INVISIBLE_CIT).
final boolean removeBracketsFromEmpty = false;
String name = this.getRangeName();
XTextCursor full = this.getRawCursor(doc).orElseThrow(IllegalStateException::new);
final String fullText = full.getString();
final String left = REFERENCE_MARK_LEFT_BRACKET;
if (!fullText.startsWith(left)) {
String msg = String.format("cleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name);
throw new IllegalStateException(msg);
}
final String right = REFERENCE_MARK_RIGHT_BRACKET;
if (!fullText.endsWith(right)) {
String msg = String.format("cleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name);
throw new IllegalStateException(msg);
}
final int fullTextLength = fullText.length();
final short leftLength = (short) left.length();
final short rightLength = (short) right.length();
final int contentLength = fullTextLength - (leftLength + rightLength);
if (contentLength < 0) {
String msg = String.format("cleanFillCursor: length(%s) < 0", name);
throw new IllegalStateException(msg);
}
boolean removeRight = (contentLength >= 1)
|| ((contentLength == 0) && removeBracketsFromEmpty)
|| alwaysRemoveBrackets;
boolean removeLeft = (contentLength >= 2)
|| ((contentLength == 0) && removeBracketsFromEmpty)
|| alwaysRemoveBrackets;
if (removeRight) {
XTextCursor omega = full.getText().createTextCursorByRange(full);
omega.collapseToEnd();
omega.goLeft(rightLength, true);
omega.setString("");
}
if (removeLeft) {
XTextCursor alpha = full.getText().createTextCursorByRange(full);
alpha.collapseToStart();
alpha.goRight(leftLength, true);
alpha.setString("");
}
}
}
| 17,017 | 38.121839 | 155 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java | package org.jabref.logic.openoffice.frontend;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jabref.logic.JabRefException;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.openoffice.backend.Backend52;
import org.jabref.model.openoffice.CitationEntry;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor;
import org.jabref.model.openoffice.rangesort.RangeOverlap;
import org.jabref.model.openoffice.rangesort.RangeOverlapBetween;
import org.jabref.model.openoffice.rangesort.RangeOverlapWithin;
import org.jabref.model.openoffice.rangesort.RangeSort;
import org.jabref.model.openoffice.rangesort.RangeSortEntry;
import org.jabref.model.openoffice.rangesort.RangeSortVisual;
import org.jabref.model.openoffice.rangesort.RangeSortable;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroupId;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.style.OODataModel;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoCursor;
import org.jabref.model.openoffice.uno.UnoTextRange;
import org.jabref.model.openoffice.util.OOListUtil;
import org.jabref.model.openoffice.util.OOVoidResult;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
public class OOFrontend {
public final Backend52 backend;
public final CitationGroups citationGroups;
public OOFrontend(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
// TODO: dataModel should come from looking at the document and preferences.
this.backend = new Backend52();
// Get the citationGroupNames
List<String> citationGroupNames = this.backend.getJabRefReferenceMarkNames(doc);
Map<CitationGroupId, CitationGroup> citationGroups =
readCitationGroupsFromDocument(this.backend, doc, citationGroupNames);
this.citationGroups = new CitationGroups(citationGroups);
}
public OODataModel getDataModel() {
return backend.dataModel;
}
public Optional<String> healthReport(XTextDocument doc)
throws
NoDocumentException {
return backend.healthReport(doc);
}
private static Map<CitationGroupId, CitationGroup>
readCitationGroupsFromDocument(Backend52 backend,
XTextDocument doc,
List<String> citationGroupNames)
throws
WrappedTargetException,
NoDocumentException {
Map<CitationGroupId, CitationGroup> citationGroups = new HashMap<>();
for (String name : citationGroupNames) {
CitationGroup group = backend.readCitationGroupFromDocumentOrThrow(doc, name);
citationGroups.put(group.groupId, group);
}
return citationGroups;
}
/**
* Creates a list of {@code RangeSortable<CitationGroup>} values for our {@code CitationGroup} values. Originally designed to be passed to {@code visualSort}.
* <p>
* The elements of the returned list are actually of type {@code RangeSortEntry<CitationGroup>}.
* <p>
* The result is sorted within {@code XTextRange.getText()} partitions of the citation groups according to their {@code XTextRange} (before mapping to footnote marks).
* <p>
* In the result, RangeSortable.getIndexInPosition() contains unique indexes within the original partition (not after mapFootnotesToFootnoteMarks).
*
* @param mapFootnotesToFootnoteMarks If true, replace ranges in footnotes with the range of the corresponding footnote mark. This is used for numbering the citations.
*/
private List<RangeSortable<CitationGroup>> createVisualSortInput(XTextDocument doc,
boolean mapFootnotesToFootnoteMarks)
throws
NoDocumentException,
WrappedTargetException {
List<RangeSortEntry<CitationGroup>> sortables = new ArrayList<>();
for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) {
XTextRange range = this
.getMarkRange(doc, group)
.orElseThrow(IllegalStateException::new);
sortables.add(new RangeSortEntry<>(range, 0, group));
}
/*
* At this point we are almost ready to return sortables.
*
* But we may want to number citations in a footnote as if it appeared where the footnote
* mark is.
*
* The following code replaces ranges within footnotes with the range for the corresponding
* footnote mark.
*
* This brings further ambiguity if we have multiple citation groups within the same
* footnote: for the comparison they become indistinguishable. Numbering between them is
* not controlled. Also combineCiteMarkers will see them in the wrong order (if we use this
* comparison), and will not be able to merge. To avoid these, we sort textually within
* each .getText() partition and add indexInPosition accordingly.
*
*/
// Sort within partitions
RangeSort.RangePartitions<RangeSortEntry<CitationGroup>> partitions =
RangeSort.partitionAndSortRanges(sortables);
// build final list
List<RangeSortEntry<CitationGroup>> result = new ArrayList<>();
for (List<RangeSortEntry<CitationGroup>> partition : partitions.getPartitions()) {
int indexInPartition = 0;
for (RangeSortEntry<CitationGroup> sortable : partition) {
sortable.setIndexInPosition(indexInPartition++);
if (mapFootnotesToFootnoteMarks) {
Optional<XTextRange> footnoteMarkRange =
UnoTextRange.getFootnoteMarkRange(sortable.getRange());
// Adjust range if we are inside a footnote:
footnoteMarkRange.ifPresent(sortable::setRange);
}
result.add(sortable);
}
}
return new ArrayList<>(result);
}
/**
* @param mapFootnotesToFootnoteMarks If true, sort reference marks in footnotes as if they appeared at the corresponding footnote mark.
* @return citation groups sorted by their visual positions. Limitation: for two column layout visual (top-down, left-right) order does not match the expected (textual) order.
*/
private List<CitationGroup> getVisuallySortedCitationGroups(XTextDocument doc,
boolean mapFootnotesToFootnoteMarks,
FunctionalTextViewCursor fcursor)
throws
WrappedTargetException,
NoDocumentException {
List<RangeSortable<CitationGroup>> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks);
List<RangeSortable<CitationGroup>> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor);
return sorted.stream()
.map(RangeSortable::getContent)
.collect(Collectors.toList());
}
/**
* Return citation groups in visual order within (but not across) XText partitions.
* <p>
* This is (1) sufficient for combineCiteMarkers which looks for consecutive XTextRanges within each XText, (2) not confused by multicolumn layout or multipage display.
*/
public List<CitationGroup>
getCitationGroupsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks)
throws
NoDocumentException,
WrappedTargetException {
// This is like getVisuallySortedCitationGroups,
// but we skip the visualSort part.
List<RangeSortable<CitationGroup>> sortables =
createVisualSortInput(doc, mapFootnotesToFootnoteMarks);
return sortables.stream().map(RangeSortable::getContent).collect(Collectors.toList());
}
/**
* Create a citation group for the given citation keys, at the end of position.
* <p>
* On return {@code position} is collapsed, and is after the inserted space, or at the end of the reference mark.
*
* @param citationKeys In storage order
* @param pageInfos In storage order
* @param position Collapsed to its end.
* @param insertSpaceAfter If true, we insert a space after the mark, that carries on format of characters from the original position.
*/
public CitationGroup createCitationGroup(XTextDocument doc,
List<String> citationKeys,
List<Optional<OOText>> pageInfos,
CitationType citationType,
XTextCursor position,
boolean insertSpaceAfter)
throws
CreationException,
NoDocumentException,
WrappedTargetException,
NotRemoveableException,
PropertyVetoException,
IllegalTypeException {
Objects.requireNonNull(pageInfos);
if (pageInfos.size() != citationKeys.size()) {
throw new IllegalArgumentException("pageInfos.size != citationKeys.size");
}
CitationGroup group = backend.createCitationGroup(doc,
citationKeys,
pageInfos,
citationType,
position,
insertSpaceAfter);
this.citationGroups.afterCreateCitationGroup(group);
return group;
}
/**
* Remove {@code group} both from the document and notify {@code citationGroups}
*/
public void removeCitationGroup(CitationGroup group, XTextDocument doc)
throws
WrappedTargetException,
NoDocumentException,
NotRemoveableException {
backend.removeCitationGroup(group, doc);
this.citationGroups.afterRemoveCitationGroup(group);
}
public void removeCitationGroups(List<CitationGroup> citationGroups, XTextDocument doc)
throws
WrappedTargetException,
NoDocumentException,
NotRemoveableException {
for (CitationGroup group : citationGroups) {
removeCitationGroup(group, doc);
}
}
/**
* ranges controlled by citation groups should not overlap with each other.
*
* @return Optional.empty() if the reference mark is missing.
*/
public Optional<XTextRange> getMarkRange(XTextDocument doc, CitationGroup group)
throws
NoDocumentException,
WrappedTargetException {
return backend.getMarkRange(group, doc);
}
public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroup group)
throws
NoDocumentException,
WrappedTargetException,
CreationException {
return backend.getFillCursorForCitationGroup(group, doc);
}
/**
* Remove brackets added by getFillCursorForCitationGroup.
*/
public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup group)
throws
NoDocumentException,
WrappedTargetException {
backend.cleanFillCursorForCitationGroup(group, doc);
}
/**
* @return A RangeForOverlapCheck for each citation group. result.size() == nRefMarks
*/
public List<RangeForOverlapCheck<CitationGroupId>> citationRanges(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
List<RangeForOverlapCheck<CitationGroupId>> result =
new ArrayList<>(citationGroups.numberOfCitationGroups());
for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) {
XTextRange range = this.getMarkRange(doc, group).orElseThrow(IllegalStateException::new);
String description = group.groupId.citationGroupIdAsString();
result.add(new RangeForOverlapCheck<>(range,
group.groupId,
RangeForOverlapCheck.REFERENCE_MARK_KIND,
description));
}
return result;
}
public List<RangeForOverlapCheck<CitationGroupId>> bibliographyRanges(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
List<RangeForOverlapCheck<CitationGroupId>> result = new ArrayList<>();
Optional<XTextRange> range = UpdateBibliography.getBibliographyRange(doc);
if (range.isPresent()) {
String description = "bibliography";
result.add(new RangeForOverlapCheck<>(range.get(),
new CitationGroupId("bibliography"),
RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND,
description));
}
return result;
}
public List<RangeForOverlapCheck<CitationGroupId>> viewCursorRanges(XTextDocument doc) {
List<RangeForOverlapCheck<CitationGroupId>> result = new ArrayList<>();
Optional<XTextRange> range = UnoCursor.getViewCursor(doc).map(e -> e);
if (range.isPresent()) {
String description = "cursor";
result.add(new RangeForOverlapCheck<>(range.get(),
new CitationGroupId("cursor"),
RangeForOverlapCheck.CURSOR_MARK_KIND,
description));
}
return result;
}
/**
* @return A range for each footnote mark where the footnote contains at least one citation group. Purpose: We do not want markers of footnotes containing reference marks to overlap with reference marks. Overwriting these footnote marks might kill our reference marks in the footnote.
* <p>
* Note: Here we directly communicate to the document, not through the backend. This is because mapping ranges to footnote marks does not depend on how do we mark or structure those ranges.
*/
public List<RangeForOverlapCheck<CitationGroupId>>
footnoteMarkRanges(XTextDocument doc, List<RangeForOverlapCheck<CitationGroupId>> citationRanges) {
// We partition by XText and use a single range from
// each partition to get at the corresponding footnotemark range.
List<RangeForOverlapCheck<CitationGroupId>> result = new ArrayList<>();
RangeSort.RangePartitions<RangeForOverlapCheck<CitationGroupId>> partitions =
RangeSort.partitionRanges(citationRanges);
// Each partition corresponds to an XText, and each footnote has a single XText.
// (This latter ignores the possibility of XTextContents inserted into footnotes.)
// Also: different footnotes cannot share a footnotemark range, we are not creating duplicates.
for (List<RangeForOverlapCheck<CitationGroupId>> partition : partitions.getPartitions()) {
if (partition.isEmpty()) {
continue;
}
RangeForOverlapCheck<CitationGroupId> citationRange = partition.get(0);
Optional<XTextRange> footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range);
if (footnoteMarkRange.isEmpty()) {
// not in footnote
continue;
}
result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(),
citationRange.idWithinKind,
RangeForOverlapCheck.FOOTNOTE_MARK_KIND,
"FootnoteMark for " + citationRange.format()));
}
return result;
}
static String rangeOverlapsToMessage(List<RangeOverlap<RangeForOverlapCheck<CitationGroupId>>> overlaps) {
if (overlaps.isEmpty()) {
return "(*no overlaps*)";
}
StringBuilder msg = new StringBuilder();
for (RangeOverlap<RangeForOverlapCheck<CitationGroupId>> overlap : overlaps) {
String listOfRanges = overlap.valuesForOverlappingRanges.stream()
.map(v -> String.format("'%s'", v.format()))
.collect(Collectors.joining(", "));
msg.append(
switch (overlap.kind) {
case EQUAL_RANGE -> Localization.lang("Found identical ranges");
case OVERLAP -> Localization.lang("Found overlapping ranges");
case TOUCH -> Localization.lang("Found touching ranges");
});
msg.append(": ");
msg.append(listOfRanges);
msg.append("\n");
}
return msg.toString();
}
/**
* Check for any overlap between userRanges and protected ranges.
* <p>
* Assume userRanges is small (usually 1 elements for checking the cursor)
* <p>
* Returns on first problem found.
*/
public OOVoidResult<JabRefException>
checkRangeOverlapsWithCursor(XTextDocument doc,
List<RangeForOverlapCheck<CitationGroupId>> userRanges,
boolean requireSeparation)
throws
NoDocumentException,
WrappedTargetException {
List<RangeForOverlapCheck<CitationGroupId>> citationRanges = citationRanges(doc);
List<RangeForOverlapCheck<CitationGroupId>> ranges = new ArrayList<>();
// ranges.addAll(userRanges);
ranges.addAll(bibliographyRanges(doc));
ranges.addAll(citationRanges);
ranges.addAll(footnoteMarkRanges(doc, citationRanges));
List<RangeOverlap<RangeForOverlapCheck<CitationGroupId>>> overlaps =
RangeOverlapBetween.findFirst(doc,
userRanges,
ranges,
requireSeparation);
if (overlaps.isEmpty()) {
return OOVoidResult.ok();
}
return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges",
rangeOverlapsToMessage(overlaps)));
}
/**
* @param requireSeparation Report range pairs that only share a boundary.
* @param reportAtMost Limit number of overlaps reported (0 for no limit)
*/
public OOVoidResult<JabRefException> checkRangeOverlaps(XTextDocument doc,
List<RangeForOverlapCheck<CitationGroupId>> userRanges,
boolean requireSeparation,
int reportAtMost)
throws
NoDocumentException,
WrappedTargetException {
List<RangeForOverlapCheck<CitationGroupId>> citationRanges = citationRanges(doc);
List<RangeForOverlapCheck<CitationGroupId>> ranges = new ArrayList<>();
ranges.addAll(userRanges);
ranges.addAll(bibliographyRanges(doc));
ranges.addAll(citationRanges);
ranges.addAll(footnoteMarkRanges(doc, citationRanges));
List<RangeOverlap<RangeForOverlapCheck<CitationGroupId>>> overlaps =
RangeOverlapWithin.findOverlappingRanges(doc, ranges, requireSeparation, reportAtMost);
if (overlaps.isEmpty()) {
return OOVoidResult.ok();
}
return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges",
rangeOverlapsToMessage(overlaps)));
}
/**
* GUI: Get a list of CitationEntry objects corresponding to citations in the document.
* <p>
* Called from: ManageCitationsDialogViewModel constructor.
*
* @return A list with entries corresponding to citations in the text, in arbitrary order (same order as from getJabRefReferenceMarkNames). Note: visual or alphabetic order could be more manageable for the user. We could provide these here, but switching between them needs change on GUI (adding a toggle or selector).
* <p>
* Note: CitationEntry implements Comparable, where compareTo() and equals() are based on refMarkName. The order used in the "Manage citations" dialog does not seem to use that.
* <p>
* The 1st is labeled "Citation" (show citation in bold, and some context around it).
* <p>
* The columns can be sorted by clicking on the column title. For the "Citation" column, the sorting is based on the content, (the context before the citation), not on the citation itself.
* <p>
* In the "Extra information ..." column some visual indication of the editable part could be helpful.
* <p>
* Wish: selecting an entry (or a button in the line) in the GUI could move the cursor in the document to the entry.
*/
public List<CitationEntry> getCitationEntries(XTextDocument doc)
throws
WrappedTargetException,
NoDocumentException {
return this.backend.getCitationEntries(doc, citationGroups);
}
public void applyCitationEntries(XTextDocument doc, List<CitationEntry> citationEntries)
throws
PropertyVetoException,
IllegalTypeException,
IllegalArgumentException,
WrappedTargetException {
this.backend.applyCitationEntries(doc, citationEntries);
}
public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcursor)
throws
WrappedTargetException,
NoDocumentException {
boolean mapFootnotesToFootnoteMarks = true;
List<CitationGroup> sortedCitationGroups =
getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor);
List<CitationGroupId> sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, group -> group.groupId);
citationGroups.setGlobalOrder(sortedCitationGroupIds);
}
}
| 22,748 | 43.431641 | 322 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java | package org.jabref.logic.openoffice.frontend;
import org.jabref.model.openoffice.rangesort.RangeHolder;
import com.sun.star.text.XTextRange;
/**
* Describe a protected range for overlap checking and reporting.
* <p>
* To check that our protected ranges do not overlap, we collect these ranges. To check for overlaps between these, we need the {@code range} itself. To report the results of overlap checking, we need a {@code description} that can be understood by the user.
* <p>
* To be able to refer back to more extended data, we might need to identify its {@code kind}, and its index in the corresponding tables or other identifier within its kind ({@code idWithinKind})
*/
public class RangeForOverlapCheck<T> implements RangeHolder {
public final static int REFERENCE_MARK_KIND = 0;
public final static int FOOTNOTE_MARK_KIND = 1;
public final static int CURSOR_MARK_KIND = 2;
public final static int BIBLIOGRAPHY_MARK_KIND = 3;
public final XTextRange range;
public final int kind;
public final T idWithinKind;
private final String description;
public RangeForOverlapCheck(XTextRange range, T idWithinKind, int kind, String description) {
this.range = range;
this.kind = kind;
this.idWithinKind = idWithinKind;
this.description = description;
}
public String format() {
return description;
}
@Override
public XTextRange getRange() {
return range;
}
}
| 1,481 | 33.465116 | 258 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java | package org.jabref.logic.openoffice.frontend;
import java.util.Optional;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.logic.openoffice.style.OOFormatBibliography;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.ootext.OOTextIntoOO;
import org.jabref.model.openoffice.style.CitedKeys;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import org.jabref.model.openoffice.uno.UnoBookmark;
import org.jabref.model.openoffice.uno.UnoTextSection;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
public class UpdateBibliography {
private static final String BIB_SECTION_NAME = "JR_bib";
private static final String BIB_SECTION_END_NAME = "JR_bib_end";
private UpdateBibliography() {
}
public static Optional<XTextRange> getBibliographyRange(XTextDocument doc)
throws
NoDocumentException,
WrappedTargetException {
return UnoTextSection.getAnchor(doc, BIB_SECTION_NAME);
}
/**
* Rebuilds the bibliography.
*/
public static void rebuildBibTextSection(XTextDocument doc,
OOFrontend frontend,
CitedKeys bibliography,
OOBibStyle style,
boolean alwaysAddCitedOnPages)
throws
WrappedTargetException,
CreationException,
NoDocumentException {
clearBibTextSectionContent2(doc);
populateBibTextSection(doc,
frontend,
bibliography,
style,
alwaysAddCitedOnPages);
}
/**
* Insert a paragraph break and create a text section for the bibliography.
* <p>
* Only called from `clearBibTextSectionContent2`
*/
private static void createBibTextSection2(XTextDocument doc)
throws
CreationException {
// Always creating at the end of the document.
// Alternatively, we could receive a cursor.
XTextCursor textCursor = doc.getText().createTextCursor();
textCursor.gotoEnd(false);
UnoTextSection.create(doc, BIB_SECTION_NAME, textCursor, false);
}
/**
* Find and clear the text section BIB_SECTION_NAME to "", or create it.
* <p>
* Only called from: `rebuildBibTextSection`
*/
private static void clearBibTextSectionContent2(XTextDocument doc)
throws
CreationException,
NoDocumentException,
WrappedTargetException {
// Optional<XTextRange> sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME);
Optional<XTextRange> sectionRange = getBibliographyRange(doc);
if (sectionRange.isEmpty()) {
createBibTextSection2(doc);
} else {
// Clear it
XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange.get());
cursor.setString("");
}
}
/**
* Only called from: `rebuildBibTextSection`
* <p>
* Assumes the section named BIB_SECTION_NAME exists.
*/
private static void populateBibTextSection(XTextDocument doc,
OOFrontend frontend,
CitedKeys bibliography,
OOBibStyle style,
boolean alwaysAddCitedOnPages)
throws
CreationException,
IllegalArgumentException,
NoDocumentException,
WrappedTargetException {
XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new);
XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange);
// emit the title of the bibliography
OOTextIntoOO.removeDirectFormatting(cursor);
OOText bibliographyText = OOFormatBibliography.formatBibliography(frontend.citationGroups,
bibliography,
style,
alwaysAddCitedOnPages);
OOTextIntoOO.write(doc, cursor, bibliographyText);
cursor.collapseToEnd();
// remove the initial empty paragraph from the section.
sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new);
XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange);
initialParagraph.collapseToStart();
initialParagraph.goRight((short) 1, true);
initialParagraph.setString("");
UnoBookmark.removeIfExists(doc, BIB_SECTION_END_NAME);
UnoBookmark.create(doc, BIB_SECTION_END_NAME, cursor, true);
cursor.collapseToEnd();
}
}
| 5,007 | 35.554745 | 100 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java | package org.jabref.logic.openoffice.frontend;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.jabref.logic.openoffice.style.OOBibStyle;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.ootext.OOTextIntoOO;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.uno.CreationException;
import org.jabref.model.openoffice.uno.NoDocumentException;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UpdateCitationMarkers {
private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCitationMarkers.class);
private UpdateCitationMarkers() {
}
/**
* Visit each reference mark in referenceMarkNames, overwrite its text content.
* <p>
* After each fillCitationMarkInCursor call check if we lost the BIB_SECTION_NAME bookmark and recreate it if we did.
*
* @param style Bibliography style to use.
*/
public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend frontend, OOBibStyle style)
throws
NoDocumentException,
CreationException,
WrappedTargetException {
CitationGroups citationGroups = frontend.citationGroups;
for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) {
boolean withText = group.citationType != CitationType.INVISIBLE_CIT;
Optional<OOText> marker = group.getCitationMarker();
if (marker.isEmpty()) {
LOGGER.warn("applyNewCitationMarkers: no marker for {}",
group.groupId.citationGroupIdAsString());
continue;
}
if (withText && marker.isPresent()) {
XTextCursor cursor = frontend.getFillCursorForCitationGroup(doc, group);
fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style);
frontend.cleanFillCursorForCitationGroup(doc, group);
}
}
}
public static void fillCitationMarkInCursor(XTextDocument doc,
XTextCursor cursor,
OOText citationText,
boolean withText,
OOBibStyle style)
throws
WrappedTargetException,
CreationException,
IllegalArgumentException {
Objects.requireNonNull(cursor);
Objects.requireNonNull(citationText);
Objects.requireNonNull(style);
if (withText) {
OOText citationText2 = style.decorateCitationMarker(citationText);
// inject a ZERO_WIDTH_SPACE to hold the initial character format
final String ZERO_WIDTH_SPACE = "\u200b";
citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.toString());
OOTextIntoOO.write(doc, cursor, citationText2);
} else {
cursor.setString("");
}
}
/**
* Inserts a citation group in the document: creates and fills it.
*
* @param citationKeys BibTeX keys of
* @param citationText Text for the citation. A citation mark or placeholder if not yet available.
* @param position Location to insert at.
* @param insertSpaceAfter A space inserted after the reference mark makes it easier to separate from the text coming after. But is not wanted when we recreate a reference mark.
*/
public static void createAndFillCitationGroup(OOFrontend frontend,
XTextDocument doc,
List<String> citationKeys,
List<Optional<OOText>> pageInfos,
CitationType citationType,
OOText citationText,
XTextCursor position,
OOBibStyle style,
boolean insertSpaceAfter)
throws
NotRemoveableException,
WrappedTargetException,
PropertyVetoException,
IllegalArgumentException,
CreationException,
NoDocumentException,
IllegalTypeException {
Objects.requireNonNull(pageInfos);
if (pageInfos.size() != citationKeys.size()) {
throw new IllegalArgumentException("pageInfos.size != citationKeys.size");
}
CitationGroup group = frontend.createCitationGroup(doc,
citationKeys,
pageInfos,
citationType,
position,
insertSpaceAfter);
final boolean withText = citationType.withText();
if (withText) {
XTextCursor fillCursor = frontend.getFillCursorForCitationGroup(doc, group);
UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style);
frontend.cleanFillCursorForCitationGroup(doc, group);
}
position.collapseToEnd();
}
}
| 5,697 | 39.992806 | 181 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java | package org.jabref.logic.openoffice.style;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.layout.Layout;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.logic.layout.LayoutFormatterPreferences;
import org.jabref.logic.layout.LayoutHelper;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.OrFields;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.EntryTypeFactory;
import org.jabref.model.openoffice.ootext.OOFormat;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.CitationMarkerEntry;
import org.jabref.model.openoffice.style.CitationMarkerNormEntry;
import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry;
import org.jabref.model.openoffice.style.CitationMarkerNumericEntry;
import org.jabref.model.openoffice.style.NonUniqueCitationMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class embodies a bibliography formatting for OpenOffice, which is composed
* of the following elements:
* <p>
* 1) Each OO BIB entry type must have a formatting. A formatting is an array of elements, each
* of which is either a piece of constant text, an entry field value, or a tab. Each element has
* a character format associated with it.
* <p>
* 2) Many field values (e.g. author) need to be formatted before input to OpenOffice. The style
* has the responsibility of formatting all field values. Formatting is handled by 0-n
* JabRef LayoutFormatter classes.
* <p>
* 3) If the entries are not numbered, a citation marker must be produced for each entry. This
* operation is performed for each JabRef BibEntry.
*/
public class OOBibStyle implements Comparable<OOBibStyle> {
public static final String ITALIC_ET_AL = "ItalicEtAl";
public static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological";
public static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount";
public static final String ET_AL_STRING = "EtAlString";
public static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst";
public static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat";
public static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat";
public static final String TITLE = "Title";
public static final String UNDEFINED_CITATION_MARKER = "??";
private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+");
private static final String LAYOUT_MRK = "LAYOUT";
private static final String PROPERTIES_MARK = "PROPERTIES";
private static final String CITATION_MARK = "CITATION";
private static final String NAME_MARK = "NAME";
private static final String JOURNALS_MARK = "JOURNALS";
private static final String DEFAULT_MARK = "default";
private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList";
private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList";
private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator";
private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations";
private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations";
private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations";
private static final String BOLD_CITATIONS = "BoldCitations";
private static final String ITALIC_CITATIONS = "ItalicCitations";
private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat";
private static final String FORMAT_CITATIONS = "FormatCitations";
private static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator";
// These two can do what ItalicCitations, BoldCitations,
// SuperscriptCitations and SubscriptCitations were supposed to do,
// as well as underline smallcaps and strikeout.
private static final String CITATION_GROUP_MARKUP_BEFORE = "CitationGroupMarkupBefore";
private static final String CITATION_GROUP_MARKUP_AFTER = "CitationGroupMarkupAfter";
private static final String AUTHORS_PART_MARKUP_BEFORE = "AuthorsPartMarkupBefore";
private static final String AUTHORS_PART_MARKUP_AFTER = "AuthorsPartMarkupAfter";
private static final String AUTHOR_NAMES_LIST_MARKUP_BEFORE = "AuthorNamesListMarkupBefore";
private static final String AUTHOR_NAMES_LIST_MARKUP_AFTER = "AuthorNamesListMarkupAfter";
private static final String AUTHOR_NAME_MARKUP_BEFORE = "AuthorNameMarkupBefore";
private static final String AUTHOR_NAME_MARKUP_AFTER = "AuthorNameMarkupAfter";
private static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator";
private static final String CITATION_SEPARATOR = "CitationSeparator";
private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator";
private static final String MAX_AUTHORS = "MaxAuthors";
private static final String YEAR_FIELD = "YearField";
private static final String AUTHOR_FIELD = "AuthorField";
private static final String BRACKET_AFTER = "BracketAfter";
private static final String BRACKET_BEFORE = "BracketBefore";
private static final String IS_NUMBER_ENTRIES = "IsNumberEntries";
private static final String IS_SORT_BY_POSITION = "IsSortByPosition";
private static final String SORT_ALGORITHM = "SortAlgorithm";
private static final String OXFORD_COMMA = "OxfordComma";
private static final String YEAR_SEPARATOR = "YearSeparator";
private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText";
private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator";
private static final String AUTHOR_SEPARATOR = "AuthorSeparator";
private static final Pattern QUOTED = Pattern.compile("\".*\"");
private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class);
private final SortedSet<String> journals = new TreeSet<>();
// Formatter to be run on fields before they are used as part of citation marker:
private final LayoutFormatter fieldFormatter = new OOPreFormatter();
// reference layout mapped from entry type:
private final Map<EntryType, Layout> bibLayout = new HashMap<>();
private final Map<String, Object> properties = new HashMap<>();
private final Map<String, Object> citProperties = new HashMap<>();
private final boolean fromResource;
private final String path;
private final LayoutFormatterPreferences layoutPreferences;
private final JournalAbbreviationRepository abbreviationRepository;
private String name = "";
private Layout defaultBibLayout;
private boolean valid;
private Path styleFile;
private long styleFileModificationTime = Long.MIN_VALUE;
private String localCopy;
private boolean isDefaultLayoutPresent;
public OOBibStyle(Path styleFile, LayoutFormatterPreferences layoutPreferences, JournalAbbreviationRepository abbreviationRepository) throws IOException {
this.layoutPreferences = Objects.requireNonNull(layoutPreferences);
this.abbreviationRepository = abbreviationRepository;
this.styleFile = Objects.requireNonNull(styleFile);
setDefaultProperties();
reload();
fromResource = false;
path = styleFile.toAbsolutePath().toString();
}
public OOBibStyle(String resourcePath, LayoutFormatterPreferences layoutPreferences, JournalAbbreviationRepository abbreviationRepository) throws IOException {
this.layoutPreferences = Objects.requireNonNull(layoutPreferences);
this.abbreviationRepository = abbreviationRepository;
Objects.requireNonNull(resourcePath);
setDefaultProperties();
initialize(OOBibStyle.class.getResourceAsStream(resourcePath));
fromResource = true;
path = resourcePath;
}
public Layout getDefaultBibLayout() {
return defaultBibLayout;
}
private void setDefaultProperties() {
// Set default property values:
properties.put(TITLE, "Bibliography");
properties.put(SORT_ALGORITHM, "alphanumeric");
properties.put(IS_SORT_BY_POSITION, Boolean.FALSE);
properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE);
properties.put(BRACKET_BEFORE, "[");
properties.put(BRACKET_AFTER, "]");
properties.put(REFERENCE_PARAGRAPH_FORMAT, "Standard");
properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1");
// Set default properties for the citation marker:
citProperties.put(AUTHOR_FIELD, FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR));
citProperties.put(CITATION_GROUP_MARKUP_BEFORE, "");
citProperties.put(CITATION_GROUP_MARKUP_AFTER, "");
citProperties.put(AUTHORS_PART_MARKUP_BEFORE, "");
citProperties.put(AUTHORS_PART_MARKUP_AFTER, "");
citProperties.put(AUTHOR_NAMES_LIST_MARKUP_BEFORE, "");
citProperties.put(AUTHOR_NAMES_LIST_MARKUP_AFTER, "");
citProperties.put(AUTHOR_NAME_MARKUP_BEFORE, "");
citProperties.put(AUTHOR_NAME_MARKUP_AFTER, "");
citProperties.put(YEAR_FIELD, StandardField.YEAR.getName());
citProperties.put(MAX_AUTHORS, 3);
citProperties.put(MAX_AUTHORS_FIRST, -1);
citProperties.put(AUTHOR_SEPARATOR, ", ");
citProperties.put(AUTHOR_LAST_SEPARATOR, " & ");
citProperties.put(AUTHOR_LAST_SEPARATOR_IN_TEXT, null);
citProperties.put(ET_AL_STRING, " et al.");
citProperties.put(YEAR_SEPARATOR, ", ");
citProperties.put(IN_TEXT_YEAR_SEPARATOR, " ");
citProperties.put(BRACKET_BEFORE, "(");
citProperties.put(BRACKET_AFTER, ")");
citProperties.put(CITATION_SEPARATOR, "; ");
citProperties.put(PAGE_INFO_SEPARATOR, "; ");
citProperties.put(GROUPED_NUMBERS_SEPARATOR, "-");
citProperties.put(MINIMUM_GROUPING_COUNT, 3);
citProperties.put(FORMAT_CITATIONS, Boolean.FALSE);
citProperties.put(CITATION_CHARACTER_FORMAT, "Standard");
citProperties.put(ITALIC_CITATIONS, Boolean.FALSE);
citProperties.put(BOLD_CITATIONS, Boolean.FALSE);
citProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE);
citProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE);
citProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE);
citProperties.put(CITATION_KEY_CITATIONS, Boolean.FALSE);
citProperties.put(ITALIC_ET_AL, Boolean.FALSE);
citProperties.put(OXFORD_COMMA, "");
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public Path getFile() {
return styleFile;
}
public Set<String> getJournals() {
return Collections.unmodifiableSet(journals);
}
private void initialize(InputStream stream) throws IOException {
Objects.requireNonNull(stream);
try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
readFormatFile(reader);
}
}
/**
* If this style was initialized from a file on disk, reload the style
* if the file has been modified since it was read.
*
* @throws IOException
*/
public void ensureUpToDate() throws IOException {
if (!isUpToDate()) {
reload();
}
}
/**
* If this style was initialized from a file on disk, reload the style
* information.
*
* @throws IOException
*/
private void reload() throws IOException {
if (styleFile != null) {
this.styleFileModificationTime = Files.getLastModifiedTime(styleFile).toMillis();
try (InputStream stream = Files.newInputStream(styleFile)) {
initialize(stream);
}
}
}
/**
* If this style was initialized from a file on disk, check whether the file
* is unmodified since initialization.
*
* @return true if the file has not been modified, false otherwise.
*/
private boolean isUpToDate() {
if (styleFile == null) {
return true;
} else {
try {
return Files.getLastModifiedTime(styleFile).toMillis() == this.styleFileModificationTime;
} catch (IOException e) {
return false;
}
}
}
private void readFormatFile(Reader input) throws IOException {
// First read all the contents of the file:
StringBuilder stringBuilder = new StringBuilder();
int chr;
while ((chr = input.read()) != -1) {
stringBuilder.append((char) chr);
}
// Store a local copy for viewing
localCopy = stringBuilder.toString();
// Break into separate lines:
String[] lines = stringBuilder.toString().split("\n");
BibStyleMode mode = BibStyleMode.NONE;
for (String line1 : lines) {
String line = line1;
if (!line.isEmpty() && (line.charAt(line.length() - 1) == '\r')) {
line = line.substring(0, line.length() - 1);
}
// Check for empty line or comment:
if (line.trim().isEmpty() || (line.charAt(0) == '#')) {
continue;
}
// Check if we should change mode:
switch (line) {
case NAME_MARK:
mode = BibStyleMode.NAME;
continue;
case LAYOUT_MRK:
mode = BibStyleMode.LAYOUT;
continue;
case PROPERTIES_MARK:
mode = BibStyleMode.PROPERTIES;
continue;
case CITATION_MARK:
mode = BibStyleMode.CITATION;
continue;
case JOURNALS_MARK:
mode = BibStyleMode.JOURNALS;
continue;
default:
break;
}
switch (mode) {
case NAME:
if (!line.trim().isEmpty()) {
name = line.trim();
}
break;
case LAYOUT:
handleStructureLine(line);
break;
case PROPERTIES:
handlePropertiesLine(line, properties);
break;
case CITATION:
handlePropertiesLine(line, citProperties);
break;
case JOURNALS:
handleJournalsLine(line);
break;
default:
break;
}
}
// Set validity boolean based on whether we found anything interesting
// in the file:
if ((mode != BibStyleMode.NONE) && isDefaultLayoutPresent) {
valid = true;
}
}
/**
* After initializing this style from a file, this method can be used to check
* whether the file appeared to be a proper style file.
*
* @return true if the file could be parsed as a style file, false otherwise.
*/
public boolean isValid() {
return valid;
}
/**
* Parse a line providing bibliography structure information for an entry type.
*
* @param line The string containing the structure description.
*/
private void handleStructureLine(String line) {
int index = line.indexOf('=');
if ((index > 0) && (index < (line.length() - 1))) {
try {
final String typeName = line.substring(0, index);
final String formatString = line.substring(index + 1);
Layout layout = new LayoutHelper(new StringReader(formatString), layoutPreferences, abbreviationRepository).getLayoutFromText();
EntryType type = EntryTypeFactory.parse(typeName);
if (!isDefaultLayoutPresent && OOBibStyle.DEFAULT_MARK.equals(typeName)) {
isDefaultLayoutPresent = true;
defaultBibLayout = layout;
} else {
bibLayout.put(type, layout);
}
} catch (IOException ex) {
LOGGER.warn("Cannot parse bibliography structure", ex);
}
}
}
/**
* Parse a line providing a property name and value.
*
* @param line The line containing the formatter names.
*/
private void handlePropertiesLine(String line, Map<String, Object> map) {
int index = line.indexOf('=');
if ((index > 0) && (index <= (line.length() - 1))) {
String propertyName = line.substring(0, index).trim();
String value = line.substring(index + 1);
if ((value.trim().length() > 1) && QUOTED.matcher(value.trim()).matches()) {
value = value.trim().substring(1, value.trim().length() - 1);
}
Object toSet = value;
if (NUM_PATTERN.matcher(value.trim()).matches()) {
toSet = Integer.parseInt(value.trim());
} else if ("true".equalsIgnoreCase(value.trim())) {
toSet = Boolean.TRUE;
} else if ("false".equalsIgnoreCase(value.trim())) {
toSet = Boolean.FALSE;
}
map.put(propertyName, toSet);
}
}
/**
* Parse a line providing a journal name for which this style is valid.
*/
private void handleJournalsLine(String line) {
if (!line.trim().isEmpty()) {
journals.add(line.trim());
}
}
public Layout getReferenceFormat(EntryType type) {
Layout layout = bibLayout.get(type);
if (layout == null) {
return defaultBibLayout;
} else {
return layout;
}
}
/**
* Convenience method for checking the property for whether we use number citations or
* author-year citations.
*
* @return true if we use numbered citations, false otherwise.
*/
public boolean isNumberEntries() {
return (Boolean) getProperty(IS_NUMBER_ENTRIES);
}
/**
* Convenience method for checking the property for whether we sort the bibliography
* according to their order of appearance in the text.
*
* @return true to sort by appearance, false to sort alphabetically.
*/
public boolean isSortByPosition() {
return (Boolean) getProperty(IS_SORT_BY_POSITION);
}
/**
* Convenience method for checking whether citation markers should be italicized.
* Will only be relevant if isFormatCitations() returns true.
*
* @return true to indicate that citations should be in italics.
*/
public boolean isItalicCitations() {
return (Boolean) citProperties.get(ITALIC_CITATIONS);
}
/**
* Convenience method for checking whether citation markers should be bold.
* Will only be relevant if isFormatCitations() returns true.
*
* @return true to indicate that citations should be in bold.
*/
public boolean isBoldCitations() {
return (Boolean) citProperties.get(BOLD_CITATIONS);
}
/**
* Convenience method for checking whether citation markers formatted
* according to the results of the isItalicCitations() and
* isBoldCitations() methods.
*
* @return true to indicate that citations should be in italics.
*/
public boolean isFormatCitations() {
return (Boolean) citProperties.get(FORMAT_CITATIONS);
}
public boolean isCitationKeyCiteMarkers() {
return (Boolean) citProperties.get(CITATION_KEY_CITATIONS);
}
/**
* Get boolean property.
*
* @param key The property key
* @return the value
*/
public boolean getBooleanCitProperty(String key) {
return (Boolean) citProperties.get(key);
}
public int getIntCitProperty(String key) {
return (Integer) citProperties.get(key);
}
public String getStringCitProperty(String key) {
return (String) citProperties.get(key);
}
public String getCitationCharacterFormat() {
return getStringCitProperty(CITATION_CHARACTER_FORMAT);
}
/**
* Get a style property.
*
* @param propName The property name.
* @return The property value, or null if it doesn't exist.
*/
public Object getProperty(String propName) {
return properties.get(propName);
}
/**
* Indicate if it is an internal style
*
* @return True if an internal style
*/
public boolean isInternalStyle() {
return fromResource;
}
public String getLocalCopy() {
return localCopy;
}
@Override
public int compareTo(OOBibStyle other) {
return getName().compareTo(other.getName());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof OOBibStyle otherStyle) {
return Objects.equals(path, otherStyle.path)
&& Objects.equals(name, otherStyle.name)
&& Objects.equals(citProperties, otherStyle.citProperties)
&& Objects.equals(properties, otherStyle.properties);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(path, name, citProperties, properties);
}
enum BibStyleMode {
NONE,
LAYOUT,
PROPERTIES,
CITATION,
NAME,
JOURNALS
}
/** The String to represent authors that are not mentioned,
* e.g. " et al."
*/
public String getEtAlString() {
return getStringCitProperty(OOBibStyle.ET_AL_STRING);
}
/** The String to add between author names except the last two:
* "[Smith{, }Jones and Brown]"
*/
protected String getAuthorSeparator() {
return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR);
}
/** The String to put after the second to last author in case
* of three or more authors: (A, B{,} and C)
*/
protected String getOxfordComma() {
return getStringCitProperty(OOBibStyle.OXFORD_COMMA);
}
/**
* Title for the bibliography.
*/
public OOText getReferenceHeaderText() {
return OOText.fromString(getStringProperty(OOBibStyle.TITLE));
}
/**
* Name of paragraph format (within OO/LO) to be used for
* the title of the bibliography.
*/
public String getReferenceHeaderParagraphFormat() {
return getStringProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT);
}
/**
* Name of paragraph format (within OO/LO) to be used for
* the entries in the bibliography.
*/
public String getReferenceParagraphFormat() {
return getStringProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT);
}
protected LayoutFormatter getFieldFormatter() {
return fieldFormatter;
}
protected Map<EntryType, Layout> getBibLayout() {
return bibLayout;
}
protected Map<String, Object> getProperties() {
return properties;
}
protected Map<String, Object> getCitProperties() {
return citProperties;
}
protected void addJournal(String journalName) {
journals.add(journalName);
}
protected void setLocalCopy(String contentsOfJstyleFile) {
localCopy = contentsOfJstyleFile;
}
protected void setName(String nameOfTheStyle) {
name = nameOfTheStyle;
}
protected boolean getIsDefaultLayoutPresent() {
return isDefaultLayoutPresent;
}
protected void setIsDefaultLayoutPresent(boolean isPresent) {
isDefaultLayoutPresent = isPresent;
}
protected void setValid(boolean isValid) {
valid = isValid;
}
protected LayoutFormatterPreferences getLayoutPreferences() {
return layoutPreferences;
}
protected void setDefaultBibLayout(Layout layout) {
defaultBibLayout = layout;
}
/**
* Format a number-based citation marker for the given entries.
*
* @return The text for the citation.
*/
public OOText getNumCitationMarker2(List<CitationMarkerNumericEntry> entries) {
final int minGroupingCount = this.getMinimumGroupingCount();
return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this,
entries,
minGroupingCount);
}
/**
* For some tests we need to override minGroupingCount.
*/
public OOText getNumCitationMarker2(List<CitationMarkerNumericEntry> entries,
int minGroupingCount) {
return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this,
entries,
minGroupingCount);
}
/**
* Format a number-based bibliography label for the given number.
*/
public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry entry) {
return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, entry);
}
public OOText getNormalizedCitationMarker(CitationMarkerNormEntry entry) {
return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, entry, Optional.empty());
}
/**
* Format the marker for the in-text citation according to this
* BIB style. Uniquefier letters are added as provided by the
* citationMarkerEntries argument. If successive entries within
* the citation are uniquefied from each other, this method will
* perform a grouping of these entries.
*
* If successive entries within the citation are uniquefied from
* each other, this method will perform a grouping of these
* entries.
*
* @param citationMarkerEntries The list of entries providing the
* data.
*
* @param inParenthesis Signals whether a parenthesized citation
* or an in-text citation is wanted.
*
* @param nonUniqueCitationMarkerHandling
*
* THROWS : Should throw if finds that uniqueLetters
* provided do not make the entries unique.
*
* FORGIVEN : is needed to allow preliminary markers
* for freshly inserted citations without
* going throw the uniquefication process.
*
* @return The formatted citation. The result does not include
* the standard wrappers:
* OOFormat.setLocaleNone() and OOFormat.setCharStyle().
* These are added by decorateCitationMarker()
*/
public OOText createCitationMarker(List<CitationMarkerEntry> citationMarkerEntries,
boolean inParenthesis,
NonUniqueCitationMarker nonUniqueCitationMarkerHandling) {
return OOBibStyleGetCitationMarker.createCitationMarker(this,
citationMarkerEntries,
inParenthesis,
nonUniqueCitationMarkerHandling);
}
/**
* Add setLocaleNone and optionally setCharStyle(CitationCharacterFormat) around
* citationText. Called in fillCitationMarkInCursor, so these are
* also applied to "Unresolved()" entries and numeric styles.
*/
public OOText decorateCitationMarker(OOText citationText) {
OOBibStyle style = this;
OOText citationText2 = OOFormat.setLocaleNone(citationText);
if (style.isFormatCitations()) {
String charStyle = style.getCitationCharacterFormat();
citationText2 = OOFormat.setCharStyle(citationText2, charStyle);
}
return citationText2;
}
/*
*
* Property getters
*
*/
/**
* Minimal number of consecutive citation numbers needed to start
* replacing with an range like "10-13".
*/
public int getMinimumGroupingCount() {
return getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT);
}
/**
* Used in number ranges like "10-13" in numbered citations.
*/
public String getGroupedNumbersSeparator() {
return getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR);
}
private String getStringProperty(String propName) {
return (String) properties.get(propName);
}
/**
* Should citation markers be italicized?
*
*/
public String getCitationGroupMarkupBefore() {
return getStringCitProperty(CITATION_GROUP_MARKUP_BEFORE);
}
public String getCitationGroupMarkupAfter() {
return getStringCitProperty(CITATION_GROUP_MARKUP_AFTER);
}
/** Author list, including " et al." */
public String getAuthorsPartMarkupBefore() {
return getStringCitProperty(AUTHORS_PART_MARKUP_BEFORE);
}
public String getAuthorsPartMarkupAfter() {
return getStringCitProperty(AUTHORS_PART_MARKUP_AFTER);
}
/** Author list, excluding " et al." */
public String getAuthorNamesListMarkupBefore() {
return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_BEFORE);
}
public String getAuthorNamesListMarkupAfter() {
return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_AFTER);
}
/** Author names. Excludes Author separators */
public String getAuthorNameMarkupBefore() {
return getStringCitProperty(AUTHOR_NAME_MARKUP_BEFORE);
}
public String getAuthorNameMarkupAfter() {
return getStringCitProperty(AUTHOR_NAME_MARKUP_AFTER);
}
public boolean getMultiCiteChronological() {
// "MultiCiteChronological"
return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL);
}
// Probably obsolete, now we can use " <i>et al.</i>" instead in EtAlString
public boolean getItalicEtAl() {
// "ItalicEtAl"
return this.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL);
}
/**
* @return Names of fields containing authors: the first
* non-empty field will be used.
*/
protected OrFields getAuthorFieldNames() {
String authorFieldNamesString = this.getStringCitProperty(OOBibStyle.AUTHOR_FIELD);
return FieldFactory.parseOrFields(authorFieldNamesString);
}
/**
* @return Field containing year, with fallback fields.
*/
protected OrFields getYearFieldNames() {
String yearFieldNamesString = this.getStringCitProperty(OOBibStyle.YEAR_FIELD);
return FieldFactory.parseOrFields(yearFieldNamesString);
}
/* The String to add between the two last author names, e.g. " & ". */
protected String getAuthorLastSeparator() {
return getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR);
}
/* As getAuthorLastSeparator, for in-text citation. */
protected String getAuthorLastSeparatorInTextWithFallBack() {
String preferred = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT);
String fallback = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR);
return Objects.requireNonNullElse(preferred, fallback);
}
protected String getPageInfoSeparator() {
return getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR);
}
protected String getUniquefierSeparator() {
return getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR);
}
protected String getCitationSeparator() {
return getStringCitProperty(OOBibStyle.CITATION_SEPARATOR);
}
protected String getYearSeparator() {
return getStringCitProperty(OOBibStyle.YEAR_SEPARATOR);
}
protected String getYearSeparatorInText() {
return getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR);
}
/** The maximum number of authors to write out in full without
* using "et al." Set to -1 to always write out all authors.
*/
protected int getMaxAuthors() {
return getIntCitProperty(OOBibStyle.MAX_AUTHORS);
}
public int getMaxAuthorsFirst() {
return getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST);
}
/** Opening parenthesis before citation (or year, for in-text) */
protected String getBracketBefore() {
return getStringCitProperty(OOBibStyle.BRACKET_BEFORE);
}
/** Closing parenthesis after citation */
protected String getBracketAfter() {
return getStringCitProperty(OOBibStyle.BRACKET_AFTER);
}
/** Opening parenthesis before citation marker in the bibliography. */
private String getBracketBeforeInList() {
return getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST);
}
public String getBracketBeforeInListWithFallBack() {
return Objects.requireNonNullElse(getBracketBeforeInList(), getBracketBefore());
}
/** Closing parenthesis after citation marker in the bibliography */
private String getBracketAfterInList() {
return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST);
}
String getBracketAfterInListWithFallBack() {
return Objects.requireNonNullElse(getBracketAfterInList(), getBracketAfter());
}
public OOText getFormattedBibliographyTitle() {
OOBibStyle style = this;
OOText title = style.getReferenceHeaderText();
String parStyle = style.getReferenceHeaderParagraphFormat();
return parStyle == null
? OOFormat.paragraph(title)
: OOFormat.paragraph(title, parStyle);
}
}
| 34,545 | 36.146237 | 163 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java | package org.jabref.logic.openoffice.style;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.Author;
import org.jabref.model.entry.AuthorList;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.OrFields;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.CitationLookupResult;
import org.jabref.model.openoffice.style.CitationMarkerEntry;
import org.jabref.model.openoffice.style.CitationMarkerNormEntry;
import org.jabref.model.openoffice.style.NonUniqueCitationMarker;
import org.jabref.model.openoffice.style.PageInfo;
import org.jabref.model.strings.StringUtil;
class OOBibStyleGetCitationMarker {
private OOBibStyleGetCitationMarker() {
}
/**
* Look up the nth author and return the "proper" last name for
* citation markers.
*
* Note: "proper" in the sense that it includes the "von" part
* of the name (followed by a space) if there is one.
*
* @param authorList The author list.
* @param number The number of the author to return.
* @return The author name, or an empty String if inapplicable.
*/
private static String getAuthorLastName(AuthorList authorList, int number) {
StringBuilder stringBuilder = new StringBuilder();
if (authorList.getNumberOfAuthors() > number) {
Author author = authorList.getAuthor(number);
// "von " if von exists
Optional<String> von = author.getVon();
if (von.isPresent() && !von.get().isEmpty()) {
stringBuilder.append(von.get());
stringBuilder.append(' ');
}
// last name if it exists
stringBuilder.append(author.getLast().orElse(""));
}
return stringBuilder.toString();
}
private static String markupAuthorName(OOBibStyle style, String name) {
return style.getAuthorNameMarkupBefore()
+ name
+ style.getAuthorNameMarkupAfter();
}
/**
* @param authorList Parsed list of authors.
*
* @param maxAuthors The maximum number of authors to write out.
* If there are more authors, then ET_AL_STRING is emitted
* to mark their omission.
* Set to -1 to write out all authors.
*
* maxAuthors=0 is pointless, now throws IllegalArgumentException
* (Earlier it behaved as maxAuthors=1)
*
* maxAuthors less than -1 : throw IllegalArgumentException
*
* @param andString For "A, B[ and ]C"
*
* @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]"
* or "Au[etAlString][yearSep]"
*
* where AS = AUTHOR_SEPARATOR
* Au, Bu, Cu, Du are last names of authors.
*
* Note:
* - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0).
* - OXFORD_COMMA is only emitted if nAuthors is at least 3.
* - andString is only emitted if nAuthors is at least 2.
*/
private static String formatAuthorList(OOBibStyle style,
AuthorList authorList,
int maxAuthors,
String andString) {
Objects.requireNonNull(authorList);
// Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations.
// In reference lists can be for example 7,
// (https://www.chicagomanualofstyle.org/turabian/turabian-author-date-citation-quick-guide.html)
// but those are handled elsewhere.
//
// There is also
// https://apastyle.apa.org/style-grammar-guidelines/ ...
// ... citations/basic-principles/same-year-first-author
// suggesting the to avoid ambiguity, we may need more than one name
// before "et al.". We do not currently do this kind of disambiguation,
// but we might, one day.
//
final int maxAuthorsBeforeEtAl = 1;
// The String to represent authors that are not mentioned,
// e.g. " et al."
String etAlString = style.getEtAlString();
// getItalicEtAl is not necessary now, since etAlString could
// itself contain the markup.
// This is for backward compatibility.
if (style.getItalicEtAl()) {
etAlString = "<i>" + etAlString + "</i>";
}
// The String to add between author names except the last two,
// e.g. ", ".
String authorSep = style.getAuthorSeparator();
// The String to put after the second to last author in case
// of three or more authors: (A, B[,] and C)
String oxfordComma = style.getOxfordComma();
StringBuilder stringBuilder = new StringBuilder();
final int nAuthors = authorList.getNumberOfAuthors();
// To reduce ambiguity, throw on unexpected values of maxAuthors
if (maxAuthors == 0 && nAuthors != 0) {
throw new IllegalArgumentException("maxAuthors = 0 in formatAuthorList");
}
if (maxAuthors < -1) {
throw new IllegalArgumentException("maxAuthors < -1 in formatAuthorList");
}
// emitAllAuthors == false means use "et al."
boolean emitAllAuthors = (nAuthors <= maxAuthors) || (maxAuthors == -1);
int nAuthorsToEmit = emitAllAuthors
? nAuthors
// If we use "et al." maxAuthorsBeforeEtAl also limits the
// number of authors emitted.
: Math.min(maxAuthorsBeforeEtAl, nAuthors);
if (nAuthorsToEmit >= 1) {
stringBuilder.append(style.getAuthorsPartMarkupBefore());
stringBuilder.append(style.getAuthorNamesListMarkupBefore());
// The first author
String name = getAuthorLastName(authorList, 0);
stringBuilder.append(markupAuthorName(style, name));
}
if (nAuthors >= 2) {
if (emitAllAuthors) {
// Emit last names, except for the last author
int j = 1;
while (j < (nAuthors - 1)) {
stringBuilder.append(authorSep);
String name = getAuthorLastName(authorList, j);
stringBuilder.append(markupAuthorName(style, name));
j++;
}
// oxfordComma if at least 3 authors
if (nAuthors >= 3) {
stringBuilder.append(oxfordComma);
}
// Emit " and "+"LastAuthor"
stringBuilder.append(andString);
String name = getAuthorLastName(authorList, nAuthors - 1);
stringBuilder.append(markupAuthorName(style, name));
} else {
// Emit last names up to nAuthorsToEmit.
//
// The (maxAuthorsBeforeEtAl > 1) test is intended to
// make sure the compiler eliminates this block as
// long as maxAuthorsBeforeEtAl is fixed to 1.
if (maxAuthorsBeforeEtAl > 1) {
int j = 1;
while (j < nAuthorsToEmit) {
stringBuilder.append(authorSep);
String name = getAuthorLastName(authorList, j);
stringBuilder.append(markupAuthorName(style, name));
j++;
}
}
}
}
if (nAuthorsToEmit >= 1) {
stringBuilder.append(style.getAuthorNamesListMarkupAfter());
}
if (nAuthors >= 2 && !emitAllAuthors) {
stringBuilder.append(etAlString);
}
stringBuilder.append(style.getAuthorsPartMarkupAfter());
return stringBuilder.toString();
}
/**
* On success, getRawCitationMarkerField returns content,
* but we also need to know which field matched, because
* for some fields (actually: for author names) we need to
* reproduce the surrounding braces to inform AuthorList.parse
* not to split up the content.
*/
private static class FieldAndContent {
Field field;
String content;
FieldAndContent(Field field, String content) {
this.field = field;
this.content = content;
}
}
/**
* @return the field and the content of the first nonempty (after trimming)
* field (or alias) from {@code fields} found in {@code entry}.
* Return {@code Optional.empty()} if found nothing.
*/
private static Optional<FieldAndContent> getRawCitationMarkerField(BibEntry entry,
BibDatabase database,
OrFields fields) {
Objects.requireNonNull(entry, "Entry cannot be null");
Objects.requireNonNull(database, "database cannot be null");
for (Field field : fields /* FieldFactory.parseOrFields(fields)*/) {
Optional<String> optionalContent = entry.getResolvedFieldOrAlias(field, database);
final boolean foundSomething = optionalContent.isPresent()
&& !optionalContent.get().trim().isEmpty();
if (foundSomething) {
return Optional.of(new FieldAndContent(field, optionalContent.get()));
}
}
return Optional.empty();
}
/**
* This method looks up a field for an entry in a database.
*
* Any number of backup fields can be used if the primary field is
* empty.
*
* @param fields A list of fields, to look up, using first nonempty hit.
*
* If backup fields are needed, separate field
* names by /.
*
* E.g. to use "author" with "editor" as backup,
* specify
* FieldFactory.serializeOrFields(StandardField.AUTHOR,
* StandardField.EDITOR)
*
* @return The resolved field content, or an empty string if the
* field(s) were empty.
*
*
*
*/
private static String getCitationMarkerField(OOBibStyle style,
CitationLookupResult db,
OrFields fields) {
Objects.requireNonNull(db);
Optional<FieldAndContent> optionalFieldAndContent =
getRawCitationMarkerField(db.entry, db.database, fields);
if (optionalFieldAndContent.isEmpty()) {
// No luck? Return an empty string:
return "";
}
FieldAndContent fieldAndContent = optionalFieldAndContent.get();
String result = style.getFieldFormatter().format(fieldAndContent.content);
// If the field we found is mentioned in authorFieldNames and
// content has a pair of braces around it, we add a pair of
// braces around the result, so that AuthorList.parse does not split
// the content.
final OrFields fieldsToRebrace = style.getAuthorFieldNames();
if (fieldsToRebrace.contains(fieldAndContent.field) && StringUtil.isInCurlyBrackets(fieldAndContent.content)) {
result = "{" + result + "}";
}
return result;
}
private static AuthorList getAuthorList(OOBibStyle style, CitationLookupResult db) {
// The bibtex fields providing author names, e.g. "author" or
// "editor".
OrFields authorFieldNames = style.getAuthorFieldNames();
String authorListAsString = getCitationMarkerField(style, db, authorFieldNames);
return AuthorList.parse(authorListAsString);
}
private enum AuthorYearMarkerPurpose {
IN_PARENTHESIS,
IN_TEXT,
NORMALIZED
}
/**
* How many authors would be emitted for entry, considering
* style and entry.getIsFirstAppearanceOfSource()
*
* If entry is unresolved, return 0.
*/
private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry entry) {
if (entry.getLookupResult().isEmpty()) {
// unresolved
return 0;
}
int maxAuthors = entry.getIsFirstAppearanceOfSource()
? style.getMaxAuthorsFirst()
: style.getMaxAuthors();
AuthorList authorList = getAuthorList(style, entry.getLookupResult().get());
int nAuthors = authorList.getNumberOfAuthors();
if (maxAuthors == -1) {
return nAuthors;
} else {
return Integer.min(nAuthors, maxAuthors);
}
}
/**
* Produce (Author, year) or "Author (year)" style citation strings.
*
* @param purpose IN_PARENTHESIS and NORMALIZED puts parentheses around the whole,
* IN_TEXT around each (year,uniqueLetter,pageInfo) part.
*
* NORMALIZED omits uniqueLetter and pageInfo,
* ignores isFirstAppearanceOfSource (always
* style.getMaxAuthors, not getMaxAuthorsFirst)
*
* @param entries The list of CitationMarkerEntry values to process.
*
* Here we do not check for duplicate entries: those
* are handled by {@code getCitationMarker} by
* omitting them from the list.
*
* Unresolved citations recognized by
* entry.getBibEntry() and/or
* entry.getDatabase() returning empty, and
* emitted as "Unresolved${citationKey}".
*
* Neither uniqueLetter nor pageInfo are emitted
* for unresolved citations.
*
* @param startsNewGroup Should have the same length as {@code entries}, and
* contain true for entries starting a new group,
* false for those that only add a uniqueLetter to
* the grouped presentation.
*
* @param maxAuthorsOverride If not empty, always show this number of authors.
* Added to allow NORMALIZED to use maxAuthors value that differs from
* style.getMaxAuthors()
*
* @return The formatted citation.
*
*/
private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style,
AuthorYearMarkerPurpose purpose,
List<CitationMarkerEntry> entries,
boolean[] startsNewGroup,
Optional<Integer> maxAuthorsOverride) {
boolean inParenthesis = purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS
|| purpose == AuthorYearMarkerPurpose.NORMALIZED;
// The String to separate authors from year, e.g. "; ".
String yearSep = inParenthesis
? style.getYearSeparator()
: style.getYearSeparatorInText();
// The opening parenthesis.
String startBrace = style.getBracketBefore();
// The closing parenthesis.
String endBrace = style.getBracketAfter();
// The String to separate citations from each other.
String citationSeparator = style.getCitationSeparator();
// The bibtex field providing the year, e.g. "year".
OrFields yearFieldNames = style.getYearFieldNames();
// The String to add between the two last author names, e.g. " & ".
String andString = inParenthesis
? style.getAuthorLastSeparator()
: style.getAuthorLastSeparatorInTextWithFallBack();
String pageInfoSeparator = style.getPageInfoSeparator();
String uniquefierSeparator = style.getUniquefierSeparator();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(style.getCitationGroupMarkupBefore());
if (inParenthesis) {
stringBuilder.append(startBrace); // shared parenthesis
}
for (int j = 0; j < entries.size(); j++) {
CitationMarkerEntry entry = entries.get(j);
boolean startingNewGroup = startsNewGroup[j];
boolean endingAGroup = (j + 1 == entries.size()) || startsNewGroup[j + 1];
if (!startingNewGroup) {
// Just add our uniqueLetter
String uniqueLetter = entry.getUniqueLetter().orElse(null);
if (uniqueLetter != null) {
stringBuilder.append(uniquefierSeparator);
stringBuilder.append(uniqueLetter);
}
// And close the brace, if we are the last in the group.
if (!inParenthesis && endingAGroup) {
stringBuilder.append(endBrace);
}
continue;
}
if (j > 0) {
stringBuilder.append(citationSeparator);
}
StringBuilder pageInfoPart = new StringBuilder("");
if (purpose != AuthorYearMarkerPurpose.NORMALIZED) {
Optional<OOText> pageInfo =
PageInfo.normalizePageInfo(entry.getPageInfo());
if (pageInfo.isPresent()) {
pageInfoPart.append(pageInfoSeparator);
pageInfoPart.append(OOText.toString(pageInfo.get()));
}
}
final boolean isUnresolved = entry.getLookupResult().isEmpty();
if (isUnresolved) {
stringBuilder.append(String.format("Unresolved(%s)", entry.getCitationKey()));
if (purpose != AuthorYearMarkerPurpose.NORMALIZED) {
stringBuilder.append(pageInfoPart);
}
} else {
CitationLookupResult db = entry.getLookupResult().get();
int maxAuthors = purpose == AuthorYearMarkerPurpose.NORMALIZED
? style.getMaxAuthors()
: calculateNAuthorsToEmit(style, entry);
if (maxAuthorsOverride.isPresent()) {
maxAuthors = maxAuthorsOverride.get();
}
AuthorList authorList = getAuthorList(style, db);
String authorString = formatAuthorList(style, authorList, maxAuthors, andString);
stringBuilder.append(authorString);
stringBuilder.append(yearSep);
if (!inParenthesis) {
stringBuilder.append(startBrace); // parenthesis before year
}
String year = getCitationMarkerField(style, db, yearFieldNames);
if (year != null) {
stringBuilder.append(year);
}
if (purpose != AuthorYearMarkerPurpose.NORMALIZED) {
String uniqueLetter = entry.getUniqueLetter().orElse(null);
if (uniqueLetter != null) {
stringBuilder.append(uniqueLetter);
}
}
if (purpose != AuthorYearMarkerPurpose.NORMALIZED) {
stringBuilder.append(pageInfoPart);
}
if (!inParenthesis && endingAGroup) {
stringBuilder.append(endBrace); // parenthesis after year
}
}
} // for j
if (inParenthesis) {
stringBuilder.append(endBrace); // shared parenthesis
}
stringBuilder.append(style.getCitationGroupMarkupAfter());
return OOText.fromString(stringBuilder.toString());
}
/**
* Add / override methods for the purpose of creating a normalized citation marker.
*/
private static class CitationMarkerNormEntryWrap implements CitationMarkerEntry {
CitationMarkerNormEntry inner;
CitationMarkerNormEntryWrap(CitationMarkerNormEntry inner) {
this.inner = inner;
}
@Override
public String getCitationKey() {
return inner.getCitationKey();
}
@Override
public Optional<CitationLookupResult> getLookupResult() {
return inner.getLookupResult();
}
@Override
public Optional<String> getUniqueLetter() {
return Optional.empty();
}
@Override
public Optional<OOText> getPageInfo() {
return Optional.empty();
}
@Override
public boolean getIsFirstAppearanceOfSource() {
return false;
}
}
/**
* @param normEntry A citation to process.
*
* @return A normalized citation marker for deciding which
* citations need uniqueLetters.
*
* For details of what "normalized" means: {@see getAuthorYearParenthesisMarker2}
*
* Note: now includes some markup.
*/
static OOText getNormalizedCitationMarker(OOBibStyle style,
CitationMarkerNormEntry normEntry,
Optional<Integer> maxAuthorsOverride) {
boolean[] startsNewGroup = {true};
CitationMarkerEntry entry = new CitationMarkerNormEntryWrap(normEntry);
return getAuthorYearParenthesisMarker2(style,
AuthorYearMarkerPurpose.NORMALIZED,
Collections.singletonList(entry),
startsNewGroup,
maxAuthorsOverride);
}
private static List<OOText>
getNormalizedCitationMarkers(OOBibStyle style,
List<CitationMarkerEntry> citationMarkerEntries,
Optional<Integer> maxAuthorsOverride) {
List<OOText> normalizedMarkers = new ArrayList<>(citationMarkerEntries.size());
for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) {
OOText normalized = getNormalizedCitationMarker(style,
citationMarkerEntry,
maxAuthorsOverride);
normalizedMarkers.add(normalized);
}
return normalizedMarkers;
}
/**
* Produce citation marker for a citation group.
*
* Attempts to join consecutive citations: if normalized citations
* markers match and no pageInfo is present, the second entry
* can be presented by appending its uniqueLetter to the
* previous.
*
* If either entry has pageInfo, join is inhibited.
* If the previous entry has more names than we need
* we check with extended normalizedMarkers if they match.
*
* For consecutive identical entries, the second one is omitted.
* Identical requires same pageInfo here, we do not try to merge them.
* Note: notifying the user about them would be nice.
*
* @param citationMarkerEntries A group of citations to process.
*
* @param inParenthesis If true, put parenthesis around the whole group,
* otherwise around each (year,uniqueLetter,pageInfo) part.
*
* @param nonUniqueCitationMarkerHandling What should happen if we
* stumble upon citations with identical normalized
* citation markers which cite different sources and
* are not distinguished by uniqueLetters.
*
* Note: only consecutive citations are checked.
*
*/
public static OOText
createCitationMarker(OOBibStyle style,
List<CitationMarkerEntry> citationMarkerEntries,
boolean inParenthesis,
NonUniqueCitationMarker nonUniqueCitationMarkerHandling) {
final int nEntries = citationMarkerEntries.size();
// Original:
//
// Look for groups of uniquefied entries that should be combined in the output.
// E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b).
//
// Now:
// - handle pageInfos
// - allow duplicate entries with same or different pageInfos.
//
// We assume entries are already sorted, all we need is to
// group consecutive entries if we can.
//
// We also assume, that identical entries have the same uniqueLetters.
//
List<OOText> normalizedMarkers = getNormalizedCitationMarkers(style,
citationMarkerEntries,
Optional.empty());
// How many authors would be emitted without grouping.
int[] nAuthorsToEmit = new int[nEntries];
int[] nAuthorsToEmitRevised = new int[nEntries];
for (int i = 0; i < nEntries; i++) {
CitationMarkerEntry entry = citationMarkerEntries.get(i);
int nAuthors = calculateNAuthorsToEmit(style, entry);
nAuthorsToEmit[i] = nAuthors;
nAuthorsToEmitRevised[i] = nAuthors;
}
boolean[] startsNewGroup = new boolean[nEntries];
List<CitationMarkerEntry> filteredCitationMarkerEntries = new ArrayList<>(nEntries);
int i_out = 0;
if (nEntries > 0) {
filteredCitationMarkerEntries.add(citationMarkerEntries.get(0));
startsNewGroup[i_out] = true;
i_out++;
}
for (int i = 1; i < nEntries; i++) {
final CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1);
final CitationMarkerEntry ce2 = citationMarkerEntries.get(i);
final String nm1 = OOText.toString(normalizedMarkers.get(i - 1));
final String nm2 = OOText.toString(normalizedMarkers.get(i));
final boolean isUnresolved1 = ce1.getLookupResult().isEmpty();
final boolean isUnresolved2 = ce2.getLookupResult().isEmpty();
boolean startingNewGroup;
boolean sameAsPrev; /* true indicates ce2 may be omitted from output */
if (isUnresolved2) {
startingNewGroup = true;
sameAsPrev = false; // keep it visible
} else {
// Does the number of authors to be shown differ?
// Since we compared normalizedMarkers, the difference
// between maxAuthors and maxAuthorsFirst may invalidate
// our expectation that adding uniqueLetter is valid.
boolean nAuthorsShownInhibitsJoin;
if (isUnresolved1) {
nAuthorsShownInhibitsJoin = true; // no join for unresolved
} else {
final boolean isFirst1 = ce1.getIsFirstAppearanceOfSource();
final boolean isFirst2 = ce2.getIsFirstAppearanceOfSource();
// nAuthorsToEmitRevised[i-1] may have been indirectly increased,
// we have to check that too.
if (!isFirst1 &&
!isFirst2 &&
(nAuthorsToEmitRevised[i - 1] == nAuthorsToEmit[i - 1])) {
// we can rely on normalizedMarkers
nAuthorsShownInhibitsJoin = false;
} else if (style.getMaxAuthors() == style.getMaxAuthorsFirst()) {
// we can rely on normalizedMarkers
nAuthorsShownInhibitsJoin = false;
} else {
final int prevShown = nAuthorsToEmitRevised[i - 1];
final int need = nAuthorsToEmit[i];
if (prevShown < need) {
// We do not retrospectively change the number of authors shown
// at the previous entry, take that as decided.
nAuthorsShownInhibitsJoin = true;
} else {
// prevShown >= need
// Check with extended normalizedMarkers.
OOText nmx1 =
getNormalizedCitationMarker(style, ce1, Optional.of(prevShown));
OOText nmx2 =
getNormalizedCitationMarker(style, ce2, Optional.of(prevShown));
boolean extendedMarkersDiffer = !nmx2.equals(nmx1);
nAuthorsShownInhibitsJoin = extendedMarkersDiffer;
}
}
}
final boolean citationKeysDiffer = !ce2.getCitationKey().equals(ce1.getCitationKey());
final boolean normalizedMarkersDiffer = !nm2.equals(nm1);
Optional<OOText> pageInfo2 = PageInfo.normalizePageInfo(ce2.getPageInfo());
Optional<OOText> pageInfo1 = PageInfo.normalizePageInfo(ce1.getPageInfo());
final boolean bothPageInfosAreEmpty = pageInfo2.isEmpty() && pageInfo1.isEmpty();
final boolean pageInfosDiffer = !pageInfo2.equals(pageInfo1);
Optional<String> ul2 = ce2.getUniqueLetter();
Optional<String> ul1 = ce1.getUniqueLetter();
final boolean uniqueLetterPresenceChanged = ul2.isPresent() != ul1.isPresent();
final boolean uniqueLettersDiffer = !ul2.equals(ul1);
final boolean uniqueLetterDoesNotMakeUnique = citationKeysDiffer
&& !normalizedMarkersDiffer
&& !uniqueLettersDiffer;
if (uniqueLetterDoesNotMakeUnique &&
nonUniqueCitationMarkerHandling == NonUniqueCitationMarker.THROWS) {
throw new IllegalArgumentException("different citation keys,"
+ " but same normalizedMarker and uniqueLetter");
}
final boolean pageInfoInhibitsJoin = bothPageInfosAreEmpty
? false
: (citationKeysDiffer || pageInfosDiffer);
startingNewGroup = normalizedMarkersDiffer
|| nAuthorsShownInhibitsJoin
|| pageInfoInhibitsJoin
|| uniqueLetterPresenceChanged
|| uniqueLetterDoesNotMakeUnique;
if (!startingNewGroup) {
// inherit from first of group. Used at next i.
nAuthorsToEmitRevised[i] = nAuthorsToEmitRevised[i - 1];
}
sameAsPrev = !startingNewGroup
&& !uniqueLettersDiffer
&& !citationKeysDiffer
&& !pageInfosDiffer;
}
if (!sameAsPrev) {
filteredCitationMarkerEntries.add(ce2);
startsNewGroup[i_out] = startingNewGroup;
i_out++;
}
}
return getAuthorYearParenthesisMarker2(style,
(inParenthesis
? AuthorYearMarkerPurpose.IN_PARENTHESIS
: AuthorYearMarkerPurpose.IN_TEXT),
filteredCitationMarkerEntries,
startsNewGroup,
Optional.empty());
}
}
| 32,581 | 41.369311 | 119 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java | package org.jabref.logic.openoffice.style;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry;
import org.jabref.model.openoffice.style.CitationMarkerNumericEntry;
import org.jabref.model.openoffice.style.PageInfo;
import org.jabref.model.openoffice.util.OOListUtil;
class OOBibStyleGetNumCitationMarker {
// The number encoding "this entry is unresolved"
public final static int UNRESOLVED_ENTRY_NUMBER = 0;
private OOBibStyleGetNumCitationMarker() {
}
/**
* Defines sort order for CitationMarkerNumericEntry.
*/
private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry a,
CitationMarkerNumericEntry b) {
int na = a.getNumber().orElse(UNRESOLVED_ENTRY_NUMBER);
int nb = b.getNumber().orElse(UNRESOLVED_ENTRY_NUMBER);
int res = Integer.compare(na, nb);
if (res == 0) {
res = PageInfo.comparePageInfo(a.getPageInfo(), b.getPageInfo());
}
return res;
}
/**
* Create a numeric marker for use in the bibliography as label for the entry.
*
* To support for example numbers in superscript without brackets for the text,
* but "[1]" form for the bibliography, the style can provide
* the optional "BracketBeforeInList" and "BracketAfterInList" strings
* to be used in the bibliography instead of "BracketBefore" and "BracketAfter"
*
* @return "[${number}]" where
* "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE)
* "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER)
* "${number}" stands for the formatted number.
*/
public static OOText getNumCitationMarkerForBibliography(OOBibStyle style,
CitationMarkerNumericBibEntry entry) {
// prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST
String bracketBefore = style.getBracketBeforeInListWithFallBack();
String bracketAfter = style.getBracketAfterInListWithFallBack();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(style.getCitationGroupMarkupBefore());
stringBuilder.append(bracketBefore);
final Optional<Integer> current = entry.getNumber();
stringBuilder.append(current.isPresent()
? String.valueOf(current.get())
: (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()));
stringBuilder.append(bracketAfter);
stringBuilder.append(style.getCitationGroupMarkupAfter());
return OOText.fromString(stringBuilder.toString());
}
/*
* emitBlock : a helper for getNumCitationMarker2
*
* Given a block containing either a single entry or two or more
* entries that are joinable into an "i-j" form, append to {@code stringBuilder} the
* formatted text.
*
* Assumes:
*
* - block is not empty
*
* - For a block with a single element the element may have
* pageInfo and its num part may be Optional.empty()
*
* - For a block with two or more elements
*
* - The elements do not have pageInfo and their number part is
* not empty.
*
* - The elements number parts are consecutive positive integers,
* without repetition.
*
*/
private static void emitBlock(List<CitationMarkerNumericEntry> block,
OOBibStyle style,
int minGroupingCount,
StringBuilder stringBuilder) {
final int blockSize = block.size();
if (blockSize == 0) {
throw new IllegalArgumentException("The block is empty");
}
if (blockSize == 1) {
// Add single entry:
CitationMarkerNumericEntry entry = block.get(0);
final Optional<Integer> num = entry.getNumber();
stringBuilder.append(num.isEmpty()
? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())
: String.valueOf(num.get()));
// Emit pageInfo
Optional<OOText> pageInfo = entry.getPageInfo();
if (pageInfo.isPresent()) {
stringBuilder.append(style.getPageInfoSeparator());
stringBuilder.append(OOText.toString(pageInfo.get()));
}
return;
}
if (blockSize >= 2) {
/*
* Check assumptions
*/
if (block.stream().anyMatch(x -> x.getPageInfo().isPresent())) {
throw new IllegalArgumentException("Found pageInfo in a block with more than one elements");
}
if (block.stream().anyMatch(x -> x.getNumber().isEmpty())) {
throw new IllegalArgumentException("Found unresolved entry in a block with more than one elements");
}
for (int j = 1; j < blockSize; j++) {
if ((block.get(j).getNumber().get() - block.get(j - 1).getNumber().get()) != 1) {
throw new IllegalArgumentException("Numbers are not consecutive");
}
}
/*
* Do the actual work
*/
if (blockSize >= minGroupingCount) {
int first = block.get(0).getNumber().get();
int last = block.get(blockSize - 1).getNumber().get();
if (last != (first + blockSize - 1)) {
throw new IllegalArgumentException("blockSize and length of num range differ");
}
// Emit: "first-last"
stringBuilder.append(first);
stringBuilder.append(style.getGroupedNumbersSeparator());
stringBuilder.append(last);
} else {
// Emit: first, first+1,..., last
for (int j = 0; j < blockSize; j++) {
if (j > 0) {
stringBuilder.append(style.getCitationSeparator());
}
stringBuilder.append(block.get(j).getNumber().get());
}
}
}
}
/**
* Format a number-based citation marker for the given number or numbers.
*
* @param entries Provide the citation numbers.
*
* An Optional.empty() number means: could not look this up
* in the databases. Positive integers are the valid numbers.
*
* Duplicate citation numbers are allowed:
*
* - If their pageInfos are identical, only a
* single instance is emitted.
*
* - If their pageInfos differ, the number is emitted with each
* distinct pageInfo.
*
* pageInfos are expected to be normalized
*
* @param minGroupingCount Zero and negative means never group.
* Only used by tests to override the value in style.
*
* @return The text for the citation.
*
*/
public static OOText getNumCitationMarker2(OOBibStyle style,
List<CitationMarkerNumericEntry> entries,
int minGroupingCount) {
final boolean joinIsDisabled = minGroupingCount <= 0;
final int nCitations = entries.size();
final String bracketBefore = style.getBracketBefore();
final String bracketAfter = style.getBracketAfter();
// Sort a copy of entries
List<CitationMarkerNumericEntry> sorted = OOListUtil.map(entries, e -> e);
sorted.sort(OOBibStyleGetNumCitationMarker::compareCitationMarkerNumericEntry);
// "["
StringBuilder stringBuilder = new StringBuilder(bracketBefore);
/*
* Original:
* [2,3,4] -> [2-4]
* [0,1,2] -> [??,1,2]
* [0,1,2,3] -> [??,1-3]
*
* Now we have to consider: duplicate numbers and pageInfos
* [1,1] -> [1]
* [1,1 "pp nn"] -> keep separate if pageInfo differs
* [1 "pp nn",1 "pp nn"] -> [1 "pp nn"]
*/
boolean blocksEmitted = false;
List<CitationMarkerNumericEntry> currentBlock = new ArrayList<>();
List<CitationMarkerNumericEntry> nextBlock = new ArrayList<>();
for (int i = 0; i < nCitations; i++) {
final CitationMarkerNumericEntry current = sorted.get(i);
if (current.getNumber().isPresent() && current.getNumber().get() < 0) {
throw new IllegalArgumentException("getNumCitationMarker2: found negative number");
}
if (currentBlock.isEmpty()) {
currentBlock.add(current);
} else {
CitationMarkerNumericEntry prev = currentBlock.get(currentBlock.size() - 1);
if (current.getNumber().isEmpty() || prev.getNumber().isEmpty()) {
nextBlock.add(current); // do not join if not found
} else if (joinIsDisabled) {
nextBlock.add(current); // join disabled
} else if (compareCitationMarkerNumericEntry(current, prev) == 0) {
// Same as prev, just forget it.
} else if ((current.getNumber().get() == (prev.getNumber().get() + 1))
&& (prev.getPageInfo().isEmpty())
&& (current.getPageInfo().isEmpty())) {
// Just two consecutive numbers without pageInfo: join
currentBlock.add(current);
} else {
// do not join
nextBlock.add(current);
}
}
if (!nextBlock.isEmpty()) {
// emit current block
if (blocksEmitted) {
stringBuilder.append(style.getCitationSeparator());
}
emitBlock(currentBlock, style, minGroupingCount, stringBuilder);
blocksEmitted = true;
currentBlock = nextBlock;
nextBlock = new ArrayList<>();
}
}
if (!nextBlock.isEmpty()) {
throw new IllegalStateException("impossible: (nextBlock.size() != 0) after loop");
}
if (!currentBlock.isEmpty()) {
// We are emitting a block
if (blocksEmitted) {
stringBuilder.append(style.getCitationSeparator());
}
emitBlock(currentBlock, style, minGroupingCount, stringBuilder);
}
// Emit: "]"
stringBuilder.append(bracketAfter);
return OOText.fromString(stringBuilder.toString());
}
}
| 11,067 | 39.542125 | 116 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java | package org.jabref.logic.openoffice.style;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.Layout;
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.UnknownField;
import org.jabref.model.openoffice.ootext.OOFormat;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroupId;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationPath;
import org.jabref.model.openoffice.style.CitedKey;
import org.jabref.model.openoffice.style.CitedKeys;
public class OOFormatBibliography {
private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter();
private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq");
private OOFormatBibliography() {
}
/**
* @return The formatted bibliography, including its title.
*/
public static OOText formatBibliography(CitationGroups citationGroups,
CitedKeys bibliography,
OOBibStyle style,
boolean alwaysAddCitedOnPages) {
OOText title = style.getFormattedBibliographyTitle();
OOText body = formatBibliographyBody(citationGroups, bibliography, style, alwaysAddCitedOnPages);
return OOText.fromString(title.toString() + body.toString());
}
/**
* @return Formatted body of the bibliography. Excludes the title.
*/
public static OOText formatBibliographyBody(CitationGroups citationGroups,
CitedKeys bibliography,
OOBibStyle style,
boolean alwaysAddCitedOnPages) {
StringBuilder stringBuilder = new StringBuilder();
for (CitedKey citedKey : bibliography.values()) {
OOText entryText = formatBibliographyEntry(citationGroups, citedKey, style, alwaysAddCitedOnPages);
stringBuilder.append(entryText.toString());
}
return OOText.fromString(stringBuilder.toString());
}
/**
* @return A paragraph. Includes label and "Cited on pages".
*/
public static OOText formatBibliographyEntry(CitationGroups citationGroups,
CitedKey citedKey,
OOBibStyle style,
boolean alwaysAddCitedOnPages) {
StringBuilder stringBuilder = new StringBuilder();
// insert marker "[1]"
if (style.isNumberEntries()) {
stringBuilder.append(style.getNumCitationMarkerForBibliography(citedKey).toString());
} else {
// !style.isNumberEntries() : emit no prefix
// Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers();
}
// Add entry body
stringBuilder.append(formatBibliographyEntryBody(citedKey, style).toString());
// Add "Cited on pages"
if (citedKey.getLookupResult().isEmpty() || alwaysAddCitedOnPages) {
stringBuilder.append(formatCitedOnPages(citationGroups, citedKey).toString());
}
// Add paragraph
OOText entryText = OOText.fromString(stringBuilder.toString());
String parStyle = style.getReferenceParagraphFormat();
return OOFormat.paragraph(entryText, parStyle);
}
/**
* @return just the body of a bibliography entry. No label, "Cited on pages" or paragraph.
*/
public static OOText formatBibliographyEntryBody(CitedKey citedKey, OOBibStyle style) {
if (citedKey.getLookupResult().isEmpty()) {
// Unresolved entry
return OOText.fromString(String.format("Unresolved(%s)", citedKey.citationKey));
} else {
// Resolved entry, use the layout engine
BibEntry bibentry = citedKey.getLookupResult().get().entry;
Layout layout = style.getReferenceFormat(bibentry.getType());
layout.setPostFormatter(POSTFORMATTER);
return formatFullReferenceOfBibEntry(layout,
bibentry,
citedKey.getLookupResult().get().database,
citedKey.getUniqueLetter().orElse(null));
}
}
/**
* Format the reference part of a bibliography entry using a Layout.
*
* @param layout The Layout to format the reference with.
* @param entry The entry to insert.
* @param database The database the entry belongs to.
* @param uniquefier Uniqiefier letter, if any, to append to the entry's year.
*
* @return OOText The reference part of a bibliography entry formatted as OOText
*/
private static OOText formatFullReferenceOfBibEntry(Layout layout,
BibEntry entry,
BibDatabase database,
String uniquefier) {
// Backup the value of the uniq field, just in case the entry already has it:
Optional<String> oldUniqVal = entry.getField(UNIQUEFIER_FIELD);
// Set the uniq field with the supplied uniquefier:
if (uniquefier == null) {
entry.clearField(UNIQUEFIER_FIELD);
} else {
entry.setField(UNIQUEFIER_FIELD, uniquefier);
}
// Do the layout for this entry:
OOText formattedText = OOText.fromString(layout.doLayout(entry, database));
// Afterwards, reset the old value:
if (oldUniqVal.isPresent()) {
entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get());
} else {
entry.clearField(UNIQUEFIER_FIELD);
}
return formattedText;
}
/**
* Format links to citations of the source (citedKey).
*
* Requires reference marks for the citation groups.
*
* - The links are created as references that show page numbers of the reference marks.
* - We do not control the text shown, that is provided by OpenOffice.
*/
private static OOText formatCitedOnPages(CitationGroups citationGroups, CitedKey citedKey) {
if (!citationGroups.citationGroupsProvideReferenceMarkNameForLinking()) {
return OOText.fromString("");
}
StringBuilder stringBuilder = new StringBuilder();
final String prefix = String.format(" (%s: ", Localization.lang("Cited on pages"));
final String suffix = ")";
stringBuilder.append(prefix);
List<CitationGroup> filteredList = new ArrayList<>();
for (CitationPath path : citedKey.getCitationPaths()) {
CitationGroupId groupId = path.group;
Optional<CitationGroup> group = citationGroups.getCitationGroup(groupId);
if (group.isEmpty()) {
throw new IllegalStateException();
}
filteredList.add(group.get());
}
// sort the citationGroups according to their indexInGlobalOrder
filteredList.sort((a, b) -> {
Integer aa = a.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new);
Integer bb = b.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new);
return aa.compareTo(bb);
});
int index = 0;
for (CitationGroup group : filteredList) {
if (index > 0) {
stringBuilder.append(", ");
}
String markName = group.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new);
OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName);
stringBuilder.append(xref.toString());
index++;
}
stringBuilder.append(suffix);
return OOText.fromString(stringBuilder.toString());
}
}
| 8,319 | 40.809045 | 111 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java | package org.jabref.logic.openoffice.style;
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 preprocesses JabRef fields before they are run through the layout of the bibliography style. It handles translation of LaTeX italic/bold commands into HTML tags.
*/
public class OOPreFormatter implements LayoutFormatter {
private static final Map<String, String> CHARS = HTMLUnicodeConversionMaps.LATEX_UNICODE_CONVERSION_MAP;
@Override
public String format(String field) {
int i;
String finalResult = field.replaceAll("&|\\\\&", "&") // Replace & and \& with &
.replace("\\$", "$") // Replace \$ with $
.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 < finalResult.length(); i++) {
c = finalResult.charAt(i);
if (escaped && (c == '\\')) {
sb.append('\\');
escaped = false;
} else if (c == '\\') {
if (incommand) {
/* Close Command */
String command = currentCommand.toString();
String result = OOPreFormatter.CHARS.get(command);
sb.append(Objects.requireNonNullElse(result, command));
}
escaped = true;
incommand = true;
currentCommand = new StringBuilder();
} else if (!incommand && ((c == '{') || (c == '}'))) {
// Swallow braces, necessary for replacing encoded characters
} else if (Character.isLetter(c) || (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 >= (finalResult.length() - 1)) {
break testCharCom;
}
String command = currentCommand.toString();
i++;
c = finalResult.charAt(i);
String combody;
if (c == '{') {
String part = StringUtil.getPart(finalResult, i, false);
i += part.length();
combody = part;
} else {
combody = finalResult.substring(i, i + 1);
}
String result = OOPreFormatter.CHARS.get(command + combody);
if (result != null) {
sb.append(result);
}
incommand = false;
escaped = false;
} else {
// Are we already at the end of the string?
if ((i + 1) == finalResult.length()) {
String command = currentCommand.toString();
String result = OOPreFormatter.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 {
String argument;
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(finalResult, i, true);
i += part.length();
sb.append('<').append(tag).append('>').append(part).append("</").append(tag).append('>');
} else if (c == '{') {
String part = StringUtil.getPart(finalResult, i, true);
i += part.length();
argument = part;
// handle common case of general latex command
String result = OOPreFormatter.CHARS.get(command + argument);
// If found, then use translated version. If not, then keep the text of the parameter intact.
sb.append(Objects.requireNonNullElse(result, argument));
} 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 = OOPreFormatter.CHARS.get(command);
// If the command is unknown, just print it:
sb.append(Objects.requireNonNullElse(result, command));
} else {
String result = OOPreFormatter.CHARS.get(command);
sb.append(Objects.requireNonNullElse(result, command));
sb.append(' ');
}
} else if (c == '}') {
// System.out.printf("com term by }: '%s'\n", currentCommand.toString());
// argument = "";
} else {
/*
* 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("$", "$"); // Replace $ with $
}
private String getHTMLTag(String latexCommand) {
String result = "";
switch (latexCommand) {
// Should really separate between emphasized and italic but since in later stages both are converted to italic...
case "textit", "it", "emph", "em" -> result = "i"; // Italic
case "textbf", "bf" -> result = "b"; // Bold font
case "textsc" -> result = "smallcaps"; // Small caps
// Not a proper HTML tag, but used here for convenience
case "underline" -> result = "u"; // Underline
case "sout" -> result = "s"; // Strikeout
// sout is the "standard" command, although it is actually based on the package ulem
case "texttt" -> result = "tt"; // Monospace font
case "textsuperscript" -> result = "sup"; // Superscript
case "textsubscript" -> result = "sub"; // Subscript
}
return result;
}
}
| 8,187 | 48.624242 | 179 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java | package org.jabref.logic.openoffice.style;
import java.util.Comparator;
import java.util.List;
import org.jabref.logic.bibtex.comparator.FieldComparator;
import org.jabref.logic.bibtex.comparator.FieldComparatorStack;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.openoffice.style.CitationGroups;
public class OOProcess {
static final Comparator<BibEntry> AUTHOR_YEAR_TITLE_COMPARATOR = makeAuthorYearTitleComparator();
static final Comparator<BibEntry> YEAR_AUTHOR_TITLE_COMPARATOR = makeYearAuthorTitleComparator();
private OOProcess() {
}
private static Comparator<BibEntry> makeAuthorYearTitleComparator() {
List<Comparator<BibEntry>> ayt = List.of(new FieldComparator(StandardField.AUTHOR),
new FieldComparator(StandardField.YEAR),
new FieldComparator(StandardField.TITLE));
return new FieldComparatorStack<>(ayt);
}
private static Comparator<BibEntry> makeYearAuthorTitleComparator() {
List<Comparator<BibEntry>> yat = List.of(new FieldComparator(StandardField.YEAR),
new FieldComparator(StandardField.AUTHOR),
new FieldComparator(StandardField.TITLE));
return new FieldComparatorStack<>(yat);
}
/**
* The comparator used to sort within a group of merged
* citations.
*
* The term used here is "multicite". The option controlling the
* order is "MultiCiteChronological" in style files.
*
* Yes, they are always sorted one way or another.
*/
public static Comparator<BibEntry> comparatorForMulticite(OOBibStyle style) {
if (style.getMultiCiteChronological()) {
return OOProcess.YEAR_AUTHOR_TITLE_COMPARATOR;
} else {
return OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR;
}
}
/**
* Fill citationGroups.bibliography and cgs.citationGroupsUnordered//CitationMarker
* according to style.
*/
public static void produceCitationMarkers(CitationGroups citationGroups, List<BibDatabase> databases, OOBibStyle style) {
if (!citationGroups.hasGlobalOrder()) {
throw new IllegalStateException("produceCitationMarkers: globalOrder is misssing in citationGroups");
}
citationGroups.lookupCitations(databases);
citationGroups.imposeLocalOrder(comparatorForMulticite(style));
// fill CitationGroup.citationMarker
if (style.isCitationKeyCiteMarkers()) {
OOProcessCitationKeyMarkers.produceCitationMarkers(citationGroups, style);
} else if (style.isNumberEntries()) {
OOProcessNumericMarkers.produceCitationMarkers(citationGroups, style);
} else {
OOProcessAuthorYearMarkers.produceCitationMarkers(citationGroups, style);
}
}
}
| 3,048 | 40.202703 | 125 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java | package org.jabref.logic.openoffice.style;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationMarkerEntry;
import org.jabref.model.openoffice.style.CitationType;
import org.jabref.model.openoffice.style.CitedKey;
import org.jabref.model.openoffice.style.CitedKeys;
import org.jabref.model.openoffice.style.NonUniqueCitationMarker;
import org.jabref.model.openoffice.util.OOListUtil;
class OOProcessAuthorYearMarkers {
private OOProcessAuthorYearMarkers() {
}
/**
* Fills {@code sortedCitedKeys//normCitMarker}
*/
private static void createNormalizedCitationMarkers(CitedKeys sortedCitedKeys, OOBibStyle style) {
for (CitedKey ck : sortedCitedKeys.values()) {
ck.setNormalizedCitationMarker(Optional.of(style.getNormalizedCitationMarker(ck)));
}
}
/**
* For each cited source make the citation keys unique by setting
* the uniqueLetter fields to letters ("a", "b") or Optional.empty()
*
* precondition: sortedCitedKeys already has normalized citation markers.
* precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned)
*
* Expects to see data for all cited sources here.
* Clears uniqueLetters before filling.
*
* On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed.
* The same values are copied to the corresponding citations in citationGroups.
*
* Depends on: style, citations and their order.
*/
private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroups citationGroups) {
// The entries in the clashingKeys lists preserve
// firstAppearance order from sortedCitedKeys.values().
//
// The index of the citationKey in this order will decide
// which unique letter it receives.
//
Map<String, List<String>> normCitMarkerToClachingKeys = new HashMap<>();
for (CitedKey citedKey : sortedCitedKeys.values()) {
String normCitMarker = OOText.toString(citedKey.getNormalizedCitationMarker().get());
String citationKey = citedKey.citationKey;
List<String> clashingKeys = normCitMarkerToClachingKeys.putIfAbsent(normCitMarker, new ArrayList<>(1));
if (clashingKeys == null) {
clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker);
}
if (!clashingKeys.contains(citationKey)) {
// First appearance of citationKey, add to list.
clashingKeys.add(citationKey);
}
}
// Clear old uniqueLetter values.
for (CitedKey citedKey : sortedCitedKeys.values()) {
citedKey.setUniqueLetter(Optional.empty());
}
// For sets of citation keys figthing for a normCitMarker
// add unique letters to the year.
for (List<String> clashingKeys : normCitMarkerToClachingKeys.values()) {
if (clashingKeys.size() <= 1) {
continue; // No fight, no letters.
}
// Multiple citation keys: they get their letters
// according to their order in clashingKeys.
int nextUniqueLetter = 'a';
for (String citationKey : clashingKeys) {
String uniqueLetter = String.valueOf((char) nextUniqueLetter);
sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(uniqueLetter));
nextUniqueLetter++;
}
}
sortedCitedKeys.distributeUniqueLetters(citationGroups);
}
/* ***************************************
*
* Calculate presentation of citation groups
* (create citMarkers)
*
* **************************************/
/**
* Set isFirstAppearanceOfSource in each citation.
*
* Preconditions: globalOrder, localOrder
*/
private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups citationGroups) {
Set<String> seenBefore = new HashSet<>();
for (CitationGroup group : citationGroups.getCitationGroupsInGlobalOrder()) {
for (Citation cit : group.getCitationsInLocalOrder()) {
String currentKey = cit.citationKey;
if (!seenBefore.contains(currentKey)) {
cit.setIsFirstAppearanceOfSource(true);
seenBefore.add(currentKey);
} else {
cit.setIsFirstAppearanceOfSource(false);
}
}
}
}
/**
* Produce citMarkers for normal
* (!isCitationKeyCiteMarkers && !isNumberEntries) styles.
*
* @param style Bibliography style.
*/
static void produceCitationMarkers(CitationGroups citationGroups, OOBibStyle style) {
assert !style.isCitationKeyCiteMarkers();
assert !style.isNumberEntries();
// Citations in (Au1, Au2 2000) form
CitedKeys citedKeys = citationGroups.getCitedKeysSortedInOrderOfAppearance();
createNormalizedCitationMarkers(citedKeys, style);
createUniqueLetters(citedKeys, citationGroups);
citationGroups.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR);
// Mark first appearance of each citationKey
setIsFirstAppearanceOfSourceInCitations(citationGroups);
for (CitationGroup group : citationGroups.getCitationGroupsInGlobalOrder()) {
final boolean inParenthesis = group.citationType == CitationType.AUTHORYEAR_PAR;
final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS;
List<Citation> cits = group.getCitationsInLocalOrder();
List<CitationMarkerEntry> citationMarkerEntries = OOListUtil.map(cits, e -> e);
OOText citMarker = style.createCitationMarker(citationMarkerEntries,
inParenthesis,
strictlyUnique);
group.setCitationMarker(Optional.of(citMarker));
}
}
}
| 6,532 | 40.878205 | 115 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java | package org.jabref.logic.openoffice.style;
import java.util.Optional;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.Citation;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.util.OOListUtil;
class OOProcessCitationKeyMarkers {
private OOProcessCitationKeyMarkers() {
}
/**
* Produce citation markers for the case when the citation
* markers are the citation keys themselves, separated by commas.
*/
static void produceCitationMarkers(CitationGroups citationGroups, OOBibStyle style) {
assert style.isCitationKeyCiteMarkers();
citationGroups.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR);
for (CitationGroup group : citationGroups.getCitationGroupsInGlobalOrder()) {
String citMarker =
style.getCitationGroupMarkupBefore()
+ String.join(",", OOListUtil.map(group.getCitationsInLocalOrder(), Citation::getCitationKey))
+ style.getCitationGroupMarkupAfter();
group.setCitationMarker(Optional.of(OOText.fromString(citMarker)));
}
}
}
| 1,259 | 36.058824 | 110 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java | package org.jabref.logic.openoffice.style;
import java.util.List;
import java.util.Optional;
import org.jabref.model.openoffice.ootext.OOText;
import org.jabref.model.openoffice.style.CitationGroup;
import org.jabref.model.openoffice.style.CitationGroups;
import org.jabref.model.openoffice.style.CitationMarkerNumericEntry;
import org.jabref.model.openoffice.util.OOListUtil;
class OOProcessNumericMarkers {
private OOProcessNumericMarkers() {
}
/**
* Produce citation markers for the case of numbered citations
* with bibliography sorted by first appearance in the text.
*
* Numbered citation markers for each CitationGroup.
* Numbering is according to first appearance.
* Assumes global order and local order are already applied.
*/
static void produceCitationMarkers(CitationGroups citationGroups, OOBibStyle style) {
assert style.isNumberEntries();
if (style.isSortByPosition()) {
citationGroups.createNumberedBibliographySortedInOrderOfAppearance();
} else {
citationGroups.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR);
}
for (CitationGroup group : citationGroups.getCitationGroupsInGlobalOrder()) {
List<CitationMarkerNumericEntry> cits = OOListUtil.map(group.getCitationsInLocalOrder(), e -> e);
OOText citMarker = style.getNumCitationMarker2(cits);
group.setCitationMarker(Optional.of(citMarker));
}
}
}
| 1,523 | 36.170732 | 112 | java |
null | jabref-main/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java | package org.jabref.logic.openoffice.style;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.layout.LayoutFormatterPreferences;
import org.jabref.logic.openoffice.OpenOfficePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StyleLoader {
public static final String DEFAULT_AUTHORYEAR_STYLE_PATH = "/resource/openoffice/default_authoryear.jstyle";
public static final String DEFAULT_NUMERICAL_STYLE_PATH = "/resource/openoffice/default_numerical.jstyle";
private static final Logger LOGGER = LoggerFactory.getLogger(StyleLoader.class);
// All internal styles
private final List<String> internalStyleFiles = Arrays.asList(DEFAULT_AUTHORYEAR_STYLE_PATH,
DEFAULT_NUMERICAL_STYLE_PATH);
private final OpenOfficePreferences openOfficePreferences;
private final LayoutFormatterPreferences layoutFormatterPreferences;
private final JournalAbbreviationRepository abbreviationRepository;
// Lists of the internal
// and external styles
private final List<OOBibStyle> internalStyles = new ArrayList<>();
private final List<OOBibStyle> externalStyles = new ArrayList<>();
public StyleLoader(OpenOfficePreferences openOfficePreferences,
LayoutFormatterPreferences formatterPreferences,
JournalAbbreviationRepository abbreviationRepository) {
this.openOfficePreferences = Objects.requireNonNull(openOfficePreferences);
this.layoutFormatterPreferences = Objects.requireNonNull(formatterPreferences);
this.abbreviationRepository = Objects.requireNonNull(abbreviationRepository);
loadInternalStyles();
loadExternalStyles();
}
public List<OOBibStyle> getStyles() {
List<OOBibStyle> result = new ArrayList<>(internalStyles);
result.addAll(externalStyles);
return result;
}
/**
* Adds the given style to the list of styles
*
* @param filename The filename of the style
* @return True if the added style is valid, false otherwise
*/
public boolean addStyleIfValid(String filename) {
Objects.requireNonNull(filename);
try {
OOBibStyle newStyle = new OOBibStyle(Path.of(filename), layoutFormatterPreferences, abbreviationRepository);
if (externalStyles.contains(newStyle)) {
LOGGER.info("External style file {} already existing.", filename);
} else if (newStyle.isValid()) {
externalStyles.add(newStyle);
storeExternalStyles();
return true;
} else {
LOGGER.error("Style with filename {} is invalid", filename);
}
} catch (FileNotFoundException e) {
// The file couldn't be found... should we tell anyone?
LOGGER.info("Cannot find external style file {}", filename, e);
} catch (IOException e) {
LOGGER.info("Problem reading external style file {}", filename, e);
}
return false;
}
private void loadExternalStyles() {
externalStyles.clear();
// Read external lists
List<String> lists = openOfficePreferences.getExternalStyles();
for (String filename : lists) {
try {
OOBibStyle style = new OOBibStyle(Path.of(filename), layoutFormatterPreferences, abbreviationRepository);
if (style.isValid()) { // Problem!
externalStyles.add(style);
} else {
LOGGER.error("Style with filename {} is invalid", filename);
}
} catch (FileNotFoundException e) {
// The file couldn't be found... should we tell anyone?
LOGGER.info("Cannot find external style file {}", filename);
} catch (IOException e) {
LOGGER.info("Problem reading external style file {}", filename, e);
}
}
}
private void loadInternalStyles() {
internalStyles.clear();
for (String filename : internalStyleFiles) {
try {
internalStyles.add(new OOBibStyle(filename, layoutFormatterPreferences, abbreviationRepository));
} catch (IOException e) {
LOGGER.info("Problem reading internal style file {}", filename, e);
}
}
}
private void storeExternalStyles() {
List<String> filenames = new ArrayList<>(externalStyles.size());
for (OOBibStyle style : externalStyles) {
filenames.add(style.getPath());
}
openOfficePreferences.setExternalStyles(filenames);
}
public boolean removeStyle(OOBibStyle style) {
Objects.requireNonNull(style);
if (!style.isInternalStyle()) {
boolean result = externalStyles.remove(style);
storeExternalStyles();
return result;
}
return false;
}
public OOBibStyle getUsedStyle() {
String filename = openOfficePreferences.getCurrentStyle();
if (filename != null) {
for (OOBibStyle style : getStyles()) {
if (filename.equals(style.getPath())) {
return style;
}
}
}
// Pick the first internal
openOfficePreferences.setCurrentStyle(internalStyles.get(0).getPath());
return internalStyles.get(0);
}
}
| 5,677 | 37.890411 | 121 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/AnnotationImporter.java | package org.jabref.logic.pdf;
import java.nio.file.Path;
import java.util.List;
import org.jabref.model.pdf.FileAnnotation;
public interface AnnotationImporter {
List<FileAnnotation> importAnnotations(final Path path);
}
| 229 | 18.166667 | 60 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/EntryAnnotationImporter.java | package org.jabref.logic.pdf;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.preferences.FilePreferences;
/**
* Here all PDF files attached to a BibEntry are scanned for annotations using a PdfAnnotationImporter.
*/
public class EntryAnnotationImporter {
private final BibEntry entry;
/**
* @param entry The BibEntry whose attached files are scanned for annotations.
*/
public EntryAnnotationImporter(BibEntry entry) {
this.entry = entry;
}
/**
* Filter files with a web address containing "www."
*
* @return a list of file parsed files
*/
private List<LinkedFile> getFilteredFileList() {
return entry.getFiles().stream()
.filter(parsedFileField -> "pdf".equalsIgnoreCase(parsedFileField.getFileType()))
.filter(parsedFileField -> !parsedFileField.isOnlineLink()).collect(Collectors.toList());
}
/**
* Reads the annotations from the files that are attached to a BibEntry.
*
* @param databaseContext The context is needed for the importer.
* @return Map from each PDF to a list of file annotations
*/
public Map<Path, List<FileAnnotation>> importAnnotationsFromFiles(BibDatabaseContext databaseContext, FilePreferences filePreferences) {
Map<Path, List<FileAnnotation>> annotations = new HashMap<>();
AnnotationImporter importer = new PdfAnnotationImporter();
// import annotationsOfFiles if the selected files are valid which is checked in getFilteredFileList()
for (LinkedFile linkedFile : this.getFilteredFileList()) {
linkedFile.findIn(databaseContext, filePreferences)
.ifPresent(file -> annotations.put(file, importer.importAnnotations(file)));
}
return annotations;
}
}
| 2,103 | 35.275862 | 140 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/FileAnnotationCache.java | package org.jabref.logic.pdf;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.preferences.FilePreferences;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileAnnotationCache {
private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotation.class);
// cache size in entries
private final static int CACHE_SIZE = 10;
// the inner list holds the annotations per file, the outer collection maps this to a BibEntry.
private LoadingCache<BibEntry, Map<Path, List<FileAnnotation>>> annotationCache;
/**
* Creates an empty fil annotation cache. Required to allow the annotation cache to be injected into views without
* hitting the bug https://github.com/AdamBien/afterburner.fx/issues/71 .
*/
public FileAnnotationCache() {
}
public FileAnnotationCache(BibDatabaseContext context, FilePreferences filePreferences) {
annotationCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).build(new CacheLoader<BibEntry, Map<Path, List<FileAnnotation>>>() {
@Override
public Map<Path, List<FileAnnotation>> load(BibEntry entry) throws Exception {
return new EntryAnnotationImporter(entry).importAnnotationsFromFiles(context, filePreferences);
}
});
}
/**
* Note that entry becomes the most recent entry in the cache
*
* @param entry entry for which to get the annotations
* @return Map containing a list of annotations in a list for each file
*/
public Map<Path, List<FileAnnotation>> getFromCache(BibEntry entry) {
LOGGER.debug(String.format("Loading Bibentry '%s' from cache.", entry.getCitationKey().orElse(entry.getId())));
return annotationCache.getUnchecked(entry);
}
public void remove(BibEntry entry) {
LOGGER.debug(String.format("Deleted Bibentry '%s' from cache.", entry.getCitationKey().orElse(entry.getId())));
annotationCache.invalidate(entry);
}
}
| 2,308 | 38.135593 | 144 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/PdfAnnotationImporter.java | package org.jabref.logic.pdf;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.model.pdf.FileAnnotationType;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PdfAnnotationImporter implements AnnotationImporter {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfAnnotationImporter.class);
/**
* Imports the comments from a pdf specified by its path
*
* @param path a path to a pdf
* @return a list with the all the annotations found in the file of the path
*/
@Override
public List<FileAnnotation> importAnnotations(final Path path) {
if (!validatePath(path)) {
// Path could not be validated, return default result
return Collections.emptyList();
}
List<FileAnnotation> annotationsList = new LinkedList<>();
try (PDDocument document = Loader.loadPDF(path.toFile())) {
PDPageTree pdfPages = document.getDocumentCatalog().getPages();
for (int pageIndex = 0; pageIndex < pdfPages.getCount(); pageIndex++) {
PDPage page = pdfPages.get(pageIndex);
for (PDAnnotation annotation : page.getAnnotations()) {
if (!isSupportedAnnotationType(annotation)) {
continue;
}
if (FileAnnotationType.isMarkedFileAnnotationType(annotation.getSubtype())) {
annotationsList.add(createMarkedAnnotations(pageIndex, page, annotation));
} else {
FileAnnotation fileAnnotation = new FileAnnotation(annotation, pageIndex + 1);
if ((fileAnnotation.getContent() != null) && !fileAnnotation.getContent().isEmpty()) {
annotationsList.add(fileAnnotation);
}
}
}
}
} catch (IOException e) {
LOGGER.error(String.format("Failed to read file '%s'.", path), e);
}
return annotationsList;
}
private boolean isSupportedAnnotationType(PDAnnotation annotation) {
if (annotation.getSubtype() == null) {
return false;
}
if ("Link".equals(annotation.getSubtype()) || "Widget".equals(annotation.getSubtype())) {
LOGGER.debug(annotation.getSubtype() + " is excluded from the supported file annotations");
return false;
}
try {
if (!Arrays.asList(FileAnnotationType.values()).contains(FileAnnotationType.valueOf(annotation.getSubtype()))) {
return false;
}
} catch (IllegalArgumentException e) {
LOGGER.debug(String.format("Could not parse the FileAnnotation %s into any known FileAnnotationType. It was %s!", annotation, annotation.getSubtype()));
}
return true;
}
private FileAnnotation createMarkedAnnotations(int pageIndex, PDPage page, PDAnnotation annotation) {
FileAnnotation annotationBelongingToMarking = new FileAnnotation(
annotation.getCOSObject().getString(COSName.T), FileAnnotation.extractModifiedTime(annotation.getModifiedDate()),
pageIndex + 1, annotation.getContents(), FileAnnotationType.valueOf(annotation.getSubtype().toUpperCase(Locale.ROOT)), Optional.empty());
if (annotationBelongingToMarking.getAnnotationType().isLinkedFileAnnotationType()) {
try {
COSArray boundingBoxes = (COSArray) annotation.getCOSObject().getDictionaryObject(COSName.getPDFName("QuadPoints"));
annotation.setContents(new TextExtractor(page, boundingBoxes).extractMarkedText());
} catch (IOException e) {
annotation.setContents("JabRef: Could not extract any marked text!");
}
}
// Marked text that has a sticky note on it should be linked to the sticky note
return new FileAnnotation(annotation, pageIndex + 1, annotationBelongingToMarking);
}
private boolean validatePath(Path path) {
Objects.requireNonNull(path);
if (!path.toString().toLowerCase(Locale.ROOT).endsWith(".pdf")) {
LOGGER.warn(String.format("File '%s' does not end with .pdf!", path));
return false;
}
if (!Files.exists(path)) {
LOGGER.warn(String.format("File '%s' does not exist!", path));
return false;
}
if (!Files.isRegularFile(path) || !Files.isReadable(path)) {
LOGGER.warn(String.format("File '%s' is not readable!", path));
return false;
}
return true;
}
}
| 5,266 | 40.472441 | 164 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/TextExtractor.java | package org.jabref.logic.pdf;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.Objects;
import org.jabref.architecture.AllowedToUseAwt;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.text.PDFTextStripperByArea;
/**
* Extracts the text of marked annotations using bounding boxes.
*/
@AllowedToUseAwt("org.apache.pdfbox.text.PDFTextStripperByArea.addRegion uses AWT's Rectangle to indicate a region")
public final class TextExtractor {
private final COSArray boundingBoxes;
private final PDPage page;
/**
* @param page the page the annotation is on, must not be null
* @param boundingBoxes the raw annotation, must not be null
*/
public TextExtractor(PDPage page, COSArray boundingBoxes) {
this.page = Objects.requireNonNull(page);
this.boundingBoxes = Objects.requireNonNull(boundingBoxes);
}
/**
* Extracts the text of a marked annotation such as highlights, underlines, strikeouts etc.
*
* @return The text of the annotation
* @throws IOException If the PDFTextStripperByArea fails to initialize.
*/
public String extractMarkedText() throws IOException {
// Text has to be extracted by the rectangle calculated from the marking
PDFTextStripperByArea stripperByArea = new PDFTextStripperByArea();
String markedText = "";
// Iterates over the array of segments. Each segment consists of 8 points forming a bounding box.
int totalSegments = boundingBoxes.size() / 8;
for (int currentSegment = 1, segmentPointer = 0; currentSegment <= totalSegments; currentSegment++, segmentPointer += 8) {
try {
stripperByArea.addRegion("markedRegion", calculateSegmentBoundingBox(boundingBoxes, segmentPointer));
stripperByArea.extractRegions(page);
markedText = markedText.concat(stripperByArea.getTextForRegion("markedRegion"));
} catch (IllegalArgumentException e) {
throw new IOException("Cannot read annotation coordinates!", e);
}
}
return markedText.trim();
}
private Rectangle2D calculateSegmentBoundingBox(COSArray quadsArray, int segmentPointer) {
// Extract coordinate values
float upperLeftX = toFloat(quadsArray.get(segmentPointer));
float upperLeftY = toFloat(quadsArray.get(segmentPointer + 1));
float upperRightX = toFloat(quadsArray.get(segmentPointer + 2));
float upperRightY = toFloat(quadsArray.get(segmentPointer + 3));
float lowerLeftX = toFloat(quadsArray.get(segmentPointer + 4));
float lowerLeftY = toFloat(quadsArray.get(segmentPointer + 5));
// Post-processing of the raw coordinates.
PDRectangle pageSize = page.getMediaBox();
float ulx = upperLeftX - 1; // It is magic.
float uly = pageSize.getHeight() - upperLeftY;
float width = upperRightX - lowerLeftX;
float height = upperRightY - lowerLeftY;
return new Rectangle2D.Float(ulx, uly, width, height);
}
private float toFloat(Object cosNumber) {
if (cosNumber instanceof COSFloat) {
return ((COSFloat) cosNumber).floatValue();
}
if (cosNumber instanceof COSInteger) {
return ((COSInteger) cosNumber).floatValue();
}
throw new IllegalArgumentException("The number type of the annotation is not supported!");
}
}
| 3,664 | 39.722222 | 130 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/search/indexing/DocumentReader.java | package org.jabref.logic.pdf.search.indexing;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jabref.gui.LibraryTab;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.FilePreferences;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.model.pdf.search.SearchFieldConstants.ANNOTATIONS;
import static org.jabref.model.pdf.search.SearchFieldConstants.CONTENT;
import static org.jabref.model.pdf.search.SearchFieldConstants.MODIFIED;
import static org.jabref.model.pdf.search.SearchFieldConstants.PAGE_NUMBER;
import static org.jabref.model.pdf.search.SearchFieldConstants.PATH;
/**
* Utility class for reading the data from LinkedFiles of a BibEntry for Lucene.
*/
public final class DocumentReader {
private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private static final Pattern HYPHEN_LINEBREAK_PATTERN = Pattern.compile("\\-\n");
private static final Pattern LINEBREAK_WITHOUT_PERIOD_PATTERN = Pattern.compile("([^\\\\.])\\n");
private final BibEntry entry;
private final FilePreferences filePreferences;
/**
* Creates a new DocumentReader using a BibEntry.
*
* @param bibEntry Must not be null and must have at least one LinkedFile.
*/
public DocumentReader(BibEntry bibEntry, FilePreferences filePreferences) {
this.filePreferences = filePreferences;
if (bibEntry.getFiles().isEmpty()) {
throw new IllegalStateException("There are no linked PDF files to this BibEntry!");
}
this.entry = bibEntry;
}
/**
* Reads a LinkedFile of a BibEntry and converts it into a Lucene Document which is then returned.
*
* @return An Optional of a Lucene Document with the (meta)data. Can be empty if there is a problem reading the LinkedFile.
*/
public Optional<List<Document>> readLinkedPdf(BibDatabaseContext databaseContext, LinkedFile pdf) {
Optional<Path> pdfPath = pdf.findIn(databaseContext, filePreferences);
if (pdfPath.isPresent()) {
return Optional.of(readPdfContents(pdf, pdfPath.get()));
}
return Optional.empty();
}
/**
* Reads each LinkedFile of a BibEntry and converts them into Lucene Documents which are then returned.
*
* @return A List of Documents with the (meta)data. Can be empty if there is a problem reading the LinkedFile.
*/
public List<Document> readLinkedPdfs(BibDatabaseContext databaseContext) {
return entry.getFiles().stream()
.map(pdf -> readLinkedPdf(databaseContext, pdf))
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(List::stream)
.collect(Collectors.toList());
}
private List<Document> readPdfContents(LinkedFile pdf, Path resolvedPdfPath) {
List<Document> pages = new ArrayList<>();
try (PDDocument pdfDocument = Loader.loadPDF(resolvedPdfPath.toFile())) {
for (int pageNumber = 0; pageNumber < pdfDocument.getNumberOfPages(); pageNumber++) {
Document newDocument = new Document();
addIdentifiers(newDocument, pdf.getLink());
addMetaData(newDocument, resolvedPdfPath, pageNumber);
try {
addContentIfNotEmpty(pdfDocument, newDocument, pageNumber);
} catch (IOException e) {
LOGGER.warn("Could not read page {} of {}", pageNumber, resolvedPdfPath.toAbsolutePath(), e);
}
pages.add(newDocument);
}
} catch (IOException e) {
LOGGER.warn("Could not read {}", resolvedPdfPath.toAbsolutePath(), e);
}
if (pages.isEmpty()) {
Document newDocument = new Document();
addIdentifiers(newDocument, pdf.getLink());
addMetaData(newDocument, resolvedPdfPath, 0);
pages.add(newDocument);
}
return pages;
}
private void addMetaData(Document newDocument, Path resolvedPdfPath, int pageNumber) {
try {
BasicFileAttributes attributes = Files.readAttributes(resolvedPdfPath, BasicFileAttributes.class);
addStringField(newDocument, MODIFIED, String.valueOf(attributes.lastModifiedTime().to(TimeUnit.SECONDS)));
} catch (IOException e) {
LOGGER.error("Could not read timestamp for {}", resolvedPdfPath, e);
}
addStringField(newDocument, PAGE_NUMBER, String.valueOf(pageNumber));
}
private void addStringField(Document newDocument, String field, String value) {
if (!isValidField(value)) {
return;
}
newDocument.add(new StringField(field, value, Field.Store.YES));
}
private boolean isValidField(String value) {
return !(StringUtil.isNullOrEmpty(value));
}
public static String mergeLines(String text) {
String mergedHyphenNewlines = HYPHEN_LINEBREAK_PATTERN.matcher(text).replaceAll("");
return LINEBREAK_WITHOUT_PERIOD_PATTERN.matcher(mergedHyphenNewlines).replaceAll("$1 ");
}
private void addContentIfNotEmpty(PDDocument pdfDocument, Document newDocument, int pageNumber) throws IOException {
PDFTextStripper pdfTextStripper = new PDFTextStripper();
pdfTextStripper.setLineSeparator("\n");
pdfTextStripper.setStartPage(pageNumber);
pdfTextStripper.setEndPage(pageNumber);
String pdfContent = pdfTextStripper.getText(pdfDocument);
if (StringUtil.isNotBlank(pdfContent)) {
newDocument.add(new TextField(CONTENT, mergeLines(pdfContent), Field.Store.YES));
}
PDPage page = pdfDocument.getPage(pageNumber);
List<String> annotations = page.getAnnotations().stream().filter(annotation -> annotation.getContents() != null).map(PDAnnotation::getContents).collect(Collectors.toList());
if (annotations.size() > 0) {
newDocument.add(new TextField(ANNOTATIONS, annotations.stream().collect(Collectors.joining("\n")), Field.Store.YES));
}
}
private void addIdentifiers(Document newDocument, String path) {
newDocument.add(new StringField(PATH, path, Field.Store.YES));
}
}
| 7,166 | 42.174699 | 181 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/search/indexing/IndexingTaskManager.java | package org.jabref.logic.pdf.search.indexing;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
/**
* Wrapper around {@link PdfIndexer} to execute all operations in the background.
*/
public class IndexingTaskManager extends BackgroundTask<Void> {
private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<>();
private TaskExecutor taskExecutor;
private int numOfIndexedFiles = 0;
private final Object lock = new Object();
private boolean isRunning = false;
private boolean isBlockingNewTasks = false;
public IndexingTaskManager(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
showToUser(true);
willBeRecoveredAutomatically(true);
DefaultTaskExecutor.runInJavaFXThread(() -> {
this.updateProgress(1, 1);
this.titleProperty().set(Localization.lang("Indexing pdf files"));
});
}
@Override
protected Void call() throws Exception {
synchronized (lock) {
isRunning = true;
}
updateProgress();
while (!taskQueue.isEmpty() && !isCanceled()) {
taskQueue.poll().run();
numOfIndexedFiles++;
updateProgress();
}
synchronized (lock) {
isRunning = false;
}
return null;
}
private void updateProgress() {
DefaultTaskExecutor.runInJavaFXThread(() -> {
updateMessage(Localization.lang("%0 of %1 linked files added to the index", numOfIndexedFiles, numOfIndexedFiles + taskQueue.size()));
updateProgress(numOfIndexedFiles, numOfIndexedFiles + taskQueue.size());
});
}
private void enqueueTask(Runnable indexingTask) {
if (!isBlockingNewTasks) {
taskQueue.add(indexingTask);
// What if already running?
synchronized (lock) {
if (!isRunning) {
isRunning = true;
this.executeWith(taskExecutor);
showToUser(false);
}
}
}
}
public AutoCloseable blockNewTasks() {
synchronized (lock) {
isBlockingNewTasks = true;
}
return () -> {
synchronized (lock) {
isBlockingNewTasks = false;
}
};
}
public void createIndex(PdfIndexer indexer) {
enqueueTask(indexer::createIndex);
}
public void updateIndex(PdfIndexer indexer, BibDatabaseContext databaseContext) {
Set<String> pathsToRemove = indexer.getListOfFilePaths();
for (BibEntry entry : databaseContext.getEntries()) {
for (LinkedFile file : entry.getFiles()) {
enqueueTask(() -> indexer.addToIndex(entry, file, databaseContext));
pathsToRemove.remove(file.getLink());
}
}
for (String pathToRemove : pathsToRemove) {
enqueueTask(() -> indexer.removeFromIndex(pathToRemove));
}
}
public void addToIndex(PdfIndexer indexer, BibEntry entry, BibDatabaseContext databaseContext) {
enqueueTask(() -> addToIndex(indexer, entry, entry.getFiles(), databaseContext));
}
public void addToIndex(PdfIndexer indexer, BibEntry entry, List<LinkedFile> linkedFiles, BibDatabaseContext databaseContext) {
for (LinkedFile file : linkedFiles) {
enqueueTask(() -> indexer.addToIndex(entry, file, databaseContext));
}
}
public void removeFromIndex(PdfIndexer indexer, BibEntry entry, List<LinkedFile> linkedFiles) {
for (LinkedFile file : linkedFiles) {
enqueueTask(() -> indexer.removeFromIndex(file.getLink()));
}
}
public void removeFromIndex(PdfIndexer indexer, BibEntry entry) {
enqueueTask(() -> removeFromIndex(indexer, entry, entry.getFiles()));
}
public void updateDatabaseName(String name) {
DefaultTaskExecutor.runInJavaFXThread(() -> this.titleProperty().set(Localization.lang("Indexing for %0", name)));
}
}
| 4,433 | 33.372093 | 146 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/search/indexing/PdfIndexer.java | package org.jabref.logic.pdf.search.indexing;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jabref.gui.LibraryTab;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.pdf.search.EnglishStemAnalyzer;
import org.jabref.model.pdf.search.SearchFieldConstants;
import org.jabref.preferences.FilePreferences;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Indexes the text of PDF files and adds it into the lucene search index.
*/
public class PdfIndexer {
private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private final Directory directoryToIndex;
private BibDatabaseContext databaseContext;
private final FilePreferences filePreferences;
public PdfIndexer(Directory indexDirectory, FilePreferences filePreferences) {
this.directoryToIndex = indexDirectory;
this.filePreferences = filePreferences;
}
public static PdfIndexer of(BibDatabaseContext databaseContext, FilePreferences filePreferences) throws IOException {
return new PdfIndexer(new NIOFSDirectory(databaseContext.getFulltextIndexPath()), filePreferences);
}
/**
* Adds all PDF files linked to an entry in the database to new Lucene search index. Any previous state of the
* Lucene search index will be deleted!
*/
public void createIndex() {
// Create new index by creating IndexWriter but not writing anything.
try (IndexWriter indexWriter = new IndexWriter(directoryToIndex, new IndexWriterConfig(new EnglishStemAnalyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE))) {
// empty comment for checkstyle
} catch (IOException e) {
LOGGER.warn("Could not create new Index!", e);
}
}
public void addToIndex(BibDatabaseContext databaseContext) {
for (BibEntry entry : databaseContext.getEntries()) {
addToIndex(entry, databaseContext);
}
}
/**
* Adds all the pdf files linked to one entry in the database to an existing (or new) Lucene search index
*
* @param entry a bibtex entry to link the pdf files to
* @param databaseContext the associated BibDatabaseContext
*/
public void addToIndex(BibEntry entry, BibDatabaseContext databaseContext) {
addToIndex(entry, entry.getFiles(), databaseContext);
}
/**
* Adds a list of pdf files linked to one entry in the database to an existing (or new) Lucene search index
*
* @param entry a bibtex entry to link the pdf files to
* @param databaseContext the associated BibDatabaseContext
*/
public void addToIndex(BibEntry entry, List<LinkedFile> linkedFiles, BibDatabaseContext databaseContext) {
for (LinkedFile linkedFile : linkedFiles) {
addToIndex(entry, linkedFile, databaseContext);
}
}
/**
* Adds a pdf file linked to one entry in the database to an existing (or new) Lucene search index
*
* @param entry a bibtex entry
* @param linkedFile the link to the pdf files
*/
public void addToIndex(BibEntry entry, LinkedFile linkedFile, BibDatabaseContext databaseContext) {
if (databaseContext != null) {
this.databaseContext = databaseContext;
}
if (!entry.getFiles().isEmpty()) {
writeToIndex(entry, linkedFile);
}
}
/**
* Removes a pdf file identified by its path from the index
*
* @param linkedFilePath the path to the file to be removed
*/
public void removeFromIndex(String linkedFilePath) {
try (IndexWriter indexWriter = new IndexWriter(
directoryToIndex,
new IndexWriterConfig(
new EnglishStemAnalyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND))) {
indexWriter.deleteDocuments(new Term(SearchFieldConstants.PATH, linkedFilePath));
indexWriter.commit();
} catch (IOException e) {
LOGGER.warn("Could not initialize the IndexWriter!", e);
}
}
/**
* Removes all files linked to a bib-entry from the index
*
* @param entry the entry documents are linked to
*/
public void removeFromIndex(BibEntry entry) {
removeFromIndex(entry, entry.getFiles());
}
/**
* Removes a list of files linked to a bib-entry from the index
*
* @param entry the entry documents are linked to
*/
public void removeFromIndex(BibEntry entry, List<LinkedFile> linkedFiles) {
for (LinkedFile linkedFile : linkedFiles) {
removeFromIndex(linkedFile.getLink());
}
}
/**
* Deletes all entries from the Lucene search index.
*/
public void flushIndex() {
IndexWriterConfig config = new IndexWriterConfig();
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
try (IndexWriter deleter = new IndexWriter(directoryToIndex, config)) {
// Do nothing. Index is deleted.
} catch (IOException e) {
LOGGER.warn("The IndexWriter could not be initialized", e);
}
}
/**
* Writes all files linked to an entry to the index if the files are not yet in the index or the files on the fs are
* newer than the one in the index.
*
* @param entry the entry associated with the file
*/
private void writeToIndex(BibEntry entry) {
for (LinkedFile linkedFile : entry.getFiles()) {
writeToIndex(entry, linkedFile);
}
}
/**
* Writes the file to the index if the file is not yet in the index or the file on the fs is newer than the one in
* the index.
*
* @param entry the entry associated with the file
* @param linkedFile the file to write to the index
*/
private void writeToIndex(BibEntry entry, LinkedFile linkedFile) {
if (linkedFile.isOnlineLink() || !StandardFileType.PDF.getName().equals(linkedFile.getFileType())) {
return;
}
Optional<Path> resolvedPath = linkedFile.findIn(databaseContext, filePreferences);
if (resolvedPath.isEmpty()) {
LOGGER.debug("Could not find {}", linkedFile.getLink());
return;
}
try {
// Check if a document with this path is already in the index
try (IndexReader reader = DirectoryReader.open(directoryToIndex)) {
IndexSearcher searcher = new IndexSearcher(reader);
TermQuery query = new TermQuery(new Term(SearchFieldConstants.PATH, linkedFile.getLink()));
TopDocs topDocs = searcher.search(query, 1);
// If a document was found, check if is less current than the one in the FS
if (topDocs.scoreDocs.length > 0) {
Document doc = reader.document(topDocs.scoreDocs[0].doc);
long indexModificationTime = Long.parseLong(doc.getField(SearchFieldConstants.MODIFIED).stringValue());
BasicFileAttributes attributes = Files.readAttributes(resolvedPath.get(), BasicFileAttributes.class);
if (indexModificationTime >= attributes.lastModifiedTime().to(TimeUnit.SECONDS)) {
return;
}
}
} catch (IndexNotFoundException e) {
// if there is no index yet, don't need to check anything!
}
// If no document was found, add the new one
Optional<List<Document>> pages = new DocumentReader(entry, filePreferences).readLinkedPdf(this.databaseContext, linkedFile);
if (pages.isPresent()) {
try (IndexWriter indexWriter = new IndexWriter(directoryToIndex,
new IndexWriterConfig(
new EnglishStemAnalyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND))) {
indexWriter.addDocuments(pages.get());
indexWriter.commit();
}
}
} catch (IOException e) {
LOGGER.warn("Could not add the document {} to the index!", linkedFile.getLink(), e);
}
}
/**
* Lists the paths of all the files that are stored in the index
*
* @return all file paths
*/
public Set<String> getListOfFilePaths() {
Set<String> paths = new HashSet<>();
try (IndexReader reader = DirectoryReader.open(directoryToIndex)) {
IndexSearcher searcher = new IndexSearcher(reader);
MatchAllDocsQuery query = new MatchAllDocsQuery();
TopDocs allDocs = searcher.search(query, Integer.MAX_VALUE);
for (ScoreDoc scoreDoc : allDocs.scoreDocs) {
Document doc = reader.document(scoreDoc.doc);
paths.add(doc.getField(SearchFieldConstants.PATH).stringValue());
}
} catch (IOException e) {
return paths;
}
return paths;
}
}
| 10,110 | 39.444 | 172 | java |
null | jabref-main/src/main/java/org/jabref/logic/pdf/search/retrieval/PdfSearcher.java | package org.jabref.logic.pdf.search.retrieval;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import org.jabref.gui.LibraryTab;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.pdf.search.EnglishStemAnalyzer;
import org.jabref.model.pdf.search.PdfSearchResults;
import org.jabref.model.pdf.search.SearchResult;
import org.jabref.model.strings.StringUtil;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.model.pdf.search.SearchFieldConstants.PDF_FIELDS;
public final class PdfSearcher {
private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private final Directory indexDirectory;
private PdfSearcher(Directory indexDirectory) {
this.indexDirectory = indexDirectory;
}
public static PdfSearcher of(BibDatabaseContext databaseContext) throws IOException {
return new PdfSearcher(new NIOFSDirectory(databaseContext.getFulltextIndexPath()));
}
/**
* Search for results matching a query in the Lucene search index
*
* @param searchString a pattern to search for matching entries in the index, must not be null
* @param maxHits number of maximum search results, must be positive
* @return a result set of all documents that have matches in any fields
*/
public PdfSearchResults search(final String searchString, final int maxHits)
throws IOException {
if (StringUtil.isBlank(Objects.requireNonNull(searchString, "The search string was null!"))) {
return new PdfSearchResults();
}
if (maxHits <= 0) {
throw new IllegalArgumentException("Must be called with at least 1 maxHits, was" + maxHits);
}
List<SearchResult> resultDocs = new LinkedList<>();
if (!DirectoryReader.indexExists(indexDirectory)) {
LOGGER.debug("Index directory {} does not yet exist", indexDirectory);
return new PdfSearchResults();
}
try (IndexReader reader = DirectoryReader.open(indexDirectory)) {
IndexSearcher searcher = new IndexSearcher(reader);
Query query = new MultiFieldQueryParser(PDF_FIELDS, new EnglishStemAnalyzer()).parse(searchString);
TopDocs results = searcher.search(query, maxHits);
for (ScoreDoc scoreDoc : results.scoreDocs) {
resultDocs.add(new SearchResult(searcher, query, scoreDoc));
}
return new PdfSearchResults(resultDocs);
} catch (ParseException e) {
LOGGER.warn("Could not parse query: '{}'!\n{}", searchString, e.getMessage());
return new PdfSearchResults();
}
}
}
| 3,235 | 38.950617 | 111 | java |
null | jabref-main/src/main/java/org/jabref/logic/preferences/DOIPreferences.java | package org.jabref.logic.preferences;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class DOIPreferences {
private BooleanProperty useCustom;
private final StringProperty defaultBaseURI;
public DOIPreferences(boolean useCustom, String defaultBaseURI) {
this.useCustom = new SimpleBooleanProperty(useCustom);
this.defaultBaseURI = new SimpleStringProperty(defaultBaseURI);
}
public boolean isUseCustom() {
return useCustom.get();
}
public BooleanProperty useCustomProperty() {
return useCustom;
}
public void setUseCustom(boolean useCustom) {
this.useCustom.set(useCustom);
}
public String getDefaultBaseURI() {
return defaultBaseURI.get();
}
public StringProperty defaultBaseURIProperty() {
return defaultBaseURI;
}
public void setDefaultBaseURI(String defaultBaseURI) {
this.defaultBaseURI.set(defaultBaseURI);
}
}
| 1,108 | 26.04878 | 71 | java |
null | jabref-main/src/main/java/org/jabref/logic/preferences/FetcherApiKey.java | package org.jabref.logic.preferences;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class FetcherApiKey {
private final StringProperty name;
private final BooleanProperty use;
private final StringProperty key;
public FetcherApiKey(String name, boolean use, String key) {
this.name = new SimpleStringProperty(name);
this.use = new SimpleBooleanProperty(use);
this.key = new SimpleStringProperty(key);
}
public String getName() {
return name.getValue();
}
public boolean shouldUse() {
return use.getValue();
}
public BooleanProperty useProperty() {
return use;
}
public void setUse(boolean useCustom) {
this.use.setValue(useCustom);
}
public String getKey() {
return key.getValue();
}
public StringProperty keyProperty() {
return key;
}
public void setKey(String key) {
this.key.setValue(key);
}
}
| 1,117 | 22.787234 | 64 | java |
null | jabref-main/src/main/java/org/jabref/logic/preferences/OwnerPreferences.java | package org.jabref.logic.preferences;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class OwnerPreferences {
private final BooleanProperty useOwner;
private final StringProperty defaultOwner;
private final BooleanProperty overwriteOwner;
public OwnerPreferences(boolean useOwner,
String defaultOwner,
boolean overwriteOwner) {
this.useOwner = new SimpleBooleanProperty(useOwner);
this.defaultOwner = new SimpleStringProperty(defaultOwner);
this.overwriteOwner = new SimpleBooleanProperty(overwriteOwner);
}
public boolean isUseOwner() {
return useOwner.getValue();
}
public BooleanProperty useOwnerProperty() {
return useOwner;
}
public void setUseOwner(boolean useOwner) {
this.useOwner.set(useOwner);
}
public String getDefaultOwner() {
return defaultOwner.getValue();
}
public StringProperty defaultOwnerProperty() {
return defaultOwner;
}
public void setDefaultOwner(String defaultOwner) {
this.defaultOwner.set(defaultOwner);
}
public boolean isOverwriteOwner() {
return overwriteOwner.getValue();
}
public BooleanProperty overwriteOwnerProperty() {
return overwriteOwner;
}
public void setOverwriteOwner(boolean overwriteOwner) {
this.overwriteOwner.set(overwriteOwner);
}
}
| 1,592 | 26.947368 | 72 | java |
null | jabref-main/src/main/java/org/jabref/logic/preferences/TimestampPreferences.java | package org.jabref.logic.preferences;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.jabref.model.entry.field.Field;
public class TimestampPreferences {
private final BooleanProperty addCreationDate;
private final BooleanProperty addModificationDate;
// These are old preferences. They are used for migration only.
private final boolean updateTimestamp;
private final Field timestampField;
private final String timestampFormat;
public TimestampPreferences(boolean addCreationDate, boolean modifyTimestamp, boolean updateTimestamp, Field timestampField, String timestampFormat) {
this.addCreationDate = new SimpleBooleanProperty(addCreationDate);
this.addModificationDate = new SimpleBooleanProperty(modifyTimestamp);
this.updateTimestamp = updateTimestamp;
this.timestampField = timestampField;
this.timestampFormat = timestampFormat;
}
public String now() {
// Milli-, Micro-, and Nanoseconds are not relevant to us, so we remove them
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
}
public boolean shouldAddCreationDate() {
return addCreationDate.get();
}
public BooleanProperty addCreationDateProperty() {
return addCreationDate;
}
public void setAddCreationDate(boolean addCreationDate) {
this.addCreationDate.set(addCreationDate);
}
public boolean shouldAddModificationDate() {
return addModificationDate.get();
}
public BooleanProperty addModificationDateProperty() {
return addModificationDate;
}
public void setAddModificationDate(boolean addModificationDate) {
this.addModificationDate.set(addModificationDate);
}
/**
* Required for migration only.
*/
public boolean shouldUpdateTimestamp() {
return updateTimestamp;
}
/**
* Required for migration only.
*/
public Field getTimestampField() {
return timestampField;
}
/**
* Required for migration only.
*/
public String getTimestampFormat() {
return timestampFormat;
}
}
| 2,361 | 28.898734 | 154 | java |
null | jabref-main/src/main/java/org/jabref/logic/preview/PreviewLayout.java | package org.jabref.logic.preview;
import java.util.Locale;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
/**
* Used for displaying a rendered entry in the UI. Due to historical reasons, "rendering" is called "layout".
*/
public interface PreviewLayout {
String generatePreview(BibEntry entry, BibDatabaseContext databaseContext);
String getDisplayName();
String getName();
default boolean containsCaseIndependent(String searchTerm) {
return this.getDisplayName().toLowerCase(Locale.ROOT).contains(searchTerm.toLowerCase(Locale.ROOT));
}
}
| 623 | 26.130435 | 109 | java |
null | jabref-main/src/main/java/org/jabref/logic/protectedterms/ProtectedTermsList.java | package org.jabref.logic.protectedterms;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Objects;
import org.jabref.logic.util.OS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProtectedTermsList implements Comparable<ProtectedTermsList> {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtectedTermsList.class);
private String description;
private final List<String> termsList;
private final String location;
private final boolean internalList;
private boolean enabled;
public ProtectedTermsList(String description, List<String> termList, String location, boolean internalList) {
this.description = Objects.requireNonNull(description);
this.termsList = Objects.requireNonNull(termList);
this.location = Objects.requireNonNull(location);
this.internalList = internalList;
}
public ProtectedTermsList(String description, List<String> termList, String location) {
this(description, termList, location, false);
}
public String getDescription() {
return description;
}
public List<String> getTermList() {
return termsList;
}
public String getLocation() {
return location;
}
public String getTermListing() {
return String.join("\n", termsList);
}
@Override
public int compareTo(ProtectedTermsList otherList) {
return this.getDescription().compareTo(otherList.getDescription());
}
public boolean isInternalList() {
return internalList;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
public boolean createAndWriteHeading(String newDescription) {
description = newDescription;
return addProtectedTerm("# " + newDescription, true);
}
public boolean addProtectedTerm(String term) {
return addProtectedTerm(term, false);
}
public boolean addProtectedTerm(String term, boolean create) {
Objects.requireNonNull(term);
// Cannot add to internal lists
if (internalList) {
return false;
}
Path p = Path.of(location);
String s = OS.NEWLINE + term;
try (BufferedWriter writer = Files.newBufferedWriter(p, StandardCharsets.UTF_8,
create ? StandardOpenOption.CREATE : StandardOpenOption.APPEND)) {
writer.write(s);
termsList.add(term);
} catch (IOException ioe) {
LOGGER.warn("Problem adding protected term to list", ioe);
return false;
}
return true;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ProtectedTermsList)) {
return false;
}
ProtectedTermsList otherList = (ProtectedTermsList) o;
return (this.location.equals(otherList.location)) && (this.description.equals(otherList.description));
}
@Override
public int hashCode() {
return Objects.hash(location, description);
}
}
| 3,290 | 27.868421 | 113 | java |
null | jabref-main/src/main/java/org/jabref/logic/protectedterms/ProtectedTermsLoader.java | package org.jabref.logic.protectedterms;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import org.jabref.logic.l10n.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProtectedTermsLoader {
private static final Map<String, Supplier<String>> INTERNAL_LISTS = new HashMap<>();
private static final Logger LOGGER = LoggerFactory.getLogger(ProtectedTermsLoader.class);
private final List<ProtectedTermsList> mainList = new ArrayList<>();
static {
INTERNAL_LISTS.put("/protectedterms/months_weekdays.terms", () -> Localization.lang("Months and weekdays in English"));
INTERNAL_LISTS.put("/protectedterms/countries_territories.terms", () -> Localization.lang("Countries and territories in English"));
INTERNAL_LISTS.put("/protectedterms/electrical_engineering.terms", () -> Localization.lang("Electrical engineering terms"));
}
public ProtectedTermsLoader(ProtectedTermsPreferences preferences) {
update(preferences);
}
public static List<String> getInternalLists() {
return new ArrayList<>(INTERNAL_LISTS.keySet());
}
public void update(ProtectedTermsPreferences preferences) {
mainList.clear();
// Read internal lists
for (String filename : preferences.getEnabledInternalTermLists()) {
if (INTERNAL_LISTS.containsKey(filename)) {
mainList.add(readProtectedTermsListFromResource(filename, INTERNAL_LISTS.get(filename).get(), true));
} else {
LOGGER.warn("Protected terms resource '{}' is no longer available.", filename);
}
}
for (String filename : preferences.getDisabledInternalTermLists()) {
if (INTERNAL_LISTS.containsKey(filename)) {
if (!preferences.getEnabledInternalTermLists().contains(filename)) {
mainList.add(readProtectedTermsListFromResource(filename, INTERNAL_LISTS.get(filename).get(), false));
}
} else {
LOGGER.warn("Protected terms resource '{}' is no longer available.", filename);
}
}
// Check if any new internal lists have emerged
for (String filename : INTERNAL_LISTS.keySet()) {
if (!preferences.getEnabledInternalTermLists().contains(filename)
&& !preferences.getDisabledInternalTermLists().contains(filename)) {
// New internal list, add it
mainList.add(readProtectedTermsListFromResource(filename, INTERNAL_LISTS.get(filename).get(), true));
LOGGER.warn("New protected terms resource '{}' is available and enabled by default.", filename);
}
}
// Read external lists
for (String filename : preferences.getEnabledExternalTermLists()) {
Path filePath = Path.of(filename);
if (Files.exists(filePath)) {
mainList.add(readProtectedTermsListFromFile(filePath, true));
} else {
LOGGER.warn("Cannot find protected terms file {} ", filename);
}
}
for (String filename : preferences.getDisabledExternalTermLists()) {
if (!preferences.getEnabledExternalTermLists().contains(filename)) {
mainList.add(readProtectedTermsListFromFile(Path.of(filename), false));
}
}
}
public void reloadProtectedTermsList(ProtectedTermsList list) {
ProtectedTermsList newList = readProtectedTermsListFromFile(Path.of(list.getLocation()), list.isEnabled());
int index = mainList.indexOf(list);
if (index >= 0) {
mainList.set(index, newList);
} else {
LOGGER.warn("Problem reloading protected terms file");
}
}
public List<ProtectedTermsList> getProtectedTermsLists() {
return mainList;
}
public List<String> getProtectedTerms() {
Set<String> result = new HashSet<>();
for (ProtectedTermsList list : mainList) {
if (list.isEnabled()) {
result.addAll(list.getTermList());
}
}
return new ArrayList<>(result);
}
public void addProtectedTermsListFromFile(String fileName, boolean enabled) {
mainList.add(readProtectedTermsListFromFile(Path.of(fileName), enabled));
}
public static ProtectedTermsList readProtectedTermsListFromResource(String resource, String description, boolean enabled) {
ProtectedTermsParser parser = new ProtectedTermsParser();
parser.readTermsFromResource(Objects.requireNonNull(resource), Objects.requireNonNull(description));
return parser.getProtectTermsList(enabled, true);
}
public static ProtectedTermsList readProtectedTermsListFromFile(Path path, boolean enabled) {
LOGGER.debug("Reading term list from file {}", path);
ProtectedTermsParser parser = new ProtectedTermsParser();
parser.readTermsFromFile(Objects.requireNonNull(path));
return parser.getProtectTermsList(enabled, false);
}
public boolean removeProtectedTermsList(ProtectedTermsList termList) {
termList.setEnabled(false);
return mainList.remove(termList);
}
public ProtectedTermsList addNewProtectedTermsList(String newDescription, String newLocation, boolean enabled) {
Objects.requireNonNull(newDescription);
Objects.requireNonNull(newLocation);
ProtectedTermsList resultingList = new ProtectedTermsList(newDescription, new ArrayList<>(), newLocation);
resultingList.setEnabled(enabled);
resultingList.createAndWriteHeading(newDescription);
mainList.add(resultingList);
return resultingList;
}
public ProtectedTermsList addNewProtectedTermsList(String newDescription, String newLocation) {
return addNewProtectedTermsList(newDescription, newLocation, true);
}
}
| 6,159 | 40.066667 | 139 | java |
null | jabref-main/src/main/java/org/jabref/logic/protectedterms/ProtectedTermsParser.java | package org.jabref.logic.protectedterms;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jabref.logic.l10n.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Reads abbreviation files (property files using NAME = ABBREVIATION as a format) into a list of Abbreviations.
*/
public class ProtectedTermsParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtectedTermsParser.class);
private final List<String> terms = new ArrayList<>();
private String description = Localization.lang("The text after the last line starting with # will be used");
private String location;
public void readTermsFromResource(String resourceFileName, String descriptionString) {
try {
Path path = Path.of(Objects.requireNonNull(ProtectedTermsLoader.class.getResource(Objects.requireNonNull(resourceFileName))).toURI());
readTermsList(path);
description = descriptionString;
location = resourceFileName;
} catch (URISyntaxException e1) {
LOGGER.error("");
}
}
public void readTermsFromFile(Path path) {
location = path.toAbsolutePath().toString();
readTermsList(path);
}
private void readTermsList(Path path) {
if (!Files.exists(path)) {
LOGGER.warn("Could not read terms from file {}", path);
return;
}
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
this.terms.addAll(lines.map(this::setDescription).filter(Objects::nonNull).collect(Collectors.toList()));
} catch (IOException e) {
LOGGER.warn("Could not read terms from file {}", path, e);
}
}
/**
* Parse the description that starts after the # but don't include it in the terms
*
* @return line or null if the line contains the description
*/
private String setDescription(String line) {
if (line.startsWith("#")) {
description = line.substring(1).trim();
return null;
}
return line;
}
public ProtectedTermsList getProtectTermsList(boolean enabled, boolean internal) {
ProtectedTermsList termList = new ProtectedTermsList(description, terms, location, internal);
termList.setEnabled(enabled);
return termList;
}
}
| 2,635 | 32.794872 | 146 | java |
null | jabref-main/src/main/java/org/jabref/logic/protectedterms/ProtectedTermsPreferences.java | package org.jabref.logic.protectedterms;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class ProtectedTermsPreferences {
private final ObservableList<String> enabledInternalTermLists;
private final ObservableList<String> enabledExternalTermLists;
private final ObservableList<String> disabledInternalTermLists;
private final ObservableList<String> disabledExternalTermLists;
public ProtectedTermsPreferences(List<String> enabledInternalTermLists,
List<String> enabledExternalTermLists,
List<String> disabledInternalTermLists,
List<String> disabledExternalTermLists) {
this.enabledInternalTermLists = FXCollections.observableArrayList(enabledInternalTermLists);
this.disabledInternalTermLists = FXCollections.observableArrayList(disabledInternalTermLists);
this.enabledExternalTermLists = FXCollections.observableArrayList(enabledExternalTermLists);
this.disabledExternalTermLists = FXCollections.observableArrayList(disabledExternalTermLists);
}
public ObservableList<String> getEnabledInternalTermLists() {
return enabledInternalTermLists;
}
public ObservableList<String> getEnabledExternalTermLists() {
return enabledExternalTermLists;
}
public ObservableList<String> getDisabledInternalTermLists() {
return disabledInternalTermLists;
}
public ObservableList<String> getDisabledExternalTermLists() {
return disabledExternalTermLists;
}
public void setEnabledInternalTermLists(List<String> list) {
enabledInternalTermLists.clear();
enabledInternalTermLists.addAll(list);
}
public void setEnabledExternalTermLists(List<String> list) {
enabledExternalTermLists.clear();
enabledExternalTermLists.addAll(list);
}
public void setDisabledInternalTermLists(List<String> list) {
disabledInternalTermLists.clear();
disabledInternalTermLists.addAll(list);
}
public void setDisabledExternalTermLists(List<String> list) {
disabledExternalTermLists.clear();
disabledExternalTermLists.addAll(list);
}
}
| 2,297 | 36.672131 | 102 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/Protocol.java | package org.jabref.logic.remote;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @implNote The first byte of every message identifies its type as a {@link RemoteMessage}.
* Every message is terminated with '\0'.
*/
public class Protocol implements AutoCloseable {
public static final String IDENTIFIER = "jabref";
private static final Logger LOGGER = LoggerFactory.getLogger(Protocol.class);
private final Socket socket;
private final ObjectOutputStream out;
private final ObjectInputStream in;
public Protocol(Socket socket) throws IOException {
this.socket = socket;
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
}
public void sendMessage(RemoteMessage type) throws IOException {
out.writeObject(type);
out.writeObject(null);
out.write('\0');
out.flush();
}
public void sendMessage(RemoteMessage type, Object argument) throws IOException {
out.writeObject(type);
// encode the commandline arguments to handle special characters (eg. spaces and Chinese characters)
// related to issue #6487
if (type == RemoteMessage.SEND_COMMAND_LINE_ARGUMENTS) {
String[] encodedArgs = ((String[]) argument).clone();
for (int i = 0; i < encodedArgs.length; i++) {
encodedArgs[i] = URLEncoder.encode(encodedArgs[i], StandardCharsets.UTF_8);
}
out.writeObject(encodedArgs);
} else {
out.writeObject(argument);
}
out.write('\0');
out.flush();
}
public Pair<RemoteMessage, Object> receiveMessage() throws IOException {
try {
RemoteMessage type = (RemoteMessage) in.readObject();
Object argument = in.readObject();
int endOfMessage = in.read();
// decode the received commandline arguments
if (type == RemoteMessage.SEND_COMMAND_LINE_ARGUMENTS) {
for (int i = 0; i < ((String[]) argument).length; i++) {
((String[]) argument)[i] = URLDecoder.decode(((String[]) argument)[i], StandardCharsets.UTF_8);
}
}
if (endOfMessage != '\0') {
throw new IOException("Message didn't end on correct end of message identifier. Got " + endOfMessage);
}
return new Pair<>(type, argument);
} catch (ClassNotFoundException e) {
throw new IOException("Could not deserialize message", e);
}
}
@Override
public void close() {
try {
in.close();
} catch (IOException e) {
LOGGER.warn("Input stream not closed", e);
}
try {
out.close();
} catch (IOException e) {
LOGGER.warn("Output stream not closed", e);
}
try {
socket.close();
} catch (IOException e) {
LOGGER.warn("Socket not closed", e);
}
}
}
| 3,325 | 30.67619 | 118 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/RemoteMessage.java | package org.jabref.logic.remote;
public enum RemoteMessage {
/**
* Send command line arguments. The message content is of type {@code String[]}.
*/
SEND_COMMAND_LINE_ARGUMENTS,
/**
* As a response to {@link #PING}. The message content is an identifier of type {@code String}.
*/
PONG,
/**
* Response signaling that the message was received successfully. No message content.
*/
OK,
/**
* Request server to identify itself. No message content.
*/
PING
}
| 525 | 24.047619 | 99 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/RemotePreferences.java | package org.jabref.logic.remote;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
/**
* Place for handling the preferences for the remote communication
*/
public class RemotePreferences {
private final IntegerProperty port;
private final BooleanProperty useRemoteServer;
public RemotePreferences(int port, boolean useRemoteServer) {
this.port = new SimpleIntegerProperty(port);
this.useRemoteServer = new SimpleBooleanProperty(useRemoteServer);
}
public int getPort() {
return port.getValue();
}
public IntegerProperty portProperty() {
return port;
}
public void setPort(int port) {
this.port.setValue(port);
}
public boolean useRemoteServer() {
return useRemoteServer.getValue();
}
public BooleanProperty useRemoteServerProperty() {
return useRemoteServer;
}
public void setUseRemoteServer(boolean useRemoteServer) {
this.useRemoteServer.setValue(useRemoteServer);
}
public boolean isDifferentPort(int otherPort) {
return getPort() != otherPort;
}
/**
* Gets the IP address where the remote server is listening.
*/
public static InetAddress getIpAddress() throws UnknownHostException {
return InetAddress.getByName("localhost");
}
}
| 1,537 | 25.067797 | 74 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/RemoteUtil.java | package org.jabref.logic.remote;
public class RemoteUtil {
private RemoteUtil() {
}
public static boolean isUserPort(int portNumber) {
return (portNumber >= 1024) && (portNumber <= 65535);
}
}
| 220 | 17.416667 | 61 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/client/RemoteClient.java | package org.jabref.logic.remote.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import javafx.util.Pair;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.remote.Protocol;
import org.jabref.logic.remote.RemoteMessage;
import org.jabref.logic.remote.RemotePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteClient {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteClient.class);
private static final int TIMEOUT = 1000;
private final int port;
public RemoteClient(int port) {
this.port = port;
}
public boolean ping() {
try (Protocol protocol = openNewConnection()) {
protocol.sendMessage(RemoteMessage.PING);
Pair<RemoteMessage, Object> response = protocol.receiveMessage();
if ((response.getKey() == RemoteMessage.PONG) && Protocol.IDENTIFIER.equals(response.getValue())) {
return true;
} else {
String port = String.valueOf(this.port);
String errorMessage = Localization.lang("Cannot use port %0 for remote operation; another application may be using it. Try specifying another port.", port);
LOGGER.error(errorMessage);
return false;
}
} catch (IOException e) {
LOGGER.debug("Could not ping server at port {}", port, e);
return false;
}
}
/**
* Attempt to send command line arguments to already running JabRef instance.
*
* @param args command line arguments.
* @return true if successful, false otherwise.
*/
public boolean sendCommandLineArguments(String[] args) {
try (Protocol protocol = openNewConnection()) {
protocol.sendMessage(RemoteMessage.SEND_COMMAND_LINE_ARGUMENTS, args);
Pair<RemoteMessage, Object> response = protocol.receiveMessage();
return response.getKey() == RemoteMessage.OK;
} catch (IOException e) {
LOGGER.debug("Could not send args {} to the server at port {}", String.join(", ", args), port, e);
return false;
}
}
private Protocol openNewConnection() throws IOException {
Socket socket = new Socket();
socket.setSoTimeout(TIMEOUT);
socket.connect(new InetSocketAddress(RemotePreferences.getIpAddress(), port), TIMEOUT);
return new Protocol(socket);
}
}
| 2,501 | 34.239437 | 172 | java |
null | jabref-main/src/main/java/org/jabref/logic/remote/server/RemoteListenerServer.java | package org.jabref.logic.remote.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import javafx.util.Pair;
import org.jabref.logic.remote.Protocol;
import org.jabref.logic.remote.RemoteMessage;
import org.jabref.logic.remote.RemotePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteListenerServer implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteListenerServer.class);
private static final int BACKLOG = 1;
private static final int TIMEOUT = 1000;
private final RemoteMessageHandler messageHandler;
private final ServerSocket serverSocket;
public RemoteListenerServer(RemoteMessageHandler messageHandler, int port) throws IOException {
this.serverSocket = new ServerSocket(port, BACKLOG, RemotePreferences.getIpAddress());
this.messageHandler = messageHandler;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
try (Socket socket = serverSocket.accept()) {
socket.setSoTimeout(TIMEOUT);
try (Protocol protocol = new Protocol(socket)) {
Pair<RemoteMessage, Object> input = protocol.receiveMessage();
handleMessage(protocol, input.getKey(), input.getValue());
}
} catch (SocketException ex) {
return;
} catch (IOException e) {
LOGGER.warn("RemoteListenerServer crashed", e);
}
}
} finally {
closeServerSocket();
}
}
private void handleMessage(Protocol protocol, RemoteMessage type, Object argument) throws IOException {
switch (type) {
case PING:
protocol.sendMessage(RemoteMessage.PONG, Protocol.IDENTIFIER);
break;
case SEND_COMMAND_LINE_ARGUMENTS:
if (argument instanceof String[] strings) {
messageHandler.handleCommandLineArguments(strings);
protocol.sendMessage(RemoteMessage.OK);
} else {
throw new IOException("Argument for 'SEND_COMMAND_LINE_ARGUMENTS' is not of type String[]. Got " + argument);
}
break;
default:
throw new IOException("Unhandled message to server " + type);
}
}
public void closeServerSocket() {
try {
serverSocket.close();
} catch (IOException e) {
LOGGER.warn("Unable to close server socket", e);
}
}
}
| 2,731 | 33.15 | 129 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.