joiner = words.stream();
- if (!regularExpression) {
+ if (!searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) {
// Reformat string when we are looking for a literal match
joiner = joiner.map(escapeMode::format);
}
String searchPattern = joiner.collect(Collectors.joining(")|(", "(", ")"));
- if (caseSensitive) {
+ if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
return Optional.of(Pattern.compile(searchPattern));
} else {
return Optional.of(Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE));
diff --git a/src/main/java/org/jabref/model/database/BibDatabaseContext.java b/src/main/java/org/jabref/model/database/BibDatabaseContext.java
index 2b0e713614f..b0c2b96bce3 100644
--- a/src/main/java/org/jabref/model/database/BibDatabaseContext.java
+++ b/src/main/java/org/jabref/model/database/BibDatabaseContext.java
@@ -9,13 +9,19 @@
import java.util.stream.Collectors;
import org.jabref.architecture.AllowedToUseLogic;
+import org.jabref.gui.LibraryTab;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.logic.shared.DatabaseSynchronizer;
import org.jabref.logic.util.CoarseChangeFilter;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.metadata.MetaData;
+import org.jabref.model.pdf.search.SearchFieldConstants;
import org.jabref.preferences.FilePreferences;
+import net.harawata.appdirs.AppDirsFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
* Represents everything related to a BIB file. The entries are stored in BibDatabase, the other data in MetaData
* and the options relevant for this file in Defaults.
@@ -23,13 +29,17 @@
@AllowedToUseLogic("because it needs access to shared database features")
public class BibDatabaseContext {
+ public static final String SEARCH_INDEX_BASE_PATH = "JabRef";
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
+
private final BibDatabase database;
private MetaData metaData;
/**
* The path where this database was last saved to.
*/
- private Optional path;
+ private Path path;
private DatabaseSynchronizer dbmsSynchronizer;
private CoarseChangeFilter dbmsListener;
@@ -47,7 +57,6 @@ public BibDatabaseContext(BibDatabase database, MetaData metaData) {
this.database = Objects.requireNonNull(database);
this.metaData = Objects.requireNonNull(metaData);
this.location = DatabaseLocation.LOCAL;
- this.path = Optional.empty();
}
public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path) {
@@ -57,7 +66,7 @@ public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path) {
public BibDatabaseContext(BibDatabase database, MetaData metaData, Path path, DatabaseLocation location) {
this(database, metaData);
Objects.requireNonNull(location);
- this.path = Optional.ofNullable(path);
+ this.path = path;
if (location == DatabaseLocation.LOCAL) {
convertToLocalDatabase();
@@ -73,7 +82,7 @@ public void setMode(BibDatabaseMode bibDatabaseMode) {
}
public void setDatabasePath(Path file) {
- this.path = Optional.ofNullable(file);
+ this.path = file;
}
/**
@@ -82,11 +91,11 @@ public void setDatabasePath(Path file) {
* @return Optional of the relevant Path, or Optional.empty() if none is defined.
*/
public Optional getDatabasePath() {
- return path;
+ return Optional.ofNullable(path);
}
public void clearDatabasePath() {
- this.path = Optional.empty();
+ this.path = null;
}
public BibDatabase getDatabase() {
@@ -191,14 +200,6 @@ public void convertToSharedDatabase(DatabaseSynchronizer dmbsSynchronizer) {
this.location = DatabaseLocation.SHARED;
}
- @Override
- public String toString() {
- return "BibDatabaseContext{" +
- "path=" + path +
- ", location=" + location +
- '}';
- }
-
public void convertToLocalDatabase() {
if (Objects.nonNull(dbmsListener) && (location == DatabaseLocation.SHARED)) {
dbmsListener.unregisterListener(dbmsSynchronizer);
@@ -211,4 +212,30 @@ public void convertToLocalDatabase() {
public List getEntries() {
return database.getEntries();
}
+
+ public static Path getFulltextIndexBasePath() {
+ return Path.of(AppDirsFactory.getInstance().getUserDataDir(SEARCH_INDEX_BASE_PATH, SearchFieldConstants.VERSION, "org.jabref"));
+ }
+
+ public Path getFulltextIndexPath() {
+ Path appData = getFulltextIndexBasePath();
+
+ if (getDatabasePath().isPresent()) {
+ LOGGER.info("Index path for {} is {}", getDatabasePath().get(), appData.toString());
+ return appData.resolve(String.valueOf(this.getDatabasePath().get().hashCode()));
+ }
+
+ return appData.resolve("unsaved");
+ }
+
+ @Override
+ public String toString() {
+ return "BibDatabaseContext{" +
+ "metaData=" + metaData +
+ ", mode=" + getMode() +
+ ", databasePath=" + getDatabasePath() +
+ ", biblatexMode=" + isBiblatexMode() +
+ ", fulltextIndexPath=" + getFulltextIndexPath() +
+ '}';
+ }
}
diff --git a/src/main/java/org/jabref/model/groups/SearchGroup.java b/src/main/java/org/jabref/model/groups/SearchGroup.java
index 2346c23c10a..5e261c438b9 100644
--- a/src/main/java/org/jabref/model/groups/SearchGroup.java
+++ b/src/main/java/org/jabref/model/groups/SearchGroup.java
@@ -1,9 +1,11 @@
package org.jabref.model.groups;
+import java.util.EnumSet;
import java.util.Objects;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.search.GroupSearchQuery;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -17,10 +19,9 @@ public class SearchGroup extends AbstractGroup {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchGroup.class);
private final GroupSearchQuery query;
- public SearchGroup(String name, GroupHierarchyType context, String searchExpression, boolean caseSensitive,
- boolean isRegEx) {
+ public SearchGroup(String name, GroupHierarchyType context, String searchExpression, EnumSet searchFlags) {
super(name, context);
- this.query = new GroupSearchQuery(searchExpression, caseSensitive, isRegEx);
+ this.query = new GroupSearchQuery(searchExpression, searchFlags);
}
public String getSearchExpression() {
@@ -38,8 +39,7 @@ public boolean equals(Object o) {
SearchGroup other = (SearchGroup) o;
return getName().equals(other.getName())
&& getSearchExpression().equals(other.getSearchExpression())
- && (isCaseSensitive() == other.isCaseSensitive())
- && (isRegularExpression() == other.isRegularExpression())
+ && (getSearchFlags().equals(other.getSearchFlags()))
&& (getHierarchicalContext() == other.getHierarchicalContext());
}
@@ -48,11 +48,14 @@ public boolean contains(BibEntry entry) {
return query.isMatch(entry);
}
+ public EnumSet getSearchFlags() {
+ return query.getSearchFlags();
+ }
+
@Override
public AbstractGroup deepCopy() {
try {
- return new SearchGroup(getName(), getHierarchicalContext(), getSearchExpression(), isCaseSensitive(),
- isRegularExpression());
+ return new SearchGroup(getName(), getHierarchicalContext(), getSearchExpression(), getSearchFlags());
} catch (Throwable t) {
// this should never happen, because the constructor obviously
// succeeded in creating _this_ instance!
@@ -62,14 +65,6 @@ public AbstractGroup deepCopy() {
}
}
- public boolean isCaseSensitive() {
- return query.isCaseSensitive();
- }
-
- public boolean isRegularExpression() {
- return query.isRegularExpression();
- }
-
@Override
public boolean isDynamic() {
return true;
@@ -77,6 +72,6 @@ public boolean isDynamic() {
@Override
public int hashCode() {
- return Objects.hash(getName(), getHierarchicalContext(), getSearchExpression(), isCaseSensitive(), isRegularExpression());
+ return Objects.hash(getName(), getHierarchicalContext(), getSearchExpression(), getSearchFlags());
}
}
diff --git a/src/main/java/org/jabref/model/pdf/search/EnglishStemAnalyzer.java b/src/main/java/org/jabref/model/pdf/search/EnglishStemAnalyzer.java
new file mode 100644
index 00000000000..1dcccbb6583
--- /dev/null
+++ b/src/main/java/org/jabref/model/pdf/search/EnglishStemAnalyzer.java
@@ -0,0 +1,25 @@
+package org.jabref.model.pdf.search;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.LowerCaseFilter;
+import org.apache.lucene.analysis.StopFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.analysis.core.DecimalDigitFilter;
+import org.apache.lucene.analysis.en.EnglishAnalyzer;
+import org.apache.lucene.analysis.en.PorterStemFilter;
+import org.apache.lucene.analysis.standard.StandardTokenizer;
+
+public class EnglishStemAnalyzer extends Analyzer {
+
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer source = new StandardTokenizer();
+ TokenStream filter = new LowerCaseFilter(source);
+ filter = new StopFilter(filter, EnglishAnalyzer.ENGLISH_STOP_WORDS_SET);
+ filter = new DecimalDigitFilter(filter);
+ filter = new PorterStemFilter(filter);
+ return new TokenStreamComponents(source, filter);
+ }
+}
+
diff --git a/src/main/java/org/jabref/model/pdf/search/PdfSearchResults.java b/src/main/java/org/jabref/model/pdf/search/PdfSearchResults.java
new file mode 100644
index 00000000000..2c6ad8e9d89
--- /dev/null
+++ b/src/main/java/org/jabref/model/pdf/search/PdfSearchResults.java
@@ -0,0 +1,32 @@
+package org.jabref.model.pdf.search;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public final class PdfSearchResults {
+
+ private final List searchResults;
+
+ public PdfSearchResults(List search) {
+ this.searchResults = Collections.unmodifiableList(search);
+ }
+
+ public PdfSearchResults() {
+ this.searchResults = Collections.emptyList();
+ }
+
+ public List getSortedByScore() {
+ List sortedList = new ArrayList<>(searchResults);
+ sortedList.sort((searchResult, t1) -> Float.compare(searchResult.getLuceneScore(), t1.getLuceneScore()));
+ return Collections.unmodifiableList(sortedList);
+ }
+
+ public List getSearchResults() {
+ return this.searchResults;
+ }
+
+ public int numSearchResults() {
+ return this.searchResults.size();
+ }
+}
diff --git a/src/main/java/org/jabref/model/pdf/search/SearchFieldConstants.java b/src/main/java/org/jabref/model/pdf/search/SearchFieldConstants.java
new file mode 100644
index 00000000000..ca72a1fac1b
--- /dev/null
+++ b/src/main/java/org/jabref/model/pdf/search/SearchFieldConstants.java
@@ -0,0 +1,13 @@
+package org.jabref.model.pdf.search;
+
+public class SearchFieldConstants {
+
+ public static final String PATH = "path";
+ public static final String CONTENT = "content";
+ public static final String ANNOTATIONS = "annotations";
+ public static final String MODIFIED = "modified";
+
+ public static final String[] PDF_FIELDS = new String[]{PATH, CONTENT, MODIFIED, ANNOTATIONS};
+
+ public static final String VERSION = "0.3a";
+}
diff --git a/src/main/java/org/jabref/model/pdf/search/SearchResult.java b/src/main/java/org/jabref/model/pdf/search/SearchResult.java
new file mode 100644
index 00000000000..ea3dd319e6c
--- /dev/null
+++ b/src/main/java/org/jabref/model/pdf/search/SearchResult.java
@@ -0,0 +1,83 @@
+package org.jabref.model.pdf.search;
+
+import java.io.IOException;
+
+import org.jabref.model.entry.BibEntry;
+
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.index.IndexableField;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.highlight.Highlighter;
+import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
+import org.apache.lucene.search.highlight.QueryScorer;
+import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
+import org.apache.lucene.search.highlight.TextFragment;
+
+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.PATH;
+
+public final class SearchResult {
+
+ private final String path;
+ private final String content;
+ private final long modified;
+
+ private final float luceneScore;
+ private String html;
+
+ public SearchResult(IndexSearcher searcher, Query query, ScoreDoc scoreDoc) throws IOException {
+ this.path = getFieldContents(searcher, scoreDoc, PATH);
+ this.content = getFieldContents(searcher, scoreDoc, CONTENT);
+ this.modified = Long.parseLong(getFieldContents(searcher, scoreDoc, MODIFIED));
+ this.luceneScore = scoreDoc.score;
+
+ TokenStream stream = new EnglishStemAnalyzer().tokenStream(CONTENT, content);
+
+ Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter(), new QueryScorer(query));
+ try {
+
+ TextFragment[] frags = highlighter.getBestTextFragments(stream, content, true, 10);
+ this.html = "";
+ for (TextFragment frag : frags) {
+ html += "" + frag.toString() + "
";
+ }
+ } catch (InvalidTokenOffsetsException e) {
+ this.html = "";
+ }
+ }
+
+ private String getFieldContents(IndexSearcher searcher, ScoreDoc scoreDoc, String field) throws IOException {
+ IndexableField indexableField = searcher.doc(scoreDoc.doc).getField(field);
+ if (indexableField == null) {
+ return "";
+ }
+ return indexableField.stringValue();
+ }
+
+ public boolean isResultFor(BibEntry entry) {
+ return entry.getFiles().stream().anyMatch(linkedFile -> path.equals(linkedFile.getLink()));
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public long getModified() {
+ return modified;
+ }
+
+ public float getLuceneScore() {
+ return luceneScore;
+ }
+
+ public String getHtml() {
+ return html;
+ }
+}
diff --git a/src/main/java/org/jabref/model/search/GroupSearchQuery.java b/src/main/java/org/jabref/model/search/GroupSearchQuery.java
index 3eea63f99d9..90056d9b0f7 100644
--- a/src/main/java/org/jabref/model/search/GroupSearchQuery.java
+++ b/src/main/java/org/jabref/model/search/GroupSearchQuery.java
@@ -1,22 +1,22 @@
package org.jabref.model.search;
+import java.util.EnumSet;
import java.util.Objects;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.search.rules.SearchRule;
import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
public class GroupSearchQuery implements SearchMatcher {
private final String query;
- private final boolean caseSensitive;
- private final boolean regularExpression;
+ private final EnumSet searchFlags;
private final SearchRule rule;
- public GroupSearchQuery(String query, boolean caseSensitive, boolean regularExpression) {
+ public GroupSearchQuery(String query, EnumSet searchFlags) {
this.query = Objects.requireNonNull(query);
- this.caseSensitive = caseSensitive;
- this.regularExpression = regularExpression;
+ this.searchFlags = searchFlags;
this.rule = Objects.requireNonNull(getSearchRule());
}
@@ -32,11 +32,11 @@ public boolean isMatch(BibEntry entry) {
}
private SearchRule getSearchRule() {
- return SearchRules.getSearchRuleByQuery(query, caseSensitive, regularExpression);
+ return SearchRules.getSearchRuleByQuery(query, searchFlags);
}
private String getCaseSensitiveDescription() {
- if (caseSensitive) {
+ if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
return "case sensitive";
} else {
return "case insensitive";
@@ -44,7 +44,7 @@ private String getCaseSensitiveDescription() {
}
private String getRegularExpressionDescription() {
- if (regularExpression) {
+ if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) {
return "regular expression";
} else {
return "plain text";
@@ -59,11 +59,7 @@ public String getSearchExpression() {
return query;
}
- public boolean isCaseSensitive() {
- return caseSensitive;
- }
-
- public boolean isRegularExpression() {
- return regularExpression;
+ public EnumSet getSearchFlags() {
+ return searchFlags;
}
}
diff --git a/src/main/java/org/jabref/model/search/rules/ContainBasedSearchRule.java b/src/main/java/org/jabref/model/search/rules/ContainBasedSearchRule.java
index f77c57324d2..cf7c7568368 100644
--- a/src/main/java/org/jabref/model/search/rules/ContainBasedSearchRule.java
+++ b/src/main/java/org/jabref/model/search/rules/ContainBasedSearchRule.java
@@ -1,25 +1,48 @@
package org.jabref.model.search.rules;
+import java.io.IOException;
+import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
+import java.util.Vector;
+import java.util.stream.Collectors;
+import org.jabref.architecture.AllowedToUseLogic;
+import org.jabref.gui.Globals;
+import org.jabref.gui.LibraryTab;
+import org.jabref.logic.pdf.search.retrieval.PdfSearcher;
+import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
+import org.jabref.model.pdf.search.PdfSearchResults;
+import org.jabref.model.pdf.search.SearchResult;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Search rule for contain-based search.
*/
+@AllowedToUseLogic("Because access to the lucene index is needed")
public class ContainBasedSearchRule implements SearchRule {
- private final boolean caseSensitive;
+ private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
- public ContainBasedSearchRule(boolean caseSensitive) {
- this.caseSensitive = caseSensitive;
- }
+ private final EnumSet searchFlags;
+
+ private String lastQuery;
+ private List lastSearchResults;
+
+ private final BibDatabaseContext databaseContext;
- public boolean isCaseSensitive() {
- return caseSensitive;
+ public ContainBasedSearchRule(EnumSet searchFlags) {
+ this.searchFlags = searchFlags;
+ this.lastQuery = "";
+ lastSearchResults = new Vector<>();
+
+ databaseContext = Globals.stateManager.getActiveDatabase().orElse(null);
}
@Override
@@ -31,7 +54,7 @@ public boolean validateSearchStrings(String query) {
public boolean applyRule(String query, BibEntry bibEntry) {
String searchString = query;
- if (!caseSensitive) {
+ if (!searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
searchString = searchString.toLowerCase(Locale.ROOT);
}
@@ -39,7 +62,7 @@ public boolean applyRule(String query, BibEntry bibEntry) {
for (Field fieldKey : bibEntry.getFields()) {
String formattedFieldContent = bibEntry.getLatexFreeField(fieldKey).get();
- if (!caseSensitive) {
+ if (!searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
formattedFieldContent = formattedFieldContent.toLowerCase(Locale.ROOT);
}
@@ -56,6 +79,32 @@ public boolean applyRule(String query, BibEntry bibEntry) {
}
}
- return false; // Didn't match all words.
+ return getFulltextResults(query, bibEntry).numSearchResults() > 0; // Didn't match all words.
+ }
+
+ @Override
+ public PdfSearchResults getFulltextResults(String query, BibEntry bibEntry) {
+
+ if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || databaseContext == null) {
+ return new PdfSearchResults(List.of());
+ }
+
+ if (!query.equals(this.lastQuery)) {
+ this.lastQuery = query;
+ lastSearchResults = List.of();
+ try {
+ PdfSearcher searcher = PdfSearcher.of(databaseContext);
+ PdfSearchResults results = searcher.search(query, 5);
+ lastSearchResults = results.getSortedByScore();
+ } catch (IOException e) {
+ LOGGER.error("Could not retrieve search results!", e);
+ }
+ }
+
+ return new PdfSearchResults(lastSearchResults.stream().filter(searchResult -> searchResult.isResultFor(bibEntry)).collect(Collectors.toList()));
+ }
+
+ public EnumSet getSearchFlags() {
+ return searchFlags;
}
}
diff --git a/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java b/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
index 98e12978963..5b0b5c40ea3 100644
--- a/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
+++ b/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
@@ -1,5 +1,8 @@
package org.jabref.model.search.rules;
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -8,10 +11,17 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import org.jabref.architecture.AllowedToUseLogic;
+import org.jabref.gui.Globals;
+import org.jabref.logic.pdf.search.retrieval.PdfSearcher;
+import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Keyword;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
+import org.jabref.model.pdf.search.PdfSearchResults;
+import org.jabref.model.pdf.search.SearchResult;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.search.SearchBaseVisitor;
import org.jabref.search.SearchLexer;
import org.jabref.search.SearchParser;
@@ -32,15 +42,18 @@
*
* This class implements the "Advanced Search Mode" described in the help
*/
+@AllowedToUseLogic("Because access to the lucene index is needed")
public class GrammarBasedSearchRule implements SearchRule {
private static final Logger LOGGER = LoggerFactory.getLogger(GrammarBasedSearchRule.class);
- private final boolean caseSensitiveSearch;
- private final boolean regExpSearch;
+ private final EnumSet searchFlags;
private ParseTree tree;
private String query;
+ private List searchResults;
+
+ private final BibDatabaseContext databaseContext;
public static class ThrowingErrorListener extends BaseErrorListener {
@@ -54,21 +67,13 @@ public void syntaxError(Recognizer, ?> recognizer, Object offendingSymbol,
}
}
- public GrammarBasedSearchRule(boolean caseSensitiveSearch, boolean regExpSearch) throws RecognitionException {
- this.caseSensitiveSearch = caseSensitiveSearch;
- this.regExpSearch = regExpSearch;
- }
-
- public static boolean isValid(boolean caseSensitive, boolean regExp, String query) {
- return new GrammarBasedSearchRule(caseSensitive, regExp).validateSearchStrings(query);
- }
-
- public boolean isCaseSensitiveSearch() {
- return this.caseSensitiveSearch;
+ public GrammarBasedSearchRule(EnumSet searchFlags) throws RecognitionException {
+ this.searchFlags = searchFlags;
+ databaseContext = Globals.stateManager.getActiveDatabase().orElse(null);
}
- public boolean isRegExpSearch() {
- return this.regExpSearch;
+ public static boolean isValid(EnumSet searchFlags, String query) {
+ return new GrammarBasedSearchRule(searchFlags).validateSearchStrings(query);
}
public ParseTree getTree() {
@@ -93,18 +98,34 @@ private void init(String query) throws ParseCancellationException {
parser.setErrorHandler(new BailErrorStrategy()); // ParseCancelationException on parse errors
tree = parser.start();
this.query = query;
+
+ if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || databaseContext == null) {
+ return;
+ }
+ try {
+ PdfSearcher searcher = PdfSearcher.of(databaseContext);
+ PdfSearchResults results = searcher.search(query, 5);
+ searchResults = results.getSortedByScore();
+ } catch (IOException e) {
+ LOGGER.error("Could not retrieve search results!", e);
+ }
}
@Override
public boolean applyRule(String query, BibEntry bibEntry) {
try {
- return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibEntry).visit(tree);
+ return new BibtexSearchVisitor(searchFlags, bibEntry).visit(tree);
} catch (Exception e) {
LOGGER.debug("Search failed", e);
- return false;
+ return getFulltextResults(query, bibEntry).numSearchResults() > 0;
}
}
+ @Override
+ public PdfSearchResults getFulltextResults(String query, BibEntry bibEntry) {
+ return new PdfSearchResults(searchResults.stream().filter(searchResult -> searchResult.isResultFor(bibEntry)).collect(Collectors.toList()));
+ }
+
@Override
public boolean validateSearchStrings(String query) {
try {
@@ -116,6 +137,10 @@ public boolean validateSearchStrings(String query) {
}
}
+ public EnumSet getSearchFlags() {
+ return searchFlags;
+ }
+
public enum ComparisonOperator {
EXACT, CONTAINS, DOES_NOT_CONTAIN;
@@ -136,12 +161,12 @@ public static class Comparator {
private final Pattern fieldPattern;
private final Pattern valuePattern;
- public Comparator(String field, String value, ComparisonOperator operator, boolean caseSensitive, boolean regex) {
+ public Comparator(String field, String value, ComparisonOperator operator, EnumSet searchFlags) {
this.operator = operator;
- int option = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
- this.fieldPattern = Pattern.compile(regex ? field : "\\Q" + field + "\\E", option);
- this.valuePattern = Pattern.compile(regex ? value : "\\Q" + value + "\\E", option);
+ int option = searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE;
+ this.fieldPattern = Pattern.compile(searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? field : "\\Q" + field + "\\E", option);
+ this.valuePattern = Pattern.compile(searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? value : "\\Q" + value + "\\E", option);
}
public boolean compare(BibEntry entry) {
@@ -200,19 +225,17 @@ public boolean matchFieldValue(String content) {
*/
static class BibtexSearchVisitor extends SearchBaseVisitor {
- private final boolean caseSensitive;
- private final boolean regex;
+ private final EnumSet searchFlags;
private final BibEntry entry;
- public BibtexSearchVisitor(boolean caseSensitive, boolean regex, BibEntry bibEntry) {
- this.caseSensitive = caseSensitive;
- this.regex = regex;
+ public BibtexSearchVisitor(EnumSet searchFlags, BibEntry bibEntry) {
+ this.searchFlags = searchFlags;
this.entry = bibEntry;
}
public boolean comparison(String field, ComparisonOperator operator, String value) {
- return new Comparator(field, value, operator, caseSensitive, regex).compare(entry);
+ return new Comparator(field, value, operator, searchFlags).compare(entry);
}
@Override
@@ -232,7 +255,7 @@ public Boolean visitComparison(SearchParser.ComparisonContext context) {
if (fieldDescriptor.isPresent()) {
return comparison(fieldDescriptor.get().getText(), ComparisonOperator.build(context.operator.getText()), right);
} else {
- return SearchRules.getSearchRule(caseSensitive, regex).applyRule(right, entry);
+ return SearchRules.getSearchRule(searchFlags).applyRule(right, entry);
}
}
diff --git a/src/main/java/org/jabref/model/search/rules/RegexBasedSearchRule.java b/src/main/java/org/jabref/model/search/rules/RegexBasedSearchRule.java
index 9d43710c655..0cc4bcb1f0a 100644
--- a/src/main/java/org/jabref/model/search/rules/RegexBasedSearchRule.java
+++ b/src/main/java/org/jabref/model/search/rules/RegexBasedSearchRule.java
@@ -1,38 +1,62 @@
package org.jabref.model.search.rules;
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import java.util.stream.Collectors;
+import org.jabref.architecture.AllowedToUseLogic;
+import org.jabref.gui.Globals;
+import org.jabref.logic.pdf.search.retrieval.PdfSearcher;
+import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
+import org.jabref.model.pdf.search.PdfSearchResults;
+import org.jabref.model.pdf.search.SearchResult;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Search rule for regex-based search.
*/
+@AllowedToUseLogic("Because access to the lucene index is needed")
public class RegexBasedSearchRule implements SearchRule {
- private final boolean caseSensitive;
+ private static final Logger LOGGER = LoggerFactory.getLogger(GrammarBasedSearchRule.class);
+
+ private final EnumSet searchFlags;
+
+ private String lastQuery;
+ private List lastSearchResults;
+
+ private final BibDatabaseContext databaseContext;
- public RegexBasedSearchRule(boolean caseSensitive) {
- this.caseSensitive = caseSensitive;
+ public RegexBasedSearchRule(EnumSet searchFlags) {
+ this.searchFlags = searchFlags;
+
+ databaseContext = Globals.stateManager.getActiveDatabase().orElse(null);
}
- public boolean isCaseSensitive() {
- return caseSensitive;
+ public EnumSet getSearchFlags() {
+ return searchFlags;
}
@Override
public boolean validateSearchStrings(String query) {
String searchString = query;
- if (!caseSensitive) {
+ if (!searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
searchString = searchString.toLowerCase(Locale.ROOT);
}
try {
- Pattern.compile(searchString, caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);
+ Pattern.compile(searchString, searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException ex) {
return false;
}
@@ -44,7 +68,7 @@ public boolean applyRule(String query, BibEntry bibEntry) {
Pattern pattern;
try {
- pattern = Pattern.compile(query, caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);
+ pattern = Pattern.compile(query, searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException ex) {
return false;
}
@@ -59,6 +83,27 @@ public boolean applyRule(String query, BibEntry bibEntry) {
}
}
}
- return false;
+ return getFulltextResults(query, bibEntry).numSearchResults() > 0;
+ }
+
+ @Override
+ public PdfSearchResults getFulltextResults(String query, BibEntry bibEntry) {
+
+ if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || databaseContext == null) {
+ return new PdfSearchResults(List.of());
+ }
+
+ if (!query.equals(this.lastQuery)) {
+ this.lastQuery = query;
+ lastSearchResults = List.of();
+ try {
+ PdfSearcher searcher = PdfSearcher.of(databaseContext);
+ PdfSearchResults results = searcher.search(query, 5);
+ lastSearchResults = results.getSortedByScore();
+ } catch (IOException e) {
+ LOGGER.error("Could not retrieve search results!", e);
+ }
+ }
+ return new PdfSearchResults(lastSearchResults.stream().filter(searchResult -> searchResult.isResultFor(bibEntry)).collect(Collectors.toList()));
}
}
diff --git a/src/main/java/org/jabref/model/search/rules/SearchRule.java b/src/main/java/org/jabref/model/search/rules/SearchRule.java
index ffc4dced699..1be2b05b342 100644
--- a/src/main/java/org/jabref/model/search/rules/SearchRule.java
+++ b/src/main/java/org/jabref/model/search/rules/SearchRule.java
@@ -1,10 +1,13 @@
package org.jabref.model.search.rules;
import org.jabref.model.entry.BibEntry;
+import org.jabref.model.pdf.search.PdfSearchResults;
public interface SearchRule {
boolean applyRule(String query, BibEntry bibEntry);
+ PdfSearchResults getFulltextResults(String query, BibEntry bibEntry);
+
boolean validateSearchStrings(String query);
}
diff --git a/src/main/java/org/jabref/model/search/rules/SearchRules.java b/src/main/java/org/jabref/model/search/rules/SearchRules.java
index dcde2b66227..9b6ffb51b77 100644
--- a/src/main/java/org/jabref/model/search/rules/SearchRules.java
+++ b/src/main/java/org/jabref/model/search/rules/SearchRules.java
@@ -1,5 +1,6 @@
package org.jabref.model.search.rules;
+import java.util.EnumSet;
import java.util.regex.Pattern;
public class SearchRules {
@@ -12,18 +13,18 @@ private SearchRules() {
/**
* Returns the appropriate search rule that fits best to the given parameter.
*/
- public static SearchRule getSearchRuleByQuery(String query, boolean caseSensitive, boolean regex) {
+ public static SearchRule getSearchRuleByQuery(String query, EnumSet searchFlags) {
if (isSimpleQuery(query)) {
- return new ContainBasedSearchRule(caseSensitive);
+ return new ContainBasedSearchRule(searchFlags);
}
// this searches specified fields if specified,
// and all fields otherwise
- SearchRule searchExpression = new GrammarBasedSearchRule(caseSensitive, regex);
+ SearchRule searchExpression = new GrammarBasedSearchRule(searchFlags);
if (searchExpression.validateSearchStrings(query)) {
return searchExpression;
} else {
- return getSearchRule(caseSensitive, regex);
+ return getSearchRule(searchFlags);
}
}
@@ -31,11 +32,15 @@ private static boolean isSimpleQuery(String query) {
return SIMPLE_EXPRESSION.matcher(query).matches();
}
- static SearchRule getSearchRule(boolean caseSensitive, boolean regex) {
- if (regex) {
- return new RegexBasedSearchRule(caseSensitive);
+ static SearchRule getSearchRule(EnumSet searchFlags) {
+ if (searchFlags.contains(SearchFlags.REGULAR_EXPRESSION)) {
+ return new RegexBasedSearchRule(searchFlags);
} else {
- return new ContainBasedSearchRule(caseSensitive);
+ return new ContainBasedSearchRule(searchFlags);
}
}
+
+ public enum SearchFlags {
+ CASE_SENSITIVE, REGULAR_EXPRESSION, FULLTEXT;
+ }
}
diff --git a/src/main/java/org/jabref/model/util/FileHelper.java b/src/main/java/org/jabref/model/util/FileHelper.java
index cb93884acfa..25509e50c69 100644
--- a/src/main/java/org/jabref/model/util/FileHelper.java
+++ b/src/main/java/org/jabref/model/util/FileHelper.java
@@ -17,6 +17,7 @@
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypeException;
@@ -42,7 +43,7 @@ public static Optional getFileExtension(Path file) {
*/
public static Optional getFileExtension(String fileName) {
Metadata metadata = new Metadata();
- metadata.add(Metadata.RESOURCE_NAME_KEY, fileName);
+ metadata.add(TikaCoreProperties.RESOURCE_NAME_KEY, fileName);
if (isUrl(fileName)) {
try (InputStream is = new URL(fileName).openStream()) {
diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java
index ba5df0fa216..8a459c260ea 100644
--- a/src/main/java/org/jabref/preferences/JabRefPreferences.java
+++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java
@@ -236,6 +236,7 @@ public class JabRefPreferences implements PreferencesService {
public static final String SEARCH_DISPLAY_MODE = "searchDisplayMode";
public static final String SEARCH_CASE_SENSITIVE = "caseSensitiveSearch";
public static final String SEARCH_REG_EXP = "regExpSearch";
+ public static final String SEARCH_FULLTEXT = "fulltextSearch";
public static final String GENERATE_KEY_ON_IMPORT = "generateKeyOnImport";
@@ -438,6 +439,7 @@ private JabRefPreferences() {
defaults.put(SEARCH_DISPLAY_MODE, SearchDisplayMode.FILTER.toString());
defaults.put(SEARCH_CASE_SENSITIVE, Boolean.FALSE);
defaults.put(SEARCH_REG_EXP, Boolean.FALSE);
+ defaults.put(SEARCH_FULLTEXT, Boolean.TRUE);
defaults.put(GENERATE_KEY_ON_IMPORT, Boolean.TRUE);
@@ -2532,7 +2534,8 @@ public SearchPreferences getSearchPreferences() {
return new SearchPreferences(
searchDisplayMode,
getBoolean(SEARCH_CASE_SENSITIVE),
- getBoolean(SEARCH_REG_EXP));
+ getBoolean(SEARCH_REG_EXP),
+ getBoolean(SEARCH_FULLTEXT));
}
@Override
@@ -2540,6 +2543,7 @@ public void storeSearchPreferences(SearchPreferences preferences) {
put(SEARCH_DISPLAY_MODE, Objects.requireNonNull(preferences.getSearchDisplayMode()).toString());
putBoolean(SEARCH_CASE_SENSITIVE, preferences.isCaseSensitive());
putBoolean(SEARCH_REG_EXP, preferences.isRegularExpression());
+ putBoolean(SEARCH_FULLTEXT, preferences.isFulltext());
}
//*************************************************************************************************************
diff --git a/src/main/java/org/jabref/preferences/SearchPreferences.java b/src/main/java/org/jabref/preferences/SearchPreferences.java
index e85594dd7b2..2674c0e897f 100644
--- a/src/main/java/org/jabref/preferences/SearchPreferences.java
+++ b/src/main/java/org/jabref/preferences/SearchPreferences.java
@@ -1,17 +1,33 @@
package org.jabref.preferences;
+import java.util.EnumSet;
+
import org.jabref.gui.search.SearchDisplayMode;
+import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
public class SearchPreferences {
private final SearchDisplayMode searchDisplayMode;
- private final boolean isCaseSensitive;
- private final boolean isRegularExpression;
+ private final EnumSet searchFlags;
- public SearchPreferences(SearchDisplayMode searchDisplayMode, boolean isCaseSensitive, boolean isRegularExpression) {
+ public SearchPreferences(SearchDisplayMode searchDisplayMode, boolean isCaseSensitive, boolean isRegularExpression, boolean isFulltext) {
this.searchDisplayMode = searchDisplayMode;
- this.isCaseSensitive = isCaseSensitive;
- this.isRegularExpression = isRegularExpression;
+ searchFlags = EnumSet.noneOf(SearchFlags.class);
+ if (isCaseSensitive) {
+ searchFlags.add(SearchFlags.CASE_SENSITIVE);
+ }
+ if (isRegularExpression) {
+ searchFlags.add(SearchFlags.REGULAR_EXPRESSION);
+ }
+ if (isFulltext) {
+ searchFlags.add(SearchFlags.FULLTEXT);
+ }
+ }
+
+ public SearchPreferences(SearchDisplayMode searchDisplayMode, EnumSet searchFlags) {
+ this.searchDisplayMode = searchDisplayMode;
+ this.searchFlags = searchFlags;
}
public SearchDisplayMode getSearchDisplayMode() {
@@ -19,22 +35,44 @@ public SearchDisplayMode getSearchDisplayMode() {
}
public boolean isCaseSensitive() {
- return isCaseSensitive;
+ return searchFlags.contains(SearchFlags.CASE_SENSITIVE);
}
public boolean isRegularExpression() {
- return isRegularExpression;
+ return searchFlags.contains(SearchFlags.REGULAR_EXPRESSION);
+ }
+
+ public boolean isFulltext() {
+ return searchFlags.contains(SearchFlags.FULLTEXT);
+ }
+
+ public EnumSet getSearchFlags() {
+ EnumSet searchFlags = EnumSet.noneOf(SearchFlags.class);
+ if (isCaseSensitive()) {
+ searchFlags.add(SearchRules.SearchFlags.CASE_SENSITIVE);
+ }
+ if (isRegularExpression()) {
+ searchFlags.add(SearchRules.SearchFlags.REGULAR_EXPRESSION);
+ }
+ if (isFulltext()) {
+ searchFlags.add(SearchRules.SearchFlags.FULLTEXT);
+ }
+ return searchFlags;
}
public SearchPreferences withSearchDisplayMode(SearchDisplayMode newSearchDisplayMode) {
- return new SearchPreferences(newSearchDisplayMode, isCaseSensitive, isRegularExpression);
+ return new SearchPreferences(newSearchDisplayMode, isCaseSensitive(), isRegularExpression(), isFulltext());
}
public SearchPreferences withCaseSensitive(boolean newCaseSensitive) {
- return new SearchPreferences(searchDisplayMode, newCaseSensitive, isRegularExpression);
+ return new SearchPreferences(searchDisplayMode, newCaseSensitive, isRegularExpression(), isFulltext());
}
public SearchPreferences withRegularExpression(boolean newRegularExpression) {
- return new SearchPreferences(searchDisplayMode, isCaseSensitive, newRegularExpression);
+ return new SearchPreferences(searchDisplayMode, isCaseSensitive(), newRegularExpression, isFulltext());
+ }
+
+ public SearchPreferences withFulltext(boolean newFulltext) {
+ return new SearchPreferences(searchDisplayMode, isCaseSensitive(), isRegularExpression(), newFulltext);
}
}
diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties
index 431a2fc0a71..4b2b378b9a0 100644
--- a/src/main/resources/l10n/JabRef_en.properties
+++ b/src/main/resources/l10n/JabRef_en.properties
@@ -363,6 +363,8 @@ Formatter\ name=Formatter name
found\ in\ AUX\ file=found in AUX file
+Fulltext\ search=Fulltext search
+
Fulltext\ for=Fulltext for
Further\ information\ about\ Mr.\ DLib\ for\ JabRef\ users.=Further information about Mr. DLib for JabRef users.
@@ -440,6 +442,8 @@ Include\ subgroups\:\ When\ selected,\ view\ entries\ contained\ in\ this\ group
Independent\ group\:\ When\ selected,\ view\ only\ this\ group's\ entries=Independent group: When selected, view only this group's entries
I\ Agree=I Agree
+Indexing\ pdf\ files=Indexing pdf files
+
Invalid\ citation\ key=Invalid citation key
Invalid\ URL=Invalid URL
@@ -452,6 +456,9 @@ JabRef\ requests\ recommendations\ from\ Mr.\ DLib,\ which\ is\ an\ external\ se
JabRef\ Version\ (Required\ to\ ensure\ backwards\ compatibility\ with\ Mr.\ DLib's\ Web\ Service)=JabRef Version (Required to ensure backwards compatibility with Mr. DLib's Web Service)
Journal\ abbreviations=Journal abbreviations
+Journal\ lists\:=Journal lists:
+Remove\ journal\ '%0'=Remove journal '%0'
+
Keep\ both=Keep both
Keep\ subgroups=Keep subgroups
@@ -1291,6 +1298,7 @@ Return\ to\ JabRef=Return to JabRef
Could\ not\ connect\ to\ %0=Could not connect to %0
Warning\:\ %0\ out\ of\ %1\ entries\ have\ undefined\ title.=Warning: %0 out of %1 entries have undefined title.
Warning\:\ %0\ out\ of\ %1\ entries\ have\ undefined\ citation\ key.=Warning: %0 out of %1 entries have undefined citation key.
+Warning\:\ %0\ out\ of\ %1\ entries\ have\ undefined\ DOIs.=Warning: %0 out of %1 entries have undefined DOIs.
Really\ delete\ the\ selected\ entry?=Really delete the selected entry?
Really\ delete\ the\ %0\ selected\ entries?=Really delete the %0 selected entries?
Keep\ merged\ entry\ only=Keep merged entry only
@@ -1391,6 +1399,7 @@ Display\ keywords\ appearing\ in\ ALL\ entries=Display keywords appearing in ALL
Display\ keywords\ appearing\ in\ ANY\ entry=Display keywords appearing in ANY entry
None\ of\ the\ selected\ entries\ have\ titles.=None of the selected entries have titles.
None\ of\ the\ selected\ entries\ have\ citation\ keys.=None of the selected entries have citation keys.
+None\ of\ the\ selected\ entries\ have\ DOIs.=None of the selected entries have DOIs.
Unabbreviate\ journal\ names=Unabbreviate journal names
Unabbreviating...=Unabbreviating...
Usage=Usage
@@ -1625,7 +1634,6 @@ Add\ new\ list=Add new list
Open\ existing\ list=Open existing list
Remove\ list=Remove list
Add\ abbreviation=Add abbreviation
-Remove\ abbreviation=Remove abbreviation
Full\ journal\ name=Full journal name
Abbreviation\ name=Abbreviation name
Shortest\ unique\ abbreviation=Shortest unique abbreviation
@@ -2430,3 +2438,8 @@ Query=Query
Question=Question
Select\ directory=Select directory
+Rebuild\ fulltext\ search\ index=Rebuild fulltext search index
+Rebuild\ fulltext\ search\ index\ for\ current\ library?=Rebuild fulltext search index for current library?
+Rebuilding\ fulltext\ search\ index...=Rebuilding fulltext search index...
+Failed\ to\ access\ fulltext\ search\ index=Failed to access fulltext search index
+Found\ match\ in\ %0=Found match in %0
diff --git a/src/main/resources/luceneIndex/.gitignore b/src/main/resources/luceneIndex/.gitignore
new file mode 100644
index 00000000000..72e8ffc0db8
--- /dev/null
+++ b/src/main/resources/luceneIndex/.gitignore
@@ -0,0 +1 @@
+*
diff --git a/src/main/resources/luceneIndex/.gitkeep b/src/main/resources/luceneIndex/.gitkeep
new file mode 100644
index 00000000000..ef056e1e450
--- /dev/null
+++ b/src/main/resources/luceneIndex/.gitkeep
@@ -0,0 +1,2 @@
+# For ensuring this directory is not deleted.
+# This directory is used for the Lucene indices.
diff --git a/src/test/java/org/jabref/architecture/MainArchitectureTests.java b/src/test/java/org/jabref/architecture/MainArchitectureTests.java
index a6459ed2fe3..40e3d945f2b 100644
--- a/src/test/java/org/jabref/architecture/MainArchitectureTests.java
+++ b/src/test/java/org/jabref/architecture/MainArchitectureTests.java
@@ -117,7 +117,12 @@ public static void doNotUseLogicInModel(JavaClasses classes) {
@ArchTest
public static void restrictUsagesInModel(JavaClasses classes) {
- noClasses().that().resideInAPackage(PACKAGE_ORG_JABREF_MODEL)
+ // Until we switch to Lucene, we need to access Globals.stateManager().getActiveDatabase() from the search classes,
+ // because the PDFSearch needs to access the index of the corresponding database
+ noClasses().that().areNotAssignableFrom("org.jabref.model.search.rules.ContainBasedSearchRule")
+ .and().areNotAssignableFrom("org.jabref.model.search.rules.RegexBasedSearchRule")
+ .and().areNotAssignableFrom("org.jabref.model.search.rules.GrammarBasedSearchRule")
+ .and().resideInAPackage(PACKAGE_ORG_JABREF_MODEL)
.should().dependOnClassesThat().resideInAPackage(PACKAGE_JAVAX_SWING)
.orShould().dependOnClassesThat().haveFullyQualifiedName(CLASS_ORG_JABREF_GLOBALS)
.check(classes);
diff --git a/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java b/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java
index ee8756d73a6..594664f4f47 100644
--- a/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java
+++ b/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java
@@ -40,6 +40,7 @@ public class CopyMoreActionTest {
private BibEntry entry;
private List titles = new ArrayList();
private List keys = new ArrayList();
+ private List dois = new ArrayList();
@BeforeEach
public void setUp() {
@@ -53,6 +54,7 @@ public void setUp() {
.withCitationKey("abc");
titles.add(title);
keys.add("abc");
+ dois.add("10.1145/3377811.3380330");
}
@Test
@@ -165,4 +167,54 @@ public void testExecuteCopyKeyOnSuccess() {
verify(dialogService, times(1)).notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(copiedKeys)));
}
+
+ @Test
+ public void testExecuteCopyDoiWithNoDoi() {
+ BibEntry entryWithNoDoi = (BibEntry) entry.clone();
+ entryWithNoDoi.clearField(StandardField.DOI);
+ ObservableList entriesWithNoDois = FXCollections.observableArrayList(entryWithNoDoi);
+ BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithNoDois));
+
+ when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
+ when(stateManager.getSelectedEntries()).thenReturn(entriesWithNoDois);
+ copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService);
+ copyMoreAction.execute();
+
+ verify(clipBoardManager, times(0)).setContent(any(String.class));
+ verify(dialogService, times(1)).notify(Localization.lang("None of the selected entries have DOIs."));
+ }
+
+ @Test
+ public void testExecuteCopyDoiOnPartialSuccess() {
+ BibEntry entryWithNoDoi = (BibEntry) entry.clone();
+ entryWithNoDoi.clearField(StandardField.DOI);
+ ObservableList mixedEntries = FXCollections.observableArrayList(entryWithNoDoi, entry);
+ BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(mixedEntries));
+
+ when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
+ when(stateManager.getSelectedEntries()).thenReturn(mixedEntries);
+ copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService);
+ copyMoreAction.execute();
+
+ String copiedDois = String.join("\n", dois);
+ verify(clipBoardManager, times(1)).setContent(copiedDois);
+ verify(dialogService, times(1)).notify(Localization.lang("Warning: %0 out of %1 entries have undefined DOIs.",
+ Integer.toString(mixedEntries.size() - titles.size()), Integer.toString(mixedEntries.size())));
+ }
+
+ @Test
+ public void testExecuteCopyDoiOnSuccess() {
+ ObservableList entriesWithDois = FXCollections.observableArrayList(entry);
+ BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithDois));
+
+ when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
+ when(stateManager.getSelectedEntries()).thenReturn(entriesWithDois);
+ copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService);
+ copyMoreAction.execute();
+
+ String copiedDois = String.join("\n", dois);
+ verify(clipBoardManager, times(1)).setContent(copiedDois);
+ verify(dialogService, times(1)).notify(Localization.lang("Copied '%0' to clipboard.",
+ JabRefDialogService.shortenDialogMessage(copiedDois)));
+ }
}
diff --git a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelNoShortestUniqueAbbreviationsTabTest.java b/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelNoShortestUniqueAbbreviationsTabTest.java
deleted file mode 100644
index 7c355f55cdc..00000000000
--- a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelNoShortestUniqueAbbreviationsTabTest.java
+++ /dev/null
@@ -1,465 +0,0 @@
-package org.jabref.gui.journals;
-
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import javafx.collections.FXCollections;
-import javafx.collections.ObservableList;
-
-import org.jabref.gui.DialogService;
-import org.jabref.gui.preferences.journals.AbbreviationViewModel;
-import org.jabref.gui.preferences.journals.AbbreviationsFileViewModel;
-import org.jabref.gui.preferences.journals.JournalAbbreviationsTabViewModel;
-import org.jabref.gui.util.CurrentThreadTaskExecutor;
-import org.jabref.gui.util.TaskExecutor;
-import org.jabref.logic.JabRefException;
-import org.jabref.logic.journals.Abbreviation;
-import org.jabref.logic.journals.JournalAbbreviationLoader;
-import org.jabref.logic.journals.JournalAbbreviationPreferences;
-import org.jabref.logic.journals.JournalAbbreviationRepository;
-import org.jabref.preferences.PreferencesService;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
-
-import static org.jabref.logic.util.OS.NEWLINE;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-class JournalAbbreviationsViewModelNoShortestUniqueAbbreviationsTabTest {
-
- private JournalAbbreviationsTabViewModel viewModel;
- private Path emptyTestFile;
- private Path testFile1Entries;
- private Path testFile3Entries;
- private Path testFile4Entries;
- private Path testFile5EntriesWithDuplicate;
- private JournalAbbreviationPreferences abbreviationPreferences;
- private DialogService dialogService;
- private final JournalAbbreviationRepository repository = JournalAbbreviationLoader.loadBuiltInRepository();
-
- @BeforeEach
- void setUpViewModel(@TempDir Path tempFolder) throws Exception {
- abbreviationPreferences = mock(JournalAbbreviationPreferences.class);
- PreferencesService preferences = mock(PreferencesService.class);
- when(preferences.getJournalAbbreviationPreferences()).thenReturn(abbreviationPreferences);
-
- dialogService = mock(DialogService.class);
- TaskExecutor taskExecutor = new CurrentThreadTaskExecutor();
- viewModel = new JournalAbbreviationsTabViewModel(preferences, dialogService, taskExecutor, repository);
- emptyTestFile = createTestFile(tempFolder, "emptyTestFile.csv", "");
- testFile1Entries = createTestFile(tempFolder, "testFile1Entries.csv", "Test Entry;TE" + NEWLINE + "");
- testFile3Entries = createTestFile(tempFolder, "testFile3Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + "");
- testFile4Entries = createTestFile(tempFolder, "testFile4Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + "Entry;E" + NEWLINE + "");
- testFile5EntriesWithDuplicate = createTestFile(tempFolder, "testFile5Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + "EntryEntry;EE" + NEWLINE + "");
- }
-
- @Test
- void testInitialHasNoFilesAndNoAbbreviations() {
- assertEquals(0, viewModel.journalFilesProperty().size());
- assertEquals(0, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void testInitialWithSavedFilesIncrementsFilesCounter() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
-
- assertEquals(4, viewModel.journalFilesProperty().size());
- }
-
- @Test
- void testRemoveDuplicatesWhenReadingFiles() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
- viewModel.selectLastJournalFile();
-
- // should result in 4 real abbreviations and one pseudo abbreviation
- assertEquals(5, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void addFileIncreasesCounterOfOpenFilesAndHasNoAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
-
- assertEquals(1, viewModel.journalFilesProperty().size());
- assertEquals(1, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void addDuplicatedFileResultsInErrorDialog() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.addNewFile();
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testOpenDuplicatedFileResultsInAnException() throws Exception {
- when(dialogService.showFileOpenDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.openFile();
- viewModel.openFile();
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testSelectLastJournalFileSwitchesFilesAndTheirAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- assertEquals(1, viewModel.abbreviationsCountProperty().get());
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- assertEquals(2, viewModel.abbreviationsCountProperty().get());
- }
-
- @Test
- void testOpenValidFileContainsTheSpecificEntryAndEnoughAbbreviations() throws Exception {
- Abbreviation testAbbreviation = new Abbreviation("Test Entry", "TE");
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
-
- assertEquals(1, viewModel.journalFilesProperty().size());
- // our test file has 3 abbreviations and one pseudo abbreviation
- assertEquals(4, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.removeCurrentFile();
-
- assertEquals(0, viewModel.journalFilesProperty().size());
- assertEquals(0, viewModel.abbreviationsProperty().size());
- assertNull(viewModel.currentFileProperty().get());
- assertNull(viewModel.currentAbbreviationProperty().get());
- }
-
- @Test
- void testMixedFileUsage() throws Exception {
- Abbreviation testAbbreviation = new Abbreviation("Entry", "E");
- Abbreviation testAbbreviation2 = new Abbreviation("EntryEntry", "EE");
-
- // simulate open file button twice
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(1));
-
- // size of the list of journal files should be incremented by two
- assertEquals(2, viewModel.journalFilesProperty().size());
- // our second test file has 4 abbreviations
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check some abbreviation
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- // simulate add new file button
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(2));
-
- // size of the list of journal files should be incremented by one
- assertEquals(3, viewModel.journalFilesProperty().size());
- // a new file has zero abbreviations
- assertEquals(1, viewModel.abbreviationsProperty().size());
-
- // simulate open file button
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(3));
-
- // size of the list of journal files should be incremented by one
- assertEquals(4, viewModel.journalFilesProperty().size());
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check some abbreviation
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation2)));
- }
-
- @Test
- void testBuiltInListsIncludeAllBuiltInAbbreviations() {
- viewModel.addBuiltInList();
- assertEquals(1, viewModel.journalFilesProperty().getSize());
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0));
- ObservableList expected = FXCollections
- .observableArrayList(repository.getAllLoaded());
- ObservableList actualAbbreviations = FXCollections
- .observableArrayList(viewModel.abbreviationsProperty().stream()
- .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList()));
-
- assertEquals(expected, actualAbbreviations);
- }
-
- @Test
- void testcurrentFilePropertyChangeActiveFile() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- AbbreviationsFileViewModel test1 = viewModel.journalFilesProperty().get(0);
- AbbreviationsFileViewModel test3 = viewModel.journalFilesProperty().get(1);
- AbbreviationsFileViewModel test4 = viewModel.journalFilesProperty().get(2);
- AbbreviationsFileViewModel test5 = viewModel.journalFilesProperty().get(3);
-
- // test if the last opened file is active, but duplicated entry has been removed
- assertEquals(5, viewModel.abbreviationsProperty().size());
-
- viewModel.currentFileProperty().set(test1);
-
- // test if the current abbreviations matches with the ones in testFile1Entries
- assertEquals(2, viewModel.abbreviationsProperty().size());
-
- viewModel.currentFileProperty().set(test3);
- assertEquals(4, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test1);
- assertEquals(2, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test4);
- assertEquals(5, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test5);
- assertEquals(5, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void testAddAbbreviationIncludesAbbreviationsInAbbreviationList() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
-
- assertEquals(6, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testAddDuplicatedAbbreviationResultsInException() throws JabRefException {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- viewModel.addAbbreviation("YetAnotherEntry", "YAE");
- viewModel.addAbbreviation("YetAnotherEntry", "YAE");
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testEditSameAbbreviationWithNoChangeDoesNotResultInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
- editAbbreviation(testAbbreviation);
-
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- editAbbreviation(testAbbreviation);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- editAbbreviation(testAbbreviation);
-
- assertEquals(1, viewModel.abbreviationsProperty().size());
- assertFalse(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testEditAbbreviationToExistingOneResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("YetAnotherEntry", "YAE");
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(2));
- viewModel.editAbbreviation("YetAnotherEntry", "YAE");
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testEditAbbreviationToEmptyNameResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("", "YAE");
- verify(dialogService).showErrorDialogAndWait(anyString());
- }
-
- @Test
- void testEditAbbreviationToEmptyAbbreviationResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("YetAnotherEntry", "");
- verify(dialogService).showErrorDialogAndWait(anyString());
- }
-
- @Test
- void testDeleteAbbreviationSelectsPreviousOne() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
-
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
-
- viewModel.deleteAbbreviation();
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check if the previous (the last) element is the current abbreviation
- assertEquals(viewModel.currentAbbreviationProperty().get(), viewModel.abbreviationsProperty().get(4));
- }
-
- @Test
- void testDeleteAbbreviationSelectsNextOne() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(1));
- viewModel.deleteAbbreviation();
-
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
- }
-
- @Test
- void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- Abbreviation testAbbreviation = new Abbreviation("JabRefTestEntry", "JTE");
- editAbbreviation(testAbbreviation);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- viewModel.deleteAbbreviation();
- Abbreviation testAbbreviation1 = new Abbreviation("SomeOtherEntry", "SOE");
- addAbbrevaition(testAbbreviation1);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation1)));
-
- viewModel.saveJournalAbbreviationFiles();
- List expected = Arrays.asList(
- "Abbreviations;Abb;Abb",
- "Test Entry;TE;TE",
- "MoreEntries;ME;ME",
- "JabRefTestEntry;JTE;JTE");
- List actual = Files.readAllLines(testFile4Entries, StandardCharsets.UTF_8);
-
- assertEquals(expected, actual);
-
- expected = Arrays.asList(
- "EntryEntry;EE;EE",
- "Abbreviations;Abb;Abb",
- "Test Entry;TE;TE",
- "SomeOtherEntry;SOE;SOE");
- actual = Files.readAllLines(testFile5EntriesWithDuplicate, StandardCharsets.UTF_8);
-
- assertEquals(expected, actual);
- }
-
- @Test
- void testSaveExternalFilesListToPreferences() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- List expected = Stream.of(testFile1Entries, testFile3Entries, testFile4Entries, testFile5EntriesWithDuplicate)
- .map(Path::toString).collect(Collectors.toList());
- verify(abbreviationPreferences).setExternalJournalLists(expected);
- }
-
- private Path createTestFile(Path folder, String name, String content) throws Exception {
- Path file = folder.resolve(name);
- Files.writeString(file, content);
- return file;
- }
-
- private void addAbbrevaition(Abbreviation testAbbreviation) throws Exception {
- viewModel.addAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
- }
-
- private void editAbbreviation(Abbreviation testAbbreviation) throws Exception {
- viewModel.editAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
- }
-
- private void addFourTestFileToViewModelAndPreferences() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.storeSettings();
- }
-
- /**
- * Select the last abbreviation in the list of abbreviations
- */
- private void selectLastAbbreviation() {
- viewModel.currentAbbreviationProperty()
- .set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1));
- }
-}
diff --git a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelWithShortestUniqueAbbreviationsTabTest.java b/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelWithShortestUniqueAbbreviationsTabTest.java
deleted file mode 100644
index f0811c06f45..00000000000
--- a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelWithShortestUniqueAbbreviationsTabTest.java
+++ /dev/null
@@ -1,465 +0,0 @@
-package org.jabref.gui.journals;
-
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import javafx.collections.FXCollections;
-import javafx.collections.ObservableList;
-
-import org.jabref.gui.DialogService;
-import org.jabref.gui.preferences.journals.AbbreviationViewModel;
-import org.jabref.gui.preferences.journals.AbbreviationsFileViewModel;
-import org.jabref.gui.preferences.journals.JournalAbbreviationsTabViewModel;
-import org.jabref.gui.util.CurrentThreadTaskExecutor;
-import org.jabref.gui.util.TaskExecutor;
-import org.jabref.logic.JabRefException;
-import org.jabref.logic.journals.Abbreviation;
-import org.jabref.logic.journals.JournalAbbreviationLoader;
-import org.jabref.logic.journals.JournalAbbreviationPreferences;
-import org.jabref.logic.journals.JournalAbbreviationRepository;
-import org.jabref.preferences.PreferencesService;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
-
-import static org.jabref.logic.util.OS.NEWLINE;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-class JournalAbbreviationsViewModelWithShortestUniqueAbbreviationsTabTest {
-
- private JournalAbbreviationsTabViewModel viewModel;
- private Path emptyTestFile;
- private Path testFile1Entries;
- private Path testFile3Entries;
- private Path testFile4Entries;
- private Path testFile5EntriesWithDuplicate;
- private JournalAbbreviationPreferences abbreviationPreferences;
- private DialogService dialogService;
- private final JournalAbbreviationRepository repository = JournalAbbreviationLoader.loadBuiltInRepository();
-
- @BeforeEach
- void setUpViewModel(@TempDir Path tempFolder) throws Exception {
- abbreviationPreferences = mock(JournalAbbreviationPreferences.class);
- PreferencesService preferences = mock(PreferencesService.class);
- when(preferences.getJournalAbbreviationPreferences()).thenReturn(abbreviationPreferences);
-
- dialogService = mock(DialogService.class);
- TaskExecutor taskExecutor = new CurrentThreadTaskExecutor();
- viewModel = new JournalAbbreviationsTabViewModel(preferences, dialogService, taskExecutor, repository);
- emptyTestFile = createTestFile(tempFolder, "emptyTestFile.csv", "");
- testFile1Entries = createTestFile(tempFolder, "testFile1Entries.csv", "Test Entry;TE;T" + NEWLINE + "");
- testFile3Entries = createTestFile(tempFolder, "testFile3Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "");
- testFile4Entries = createTestFile(tempFolder, "testFile4Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "Entry;En;E" + NEWLINE + "");
- testFile5EntriesWithDuplicate = createTestFile(tempFolder, "testFile5Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "EntryEntry;EE" + NEWLINE + "");
- }
-
- @Test
- void testInitialHasNoFilesAndNoAbbreviations() {
- assertEquals(0, viewModel.journalFilesProperty().size());
- assertEquals(0, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void testInitialWithSavedFilesIncrementsFilesCounter() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
-
- assertEquals(4, viewModel.journalFilesProperty().size());
- }
-
- @Test
- void testRemoveDuplicatesWhenReadingFiles() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
- viewModel.selectLastJournalFile();
-
- // should result in 4 real abbreviations and one pseudo abbreviation
- assertEquals(5, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void addFileIncreasesCounterOfOpenFilesAndHasNoAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
-
- assertEquals(1, viewModel.journalFilesProperty().size());
- assertEquals(1, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void addDuplicatedFileResultsInErrorDialog() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.addNewFile();
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testOpenDuplicatedFileResultsInAnException() throws Exception {
- when(dialogService.showFileOpenDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.openFile();
- viewModel.openFile();
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testSelectLastJournalFileSwitchesFilesAndTheirAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- assertEquals(1, viewModel.abbreviationsCountProperty().get());
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- assertEquals(2, viewModel.abbreviationsCountProperty().get());
- }
-
- @Test
- void testOpenValidFileContainsTheSpecificEntryAndEnoughAbbreviations() throws Exception {
- Abbreviation testAbbreviation = new Abbreviation("Test Entry", "TE");
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
-
- assertEquals(1, viewModel.journalFilesProperty().size());
- // our test file has 3 abbreviations and one pseudo abbreviation
- assertEquals(4, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.removeCurrentFile();
-
- assertEquals(0, viewModel.journalFilesProperty().size());
- assertEquals(0, viewModel.abbreviationsProperty().size());
- assertNull(viewModel.currentFileProperty().get());
- assertNull(viewModel.currentAbbreviationProperty().get());
- }
-
- @Test
- void testMixedFileUsage() throws Exception {
- Abbreviation testAbbreviation = new Abbreviation("Entry", "En", "E");
- Abbreviation testAbbreviation2 = new Abbreviation("EntryEntry", "EnEn", "EE");
-
- // simulate open file button twice
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(1));
-
- // size of the list of journal files should be incremented by two
- assertEquals(2, viewModel.journalFilesProperty().size());
- // our second test file has 4 abbreviations
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check some abbreviation
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- // simulate add new file button
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(2));
-
- // size of the list of journal files should be incremented by one
- assertEquals(3, viewModel.journalFilesProperty().size());
- // a new file has zero abbreviations
- assertEquals(1, viewModel.abbreviationsProperty().size());
-
- // simulate open file button
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(3));
-
- // size of the list of journal files should be incremented by one
- assertEquals(4, viewModel.journalFilesProperty().size());
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check some abbreviation
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation2)));
- }
-
- @Test
- void testBuiltInListsIncludeAllBuiltInAbbreviations() {
- viewModel.addBuiltInList();
- assertEquals(1, viewModel.journalFilesProperty().getSize());
- viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0));
- ObservableList expected = FXCollections
- .observableArrayList(repository.getAllLoaded());
- ObservableList actualAbbreviations = FXCollections
- .observableArrayList(viewModel.abbreviationsProperty().stream()
- .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList()));
-
- assertEquals(expected, actualAbbreviations);
- }
-
- @Test
- void testcurrentFilePropertyChangeActiveFile() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- AbbreviationsFileViewModel test1 = viewModel.journalFilesProperty().get(0);
- AbbreviationsFileViewModel test3 = viewModel.journalFilesProperty().get(1);
- AbbreviationsFileViewModel test4 = viewModel.journalFilesProperty().get(2);
- AbbreviationsFileViewModel test5 = viewModel.journalFilesProperty().get(3);
-
- // test if the last opened file is active, but duplicated entry has been removed
- assertEquals(5, viewModel.abbreviationsProperty().size());
-
- viewModel.currentFileProperty().set(test1);
-
- // test if the current abbreviations matches with the ones in testFile1Entries
- assertEquals(2, viewModel.abbreviationsProperty().size());
-
- viewModel.currentFileProperty().set(test3);
- assertEquals(4, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test1);
- assertEquals(2, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test4);
- assertEquals(5, viewModel.abbreviationsProperty().size());
- viewModel.currentFileProperty().set(test5);
- assertEquals(5, viewModel.abbreviationsProperty().size());
- }
-
- @Test
- void testAddAbbreviationIncludesAbbreviationsInAbbreviationList() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE", "Y");
- addAbbrevaition(testAbbreviation);
-
- assertEquals(6, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testAddDuplicatedAbbreviationResultsInException() throws JabRefException {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- viewModel.addAbbreviation("YetAnotherEntry", "YAE", "Y");
- viewModel.addAbbreviation("YetAnotherEntry", "YAE", "Y");
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testEditSameAbbreviationWithNoChangeDoesNotResultInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE", "Y");
- addAbbrevaition(testAbbreviation);
- editAbbreviation(testAbbreviation);
-
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE", "Y");
- editAbbreviation(testAbbreviation);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- editAbbreviation(testAbbreviation);
-
- assertEquals(1, viewModel.abbreviationsProperty().size());
- assertFalse(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- }
-
- @Test
- void testEditAbbreviationToExistingOneResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("YetAnotherEntry", "YAE", "Y");
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(2));
- viewModel.editAbbreviation("YetAnotherEntry", "YAE", "Y");
- verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
- }
-
- @Test
- void testEditAbbreviationToEmptyNameResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("", "YAE", "Y");
- verify(dialogService).showErrorDialogAndWait(anyString());
- }
-
- @Test
- void testEditAbbreviationToEmptyAbbreviationResultsInException() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
-
- assertEquals(4, viewModel.abbreviationsProperty().size());
-
- viewModel.editAbbreviation("YetAnotherEntry", "", "Y");
- verify(dialogService).showErrorDialogAndWait(anyString());
- }
-
- @Test
- void testDeleteAbbreviationSelectsPreviousOne() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE", "Y");
- addAbbrevaition(testAbbreviation);
-
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
-
- viewModel.deleteAbbreviation();
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check if the previous (the last) element is the current abbreviation
- assertEquals(viewModel.currentAbbreviationProperty().get(), viewModel.abbreviationsProperty().get(4));
- }
-
- @Test
- void testDeleteAbbreviationSelectsNextOne() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE", "Y");
- addAbbrevaition(testAbbreviation);
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(1));
- viewModel.deleteAbbreviation();
-
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
- }
-
- @Test
- void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- Abbreviation testAbbreviation = new Abbreviation("JabRefTestEntry", "JTE");
- editAbbreviation(testAbbreviation);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
-
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- selectLastAbbreviation();
- viewModel.deleteAbbreviation();
- Abbreviation testAbbreviation1 = new Abbreviation("SomeOtherEntry", "SOE");
- addAbbrevaition(testAbbreviation1);
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation1)));
-
- viewModel.saveJournalAbbreviationFiles();
- List expected = Arrays.asList(
- "Abbreviations;Abb;A",
- "Test Entry;TE;T",
- "MoreEntries;ME;M",
- "JabRefTestEntry;JTE;JTE");
- List actual = Files.readAllLines(testFile4Entries, StandardCharsets.UTF_8);
-
- assertEquals(expected, actual);
-
- expected = Arrays.asList(
- "EntryEntry;EE;EE",
- "Abbreviations;Abb;A",
- "Test Entry;TE;T",
- "SomeOtherEntry;SOE;SOE");
- actual = Files.readAllLines(testFile5EntriesWithDuplicate, StandardCharsets.UTF_8);
-
- assertEquals(expected, actual);
- }
-
- @Test
- void testSaveExternalFilesListToPreferences() throws Exception {
- addFourTestFileToViewModelAndPreferences();
- List expected = Stream.of(testFile1Entries, testFile3Entries, testFile4Entries, testFile5EntriesWithDuplicate)
- .map(Path::toString).collect(Collectors.toList());
- verify(abbreviationPreferences).setExternalJournalLists(expected);
- }
-
- private Path createTestFile(Path folder, String name, String content) throws Exception {
- Path file = folder.resolve(name);
- Files.writeString(file, content);
- return file;
- }
-
- private void addAbbrevaition(Abbreviation testAbbreviation) throws Exception {
- viewModel.addAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
- }
-
- private void editAbbreviation(Abbreviation testAbbreviation) throws Exception {
- viewModel.editAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
- }
-
- private void addFourTestFileToViewModelAndPreferences() throws Exception {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.storeSettings();
- }
-
- /**
- * Select the last abbreviation in the list of abbreviations
- */
- private void selectLastAbbreviation() {
- viewModel.currentAbbreviationProperty()
- .set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1));
- }
-}
diff --git a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelMixedAbbreviationsTabTest.java b/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java
similarity index 58%
rename from src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelMixedAbbreviationsTabTest.java
rename to src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java
index 9c906027888..c7db04c42e4 100644
--- a/src/test/java/org/jabref/gui/journals/JournalAbbreviationsViewModelMixedAbbreviationsTabTest.java
+++ b/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java
@@ -1,9 +1,9 @@
-package org.jabref.gui.journals;
+package org.jabref.gui.preferences.journals;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -13,9 +13,6 @@
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
-import org.jabref.gui.preferences.journals.AbbreviationViewModel;
-import org.jabref.gui.preferences.journals.AbbreviationsFileViewModel;
-import org.jabref.gui.preferences.journals.JournalAbbreviationsTabViewModel;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.Abbreviation;
@@ -27,6 +24,9 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import static org.jabref.logic.util.OS.NEWLINE;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -39,32 +39,62 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-class JournalAbbreviationsViewModelMixedAbbreviationsTabTest {
+class JournalAbbreviationsViewModelTabTest {
private JournalAbbreviationsTabViewModel viewModel;
private Path emptyTestFile;
- private Path testFile1Entries;
- private Path testFile3Entries;
- private Path testFile4Entries;
- private Path testFile5EntriesWithDuplicate;
- private JournalAbbreviationPreferences abbreviationPreferences;
+ private Path tempFolder;
+ private PreferencesService preferencesService;
private final JournalAbbreviationRepository repository = JournalAbbreviationLoader.loadBuiltInRepository();
private DialogService dialogService;
+ public static Stream provideTestFiles() {
+ return Stream.of(
+ // Mixed abbreviations
+ Arguments.of(
+ List.of(List.of("testFile1Entries.csv", "Test Entry;TE" + NEWLINE + ""),
+ List.of("testFile3Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + ""),
+ List.of("testFile4Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "Entry;E" + NEWLINE + ""),
+ List.of("testFile5Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "EntryEntry;EE" + NEWLINE + "")),
+ List.of(
+ List.of("Abbreviations;Abb;Abb", "Test Entry;TE;T", "MoreEntries;ME;M", "JabRefTestEntry;JTE;JTE"),
+ List.of("EntryEntry;EE;EE", "Abbreviations;Abb;Abb", "Test Entry;TE;T", "SomeOtherEntry;SOE;SOE"))),
+
+ // No shortest unique abbreviations
+ Arguments.of(
+ List.of(List.of("testFile1Entries.csv", "Test Entry;TE" + NEWLINE + ""),
+ List.of("testFile3Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + ""),
+ List.of("testFile4Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + "Entry;E" + NEWLINE + ""),
+ List.of("testFile5Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME" + NEWLINE + "EntryEntry;EE" + NEWLINE + "")),
+ List.of(
+ List.of("Abbreviations;Abb;Abb", "Test Entry;TE;TE", "MoreEntries;ME;ME", "JabRefTestEntry;JTE;JTE"),
+ List.of("EntryEntry;EE;EE", "Abbreviations;Abb;Abb", "Test Entry;TE;TE", "SomeOtherEntry;SOE;SOE"))),
+
+ // Shortest unique abbreviations
+ Arguments.of(
+ List.of(List.of("testFile1Entries.csv", "Test Entry;TE;T" + NEWLINE + ""),
+ List.of("testFile3Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + ""),
+ List.of("testFile4Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "Entry;En;E" + NEWLINE + ""),
+ List.of("testFile5Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "EntryEntry;EE" + NEWLINE + "")),
+ List.of(
+ List.of("Abbreviations;Abb;A", "Test Entry;TE;T", "MoreEntries;ME;M", "JabRefTestEntry;JTE;JTE"),
+ List.of("EntryEntry;EE;EE", "Abbreviations;Abb;A", "Test Entry;TE;T", "SomeOtherEntry;SOE;SOE")))
+ );
+ }
+
@BeforeEach
void setUpViewModel(@TempDir Path tempFolder) throws Exception {
- abbreviationPreferences = mock(JournalAbbreviationPreferences.class);
- PreferencesService preferences = mock(PreferencesService.class);
- when(preferences.getJournalAbbreviationPreferences()).thenReturn(abbreviationPreferences);
+ JournalAbbreviationPreferences abbreviationPreferences = mock(JournalAbbreviationPreferences.class);
+ preferencesService = mock(PreferencesService.class);
+ when(preferencesService.getJournalAbbreviationPreferences()).thenReturn(abbreviationPreferences);
dialogService = mock(DialogService.class);
+ this.tempFolder = tempFolder;
+
TaskExecutor taskExecutor = new CurrentThreadTaskExecutor();
- viewModel = new JournalAbbreviationsTabViewModel(preferences, dialogService, taskExecutor, repository);
- emptyTestFile = createTestFile(tempFolder, "emptyTestFile.csv", "");
- testFile1Entries = createTestFile(tempFolder, "testFile1Entries.csv", "Test Entry;TE" + NEWLINE + "");
- testFile3Entries = createTestFile(tempFolder, "testFile3Entries.csv", "Abbreviations;Abb;A" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "");
- testFile4Entries = createTestFile(tempFolder, "testFile4Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "Entry;E" + NEWLINE + "");
- testFile5EntriesWithDuplicate = createTestFile(tempFolder, "testFile5Entries.csv", "Abbreviations;Abb" + NEWLINE + "Test Entry;TE;T" + NEWLINE + "Test Entry;TE" + NEWLINE + "MoreEntries;ME;M" + NEWLINE + "EntryEntry;EE" + NEWLINE + "");
+ viewModel = new JournalAbbreviationsTabViewModel(preferencesService, dialogService, taskExecutor, repository);
+
+ emptyTestFile = createTestFile("emptyTestFile.csv", "");
}
@Test
@@ -73,22 +103,21 @@ void testInitialHasNoFilesAndNoAbbreviations() {
assertEquals(0, viewModel.abbreviationsProperty().size());
}
- @Test
- void testInitialWithSavedFilesIncrementsFilesCounter() {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
-
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testInitialWithSavedFilesIncrementsFilesCounter(List> testFiles) throws IOException {
+ addFourTestFileToViewModelAndPreferences(testFiles);
assertEquals(4, viewModel.journalFilesProperty().size());
}
- @Test
- void testRemoveDuplicatesWhenReadingFiles() {
- addFourTestFileToViewModelAndPreferences();
- viewModel.createFileObjects();
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testRemoveDuplicatesWhenReadingFiles(List> testFiles) throws IOException {
+ addFourTestFileToViewModelAndPreferences(testFiles);
viewModel.selectLastJournalFile();
- // should result in 4 real abbreviations and one pseudo abbreviation
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.journalFilesProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
}
@Test
@@ -97,54 +126,58 @@ void addFileIncreasesCounterOfOpenFilesAndHasNoAbbreviations() {
viewModel.addNewFile();
assertEquals(1, viewModel.journalFilesProperty().size());
- assertEquals(1, viewModel.abbreviationsProperty().size());
+ assertEquals(0, viewModel.abbreviationsProperty().size());
}
- @Test
- void addDuplicatedFileResultsInErrorDialog() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void addDuplicatedFileResultsInErrorDialog(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(0))));
viewModel.addNewFile();
viewModel.addNewFile();
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
- @Test
- void testOpenDuplicatedFileResultsInAnException() {
- when(dialogService.showFileOpenDialog(any())).thenReturn(Optional.of(testFile1Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testOpenDuplicatedFileResultsInAnException(List> testFiles) throws IOException {
+ when(dialogService.showFileOpenDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(0))));
viewModel.openFile();
viewModel.openFile();
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
- @Test
- void testSelectLastJournalFileSwitchesFilesAndTheirAbbreviations() {
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testSelectLastJournalFileSwitchesFilesAndTheirAbbreviations(List> testFiles) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
- assertEquals(1, viewModel.abbreviationsCountProperty().get());
+ assertEquals(0, viewModel.abbreviationsCountProperty().get());
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(0))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
- assertEquals(2, viewModel.abbreviationsCountProperty().get());
+ assertEquals(1, viewModel.abbreviationsCountProperty().get());
}
- @Test
- void testOpenValidFileContainsTheSpecificEntryAndEnoughAbbreviations() {
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testOpenValidFileContainsTheSpecificEntryAndEnoughAbbreviations(List> testFiles) throws IOException {
Abbreviation testAbbreviation = new Abbreviation("Test Entry", "TE");
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
assertEquals(1, viewModel.journalFilesProperty().size());
- // our test file has 3 abbreviations and one pseudo abbreviation
- assertEquals(4, viewModel.abbreviationsProperty().size());
+ assertEquals(3, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
- @Test
- void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(0))));
viewModel.addNewFile();
viewModel.removeCurrentFile();
@@ -154,22 +187,23 @@ void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull() {
assertNull(viewModel.currentAbbreviationProperty().get());
}
- @Test
- void testMixedFileUsage() {
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testMixedFileUsage(List> testFiles) throws IOException {
Abbreviation testAbbreviation = new Abbreviation("Entry", "E");
Abbreviation testAbbreviation2 = new Abbreviation("EntryEntry", "EE");
// simulate open file button twice
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(2))));
viewModel.addNewFile();
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(1));
// size of the list of journal files should be incremented by two
assertEquals(2, viewModel.journalFilesProperty().size());
// our second test file has 4 abbreviations
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
// check some abbreviation
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
@@ -181,17 +215,17 @@ void testMixedFileUsage() {
// size of the list of journal files should be incremented by one
assertEquals(3, viewModel.journalFilesProperty().size());
// a new file has zero abbreviations
- assertEquals(1, viewModel.abbreviationsProperty().size());
+ assertEquals(0, viewModel.abbreviationsProperty().size());
// simulate open file button
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(3))));
viewModel.addNewFile();
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(3));
// size of the list of journal files should be incremented by one
assertEquals(4, viewModel.journalFilesProperty().size());
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
// check some abbreviation
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation2)));
}
@@ -210,57 +244,57 @@ void testBuiltInListsIncludeAllBuiltInAbbreviations() {
assertEquals(expected, actualAbbreviations);
}
- @Test
- void testCurrentFilePropertyChangeActiveFile() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testCurrentFilePropertyChangeActiveFile(List> testFiles) throws IOException {
+ for (List testFile : testFiles) {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFile)));
+ viewModel.addNewFile();
+ }
viewModel.selectLastJournalFile();
+
AbbreviationsFileViewModel test1 = viewModel.journalFilesProperty().get(0);
AbbreviationsFileViewModel test3 = viewModel.journalFilesProperty().get(1);
AbbreviationsFileViewModel test4 = viewModel.journalFilesProperty().get(2);
AbbreviationsFileViewModel test5 = viewModel.journalFilesProperty().get(3);
// test if the last opened file is active, but duplicated entry has been removed
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test1);
// test if the current abbreviations matches with the ones in testFile1Entries
- assertEquals(2, viewModel.abbreviationsProperty().size());
+ assertEquals(1, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test3);
- assertEquals(4, viewModel.abbreviationsProperty().size());
+ assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test1);
- assertEquals(2, viewModel.abbreviationsProperty().size());
+ assertEquals(1, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test4);
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test5);
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
}
- @Test
- void testAddAbbreviationIncludesAbbreviationsInAbbreviationList() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testAddAbbreviationIncludesAbbreviationsInAbbreviationList(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(2))));
viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(3))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
+ addAbbreviation(testAbbreviation);
- assertEquals(6, viewModel.abbreviationsProperty().size());
+ assertEquals(5, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
- @Test
- void testAddDuplicatedAbbreviationResultsInException() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testAddDuplicatedAbbreviationResultsInException(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
viewModel.addAbbreviation("YetAnotherEntry", "YAE");
@@ -274,22 +308,23 @@ void testEditSameAbbreviationWithNoChangeDoesNotResultInException() {
viewModel.addNewFile();
viewModel.selectLastJournalFile();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
+ addAbbreviation(testAbbreviation);
editAbbreviation(testAbbreviation);
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
- @Test
- void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(2))));
viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(3))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- editAbbreviation(testAbbreviation);
+ addAbbreviation(testAbbreviation);
assertEquals(5, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
@@ -297,88 +332,62 @@ void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList() {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
- editAbbreviation(testAbbreviation);
+ // addAbbreviation(testAbbreviation);
- assertEquals(1, viewModel.abbreviationsProperty().size());
+ assertEquals(0, viewModel.abbreviationsProperty().size());
assertFalse(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
- @Test
- void testEditAbbreviationToExistingOneResultsInException() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testEditAbbreviationToExistingOneResultsInException(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
- assertEquals(4, viewModel.abbreviationsProperty().size());
+ assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation("YetAnotherEntry", "YAE");
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(2));
+ viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(1));
viewModel.editAbbreviation("YetAnotherEntry", "YAE");
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
- @Test
- void testEditAbbreviationToEmptyNameResultsInException() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testEditAbbreviationToEmptyNameResultsInException(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
- assertEquals(4, viewModel.abbreviationsProperty().size());
+ assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation("", "YAE");
verify(dialogService).showErrorDialogAndWait(anyString());
}
- @Test
- void testEditAbbreviationToEmptyAbbreviationResultsInException() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testEditAbbreviationToEmptyAbbreviationResultsInException(List> testFiles) throws IOException {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
- assertEquals(4, viewModel.abbreviationsProperty().size());
+ assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation("YetAnotherEntry", "");
verify(dialogService).showErrorDialogAndWait(anyString());
}
- @Test
- void testDeleteAbbreviationSelectsPreviousOne() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
-
- assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
-
- viewModel.deleteAbbreviation();
-
- assertEquals(5, viewModel.abbreviationsProperty().size());
- // check if the previous (the last) element is the current abbreviation
- assertEquals(viewModel.currentAbbreviationProperty().get(), viewModel.abbreviationsProperty().get(4));
- }
-
- @Test
- void testDeleteAbbreviationSelectsNextOne() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- viewModel.selectLastJournalFile();
- Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
- addAbbrevaition(testAbbreviation);
- viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(1));
- viewModel.deleteAbbreviation();
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations(List> testFiles, List> testEntries) throws Exception {
+ Path testFile4Entries = createTestFile(testFiles.get(2));
+ Path testFile5EntriesWithDuplicate = createTestFile(testFiles.get(3));
- assertEquals(new AbbreviationViewModel(testAbbreviation), viewModel.currentAbbreviationProperty().get());
- }
-
- @Test
- void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throws Exception {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
@@ -386,7 +395,7 @@ void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throw
Abbreviation testAbbreviation = new Abbreviation("JabRefTestEntry", "JTE");
editAbbreviation(testAbbreviation);
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
@@ -395,47 +404,28 @@ void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations() throw
selectLastAbbreviation();
viewModel.deleteAbbreviation();
Abbreviation testAbbreviation1 = new Abbreviation("SomeOtherEntry", "SOE");
- addAbbrevaition(testAbbreviation1);
+ addAbbreviation(testAbbreviation1);
- assertEquals(5, viewModel.abbreviationsProperty().size());
+ assertEquals(4, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation1)));
viewModel.saveJournalAbbreviationFiles();
- List expected = Arrays.asList(
- "Abbreviations;Abb;Abb",
- "Test Entry;TE;T",
- "MoreEntries;ME;M",
- "JabRefTestEntry;JTE;JTE");
- List actual = Files.readAllLines(testFile4Entries, StandardCharsets.UTF_8);
- assertEquals(expected, actual);
+ List actual = Files.readAllLines(testFile4Entries, StandardCharsets.UTF_8);
+ assertEquals(testEntries.get(0), actual);
- expected = Arrays.asList(
- "EntryEntry;EE;EE",
- "Abbreviations;Abb;Abb",
- "Test Entry;TE;T",
- "SomeOtherEntry;SOE;SOE");
actual = Files.readAllLines(testFile5EntriesWithDuplicate, StandardCharsets.UTF_8);
-
- assertEquals(expected, actual);
+ assertEquals(testEntries.get(1), actual);
}
- @Test
- void testSaveExternalFilesListToPreferences() {
- addFourTestFileToViewModelAndPreferences();
- List expected = Stream.of(testFile1Entries, testFile3Entries, testFile4Entries, testFile5EntriesWithDuplicate)
- .map(Path::toString)
- .collect(Collectors.toList());
- verify(abbreviationPreferences).setExternalJournalLists(expected);
+ @ParameterizedTest
+ @MethodSource("provideTestFiles")
+ void testSaveExternalFilesListToPreferences(List> testFiles) throws IOException {
+ addFourTestFileToViewModelAndPreferences(testFiles);
+ verify(preferencesService).storeJournalAbbreviationPreferences(any());
}
- private Path createTestFile(Path folder, String name, String content) throws Exception {
- Path file = folder.resolve(name);
- Files.writeString(file, content);
- return file;
- }
-
- private void addAbbrevaition(Abbreviation testAbbreviation) {
+ private void addAbbreviation(Abbreviation testAbbreviation) {
viewModel.addAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
}
@@ -443,18 +433,6 @@ private void editAbbreviation(Abbreviation testAbbreviation) {
viewModel.editAbbreviation(testAbbreviation.getName(), testAbbreviation.getAbbreviation());
}
- private void addFourTestFileToViewModelAndPreferences() {
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile1Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile4Entries));
- viewModel.addNewFile();
- when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate));
- viewModel.addNewFile();
- viewModel.storeSettings();
- }
-
/**
* Select the last abbreviation in the list of abbreviations
*/
@@ -462,4 +440,22 @@ private void selectLastAbbreviation() {
viewModel.currentAbbreviationProperty()
.set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1));
}
+
+ private void addFourTestFileToViewModelAndPreferences(List> testFiles) throws IOException {
+ for (List testFile : testFiles) {
+ when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFile.get(0), testFile.get(1))));
+ viewModel.addNewFile();
+ }
+ viewModel.storeSettings();
+ }
+
+ private Path createTestFile(String name, String content) throws IOException {
+ Path file = this.tempFolder.resolve(name);
+ Files.writeString(file, content);
+ return file;
+ }
+
+ private Path createTestFile(List testFile) throws IOException {
+ return createTestFile(testFile.get(0), testFile.get(1));
+ }
}
diff --git a/src/test/java/org/jabref/gui/search/ContainsAndRegexBasedSearchRuleDescriberTest.java b/src/test/java/org/jabref/gui/search/ContainsAndRegexBasedSearchRuleDescriberTest.java
index b67da25d1ca..bc3406ec43c 100644
--- a/src/test/java/org/jabref/gui/search/ContainsAndRegexBasedSearchRuleDescriberTest.java
+++ b/src/test/java/org/jabref/gui/search/ContainsAndRegexBasedSearchRuleDescriberTest.java
@@ -1,5 +1,6 @@
package org.jabref.gui.search;
+import java.util.EnumSet;
import java.util.List;
import javafx.scene.text.Text;
@@ -8,6 +9,8 @@
import org.jabref.gui.search.rules.describer.ContainsAndRegexBasedSearchRuleDescriber;
import org.jabref.gui.util.TooltipTextUtil;
+import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Test;
@@ -32,7 +35,7 @@ void testSimpleTerm() {
TooltipTextUtil.createText("This search contains entries in which any field contains the term "),
TooltipTextUtil.createText("test", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
- TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(false, false, query).getDescription();
+ TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.noneOf(SearchFlags.class), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -46,7 +49,7 @@ void testNoAst() {
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
- TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(false, false, query).getDescription();
+ TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.noneOf(SearchFlags.class), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -60,7 +63,7 @@ void testNoAstRegex() {
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
- TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(false, true, query).getDescription();
+ TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -74,7 +77,7 @@ void testNoAstRegexCaseSensitive() {
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case sensitive). "));
- TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(true, true, query).getDescription();
+ TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -88,7 +91,7 @@ void testNoAstCaseSensitive() {
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case sensitive). "));
- TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(true, false, query).getDescription();
+ TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
diff --git a/src/test/java/org/jabref/gui/search/GrammarBasedSearchRuleDescriberTest.java b/src/test/java/org/jabref/gui/search/GrammarBasedSearchRuleDescriberTest.java
index 36ae0dbea71..cad5aa79e89 100644
--- a/src/test/java/org/jabref/gui/search/GrammarBasedSearchRuleDescriberTest.java
+++ b/src/test/java/org/jabref/gui/search/GrammarBasedSearchRuleDescriberTest.java
@@ -1,6 +1,7 @@
package org.jabref.gui.search;
import java.util.Arrays;
+import java.util.EnumSet;
import java.util.List;
import javafx.scene.text.Text;
@@ -10,6 +11,8 @@
import org.jabref.gui.search.rules.describer.GrammarBasedSearchRuleDescriber;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.model.search.rules.GrammarBasedSearchRule;
+import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Test;
@@ -29,10 +32,10 @@ void onStart(Stage stage) {
stage.show();
}
- private TextFlow createDescription(String query, boolean caseSensitive, boolean regExp) {
- GrammarBasedSearchRule grammarBasedSearchRule = new GrammarBasedSearchRule(caseSensitive, regExp);
+ private TextFlow createDescription(String query, EnumSet searchFlags) {
+ GrammarBasedSearchRule grammarBasedSearchRule = new GrammarBasedSearchRule(searchFlags);
assertTrue(grammarBasedSearchRule.validateSearchStrings(query));
- GrammarBasedSearchRuleDescriber describer = new GrammarBasedSearchRuleDescriber(caseSensitive, regExp, grammarBasedSearchRule.getTree());
+ GrammarBasedSearchRuleDescriber describer = new GrammarBasedSearchRuleDescriber(searchFlags, grammarBasedSearchRule.getTree());
return describer.getDescription();
}
@@ -42,7 +45,7 @@ void testSimpleQueryCaseSensitiveRegex() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case sensitive."));
- TextFlow description = createDescription(query, true, true);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -53,7 +56,7 @@ void testSimpleQueryCaseSensitive() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case sensitive."));
- TextFlow description = createDescription(query, true, false);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -64,7 +67,7 @@ void testSimpleQuery() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case insensitive."));
- TextFlow description = createDescription(query, false, false);
+ TextFlow description = createDescription(query, EnumSet.noneOf(SearchFlags.class));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -75,7 +78,7 @@ void testSimpleQueryRegex() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case insensitive."));
- TextFlow description = createDescription(query, false, true);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -87,7 +90,7 @@ void testComplexQueryCaseSensitiveRegex() {
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case sensitive."));
- TextFlow description = createDescription(query, true, true);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -99,7 +102,7 @@ void testComplexQueryRegex() {
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case insensitive."));
- TextFlow description = createDescription(query, false, true);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -110,7 +113,7 @@ void testComplexQueryCaseSensitive() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case sensitive."));
- TextFlow description = createDescription(query, true, false);
+ TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@@ -121,7 +124,7 @@ void testComplexQuery() {
List expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case insensitive."));
- TextFlow description = createDescription(query, false, false);
+ TextFlow description = createDescription(query, EnumSet.noneOf(SearchFlags.class));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
diff --git a/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java b/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java
index 4c1bc3147fb..1753495506a 100644
--- a/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java
+++ b/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java
@@ -3,6 +3,7 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
+import java.util.EnumSet;
import java.util.List;
import javafx.scene.paint.Color;
@@ -24,6 +25,7 @@
import org.jabref.model.groups.TexGroup;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.model.metadata.MetaData;
+import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.junit.jupiter.api.BeforeEach;
@@ -89,14 +91,14 @@ void serializeSingleRegexKeywordGroup() {
@Test
void serializeSingleSearchGroup() {
- SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "author=harrer", true, true);
+ SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "author=harrer", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
List serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group));
assertEquals(Collections.singletonList("0 SearchGroup:myExplicitGroup;0;author=harrer;1;1;1;;;;"), serialization);
}
@Test
void serializeSingleSearchGroupWithRegex() {
- SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INCLUDING, "author=\"harrer\"", true, false);
+ SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INCLUDING, "author=\"harrer\"", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
List serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group));
assertEquals(Collections.singletonList("0 SearchGroup:myExplicitGroup;2;author=\"harrer\";1;0;1;;;;"), serialization);
}
diff --git a/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java
index 02e98ab4939..e3180d06c7d 100644
--- a/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java
+++ b/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java
@@ -50,14 +50,7 @@ void searchByQueryFindsEntry() throws Exception {
.withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef")
.withField(StandardField.URL, "https://doi.org/10.1145/3129790.3129810")
.withField(StandardField.PAGETOTAL, "7")
- .withField(StandardField.PAGES, "152–158"),
- new BibEntry(StandardEntryType.Book)
- .withField(StandardField.YEAR, "2016")
- .withField(StandardField.TITLE, "Proceedings of the 2016 24th ACM SIGSOFT International Symposium on Foundations of Software Engineering")
- .withField(StandardField.LOCATION, "Seattle, WA, USA")
- .withField(StandardField.ISBN, "9781450342186")
- .withField(StandardField.PUBLISHER, "Association for Computing Machinery")
- .withField(StandardField.ADDRESS, "New York, NY, USA")
+ .withField(StandardField.PAGES, "152–158")
);
List fetchedEntries = fetcher.performSearch("The relationship of code churn and architectural violations in the open source software JabRef");
diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java
index 8fe530bcfce..b5ead872a6f 100644
--- a/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java
+++ b/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java
@@ -48,7 +48,7 @@ public void setUp() {
abram2017.setField(StandardField.AUTHOR, "Ittai Abraham and Dahlia Malkhi and Kartik Nayak and Ling Ren and Alexander Spiegelman");
abram2017.setField(StandardField.DATE, "2017-11-18");
abram2017.setField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Report 2017/1118");
- abram2017.setField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2017/1118}");
+ abram2017.setField(StandardField.NOTE, "\\url{https://ia.cr/2017/1118}");
abram2017.setField(StandardField.TITLE, "Solida: A Blockchain Protocol Based on Reconfigurable Byzantine Consensus");
abram2017.setField(StandardField.URL, "https://eprint.iacr.org/2017/1118/20171124:064527");
abram2017.setField(StandardField.VERSION, "20171124:064527");
@@ -61,7 +61,7 @@ public void setUp() {
beierle2016.setField(StandardField.AUTHOR, "Christof Beierle and Thorsten Kranz and Gregor Leander");
beierle2016.setField(StandardField.DATE, "2017-02-17");
beierle2016.setField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Report 2016/119");
- beierle2016.setField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2016/119}");
+ beierle2016.setField(StandardField.NOTE, "\\url{https://ia.cr/2016/119}");
beierle2016.setField(StandardField.TITLE, "Lightweight Multiplication in GF(2^n) with Applications to MDS Matrices");
beierle2016.setField(StandardField.URL, "https://eprint.iacr.org/2016/119/20170217:150415");
beierle2016.setField(StandardField.VERSION, "20170217:150415");
@@ -74,7 +74,7 @@ public void setUp() {
delgado2017.setField(StandardField.AUTHOR, "Sergi Delgado-Segura and Cristina Pérez-Solà and Guillermo Navarro-Arribas and Jordi Herrera-Joancomartí");
delgado2017.setField(StandardField.DATE, "2018-01-19");
delgado2017.setField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Report 2017/1095");
- delgado2017.setField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2017/1095}");
+ delgado2017.setField(StandardField.NOTE, "\\url{https://ia.cr/2017/1095}");
delgado2017.setField(StandardField.TITLE, "Analysis of the Bitcoin UTXO set");
delgado2017.setField(StandardField.URL, "https://eprint.iacr.org/2017/1095/20180119:113352");
delgado2017.setField(StandardField.VERSION, "20180119:113352");
diff --git a/src/test/java/org/jabref/logic/importer/fetcher/ZbMATHTest.java b/src/test/java/org/jabref/logic/importer/fetcher/ZbMATHTest.java
index 5d281fa7213..a78b9b0227c 100644
--- a/src/test/java/org/jabref/logic/importer/fetcher/ZbMATHTest.java
+++ b/src/test/java/org/jabref/logic/importer/fetcher/ZbMATHTest.java
@@ -35,7 +35,8 @@ void setUp() throws Exception {
donaldsonEntry.setCitationKey("zbMATH03800580");
donaldsonEntry.setField(StandardField.AUTHOR, "S. K. {Donaldson}");
donaldsonEntry.setField(StandardField.JOURNAL, "Journal of Differential Geometry");
- donaldsonEntry.setField(StandardField.ISSN, "0022-040X; 1945-743X/e");
+ donaldsonEntry.setField(StandardField.DOI, "10.4310/jdg/1214437665");
+ donaldsonEntry.setField(StandardField.ISSN, "0022-040X");
donaldsonEntry.setField(StandardField.LANGUAGE, "English");
donaldsonEntry.setField(StandardField.KEYWORDS, "57N13 57R10 53C05 58J99 57R65");
donaldsonEntry.setField(StandardField.PAGES, "279--315");
diff --git a/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java b/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
index 245461167c9..66bb5759249 100644
--- a/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
+++ b/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
@@ -72,12 +72,12 @@ void testParseEntries() throws IOException, ParseException {
for (BibEntry bibEntry : bibEntries) {
bibEntry.clearField(StandardField.ABSTRACT);
}
- assertEquals(searchEntryList, bibEntries);
+ assertEquals(searchEntryList.get(0), bibEntries.get(0));
}
@Test
void testParseDoiSearchPage() throws ParseException, IOException {
- List testDoiList = List.of("10.1145/3129790.3129810", "10.1145/2950290");
+ List testDoiList = List.of("10.1145/3129790.3129810");
CookieHandler.setDefault(new CookieManager());
List doiList = parser.parseDoiSearchPage(new URLDownload(searchUrl).asInputStream());
assertEquals(testDoiList, doiList);
diff --git a/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java b/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java
index 11c74196d5c..4ccf9a150b6 100644
--- a/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java
+++ b/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java
@@ -136,6 +136,18 @@ private static Stream stringsToParseTestData() throws Exception {
Arguments.of(
Collections.singletonList(new LinkedFile("desc", Path.of("file.pdf"), "PDF")),
"desc:file.pdf:PDF:asdf"
+ ),
+
+ // url
+ Arguments.of(
+ Collections.singletonList(new LinkedFile(new URL("https://books.google.de/"), "")),
+ "https://books.google.de/"
+ ),
+
+ // url as file
+ Arguments.of(
+ Collections.singletonList(new LinkedFile("", new URL("http://ceur-ws.org/Vol-438"), "URL")),
+ ":http\\://ceur-ws.org/Vol-438:URL"
)
);
}
diff --git a/src/test/java/org/jabref/logic/pdf/search/indexing/DocumentReaderTest.java b/src/test/java/org/jabref/logic/pdf/search/indexing/DocumentReaderTest.java
new file mode 100644
index 00000000000..d8da1977f29
--- /dev/null
+++ b/src/test/java/org/jabref/logic/pdf/search/indexing/DocumentReaderTest.java
@@ -0,0 +1,50 @@
+package org.jabref.logic.pdf.search.indexing;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import org.jabref.model.database.BibDatabaseContext;
+import org.jabref.model.entry.BibEntry;
+import org.jabref.model.entry.LinkedFile;
+import org.jabref.preferences.FilePreferences;
+
+import org.apache.lucene.document.Document;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class DocumentReaderTest {
+
+ private BibDatabaseContext databaseContext;
+ private FilePreferences filePreferences;
+
+ @BeforeEach
+ public void setup() {
+ this.databaseContext = mock(BibDatabaseContext.class);
+ when(databaseContext.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs")));
+ this.filePreferences = mock(FilePreferences.class);
+ when(filePreferences.getUser()).thenReturn("test");
+ when(filePreferences.getFileDirectory()).thenReturn(Optional.empty());
+ when(filePreferences.shouldStoreFilesRelativeToBib()).thenReturn(true);
+ }
+
+ @Test
+ public void unknownFileTestShouldReturnEmptyList() throws IOException {
+ // given
+ BibEntry entry = new BibEntry();
+ entry.setFiles(Collections.singletonList(new LinkedFile("Wrong path", "NOT_PRESENT.pdf", "Type")));
+
+ // when
+ final List emptyDocumentList = new DocumentReader(entry, filePreferences).readLinkedPdfs(databaseContext);
+
+ // then
+ assertEquals(Collections.emptyList(), emptyDocumentList);
+ }
+}
diff --git a/src/test/java/org/jabref/logic/pdf/search/indexing/PdfIndexerTest.java b/src/test/java/org/jabref/logic/pdf/search/indexing/PdfIndexerTest.java
new file mode 100644
index 00000000000..9dc45525ac8
--- /dev/null
+++ b/src/test/java/org/jabref/logic/pdf/search/indexing/PdfIndexerTest.java
@@ -0,0 +1,147 @@
+package org.jabref.logic.pdf.search.indexing;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Optional;
+
+import org.jabref.logic.util.StandardFileType;
+import org.jabref.model.database.BibDatabase;
+import org.jabref.model.database.BibDatabaseContext;
+import org.jabref.model.entry.BibEntry;
+import org.jabref.model.entry.LinkedFile;
+import org.jabref.model.entry.types.StandardEntryType;
+import org.jabref.preferences.FilePreferences;
+
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.store.NIOFSDirectory;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mockito;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class PdfIndexerTest {
+
+ private PdfIndexer indexer;
+ private BibDatabase database;
+ private BibDatabaseContext context = mock(BibDatabaseContext.class);
+
+ @BeforeEach
+ public void setUp(@TempDir Path indexDir) throws IOException {
+ FilePreferences filePreferences = mock(FilePreferences.class);
+ this.database = new BibDatabase();
+
+ this.context = mock(BibDatabaseContext.class);
+ when(context.getDatabasePath()).thenReturn(Optional.of(Path.of("src/test/resources/pdfs/")));
+ when(context.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs")));
+ when(context.getFulltextIndexPath()).thenReturn(indexDir);
+ when(context.getDatabase()).thenReturn(database);
+ this.indexer = PdfIndexer.of(context, filePreferences);
+ }
+
+ @Test
+ public void exampleThesisIndex() throws IOException {
+ // given
+ BibEntry entry = new BibEntry(StandardEntryType.PhdThesis);
+ entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName())));
+ database.insertEntry(entry);
+
+ // when
+ indexer.createIndex(database, context);
+
+ // then
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(1, reader.numDocs());
+ }
+ }
+
+ @Test
+ public void exampleThesisIndexWithKey() throws IOException {
+ // given
+ BibEntry entry = new BibEntry(StandardEntryType.PhdThesis);
+ entry.setCitationKey("Example2017");
+ entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName())));
+ database.insertEntry(entry);
+
+ // when
+ indexer.createIndex(database, context);
+
+ // then
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(1, reader.numDocs());
+ }
+ }
+
+ @Test
+ public void metaDataIndex() throws IOException {
+ // given
+ BibEntry entry = new BibEntry(StandardEntryType.Article);
+ entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "metaData.pdf", StandardFileType.PDF.getName())));
+
+ database.insertEntry(entry);
+
+ // when
+ indexer.createIndex(database, context);
+
+ // then
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(1, reader.numDocs());
+ }
+ }
+
+ @Test
+ public void testFlushIndex() throws IOException {
+ // given
+ BibEntry entry = new BibEntry(StandardEntryType.PhdThesis);
+ entry.setCitationKey("Example2017");
+ entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName())));
+ database.insertEntry(entry);
+
+ indexer.createIndex(database, context);
+ // index actually exists
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(1, reader.numDocs());
+ }
+
+ // when
+ indexer.flushIndex();
+
+ // then
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(0, reader.numDocs());
+ }
+ }
+
+ @Test
+ public void exampleThesisIndexAppendMetaData() throws IOException {
+ // given
+ BibEntry exampleThesis = new BibEntry(StandardEntryType.PhdThesis);
+ exampleThesis.setCitationKey("ExampleThesis2017");
+ exampleThesis.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName())));
+ database.insertEntry(exampleThesis);
+ indexer.createIndex(database, context);
+
+ // index with first entry
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(1, reader.numDocs());
+ }
+
+ BibEntry metadata = new BibEntry(StandardEntryType.Article);
+ metadata.setCitationKey("MetaData2017");
+ metadata.setFiles(Collections.singletonList(new LinkedFile("Metadata file", "metaData.pdf", StandardFileType.PDF.getName())));
+
+ // when
+ indexer.addToIndex(metadata, null);
+
+ // then
+ try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) {
+ assertEquals(2, reader.numDocs());
+ }
+ }
+}
+
diff --git a/src/test/java/org/jabref/logic/pdf/search/retrieval/PdfSearcherTest.java b/src/test/java/org/jabref/logic/pdf/search/retrieval/PdfSearcherTest.java
new file mode 100644
index 00000000000..4be7e5fc2cd
--- /dev/null
+++ b/src/test/java/org/jabref/logic/pdf/search/retrieval/PdfSearcherTest.java
@@ -0,0 +1,106 @@
+package org.jabref.logic.pdf.search.retrieval;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+
+import org.jabref.logic.pdf.search.indexing.PdfIndexer;
+import org.jabref.logic.util.StandardFileType;
+import org.jabref.model.database.BibDatabase;
+import org.jabref.model.database.BibDatabaseContext;
+import org.jabref.model.entry.BibEntry;
+import org.jabref.model.entry.LinkedFile;
+import org.jabref.model.entry.types.StandardEntryType;
+import org.jabref.model.pdf.search.PdfSearchResults;
+import org.jabref.preferences.FilePreferences;
+
+import org.apache.lucene.queryparser.classic.ParseException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mockito;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class PdfSearcherTest {
+
+ private PdfSearcher search;
+
+ @BeforeEach
+ public void setUp(@TempDir Path indexDir) throws IOException {
+ FilePreferences filePreferences = mock(FilePreferences.class);
+ // given
+ BibDatabase database = new BibDatabase();
+ BibDatabaseContext context = mock(BibDatabaseContext.class);
+ when(context.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs")));
+ when(context.getFulltextIndexPath()).thenReturn(indexDir);
+ when(context.getDatabase()).thenReturn(database);
+ BibEntry examplePdf = new BibEntry(StandardEntryType.Article);
+ examplePdf.setFiles(Collections.singletonList(new LinkedFile("Example Entry", "example.pdf", StandardFileType.PDF.getName())));
+ database.insertEntry(examplePdf);
+
+ BibEntry metaDataEntry = new BibEntry(StandardEntryType.Article);
+ metaDataEntry.setFiles(Collections.singletonList(new LinkedFile("Metadata Entry", "metaData.pdf", StandardFileType.PDF.getName())));
+ metaDataEntry.setCitationKey("MetaData2017");
+ database.insertEntry(metaDataEntry);
+
+ BibEntry exampleThesis = new BibEntry(StandardEntryType.PhdThesis);
+ exampleThesis.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName())));
+ exampleThesis.setCitationKey("ExampleThesis");
+ database.insertEntry(exampleThesis);
+
+ PdfIndexer indexer = PdfIndexer.of(context, filePreferences);
+ search = PdfSearcher.of(context);
+
+ indexer.createIndex(database, context);
+ }
+
+ @Test
+ public void searchForTest() throws IOException, ParseException {
+ PdfSearchResults result = search.search("test", 10);
+ assertEquals(2, result.numSearchResults());
+ }
+
+ @Test
+ public void searchForUniversity() throws IOException, ParseException {
+ PdfSearchResults result = search.search("University", 10);
+ assertEquals(1, result.numSearchResults());
+ }
+
+ @Test
+ public void searchForStopWord() throws IOException, ParseException {
+ PdfSearchResults result = search.search("and", 10);
+ assertEquals(0, result.numSearchResults());
+ }
+
+ @Test
+ public void searchForSecond() throws IOException, ParseException {
+ PdfSearchResults result = search.search("second", 10);
+ assertEquals(2, result.numSearchResults());
+ }
+
+ @Test
+ public void searchForAnnotation() throws IOException, ParseException {
+ PdfSearchResults result = search.search("annotation", 10);
+ assertEquals(2, result.numSearchResults());
+ }
+
+ @Test
+ public void searchForEmptyString() throws IOException {
+ PdfSearchResults result = search.search("", 10);
+ assertEquals(0, result.numSearchResults());
+ }
+
+ @Test
+ public void searchWithNullString() throws IOException {
+ assertThrows(NullPointerException.class, () -> search.search(null, 10));
+ }
+
+ @Test
+ public void searchForZeroResults() throws IOException {
+ assertThrows(IllegalArgumentException.class, () -> search.search("test", 0));
+ }
+}
diff --git a/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java b/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java
index 22b48a39759..f276f9ddfaf 100644
--- a/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java
+++ b/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java
@@ -1,12 +1,14 @@
package org.jabref.logic.search;
import java.util.Collections;
+import java.util.EnumSet;
import java.util.List;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
+import org.jabref.model.search.rules.SearchRules;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -15,7 +17,7 @@
public class DatabaseSearcherTest {
- public static final SearchQuery INVALID_SEARCH_QUERY = new SearchQuery("\\asd123{}asdf", true, true);
+ public static final SearchQuery INVALID_SEARCH_QUERY = new SearchQuery("\\asd123{}asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
private BibDatabase database;
@@ -26,7 +28,7 @@ public void setUp() {
@Test
public void testNoMatchesFromEmptyDatabase() {
- List matches = new DatabaseSearcher(new SearchQuery("whatever", true, true), database).getMatches();
+ List matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches();
assertEquals(Collections.emptyList(), matches);
}
@@ -39,7 +41,7 @@ public void testNoMatchesFromEmptyDatabaseWithInvalidSearchExpression() {
@Test
public void testGetDatabaseFromMatchesDatabaseWithEmptyEntries() {
database.insertEntry(new BibEntry());
- List matches = new DatabaseSearcher(new SearchQuery("whatever", true, true), database).getMatches();
+ List matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches();
assertEquals(Collections.emptyList(), matches);
}
@@ -48,7 +50,7 @@ public void testNoMatchesFromDatabaseWithArticleTypeEntry() {
BibEntry entry = new BibEntry(StandardEntryType.Article);
entry.setField(StandardField.AUTHOR, "harrer");
database.insertEntry(entry);
- List matches = new DatabaseSearcher(new SearchQuery("whatever", true, true), database).getMatches();
+ List matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches();
assertEquals(Collections.emptyList(), matches);
}
@@ -57,13 +59,13 @@ public void testCorrectMatchFromDatabaseWithArticleTypeEntry() {
BibEntry entry = new BibEntry(StandardEntryType.Article);
entry.setField(StandardField.AUTHOR, "harrer");
database.insertEntry(entry);
- List matches = new DatabaseSearcher(new SearchQuery("harrer", true, true), database).getMatches();
+ List matches = new DatabaseSearcher(new SearchQuery("harrer", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches();
assertEquals(Collections.singletonList(entry), matches);
}
@Test
public void testNoMatchesFromEmptyDatabaseWithInvalidQuery() {
- SearchQuery query = new SearchQuery("asdf[", true, true);
+ SearchQuery query = new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database);
@@ -76,7 +78,7 @@ public void testCorrectMatchFromDatabaseWithIncollectionTypeEntry() {
entry.setField(StandardField.AUTHOR, "tonho");
database.insertEntry(entry);
- SearchQuery query = new SearchQuery("tonho", true, true);
+ SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
List matches = new DatabaseSearcher(query, database).getMatches();
assertEquals(Collections.singletonList(entry), matches);
@@ -91,7 +93,7 @@ public void testNoMatchesFromDatabaseWithTwoEntries() {
entry.setField(StandardField.AUTHOR, "tonho");
database.insertEntry(entry);
- SearchQuery query = new SearchQuery("tonho", true, true);
+ SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database);
assertEquals(Collections.singletonList(entry), databaseSearcher.getMatches());
@@ -103,7 +105,7 @@ public void testNoMatchesFromDabaseWithIncollectionTypeEntry() {
entry.setField(StandardField.AUTHOR, "tonho");
database.insertEntry(entry);
- SearchQuery query = new SearchQuery("asdf", true, true);
+ SearchQuery query = new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database);
assertEquals(Collections.emptyList(), databaseSearcher.getMatches());
@@ -114,7 +116,7 @@ public void testNoMatchFromDatabaseWithEmptyEntry() {
BibEntry entry = new BibEntry();
database.insertEntry(entry);
- SearchQuery query = new SearchQuery("tonho", true, true);
+ SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database);
assertEquals(Collections.emptyList(), databaseSearcher.getMatches());
diff --git a/src/test/java/org/jabref/logic/search/SearchQueryTest.java b/src/test/java/org/jabref/logic/search/SearchQueryTest.java
index 2be23fd98f4..4bf01fadb73 100644
--- a/src/test/java/org/jabref/logic/search/SearchQueryTest.java
+++ b/src/test/java/org/jabref/logic/search/SearchQueryTest.java
@@ -1,11 +1,14 @@
package org.jabref.logic.search;
+import java.util.EnumSet;
import java.util.Optional;
import java.util.regex.Pattern;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
+import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.junit.jupiter.api.Test;
@@ -17,29 +20,29 @@ public class SearchQueryTest {
@Test
public void testToString() {
- assertEquals("\"asdf\" (case sensitive, regular expression)", new SearchQuery("asdf", true, true).toString());
- assertEquals("\"asdf\" (case insensitive, plain text)", new SearchQuery("asdf", false, false).toString());
+ assertEquals("\"asdf\" (case sensitive, regular expression)", new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).toString());
+ assertEquals("\"asdf\" (case insensitive, plain text)", new SearchQuery("asdf", EnumSet.noneOf(SearchFlags.class)).toString());
}
@Test
public void testIsContainsBasedSearch() {
- assertTrue(new SearchQuery("asdf", true, false).isContainsBasedSearch());
- assertTrue(new SearchQuery("asdf", true, true).isContainsBasedSearch());
- assertFalse(new SearchQuery("author=asdf", true, false).isContainsBasedSearch());
+ assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isContainsBasedSearch());
+ assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isContainsBasedSearch());
+ assertFalse(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isContainsBasedSearch());
}
@Test
public void testIsGrammarBasedSearch() {
- assertFalse(new SearchQuery("asdf", true, false).isGrammarBasedSearch());
- assertFalse(new SearchQuery("asdf", true, true).isGrammarBasedSearch());
- assertTrue(new SearchQuery("author=asdf", true, false).isGrammarBasedSearch());
+ assertFalse(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isGrammarBasedSearch());
+ assertFalse(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isGrammarBasedSearch());
+ assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isGrammarBasedSearch());
}
@Test
public void testGrammarSearch() {
BibEntry entry = new BibEntry();
entry.addKeyword("one two", ',');
- SearchQuery searchQuery = new SearchQuery("keywords=\"one two\"", false, false);
+ SearchQuery searchQuery = new SearchQuery("keywords=\"one two\"", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(entry));
}
@@ -47,7 +50,7 @@ public void testGrammarSearch() {
public void testGrammarSearchFullEntryLastCharMissing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "systematic revie");
- SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false);
+ SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", EnumSet.noneOf(SearchFlags.class));
assertFalse(searchQuery.isMatch(entry));
}
@@ -55,7 +58,7 @@ public void testGrammarSearchFullEntryLastCharMissing() {
public void testGrammarSearchFullEntry() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "systematic review");
- SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", false, false);
+ SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(entry));
}
@@ -64,7 +67,7 @@ public void testSearchingForOpenBraketInBooktitle() {
BibEntry e = new BibEntry(StandardEntryType.InProceedings);
e.setField(StandardField.BOOKTITLE, "Super Conference (SC)");
- SearchQuery searchQuery = new SearchQuery("booktitle=\"(\"", false, false);
+ SearchQuery searchQuery = new SearchQuery("booktitle=\"(\"", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(e));
}
@@ -73,7 +76,7 @@ public void testSearchMatchesSingleKeywordNotPart() {
BibEntry e = new BibEntry(StandardEntryType.InProceedings);
e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");
- SearchQuery searchQuery = new SearchQuery("anykeyword==apple", false, false);
+ SearchQuery searchQuery = new SearchQuery("anykeyword==apple", EnumSet.noneOf(SearchFlags.class));
assertFalse(searchQuery.isMatch(e));
}
@@ -82,7 +85,7 @@ public void testSearchMatchesSingleKeyword() {
BibEntry e = new BibEntry(StandardEntryType.InProceedings);
e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");
- SearchQuery searchQuery = new SearchQuery("anykeyword==pineapple", false, false);
+ SearchQuery searchQuery = new SearchQuery("anykeyword==pineapple", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(e));
}
@@ -92,7 +95,7 @@ public void testSearchAllFields() {
e.setField(StandardField.TITLE, "Fruity features");
e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");
- SearchQuery searchQuery = new SearchQuery("anyfield==\"fruity features\"", false, false);
+ SearchQuery searchQuery = new SearchQuery("anyfield==\"fruity features\"", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(e));
}
@@ -102,7 +105,7 @@ public void testSearchAllFieldsNotForSpecificField() {
e.setField(StandardField.TITLE, "Fruity features");
e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");
- SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords!=banana", false, false);
+ SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords!=banana", EnumSet.noneOf(SearchFlags.class));
assertFalse(searchQuery.isMatch(e));
}
@@ -112,7 +115,7 @@ public void testSearchAllFieldsAndSpecificField() {
e.setField(StandardField.TITLE, "Fruity features");
e.setField(StandardField.KEYWORDS, "banana, pineapple, orange");
- SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords=apple", false, false);
+ SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords=apple", EnumSet.noneOf(SearchFlags.class));
assertTrue(searchQuery.isMatch(e));
}
@@ -122,59 +125,59 @@ public void testIsMatch() {
entry.setType(StandardEntryType.Article);
entry.setField(StandardField.AUTHOR, "asdf");
- assertFalse(new SearchQuery("BiblatexEntryType", true, true).isMatch(entry));
- assertTrue(new SearchQuery("asdf", true, true).isMatch(entry));
- assertTrue(new SearchQuery("author=asdf", true, true).isMatch(entry));
+ assertFalse(new SearchQuery("BiblatexEntryType", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry));
+ assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry));
+ assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry));
}
@Test
public void testIsValidQueryNotAsRegEx() {
- assertTrue(new SearchQuery("asdf", true, false).isValid());
+ assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid());
}
@Test
public void testIsValidQueryContainsBracketNotAsRegEx() {
- assertTrue(new SearchQuery("asdf[", true, false).isValid());
+ assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid());
}
@Test
public void testIsNotValidQueryContainsBracketNotAsRegEx() {
- assertTrue(new SearchQuery("asdf[", true, true).isValid());
+ assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryAsRegEx() {
- assertTrue(new SearchQuery("asdf", true, true).isValid());
+ assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryWithNumbersAsRegEx() {
- assertTrue(new SearchQuery("123", true, true).isValid());
+ assertTrue(new SearchQuery("123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryContainsBracketAsRegEx() {
- assertTrue(new SearchQuery("asdf[", true, true).isValid());
+ assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryWithEqualSignAsRegEx() {
- assertTrue(new SearchQuery("author=asdf", true, true).isValid());
+ assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryWithNumbersAndEqualSignAsRegEx() {
- assertTrue(new SearchQuery("author=123", true, true).isValid());
+ assertTrue(new SearchQuery("author=123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid());
}
@Test
public void testIsValidQueryWithEqualSignNotAsRegEx() {
- assertTrue(new SearchQuery("author=asdf", true, false).isValid());
+ assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid());
}
@Test
public void testIsValidQueryWithNumbersAndEqualSignNotAsRegEx() {
- assertTrue(new SearchQuery("author=123", true, false).isValid());
+ assertTrue(new SearchQuery("author=123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid());
}
@Test
@@ -184,21 +187,21 @@ public void isMatchedForNormalAndFieldBasedSearchMixed() {
entry.setField(StandardField.AUTHOR, "asdf");
entry.setField(StandardField.ABSTRACT, "text");
- assertTrue(new SearchQuery("text AND author=asdf", true, true).isMatch(entry));
+ assertTrue(new SearchQuery("text AND author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry));
}
@Test
public void testSimpleTerm() {
String query = "progress";
- SearchQuery result = new SearchQuery(query, false, false);
+ SearchQuery result = new SearchQuery(query, EnumSet.noneOf(SearchFlags.class));
assertFalse(result.isGrammarBasedSearch());
}
@Test
public void testGetPattern() {
String query = "progress";
- SearchQuery result = new SearchQuery(query, false, false);
+ SearchQuery result = new SearchQuery(query, EnumSet.noneOf(SearchFlags.class));
Pattern pattern = Pattern.compile("(\\Qprogress\\E)");
// We can't directly compare the pattern objects
assertEquals(Optional.of(pattern.toString()), result.getPatternForWords().map(Pattern::toString));
@@ -207,7 +210,7 @@ public void testGetPattern() {
@Test
public void testGetRegexpPattern() {
String queryText = "[a-c]\\d* \\d*";
- SearchQuery regexQuery = new SearchQuery(queryText, false, true);
+ SearchQuery regexQuery = new SearchQuery(queryText, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
Pattern pattern = Pattern.compile("([a-c]\\d* \\d*)");
assertEquals(Optional.of(pattern.toString()), regexQuery.getPatternForWords().map(Pattern::toString));
}
@@ -215,7 +218,7 @@ public void testGetRegexpPattern() {
@Test
public void testGetRegexpJavascriptPattern() {
String queryText = "[a-c]\\d* \\d*";
- SearchQuery regexQuery = new SearchQuery(queryText, false, true);
+ SearchQuery regexQuery = new SearchQuery(queryText, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
Pattern pattern = Pattern.compile("([a-c]\\d* \\d*)");
assertEquals(Optional.of(pattern.toString()), regexQuery.getJavaScriptPatternForWords().map(Pattern::toString));
}
@@ -224,7 +227,7 @@ public void testGetRegexpJavascriptPattern() {
public void testEscapingInPattern() {
// first word contain all java special regex characters
String queryText = "<([{\\\\^-=$!|]})?*+.> word1 word2.";
- SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, false, false);
+ SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, EnumSet.noneOf(SearchFlags.class));
String pattern = "(\\Q<([{\\^-=$!|]})?*+.>\\E)|(\\Qword1\\E)|(\\Qword2.\\E)";
assertEquals(Optional.of(pattern), textQueryWithSpecialChars.getPatternForWords().map(Pattern::toString));
}
@@ -233,7 +236,7 @@ public void testEscapingInPattern() {
public void testEscapingInJavascriptPattern() {
// first word contain all javascript special regex characters that should be escaped individually in text based search
String queryText = "([{\\\\^$|]})?*+./ word1 word2.";
- SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, false, false);
+ SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, EnumSet.noneOf(SearchFlags.class));
String pattern = "(\\(\\[\\{\\\\\\^\\$\\|\\]\\}\\)\\?\\*\\+\\.\\/)|(word1)|(word2\\.)";
assertEquals(Optional.of(pattern), textQueryWithSpecialChars.getJavaScriptPatternForWords().map(Pattern::toString));
}
diff --git a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java
index cc834a61ca7..f52b9571c4e 100644
--- a/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java
+++ b/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java
@@ -33,8 +33,7 @@ void setUp() {
void getFileDirectoriesWithEmptyDbParent() {
BibDatabaseContext database = new BibDatabaseContext();
database.setDatabasePath(Path.of("biblio.bib"));
- assertEquals(Collections.singletonList(currentWorkingDir),
- database.getFileDirectories(fileDirPrefs));
+ assertEquals(Collections.singletonList(currentWorkingDir), database.getFileDirectories(fileDirPrefs));
}
@Test
@@ -43,8 +42,7 @@ void getFileDirectoriesWithRelativeDbParent() {
BibDatabaseContext database = new BibDatabaseContext();
database.setDatabasePath(file);
- assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())),
- database.getFileDirectories(fileDirPrefs));
+ assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs));
}
@Test
@@ -53,8 +51,7 @@ void getFileDirectoriesWithRelativeDottedDbParent() {
BibDatabaseContext database = new BibDatabaseContext();
database.setDatabasePath(file);
- assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())),
- database.getFileDirectories(fileDirPrefs));
+ assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs));
}
@Test
@@ -63,8 +60,7 @@ void getFileDirectoriesWithAbsoluteDbParent() {
BibDatabaseContext database = new BibDatabaseContext();
database.setDatabasePath(file);
- assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())),
- database.getFileDirectories(fileDirPrefs));
+ assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs));
}
@Test
@@ -116,4 +112,28 @@ void testTypeBasedOnInferredModeBiblatex() {
BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(db);
assertEquals(BibDatabaseMode.BIBLATEX, bibDatabaseContext.getMode());
}
+
+ @Test
+ void testGetFullTextIndexPathWhenPathIsNull() {
+ BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
+ bibDatabaseContext.setDatabasePath(null);
+
+ Path expectedPath = BibDatabaseContext.getFulltextIndexBasePath().resolve("unsaved");
+ Path actualPath = bibDatabaseContext.getFulltextIndexPath();
+
+ assertEquals(expectedPath, actualPath);
+ }
+
+ @Test
+ void testGetFullTextIndexPathWhenPathIsNotNull() {
+ Path existingPath = Path.of("some_path.bib");
+
+ BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
+ bibDatabaseContext.setDatabasePath(existingPath);
+
+ Path expectedPath = BibDatabaseContext.getFulltextIndexBasePath().resolve(existingPath.hashCode() + "");
+ Path actualPath = bibDatabaseContext.getFulltextIndexPath();
+
+ assertEquals(expectedPath, actualPath);
+ }
}
diff --git a/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java b/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java
index faa4d9d3d56..8878219ecda 100644
--- a/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java
+++ b/src/test/java/org/jabref/model/groups/GroupTreeNodeTest.java
@@ -3,6 +3,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
@@ -11,6 +12,8 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.search.matchers.AndMatcher;
import org.jabref.model.search.matchers.OrMatcher;
+import org.jabref.model.search.rules.SearchRules;
+import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -81,7 +84,7 @@ private static AbstractGroup getKeywordGroup(String name) {
}
private static AbstractGroup getSearchGroup(String name) {
- return new SearchGroup(name, GroupHierarchyType.INCLUDING, "searchExpression", true, false);
+ return new SearchGroup(name, GroupHierarchyType.INCLUDING, "searchExpression", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
}
private static AbstractGroup getExplict(String name) {
@@ -253,7 +256,7 @@ void setGroupExplicitToSearchDoesNotKeepPreviousAssignments() {
ExplicitGroup oldGroup = new ExplicitGroup("OldGroup", GroupHierarchyType.INDEPENDENT, ',');
oldGroup.add(entry);
GroupTreeNode node = GroupTreeNode.fromGroup(oldGroup);
- AbstractGroup newGroup = new SearchGroup("NewGroup", GroupHierarchyType.INDEPENDENT, "test", false, false);
+ AbstractGroup newGroup = new SearchGroup("NewGroup", GroupHierarchyType.INDEPENDENT, "test", EnumSet.noneOf(SearchFlags.class));
node.setGroup(newGroup, true, true, entries);
@@ -331,7 +334,7 @@ void onlySubgroupsContainAllEntries() {
@Test
void addEntriesToGroupWorksNotForGroupsNotSupportingExplicitAddingOfEntries() {
- GroupTreeNode searchGroup = new GroupTreeNode(new SearchGroup("Search A", GroupHierarchyType.INCLUDING, "searchExpression", true, false));
+ GroupTreeNode searchGroup = new GroupTreeNode(new SearchGroup("Search A", GroupHierarchyType.INCLUDING, "searchExpression", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)));
List fieldChanges = searchGroup.addEntriesToGroup(entries);
assertEquals(Collections.emptyList(), fieldChanges);
@@ -339,7 +342,7 @@ void addEntriesToGroupWorksNotForGroupsNotSupportingExplicitAddingOfEntries() {
@Test
void removeEntriesFromGroupWorksNotForGroupsNotSupportingExplicitRemovalOfEntries() {
- GroupTreeNode searchGroup = new GroupTreeNode(new SearchGroup("Search A", GroupHierarchyType.INCLUDING, "searchExpression", true, false));
+ GroupTreeNode searchGroup = new GroupTreeNode(new SearchGroup("Search A", GroupHierarchyType.INCLUDING, "searchExpression", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)));
List fieldChanges = searchGroup.removeEntriesFromGroup(entries);
assertEquals(Collections.emptyList(), fieldChanges);
diff --git a/src/test/java/org/jabref/model/groups/SearchGroupTest.java b/src/test/java/org/jabref/model/groups/SearchGroupTest.java
index bdc24d22b56..9b499ccf6ee 100644
--- a/src/test/java/org/jabref/model/groups/SearchGroupTest.java
+++ b/src/test/java/org/jabref/model/groups/SearchGroupTest.java
@@ -1,6 +1,9 @@
package org.jabref.model.groups;
+import java.util.EnumSet;
+
import org.jabref.model.entry.BibEntry;
+import org.jabref.model.search.rules.SearchRules;
import org.junit.jupiter.api.Test;
@@ -10,7 +13,7 @@ public class SearchGroupTest {
@Test
public void containsFindsWordWithRegularExpression() {
- SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=rev*", true, true);
+ SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=rev*", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
BibEntry entry = new BibEntry();
entry.addKeyword("review", ',');
diff --git a/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java b/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java
index ad7b0f645ad..337263b0dbc 100644
--- a/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java
+++ b/src/test/java/org/jabref/model/search/rules/ContainBasedSearchRuleTest.java
@@ -1,5 +1,7 @@
package org.jabref.model.search.rules;
+import java.util.EnumSet;
+
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
@@ -17,10 +19,10 @@ public class ContainBasedSearchRuleTest {
@Test
public void testBasicSearchParsing() {
BibEntry be = makeBibtexEntry();
- ContainBasedSearchRule bsCaseSensitive = new ContainBasedSearchRule(true);
- ContainBasedSearchRule bsCaseInsensitive = new ContainBasedSearchRule(false);
- RegexBasedSearchRule bsCaseSensitiveRegexp = new RegexBasedSearchRule(true);
- RegexBasedSearchRule bsCaseInsensitiveRegexp = new RegexBasedSearchRule(false);
+ ContainBasedSearchRule bsCaseSensitive = new ContainBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
+ ContainBasedSearchRule bsCaseInsensitive = new ContainBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
+ RegexBasedSearchRule bsCaseSensitiveRegexp = new RegexBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
+ RegexBasedSearchRule bsCaseInsensitiveRegexp = new RegexBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
String query = "marine 2001 shields";
diff --git a/src/test/java/org/jabref/model/search/rules/GrammarBasedSearchRuleTest.java b/src/test/java/org/jabref/model/search/rules/GrammarBasedSearchRuleTest.java
index 28f045b07fb..a32394078ab 100644
--- a/src/test/java/org/jabref/model/search/rules/GrammarBasedSearchRuleTest.java
+++ b/src/test/java/org/jabref/model/search/rules/GrammarBasedSearchRuleTest.java
@@ -1,5 +1,7 @@
package org.jabref.model.search.rules;
+import java.util.EnumSet;
+
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
@@ -16,7 +18,7 @@ public class GrammarBasedSearchRuleTest {
@Test
void applyRuleMatchesSingleTermWithRegex() {
- GrammarBasedSearchRule searchRule = new GrammarBasedSearchRule(true, true);
+ GrammarBasedSearchRule searchRule = new GrammarBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
String query = "M[a-z]+e";
assertTrue(searchRule.validateSearchStrings(query));
@@ -25,7 +27,7 @@ void applyRuleMatchesSingleTermWithRegex() {
@Test
void applyRuleDoesNotMatchSingleTermWithRegex() {
- GrammarBasedSearchRule searchRule = new GrammarBasedSearchRule(true, true);
+ GrammarBasedSearchRule searchRule = new GrammarBasedSearchRule(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
String query = "M[0-9]+e";
assertTrue(searchRule.validateSearchStrings(query));
diff --git a/src/test/resources/.gitignore b/src/test/resources/.gitignore
new file mode 100644
index 00000000000..aad78953eb0
--- /dev/null
+++ b/src/test/resources/.gitignore
@@ -0,0 +1 @@
+luceneTestIndex
diff --git a/src/test/resources/org/jabref/logic/importer/fileformat/MsBibImporterTestTranslator.xml b/src/test/resources/org/jabref/logic/importer/fileformat/MsBibImporterTestTranslator.xml
index 69b03d0a6dc..65d00f3f7f6 100644
--- a/src/test/resources/org/jabref/logic/importer/fileformat/MsBibImporterTestTranslator.xml
+++ b/src/test/resources/org/jabref/logic/importer/fileformat/MsBibImporterTestTranslator.xml
@@ -1,30 +1,31 @@
-
-
- Nac16
- Misc
- {BD524449-102F-470B-951F-CFE852BA526D}
- MeinArtikel
- 2016
- 17
- MeineZeitung
-
-
- Nachname, Vorname MIddleName; Nachname2, Vorname2 MiddleName21
-
-
-
-
- TestÜbersetzer
-
-
-
-
- 1
- 07
- 1
- 2018
- 07
- 1
-
+
+
+ Nac16
+ Misc
+ {BD524449-102F-470B-951F-CFE852BA526D}
+ MeinArtikel
+ 2016
+ 17
+ MeineZeitung
+
+
+ Nachname, Vorname MIddleName; Nachname2, Vorname2 MiddleName21
+
+
+
+
+ TestÜbersetzer
+
+
+
+
+ 1
+ 07
+ 1
+ 2018
+ 07
+ 1
+
diff --git a/src/test/resources/pdfs/example.pdf b/src/test/resources/pdfs/example.pdf
new file mode 100644
index 00000000000..19ae584cebd
Binary files /dev/null and b/src/test/resources/pdfs/example.pdf differ
diff --git a/src/test/resources/pdfs/metaData.pdf b/src/test/resources/pdfs/metaData.pdf
new file mode 100644
index 00000000000..b7ed86bdf9c
Binary files /dev/null and b/src/test/resources/pdfs/metaData.pdf differ