file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Test.javapp | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/Test.javapp | package com.test;
enable statements.exit;
from lombok import RequiredArgsConstructor, ToString, EqualsAndHashCode;
from java.util import List, ArrayList,
Set, HashSet,
Map, HashMap,
Collection, Collections,
Objects,
Date,
stream.Collectors;
public class Test {
public static:
void main(String[] args) {
println "Hello, world!";
exit;
}
}
interface Literature {
@NonNull String getTitle();
@NonNull Set<String> getAuthors();
@NonNull Date? getPublicationDate();
}
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
class Book implements Literature {
private final:
String title { get; }
Set<String> authors { get; }
Date? publicationDate { get; }
long ISBN { get; }
}
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
class Magazine implements Literature {
private final:
String title { get; }
Set<String> authors { get -> authors ?: (authors = articles.stream().map(Article::getAuthors).collect(Collector.of(HashSet<String>::new, (set, element) -> set.addAll(element), (set1, set2) -> { set1.addAll(set2); return set1; }, Collections::unmodifiableSet))); }
Date? publicationDate { get; }
String publisher { get; }
String issue { get; }
Set<Article> articles { get; }
}
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
class Article implements Literature {
private final:
String title { get; }
Set<String> authors { get; }
Date? publicationDate { get; }
}
enum Day {
MONDAY("Mon."),
TUESDAY("Tues."),
WEDNESDAY("Wed."),
THURSDAY("Thurs."),
FRIDAY("Fri."),
SATURDAY("Sat.", true),
SUNDAY("Sun.", true);
public final:
boolean isWeekend { get; }
String abbreviation;
String name { get; }
private:
Day(String abbr) {
this(abbr, false);
}
Day(String abbr, boolean weekend) {
this.isWeekend = weekend;
this.abbreviation = abbreviation;
this.name = name().charAt(0) + name().substring(1).toLowerCase();
}
public String toString() -> this.name;
public static:
boolean isMiddleDay(Day day) {
return switch(day) {
case TUESDAY, WEDNESDAY, THURSDAY -> true;
default -> false;
}
}
boolean isNotMiddleDay(Day day) {
switch(day) {
case MONDAY, FRIDAY, SATURDAY, SUNDAY -> return true;
default -> return false;
}
}
}
| 2,258 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Main.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/Main.java | package jpp;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import jpp.parser.JavaPlusPlusParser;
import jpp.parser.JavaPlusPlusParser.Feature;
import lombok.SneakyThrows;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.helper.MessageLocalization;
import net.sourceforge.argparse4j.helper.TextHelper;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentAction;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.ArgumentType;
import net.sourceforge.argparse4j.inf.Namespace;
public class Main {
public static void main(String[] args) {
var parser = ArgumentParsers.newFor("java++")
.fromFilePrefix("@")
.singleMetavar(true)
.build()
.description("Parse Java++ code from files");
var filesArg = parser.addArgument("files")
.type(Arguments.fileType().acceptSystemIn().verifyCanRead().verifyExists().verifyIsFile().or().acceptSystemIn().verifyExists().verifyIsDirectory())
.nargs("*")
.metavar("FILE")
.help("The files to parse");
var listFeaturesArg = parser.addArgument("--list-features")
.action(Arguments.storeTrue())
.help("Print a list of supported features and exit");
parser.addArgument("--enable", "-e")
.type(new FeatureType())
.action(new FeatureJoiningAction())
.metavar("FEATURES")
.setDefault(EnumSet.noneOf(Feature.class));
parser.addArgument("--disable", "-d")
.type(new FeatureType())
.action(new FeatureJoiningAction())
.metavar("FEATURES")
.setDefault(EnumSet.noneOf(Feature.class));
parser.addArgument("--out", "-o")
.type(Arguments.fileType().verifyIsDirectory().verifyNotExists().verifyCanCreate().or().verifyIsDirectory().verifyExists());
parser.addArgument("--recursive", "-r")
.action(Arguments.storeTrue())
.help("Look through subdirectories of folders as well");
Namespace ns;
try {
ns = parser.parseArgs(args);
validate_args:
if(ns.getBoolean("list_features")) {
String argName;
if(!ns.getList("files").isEmpty()) {
argName = "FILE";
} else if(!ns.<EnumSet<Feature>>get("enable").isEmpty()) {
argName = "enable";
} else if(!ns.<EnumSet<Feature>>get("disable").isEmpty()) {
argName = "disable";
} else if(ns.get("out") != null) {
argName = "out";
} else if(ns.getBoolean("recursive")) {
argName = "recursive";
} else {
break validate_args;
}
throw new ArgumentParserException(String.format(
TextHelper.LOCALE_ROOT,
MessageLocalization.localize(
parser.getConfig().getResourceBundle(),
"notAllowedWithArgumentError"),
argName), parser, listFeaturesArg);
} else if(ns.getList("files").isEmpty()) {
throw new ArgumentParserException(String.format(
TextHelper.LOCALE_ROOT,
MessageLocalization.localize(
parser.getConfig().getResourceBundle(),
"expectedNArgumentsError"),
1), parser, filesArg);
}
} catch(ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
return;
}
if(ns.getBoolean("list_features")) {
System.out.println("Features:");
for(var feature : Feature.VALUES.stream().sorted((feature1, feature2) -> feature1.id.compareTo(feature2.id)).collect(Collectors.toList())) {
System.out.println(feature);
}
System.exit(1);
}
File out = ns.get("out");
if(!out.exists()) {
out.mkdirs();
}
Path outPath = out.toPath();
EnumSet<Feature> enabledFeatures = ns.get("enable"),
disabledFeatures = ns.get("disable");
BiFunction<CharSequence, String, JavaPlusPlusParser> parserSupplier;
if(enabledFeatures.isEmpty() && disabledFeatures.isEmpty()) {
parserSupplier = JavaPlusPlusParser::new;
} else {
var features = Feature.enabledByDefault();
features.addAll(enabledFeatures);
features.removeAll(disabledFeatures);
parserSupplier = (code, filename) -> new JavaPlusPlusParser(code, filename, features);
}
parseFiles(ns.getList("files"), parserSupplier, ns.getBoolean("recursive"), outPath);
}
private static void parseFiles(List<File> files, BiFunction<CharSequence, String, JavaPlusPlusParser> parserCreator, boolean recursive, Path outDir) {
for(var file : files) {
if(file.isDirectory()) {
var newOutDir = outDir.resolve(file.getName());
for(var subfile : file.listFiles(f -> f.isDirectory() || f.getName().matches("(?i).*\\.j(pp|ava(pp)?)"))) {
parseFile(subfile, parserCreator, recursive, newOutDir);
}
} else {
parseFile(file, parserCreator, recursive, outDir);
}
}
}
@SneakyThrows
private static void parseFile(File file, BiFunction<CharSequence, String, JavaPlusPlusParser> parserCreator, boolean recursive, Path outDir) {
if(file.isDirectory()) {
if(recursive) {
var newOutDir = outDir.resolve(file.getName());
for(var subfile : file.listFiles(f -> f.isDirectory() || f.getName().matches("(?i).*\\.j(pp|ava(pp)?)"))) {
parseFile(subfile, parserCreator, recursive, newOutDir);
}
}
} else {
CharSequence text;
try(var scan = new Scanner(file)) {
scan.useDelimiter("\\A");
text = scan.next();
} catch(NoSuchElementException e) {
System.out.print("Skipped ");
System.out.println(file);
return;
}
var parser = parserCreator.apply(text, file.getName());
var unit = parser.parseCompilationUnit();
String name;
if(file.getName().matches("(?i).*\\.java") && outDir.toAbsolutePath().equals(file.getParentFile().toPath())) {
name = file.getName();
int i = name.lastIndexOf('.');
name = name.substring(0, i) + "_converted.java";
} else {
name = file.getName();
int i = name.lastIndexOf('.');
name = name.substring(0, i) + ".java";
}
Path out = outDir.resolve(name);
Files.writeString(out, unit.toCode(), StandardOpenOption.CREATE);
System.out.print("Converted ");
System.out.println(file);
}
}
}
class FeatureType implements ArgumentType<EnumSet<Feature>> {
@Override
public EnumSet<Feature> convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException {
if(value.matches("\\s*\\*\\s*")) {
return EnumSet.allOf(Feature.class);
}
var result = EnumSet.noneOf(Feature.class);
boolean found, loop = true;
do {
found = false;
int i = value.indexOf(',');
if(i == -1) {
i = value.length();
loop = false;
}
String sub = value.substring(0, i).strip();
if(loop) {
value = value.substring(i+1);
}
if(sub.endsWith(".*")) {
String prefix = sub.substring(0, sub.length()-1); // removes the '*'
for(var feature : Feature.VALUES) {
if(feature.id.startsWith(prefix)) {
found = true;
result.add(feature);
}
}
} else {
for(var feature : Feature.VALUES) {
if(feature.id.equals(sub)) {
result.add(feature);
found = true;
}
}
}
} while(found && loop);
if(found) {
return result;
}
String choices = TextHelper.concat(Feature.VALUES, 0,
",", "{", "}");
throw new ArgumentParserException(String.format(TextHelper.LOCALE_ROOT,
MessageLocalization.localize(
parser.getConfig().getResourceBundle(),
"couldNotConvertChooseFromError"),
value, choices), parser, arg);
}
}
class FeatureJoiningAction implements ArgumentAction {
@SuppressWarnings("unchecked")
@Override
public void run(ArgumentParser parser, Argument arg,
Map<String, Object> attrs, String flag, Object value)
throws ArgumentParserException {
if(attrs.containsKey(arg.getDest())) {
Object obj = attrs.get(arg.getDest());
if(obj instanceof EnumSet) {
var set = (EnumSet<Feature>)obj;
if(value instanceof Feature) {
set.add((Feature)value);
} else {
for(var elem : (Collection<?>)value) {
if(elem instanceof Feature) {
set.add((Feature)elem);
} else {
set.addAll((Collection<Feature>)elem);
}
}
}
return;
} else if(obj instanceof List) {
EnumSet<Feature> set;
if(value instanceof Feature) {
set = EnumSet.of((Feature)value);
} else {
set = EnumSet.copyOf((Collection<Feature>)value);
}
for(var elem : (List<?>)obj) {
if(elem instanceof Feature) {
set.add((Feature)elem);
} else {
set.addAll((Collection<Feature>)elem);
}
}
attrs.put(arg.getDest(), set);
return;
}
}
EnumSet<Feature> set;
if(value instanceof EnumSet) {
set = (EnumSet<Feature>)value;
} else {
set = EnumSet.of((Feature)value);
}
attrs.put(arg.getDest(), set);
}
@Override
public boolean consumeArgument() {
return true;
}
@Override
public void onAttach(Argument arg) {
}
}
| 9,912 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Names.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/parser/Names.java | package jpp.parser;
import java.util.HashMap;
import jtree.nodes.Name;
import lombok.experimental.UtilityClass;
@UtilityClass
public class Names {
private static final HashMap<String,Name> normalNameMap = new HashMap<>();
public static final Name // @formatter:off
of = Name("of"),
ofNullable = Name("ofNullable"),
ofEntries = Name("ofEntries"),
NonNull = Name("NonNull"),
out = Name("out"),
entry = Name("entry"),
format = Name("format"),
compile = Name("compile"),
print = Name("print"),
println = Name("println"),
printf = Name("printf"),
empty = Name("empty"),
orElseThrow = Name("orElseThrow"),
orElseGet = Name("orElseGet"),
orElse = Name("orElse"),
value = Name("value"),
requireNonNull = Name("requireNonNull"),
requireNonNullElse = Name("requireNonNullElse"),
requireNonNullElseGet = Name("requireNonNullElseGet"),
map = Name("map"),
deepEquals = Name("deepEquals"),
naturalOrder = Name("naturalOrder"),
compare = Name("compare"),
getKey = Name("getKey"),
getValue = Name("getValue"),
entrySet = Name("entrySet"),
exit = Name("exit");
// @formatter:on
public static Name Name(String str) {
return normalNameMap.computeIfAbsent(str, Name::new);
}
}
| 1,605 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
JavaPlusPlusParser.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/parser/JavaPlusPlusParser.java | package jpp.parser;
import static jpp.parser.JavaPlusPlusParser.Feature.*;
import static jpp.parser.Names.Name;
import static jpp.parser.QualNames.*;
import static jtree.parser.JavaTokenType.*;
import static jtree.util.Utils.emptyList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
import jpp.nodes.DefaultFormalParameter;
import jpp.nodes.EnableDisableStmt;
import jpp.nodes.EnableDisableStmt.FeatureId;
import jpp.nodes.JPPModifier;
import jpp.nodes.JPPModifier.Modifiers;
import jpp.util.NonVanillaModifierRemover;
import jtree.nodes.*;
import jtree.parser.JavaParser;
import jtree.parser.JavaTokenType;
import jtree.parser.JavaTokenType.Tag;
import jtree.parser.JavaTokenizer;
import jtree.parser.ModsAndAnnotations;
import jtree.parser.SyntaxError;
import jtree.parser.Token;
import jtree.parser.TokenPredicate;
import jtree.util.ContextStack;
import jtree.util.Either;
import lombok.Getter;
import lombok.NonNull;
public class JavaPlusPlusParser extends JavaParser {
public static enum Feature {
/** {@code converter.qualifiedNames} */
FULLY_QUALIFIED_NAMES ("converter.qualifiedNames", false),
/** {@code literals.collections} */
COLLECTION_LITERALS ("literals.collections", true),
/** {@code syntax.argumentAnnotations} */
ARGUMENT_ANNOTATIONS ("syntax.argumentAnnotations", true),
/** {@code syntax.optionalNewArguments} */
OPTIONAL_CONSTRUCTOR_ARGUMENTS ("syntax.optionalNewArguments", true),
/** {@code literals.regex} */
REGEX_LITERALS ("literals.regex", true),
/** {@code literals.rawStrings} */
RAW_STRING_LITERALS ("literals.rawStrings", true),
/** {@code literals.formatStrings} */
FORMAT_STRINGS ("literals.formatStrings", true),
/** {@code literals.textBlocks} */
TEXT_BLOCKS ("literals.textBlocks", true),
/** {@code syntax.trailingCommas} */
TRAILING_COMMAS ("syntax.trailingCommas", false),
/** {@code expressions.partialMethodReferences} */
PARTIAL_METHOD_REFERENCES ("expressions.partialMethodReferences", true),
/** {@code syntax.lastLambdaArgument} */
LAST_LAMBDA_ARGUMENT ("syntax.lastLambdaArgument", true),
/** {@code syntax.optionalStatementParenthesis} */
OPTIONAL_STATEMENT_PARENTHESIS ("syntax.optionalStatementParenthesis", false),
/** {@code statements.notCondition} */
IF_NOT ("statements.notCondition", true),
/** {@code statements.emptyFor} */
EMPTY_FOR ("statements.emptyFor", true),
/** {@code statements.simpleForEach} */
SIMPLER_FOR ("statements.simpleForEach", true),
/** {@code statements.emptySynchronized} */
EMPTY_SYNCHRONIZED ("statements.emptySynchronized", true),
/** {@code expressions.variableDeclarations} */
VARDECL_EXPRESSIONS ("expressions.variableDeclarations", true),
/** {@code statements.fromImport} */
FROM_IMPORTS ("statements.fromImport", true),
/** {@code statements.commaImports} */
COMMA_IMPORTS ("statements.commaImports", true),
/** {@code statements.unimport} */
UNIMPORTS ("statements.unimport", true),
/** {@code statements.defaultCatch} */
DEFAULT_CATCH ("statements.defaultCatch", true),
/** {@code statements.tryElse} */
TRY_ELSE ("statements.tryElse", true),
/** {@code syntax.implicitBlocks} */
IMPLICIT_BLOCKS ("syntax.implicitBlocks", false),
/** {@code statements.with} */
WITH_STATEMENT ("statements.with", true),
/** {@code syntax.implicitSemicolons} */
IMPLICIT_SEMICOLONS ("syntax.implicitSemicolons", true),
/** {@code statements.print} */
PRINT_STATEMENT ("statements.print", true),
/** {@code syntax.simpleClassBodies} */
EMPTY_TYPE_BODIES ("syntax.simpleClassBodies", true),
/** {@code syntax.simpleConstructorBodies} */
EMPTY_CONSTRUCTOR_BODIES ("syntax.simpleConstructorBodies", true),
/** {@code syntax.improvedExplicitConstructorCallArguments} */
IMPROVED_CONSTRUCTOR_CALL_ARGUMENTS ("syntax.improvedExplicitConstructorCallArguments", true),
/** {@code syntax.defaultArguments} */
DEFAULT_ARGUMENTS ("syntax.defaultArguments", true),
/** {@code statements.empty} */
EMPTY_STATEMENTS ("statements.empty", true),
/** {@code syntax.defaultModifiers} */
DEFAULT_MODIFIERS ("syntax.defaultModifiers", true),
/** {@code syntax.autoDefaultModifier} */
AUTO_DEFAULT_MODIFIER ("syntax.autoDefaultModifier", true),
/** {@code syntax.simpleMethodBodies} */
SIMPLE_METHOD_BODIES ("syntax.simpleMethodBodies", true),
/** {@code literals.optional} */
OPTIONAL_LITERALS ("literals.optional", true),
/** {@code syntax.betterArrowCaseBodies} */
BETTER_ARROW_CASE_BODIES ("syntax.betterArrowCaseBodies", true),
/** {@code syntax.altAnnotationDecl} */
ALTERNATE_ANNOTATION_DECL ("syntax.altAnnotationDecl", true),
/** {@code syntax.multiVarDecls} */
MULTIPLE_VAR_DECLARATIONS ("syntax.multiVarDecls", true),
/** {@code expressions.nullSafe} */
NULL_SAFE_EXPRESSIONS ("expressions.nullSafe", true),
/** {@code expressions.equality} */
EQUALITY_OPERATOR ("expressions.equality", false),
/** {@code expressions.deepEquals} */
DEEP_EQUALS_OPERATOR ("expressions.deepEquals", true),
/** {@code expressions.notInstanceof} */
NOT_INSTANCEOF ("expressions.notInstanceof", true),
/** {@code expressions.compareTo} */
COMPARE_TO_OPERATOR ("expressions.compareTo", true),
/** {@code statements.forEntries} */
FOR_ENTRIES ("statements.forEntries", true),
/** {@code syntax.forIn} */
FOR_IN ("syntax.forIn", false),
/** {@code syntax.optionalConstructorType} */
OPTIONAL_CONSTRUCTOR_TYPE ("syntax.optionalConstructorType", true),
/** {@code syntax.sizedArrayInitializer} */
SIZED_ARRAY_INITIALIZER ("syntax.sizedArrayInitializer", true),
/** {@code syntax.implicitParameterTypes} */
IMPLICIT_PARAMETER_TYPES ("syntax.implicitParameterTypes", true),
/** {@code literals.parameter} */
PARAMETER_LITERALS ("literals.parameter", true),
/** {@code statements.exit} */
EXIT_STATEMENT ("statements.exit", false),
/** {@code syntax.quickGettersAndSetters} */
GETTERS_AND_SETTERS ("syntax.quickGettersAndSetters", true),
/** {@code syntax.constructorFields} */
CONSTRUCTOR_FIELDS ("syntax.constructorFields", true),
/** {@code expressions.asCast} */
AS_CAST ("expressions.asCast", true),
/** {@code syntax.moreNumberLiterals} */
MORE_NUMBER_LITERALS ("literals.numbers", true),
;
public static final Set<Feature> VALUES = Collections.unmodifiableSet(EnumSet.allOf(Feature.class));
public final String id;
@Getter
private boolean enabledByDefault;
Feature(String id, boolean enabledByDefault) {
this.id = id;
this.enabledByDefault = enabledByDefault;
}
@Override
public String toString() {
return id;
}
public static EnumSet<Feature> enabledByDefault() {
var features = EnumSet.noneOf(Feature.class);
for(var feature : VALUES) {
if(feature.isEnabledByDefault()) {
features.add(feature);
}
}
return features;
}
}
protected static enum Scope {
NORMAL, CONDITION
}
protected final ContextStack<Scope> scope = new ContextStack<>(Scope.NORMAL);
protected static enum Context {
STATIC, DYNAMIC
}
protected final ContextStack<Context> context = new ContextStack<>(Context.STATIC);
protected EnumSet<Feature> enabledFeatures;
protected final Set<ImportDecl> imports = new HashSet<>();
public JavaPlusPlusParser(CharSequence text) {
super(text);
}
public JavaPlusPlusParser(CharSequence text, String filename) {
super(text, filename);
}
public JavaPlusPlusParser(CharSequence text, Collection<Feature> features) {
super(text);
enabledFeatures.clear();
enabledFeatures.addAll(features);
}
public JavaPlusPlusParser(CharSequence text, String filename, Collection<Feature> features) {
super(text, filename);
enabledFeatures.clear();
enabledFeatures.addAll(features);
}
@Override
protected JavaTokenizer<JavaTokenType> createTokenizer(CharSequence text, String filename) {
return new JavaPlusPlusTokenizer(text, filename, enabledFeatures = Feature.enabledByDefault());
}
public boolean enabled(Feature feature) {
return enabledFeatures.contains(feature);
}
public void enable(String feature) {
setEnabled(feature, true);
}
public void enable(@NonNull Feature feature) {
enabledFeatures.add(feature);
}
public void disable(String feature) {
setEnabled(feature, false);
}
public void disable(@NonNull Feature feature) {
enabledFeatures.remove(feature);
}
public void setEnabled(@NonNull Feature feature, boolean enabled) {
if(enabled) {
enabledFeatures.add(feature);
} else {
enabledFeatures.remove(feature);
}
}
public void setEnabled(String featureId, boolean enabled) {
if(featureId.equals("*")) {
if(enabled) {
enabledFeatures.addAll(Feature.VALUES);
} else {
enabledFeatures.clear();
}
} else if(featureId.endsWith(".*") && featureId.length() > 2) {
String prefix = featureId.substring(0, featureId.length()-1); // removes the *
boolean found = false;
for(var feature : Feature.VALUES) {
if(feature.id.startsWith(prefix)) {
found = true;
if(enabled) {
enabledFeatures.add(feature);
} else {
enabledFeatures.remove(feature);
}
}
}
if(!found) {
throw new IllegalArgumentException("No feature found matching '" + featureId + "'");
}
} else {
for(var feature : Feature.VALUES) {
if(feature.id.equals(featureId)) {
if(enabled) {
enabledFeatures.add(feature);
} else {
enabledFeatures.remove(feature);
}
return;
}
}
throw new IllegalArgumentException("No feature found matching '" + featureId + "'");
}
}
protected boolean imported(String type) {
return imported(QualifiedName(type));
}
protected boolean imported(QualifiedName type) {
for(var importdecl : imports) {
if(!importdecl.isStatic()) {
if(importdecl.isWildcard()) {
if(importdecl.getName().equals(type.subName(0, type.nameCount()-1))) {
return true;
}
} else {
if(importdecl.getName().equals(type)) {
return true;
}
}
}
}
return false;
}
protected boolean importedNameOtherThan(String name) {
return importedNameOtherThan(QualifiedName(name));
}
protected boolean importedNameOtherThan(QualifiedName name) {
for(var importdecl : imports) {
if(!importdecl.isStatic() && !importdecl.isWildcard() && importdecl.getName().endsWith(name.lastName())) {
return !importdecl.getName().equals(name);
}
}
return false;
}
@Override
protected void requireSemi() {
if(!wouldAccept(ENDMARKER)) {
require(SEMI);
}
}
@Override
@SuppressWarnings("unchecked")
public List<REPLEntry> parseJshellEntries() {
var entries = new ArrayList<REPLEntry>();
loop:
while(!wouldAccept(ENDMARKER)) {
if(wouldAccept(AT.or(KEYWORD_MODIFIER)) || wouldAcceptPseudoOp(test("non"), SUB, KEYWORD_MODIFIER.and(not(Tag.VISIBILITY_MODIFIER)))) {
var docComment = getDocComment();
var modsAndAnnos = new ModsAndAnnotations(emptyList(), parseAnnotations());
if(wouldAccept(PACKAGE, Tag.NAMED, DOT.or(SEMI).or(ENDMARKER))) {
entries.add(parsePackageDecl(docComment, modsAndAnnos.annos));
continue loop;
}
var modsAndAnnos2 = parseKeywordModsAndAnnotations();
modsAndAnnos2.annos.addAll(0, modsAndAnnos.annos);
modsAndAnnos = modsAndAnnos2;
entries.addAll((List<? extends REPLEntry>)parseClassMember(false, docComment, modsAndAnnos));
} else {
boolean fallthru = false;
switch(token.getType()) {
case AT, INTERFACE, CLASS, ENUM:
entries.add(parseTypeDecl(getDocComment(), new ModsAndAnnotations()));
break;
case ENABLE, DISABLE:
entries.add(parseEnableOrDisableStmt());
break;
case IMPORT:
entries.addAll(parseImportSection());
break;
case FROM:
if(enabled(FROM_IMPORTS) && wouldAccept(FROM, Tag.NAMED, enabled(UNIMPORTS)? IMPORT.or(UNIMPORT).or(DOT) : IMPORT.or(DOT))) {
entries.addAll(parseImportSection());
continue loop;
}
fallthru = true;
case UNIMPORT:
if(!fallthru && enabled(UNIMPORTS)) {
entries.addAll(parseImportSection());
continue loop;
}
fallthru = true;
case VOID:
if(!fallthru) {
var docComment = getDocComment();
nextToken();
entries.addAll((List<? extends REPLEntry>)parseMethod(false, new VoidType(), emptyList(), docComment, new ModsAndAnnotations()));
continue loop;
}
fallthru = true;
case PACKAGE:
if(!fallthru && wouldAccept(PACKAGE, Tag.NAMED, DOT.or(SEMI).or(ENDMARKER))) {
entries.add(parsePackageDecl(getDocComment(), emptyList()));
continue loop;
}
fallthru = true;
default: {
vardecl:
if(wouldAccept(Tag.NAMED.or(KEYWORD_MODIFIER).or(PRIMITIVE_TYPES).or(LT))) {
try(var state = tokens.enter()) {
Optional<String> docComment;
ModsAndAnnotations modsAndAnnos;
Type type;
try {
docComment = getDocComment();
modsAndAnnos = parseFinalAndAnnotations();
if(wouldAccept(LT)) {
var typeParams = parseTypeParameters();
if(wouldAccept(Tag.NAMED, LPAREN)) {
entries.addAll((List<? extends REPLEntry>)parseConstructor(typeParams, docComment, modsAndAnnos));
} else {
type = parseType();
entries.addAll((List<? extends REPLEntry>)parseMethod(false, type, typeParams, docComment, modsAndAnnos));
}
continue loop;
}
if(accept(VOID)) {
type = new VoidType();
} else {
if(wouldAccept(Tag.NAMED, LPAREN)) {
entries.addAll((List<? extends REPLEntry>)parseConstructor(emptyList(), docComment, modsAndAnnos));
continue loop;
}
type = parseType();
}
if(!wouldAccept(Tag.NAMED)) {
state.reset();
break vardecl;
}
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
if(modsAndAnnos.canBeMethodMods() && (type instanceof VoidType || wouldAccept(Tag.NAMED, LPAREN))) {
entries.addAll((List<? extends REPLEntry>)parseMethod(false, type, emptyList(), parseName(), docComment, modsAndAnnos));
} else if(modsAndAnnos.canBeFieldMods() || modsAndAnnos.canBeLocalVarMods()) {
entries.addAll((List<? extends REPLEntry>)parseFieldDecl(type, docComment, modsAndAnnos));
} else {
throw syntaxError("Invalid modifiers");
}
continue loop;
}
}
entries.add(parseBlockStatement());
}
}
}
}
var visitor = new NonVanillaModifierRemover();
for(var entry : entries) {
entry.accept(visitor, null, null);
}
return entries;
}
@Override
public CompilationUnit parseCompilationUnit() {
var unit = super.parseCompilationUnit();
var imports = unit.getImports();
for(var importdecl : this.imports) {
if(!imports.contains(importdecl)) {
imports.add(importdecl);
}
}
return unit;
}
@Override
public NormalCompilationUnit parseNormalCompilationUnit(Optional<PackageDecl> pckg, List<ImportDecl> imports,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
var unit = super.parseNormalCompilationUnit(pckg, imports, docComment, modsAndAnnos);
unit.accept(new NonVanillaModifierRemover(), null, null);
return unit;
}
@Override
public ArrayList<ImportDecl> parseImportSection() {
for(;;) {
if(accept(ENABLE)) {
parseFeatures(true);
} else if(accept(DISABLE)) {
parseFeatures(false);
} else {
break;
}
}
var imports = new ArrayList<ImportDecl>();
for(;;) {
if(wouldAccept(IMPORT)) {
var importdecl = parseImport();
imports.addAll(importdecl);
this.imports.addAll(importdecl);
} else if(enabled(FROM_IMPORTS) && wouldAccept(FROM)) {
var importdecl = parseFromImport(imports, this.imports);
imports.addAll(importdecl);
this.imports.addAll(importdecl);
} else if(enabled(UNIMPORTS) && wouldAccept(UNIMPORT)) {
parseUnimport(imports, this.imports);
} else {
break;
}
}
return imports;
}
public EnableDisableStmt parseEnableOrDisableStmt() {
boolean disable = accept(DISABLE);
if(!disable) {
require(ENABLE);
}
if(accept(STAR)) {
requireSemi();
if(disable) {
enabledFeatures.addAll(Feature.VALUES);
} else {
enabledFeatures.clear();
}
return new EnableDisableStmt(disable, emptyList());
} else {
var features = new ArrayList<FeatureId>(1);
var firstTokens = new ArrayList<Token<JavaTokenType>>(1);
firstTokens.add(this.token);
features.add(parseFeatureId());
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
firstTokens.add(this.token);
features.add(parseFeatureId());
}
requireSemi();
for(int i = 0; i < features.size(); i++) {
try {
setEnabled(features.get(i).toCode(), !disable);
} catch(IllegalArgumentException e) {
throw syntaxError(e.getMessage(), firstTokens.get(i));
}
}
return new EnableDisableStmt(disable, features);
}
}
protected void parseFeatures(boolean enable) {
if(accept(STAR)) {
requireSemi();
if(enable) {
enabledFeatures.addAll(Feature.VALUES);
} else {
enabledFeatures.clear();
}
} else {
var features = new ArrayList<Pair<Token<JavaTokenType>, String>>();
features.add(parseFeatureName());
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
features.add(parseFeatureName());
}
requireSemi();
for(var feature : features) {
try {
setEnabled(feature.getRight(), enable);
} catch(IllegalArgumentException e) {
throw syntaxError(e.getMessage(), feature.getLeft());
}
}
}
}
protected Pair<Token<JavaTokenType>, String> parseFeatureName() {
var firstToken = token;
var sb = new StringBuilder();
sb.append(parseIdent());
while(accept(DOT)) {
if(accept(STAR)) {
sb.append(".*");
break;
} else {
sb.append('.').append(parseIdent());
}
}
return Pair.of(firstToken, sb.toString());
}
public FeatureId parseFeatureId() {
var names = new ArrayList<Name>();
names.add(parseName());
boolean wildcard = false;
while(accept(DOT)) {
if(accept(STAR)) {
wildcard = true;
break;
} else {
names.add(parseName());
}
}
return new FeatureId(new QualifiedName(names), wildcard);
}
public void parseUnimport(List<ImportDecl> imports1, Set<ImportDecl> imports2) {
require(UNIMPORT);
var imports = parseImportRest(true);
if(!imports.isEmpty()) {
Predicate<ImportDecl> inImports = decl -> {
for(var decl2 : imports) {
if(decl.equals(decl2)) {
return true;
} else if(decl.isStatic() == decl2.isStatic() && decl2.isWildcard() && !decl.isWildcard() && decl.getName().subName(0, decl.getName().nameCount()-1).equals(decl2.getName())) {
return true;
}
}
return false;
};
imports1.removeIf(inImports);
imports2.removeIf(inImports);
}
}
@Override
public List<ImportDecl> parseImport() {
require(IMPORT);
return parseImportRest(false);
}
protected List<ImportDecl> parseImportRest(boolean unimport) {
boolean isStatic = accept(STATIC);
var imports = new ArrayList<ImportDecl>();
boolean wildcard = false;
var names = new ArrayList<Name>();
names.add(parseName());
while(accept(DOT)) {
if(accept(STAR)) {
wildcard = true;
break;
} else {
names.add(parseName());
}
}
imports.add(new ImportDecl(new QualifiedName(names), isStatic, wildcard));
if(enabled(COMMA_IMPORTS)) {
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
wildcard = false;
names.clear();
names.add(parseName());
while(accept(DOT)) {
if(accept(STAR)) {
wildcard = true;
break;
} else {
names.add(parseName());
}
}
imports.add(new ImportDecl(new QualifiedName(names), isStatic, wildcard));
}
}
requireSemi();
return imports;
}
public List<ImportDecl> parseFromImport() {
return parseFromImport(new ArrayList<>(), this.imports);
}
public List<ImportDecl> parseFromImport(List<ImportDecl> imports1, Set<ImportDecl> imports2) {
require(FROM);
var pckg = parseQualName();
boolean unimport;
if(accept(IMPORT)) {
unimport = false;
} else {
if(!enabled(UNIMPORTS) && wouldAccept(UNIMPORT)) {
throw syntaxError("unimport only allowed here if prefixed by 'java++'");
}
require(UNIMPORT);
unimport = true;
}
boolean isStatic = accept(STATIC);
var imports = new ArrayList<ImportDecl>();
imports.add(parseFromImportRest(pckg, isStatic));
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
imports.add(parseFromImportRest(pckg, isStatic));
}
requireSemi();
if(unimport) {
if(!imports.isEmpty()) {
Predicate<ImportDecl> inImports = decl -> {
for(var decl2 : imports) {
if(decl.equals(decl2)) {
return true;
} else if(decl.isStatic() == decl2.isStatic() && decl2.isWildcard() && !decl.isWildcard() && decl.getName().subName(0, decl.getName().nameCount()-1).equals(decl2.getName())) {
return true;
}
}
return false;
};
imports1.removeIf(inImports);
imports2.removeIf(inImports);
}
return emptyList();
} else {
return imports;
}
}
public ImportDecl parseFromImportRest(QualifiedName pckg, boolean isStatic) {
if(accept(STAR)) {
return new ImportDecl(pckg, isStatic, true);
} else {
boolean wildcard = false;
var names = new ArrayList<Name>();
names.add(parseName());
while(accept(DOT)) {
if(accept(STAR)) {
wildcard = true;
break;
} else {
names.add(parseName());
}
}
return new ImportDecl(pckg.append(names), isStatic, wildcard);
}
}
protected Pair<Token<JavaTokenType>, String> parseFromJavaPlusPlusImportRest() {
var firstToken = token;
if(accept(STAR)) {
return Pair.of(firstToken, "*");
} else {
var sb = new StringBuilder();
sb.append(parseName());
while(accept(DOT)) {
sb.append('.');
if(accept(STAR)) {
sb.append('*');
break;
} else {
sb.append(parseName());
}
}
return Pair.of(firstToken, sb.toString());
}
}
@Override
public TypeDecl parseTypeDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(enabled(ALTERNATE_ANNOTATION_DECL) && wouldAccept(ANNOTATION, Tag.NAMED, LBRACE.or(LPAREN))) {
return parseAltAnnotationDecl(docComment, modsAndAnnos);
} else {
return super.parseTypeDecl(docComment, modsAndAnnos);
}
}
public AnnotationDecl parseAltAnnotationDecl() {
var docComment = getDocComment();
var modsAndAnnos = parseClassModsAndAnnotations();
return parseAltAnnotationDecl(docComment, modsAndAnnos);
}
public AnnotationDecl parseAltAnnotationDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeClassMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
require(ANNOTATION);
var name = parseTypeName();
var members = new ArrayList<Member>();
if(accept(LPAREN)) {
if(!accept(RPAREN)) {
try(var $ = typeNames.enter(name)) {
var docComment1 = getDocComment();
var modsAndAnnos1 = parseAnnotationPropertyModsAndAnnotations();
var type = parseType();
if(accept(EQ)) {
Optional<? extends AnnotationValue> defaultValue = Optional.of(parseAnnotationValue());
members.add(new AnnotationProperty(Names.value, type, defaultValue, modsAndAnnos1.mods, modsAndAnnos1.annos, docComment1));
} else if(wouldAccept(RPAREN)) {
members.add(new AnnotationProperty(Names.value, type, Optional.empty(), modsAndAnnos1.mods, modsAndAnnos1.annos, docComment1));
} else {
var name1 = parseName();
Optional<? extends AnnotationValue> defaultValue;
if(accept(EQ)) {
defaultValue = Optional.of(parseAnnotationValue());
} else {
defaultValue = Optional.empty();
}
members.add(new AnnotationProperty(name1, type, defaultValue, modsAndAnnos1.mods, modsAndAnnos1.annos, docComment1));
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
members.add(parseAltAnnotationProperty());
}
}
}
require(RPAREN);
}
}
if(!accept(SEMI)) {
try(var $ = typeNames.enter(name)) {
members.addAll(parseClassBody(this::parseAltAnnotationMember));
}
}
return new AnnotationDecl(name, members, modifiers, annotations, docComment);
}
public List<Member> parseAltAnnotationMember() {
var docComment = getDocComment();
var modsAndAnnos = parseKeywordModsAndAnnotations();
try(var $ = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return parseAltAnnotationMember(docComment, modsAndAnnos);
}
}
public List<Member> parseAltAnnotationMember(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(wouldAccept(CLASS.or(INTERFACE).or(ENUM)) || wouldAccept(AT, INTERFACE)) {
return List.of(parseTypeDecl(docComment, modsAndAnnos));
} else /*if(modsAndAnnos.hasModifier("static"))*/ {
return parseInterfaceMember(false, docComment, modsAndAnnos);
}
}
public AnnotationProperty parseAltAnnotationProperty() {
var docComment = getDocComment();
return parseAltAnnotationProperty(docComment, parseAnnotationPropertyModsAndAnnotations());
}
public AnnotationProperty parseAltAnnotationProperty(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeMethodMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var type = parseType();
var name = parseName();
Optional<? extends AnnotationValue> defaultValue;
if(accept(EQ)) {
defaultValue = Optional.of(parseAnnotationValue());
} else {
defaultValue = Optional.empty();
}
return new AnnotationProperty(name, type, defaultValue, modifiers, annotations, docComment);
}
@Override
public List<Member> parseAnnotationMember() {
var docComment = getDocComment();
var modsAndAnnos = parseKeywordModsAndAnnotations();
try(var $ = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return parseAnnotationMember(docComment, modsAndAnnos);
}
}
@Override
public AnnotationProperty parseAnnotationProperty() {
var docComment = getDocComment();
var modsAndAnnos = parseKeywordModsAndAnnotations();
try(var $ = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return parseAnnotationProperty(docComment, modsAndAnnos);
}
}
@Override
public List<Member> parseClassMember(boolean inInterface) {
if(wouldAccept(STATIC, LBRACE)) {
nextToken();
Block body;
try(var $1 = context.enter(Context.STATIC); var $2 = preStmts.enter()) {
body = parseBlock();
return applyMemberPreStmts(List.of(new ClassInitializer(true, body)));
}
} else if(wouldAccept(LBRACE)) {
Block body;
try(var $1 = context.enter(Context.DYNAMIC); var $2 = preStmts.enter()) {
body = parseBlock();
return applyMemberPreStmts(List.of(new ClassInitializer(false, body)));
}
} else {
var docComment = getDocComment();
return parseClassMember(inInterface, docComment, parseKeywordModsAndAnnotations());
}
}
protected List<Member> applyMemberPreStmts(List<Member> members) {
if(preStmts.isWithinContext() && !preStmts.isEmpty()) {
var newmembers = new ArrayList<>(members);
var stmts = preStmts.get();
boolean isStatic = context.current() == Context.STATIC;
for(int i = stmts.size()-1; i >= 0; i--) {
var stmt = stmts.get(i);
if(stmt instanceof VariableDecl) {
var varDecl = (VariableDecl)stmt;
if(isStatic) {
if(!varDecl.hasModifier("static")) {
varDecl.getModifiers().add(createModifier("static"));
}
}
if(!varDecl.hasVisibilityModifier()) {
varDecl.getModifiers().add(createModifier("private"));
}
} else {
if(i < stmts.size()-1) {
var last = stmts.get(i+1);
if(last instanceof Block) {
if(stmt instanceof Block) {
((Block)last).getStatements().addAll(0, ((Block)stmt).getStatements());
} else {
((Block)last).getStatements().add(0, stmt);
}
stmts.remove(i);
continue;
}
}
if(!(stmt instanceof Block)) {
stmts.set(i, new Block(stmt));
}
}
}
for(int i = stmts.size()-1; i >= 0; i--) {
var stmt = stmts.get(i);
if(stmt instanceof Block) {
newmembers.add(0, new ClassInitializer(isStatic, (Block)stmt));
} else {
newmembers.add(0, (VariableDecl)stmt);
}
}
return newmembers;
} else {
return members;
}
}
@Override
public List<Member> parseClassMember(boolean inInterface, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(!inInterface && modsAndAnnos.canBeConstructorMods() && wouldAccept(Tag.NAMED, LPAREN)) {
try(var $1 = context.enter(Context.DYNAMIC); var $2 = preStmts.enter()) {
return applyMemberPreStmts(parseConstructor(docComment, modsAndAnnos));
}
} else if(modsAndAnnos.canBeMethodMods() && wouldAccept(LT)) {
var typeParameters = parseTypeParameters();
if(!inInterface && modsAndAnnos.canBeConstructorMods() && wouldAccept(Tag.NAMED, LPAREN)) {
try(var $1 = context.enter(Context.DYNAMIC); var $2 = preStmts.enter()) {
return applyMemberPreStmts(parseConstructor(typeParameters, docComment, modsAndAnnos));
}
} else {
var typeAnnotations = parseAnnotations();
Type type;
if(accept(VOID)) {
type = new VoidType(typeAnnotations);
} else {
type = parseType(typeAnnotations);
}
try(var $1 = preStmts.enter(); var $2 = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return applyMemberPreStmts(parseMethod(inInterface, type, typeParameters, parseName(), docComment, modsAndAnnos));
}
}
} else {
return parseInterfaceMember(inInterface, docComment, modsAndAnnos);
}
}
@Override
public List<Member> parseInterfaceMember(boolean inInterface, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(modsAndAnnos.canBeClassMods() && (wouldAccept(CLASS.or(INTERFACE).or(ENUM)) || wouldAccept(AT, INTERFACE) || enabled(ALTERNATE_ANNOTATION_DECL) && wouldAccept(ANNOTATION, Tag.NAMED, LBRACE.or(LPAREN)))) {
return List.of(parseTypeDecl(docComment, modsAndAnnos));
} else if(modsAndAnnos.canBeMethodMods() && wouldAccept(LT)) {
var typeParameters = parseTypeParameters();
var typeAnnotations = parseAnnotations();
Type type;
if(accept(VOID)) {
type = new VoidType(typeAnnotations);
} else {
type = parseType(typeAnnotations);
}
try(var $1 = preStmts.enter(); var $2 = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return applyMemberPreStmts(parseMethod(inInterface, type, typeParameters, parseName(), docComment, modsAndAnnos));
}
} else if(accept(VOID)) {
try(var $1 = preStmts.enter(); var $2 = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return applyMemberPreStmts(parseMethod(inInterface, new VoidType(), emptyList(), parseName(), docComment, modsAndAnnos));
}
} else {
var type = parseType();
try(var $1 = preStmts.enter(); var $2 = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
if(wouldAccept(Tag.NAMED, LPAREN)) {
return applyMemberPreStmts(parseMethod(inInterface, type, emptyList(), parseName(), docComment, modsAndAnnos));
} else if(modsAndAnnos.canBeFieldMods()) {
return applyMemberPreStmts(parseFieldDecl(type, docComment, modsAndAnnos));
} else {
throw syntaxError("Invalid modifiers");
}
}
}
}
@Override
public <M extends Member> ArrayList<M> parseClassBody(Supplier<? extends List<M>> memberParser) {
if(enabled(EMPTY_TYPE_BODIES) && accept(SEMI)) {
return new ArrayList<>(0);
}
try(var $1 = scope.enter(Scope.NORMAL); var $2 = context.enter(Context.DYNAMIC)) {
require(LBRACE);
var members = new ArrayList<M>();
List<Modifier> parentModifiers = emptyList();
while(wouldNotAccept(RBRACE)) {
if(!accept(SEMI)) {
List<M> parsedMembers;
if(enabled(DEFAULT_MODIFIERS)) {
defaultmods:
if(wouldAccept(KEYWORD_MODIFIER)) {
try(var state = tokens.enter()) {
var mods = new ArrayList<Modifier>();
do {
mods.add(createModifier(token));
nextToken();
} while(wouldAccept(KEYWORD_MODIFIER));
if(accept(COLON)) {
parentModifiers = mods;
parsedMembers = memberParser.get();
break defaultmods;
} else {
state.reset();
}
}
parsedMembers = memberParser.get();
} else {
parsedMembers = memberParser.get();
}
for(var member : parsedMembers) {
if(member instanceof Modified) {
mergeModifiers((Modified)member, parentModifiers);
}
}
} else {
parsedMembers = memberParser.get();
}
members.addAll(parsedMembers);
}
}
require(RBRACE);
return members;
}
}
@Override
public EnumDecl parseEnumDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
try(var $1 = scope.enter(Scope.NORMAL); var $2 = context.enter(Context.DYNAMIC)) {
return super.parseEnumDecl(docComment, modsAndAnnos);
}
}
@Override
public Pair<List<EnumField>, List<Member>> parseEnumBody() {
if(enabled(EMPTY_TYPE_BODIES) && accept(SEMI)) {
return Pair.of(emptyList(), emptyList());
}
require(LBRACE);
List<EnumField> fields;
List<Member> members;
if(wouldAccept(AT.or(Tag.NAMED))) {
fields = new ArrayList<>();
fields.add(parseEnumField());
while(accept(COMMA)) {
if(wouldAccept(SEMI.or(RBRACE))) {
break;
}
fields.add(parseEnumField());
}
} else {
fields = emptyList();
}
if(accept(SEMI)) {
members = new ArrayList<>();
List<Modifier> parentModifiers = emptyList();
while(wouldNotAccept(RBRACE)) {
if(!accept(SEMI)) {
List<Member> parsedMembers;
if(enabled(DEFAULT_MODIFIERS)) {
defaultmods:
if(wouldAccept(KEYWORD_MODIFIER)) {
try(var state = tokens.enter()) {
var mods = new ArrayList<Modifier>();
do {
mods.add(createModifier(token));
nextToken();
} while(wouldAccept(KEYWORD_MODIFIER));
if(accept(COLON)) {
parentModifiers = mods;
parsedMembers = parseClassMember(false);
break defaultmods;
} else {
state.reset();
}
}
parsedMembers = parseClassMember(false);
} else {
parsedMembers = parseClassMember(false);
}
for(var member : parsedMembers) {
if(member instanceof Modified) {
mergeModifiers((Modified)member, parentModifiers);
}
}
} else {
parsedMembers = parseClassMember(false);
}
members.addAll(parsedMembers);
}
}
} else {
members = emptyList();
}
require(RBRACE);
return Pair.of(fields, members);
}
protected boolean isVisibilityModifier(Modifier modifier) {
return switch(modifier.toCode()) {
case "public", "private", "protected", "package" -> true;
default -> false;
};
}
protected boolean isValidConstructorModifier(Modifier modifier) {
return isVisibilityModifier(modifier);
}
protected boolean isValidMethodModifier(Modifier modifier) {
return switch(modifier.toCode()) {
case "public", "private", "protected", "package",
"static", "final", "synchronized", "strictfp",
"native", "abstract", "default" -> true;
default -> false;
};
}
protected boolean isValidClassModifier(Modifier modifier) {
return switch(modifier.toCode()) {
case "public", "private", "protected", "package",
"static", "final", "abstract", "strictfp" -> true;
default -> false;
};
}
protected boolean isValidFieldModifier(Modifier modifier) {
return switch(modifier.toCode()) {
case "public", "private", "protected", "package",
"static", "final", "transient", "volatile" -> true;
default -> false;
};
}
@SuppressWarnings("unlikely-arg-type")
@Override
public ModsAndAnnotations parseKeywordModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
if(enabled(DEFAULT_MODIFIERS) && mods.contains("non-" + token.getString())) {
throw syntaxError("Incompatible modifiers 'non-" + token.getString() + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(enabled(DEFAULT_MODIFIERS) && wouldAcceptPseudoOp(test("non"), SUB, KEYWORD_MODIFIER)) {
nextToken(2);
if(mods.contains(token.getString())) {
throw syntaxError("Incompatible modifiers '" + token.getString() + "' and 'non-" + token.getString() + "'");
}
if(!mods.add(createModifier("non-" + token.getString()))) {
throw syntaxError("Duplicate modifier 'non-" + token.getString() + "'");
}
nextToken();
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
@SuppressWarnings("unlikely-arg-type")
@Override
public ModsAndAnnotations parseClassModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.CLASS_MODIFIER)) {
if(enabled(DEFAULT_MODIFIERS) && mods.contains("non-" + token.getString())) {
throw syntaxError("Incompatible modifiers 'non-" + token.getString() + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(enabled(DEFAULT_MODIFIERS) && wouldAcceptPseudoOp(test("non"), SUB, Tag.CLASS_MODIFIER)) {
nextToken(2);
if(mods.contains(token.getString())) {
throw syntaxError("Incompatible modifiers '" + token.getString() + "' and 'non-" + token.getString() + "'");
}
if(!mods.add(createModifier("non-" + token.getString()))) {
throw syntaxError("Duplicate modifier 'non-" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos, EnumSet.of(ModsAndAnnotations.Type.CLASS));
}
}
}
public ModsAndAnnotations parseAnnotationPropertyModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
boolean foundAbstract = false;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(ABSTRACT)) {
if(foundAbstract) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
foundAbstract = true;
mods.add(createModifier(token));
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
@SuppressWarnings("unlikely-arg-type")
@Override
public ModsAndAnnotations parseMethodModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.METHOD_MODIFIER)) {
if(enabled(DEFAULT_MODIFIERS) && mods.contains("non-" + token.getString())) {
throw syntaxError("Incompatible modifiers 'non-" + token.getString() + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(enabled(DEFAULT_MODIFIERS) && wouldAcceptPseudoOp(test("non"), SUB, Tag.METHOD_MODIFIER)) {
nextToken(2);
if(mods.contains(token.getString())) {
throw syntaxError("Incompatible modifiers '" + token.getString() + "' and 'non-" + token.getString() + "'");
}
if(!mods.add(createModifier("non-" + token.getString()))) {
throw syntaxError("Duplicate modifier 'non-" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos, EnumSet.of(ModsAndAnnotations.Type.METHOD));
}
}
}
@SuppressWarnings("unlikely-arg-type")
@Override
public ModsAndAnnotations parseConstructorModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.CONSTRUCTOR_MODIFIER)) {
if(enabled(DEFAULT_MODIFIERS) && mods.contains("non-" + token.getString())) {
throw syntaxError("Incompatible modifiers 'non-" + token.getString() + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(enabled(DEFAULT_MODIFIERS) && wouldAcceptPseudoOp(test("non"), SUB, Tag.CONSTRUCTOR_MODIFIER)) {
nextToken(2);
if(mods.contains(token.getString())) {
throw syntaxError("Incompatible modifiers '" + token.getString() + "' and 'non-" + token.getString() + "'");
}
if(!mods.add(createModifier("non-" + token.getString()))) {
throw syntaxError("Duplicate modifier 'non-" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos, EnumSet.of(ModsAndAnnotations.Type.CONSTRUCTOR));
}
}
}
@SuppressWarnings("unlikely-arg-type")
@Override
public ModsAndAnnotations parseFieldModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.FIELD_MODIFIER)) {
if(enabled(DEFAULT_MODIFIERS) && mods.contains("non-" + token.getString())) {
throw syntaxError("Incompatible modifiers 'non-" + token.getString() + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(enabled(DEFAULT_MODIFIERS) && wouldAcceptPseudoOp(test("non"), SUB, Tag.FIELD_MODIFIER)) {
nextToken(2);
if(mods.contains(token.getString())) {
throw syntaxError("Incompatible modifiers '" + token.getString() + "' and 'non-" + token.getString() + "'");
}
if(!mods.add(createModifier("non-" + token.getString()))) {
throw syntaxError("Duplicate modifier 'non-" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos, EnumSet.of(ModsAndAnnotations.Type.FIELD));
}
}
}
@Override
public JPPModifier createModifier(JavaTokenType type) {
return new JPPModifier(switch(type) {
case PUBLIC -> Modifiers.PUBLIC;
case PRIVATE -> Modifiers.PRIVATE;
case PROTECTED -> Modifiers.PROTECTED;
case PACKAGE -> Modifiers.PACKAGE;
case STATIC -> Modifiers.STATIC;
case STRICTFP -> Modifiers.STRICTFP;
case TRANSIENT -> Modifiers.TRANSIENT;
case VOLATILE -> Modifiers.VOLATILE;
case NATIVE -> Modifiers.NATIVE;
case FINAL -> Modifiers.FINAL;
case SYNCHRONIZED -> Modifiers.SYNCHRONIZED;
case DEFAULT -> Modifiers.DEFAULT;
case ABSTRACT -> Modifiers.ABSTRACT;
case TRANSITIVE -> Modifiers.TRANSITIVE;
default -> throw new IllegalArgumentException(type + " is not a modifier");
});
}
@Override
public JPPModifier createModifier(String name) {
return new JPPModifier(Modifiers.fromString(name));
}
protected void mergeModifiers(Modified member, List<Modifier> parentMods) {
var memberMods = member.getModifiers();
Predicate<Modifier> filter;
if(member instanceof ConstructorDecl) {
filter = this::isValidConstructorModifier;
} else if(member instanceof FunctionDecl) {
filter = this::isValidMethodModifier;
} else if(member instanceof VariableDecl) {
filter = this::isValidFieldModifier;
} else if(member instanceof TypeDecl) {
filter = this::isValidClassModifier;
} else if(member instanceof AnnotationProperty) {
filter = modifier -> switch(modifier.toCode()) {
case "public", "abstract" -> true;
default -> false;
};
} else {
filter = modifier -> true;
}
boolean hasVisibility = member.hasVisibilityModifier();
memberMods.addAll(0, parentMods.stream().sequential().filter(modifier -> {
if(!filter.test(modifier)) {
return false;
}
if(isVisibilityModifier(modifier)) {
return !hasVisibility;
} else {
if(modifier.toCode().startsWith("non-")) {
if(member.hasModifier(modifier.toCode().substring(4))) {
return false;
}
} else if(member.hasModifier("non-" + modifier.toCode())) {
return false;
}
return !member.hasModifier(modifier.toCode());
}
}).collect(Collectors.toList()));
// memberMods.removeIf(mod -> mod.toCode().startsWith("non-"));
}
protected ContextStack<List<FormalParameter>> functionParameters = new ContextStack<>();
@Override
public Block parseConstructorBody(List<FormalParameter> parameters) {
if(enabled(EMPTY_CONSTRUCTOR_BODIES)) {
if(accept(SEMI)) {
return new Block();
}
if(accept(COLON)) {
Optional<Expression> object;
if(wouldAccept(SUPER.or(THIS).or(LT))) {
object = Optional.empty();
} else {
object = Optional.of(parseSuffix());
require(DOT);
}
List<? extends TypeArgument> typeArguments = parseTypeArgumentsOpt();
ConstructorCall.Type callType;
if(object.isEmpty()) {
if(accept(SUPER)) {
callType = ConstructorCall.Type.SUPER;
} else {
require(THIS);
callType = ConstructorCall.Type.THIS;
}
} else {
require(SUPER);
callType = ConstructorCall.Type.SUPER;
}
List<Expression> args;
if(wouldAccept(LPAREN) || callType == ConstructorCall.Type.THIS) {
try(var $ = functionParameters.enter(parameters)) {
args = parseConstructorArguments();
}
} else {
args = new ArrayList<>();
for(var param : parameters) {
args.add(new Variable(param.getName()));
}
}
endStatement();
return new Block(new ConstructorCall(object, typeArguments, callType, args));
}
}
try(var $ = functionParameters.enter(parameters)) {
return parseBlock();
}
}
@Override
public List<Expression> parseConstructorArguments() {
if(functionParameters.isEmpty() || !enabled(IMPROVED_CONSTRUCTOR_CALL_ARGUMENTS)) {
return parseArguments(false);
}
require(LPAREN);
var args = new ArrayList<Expression>();
var parameters = functionParameters.current();
if(!wouldAccept(RPAREN)) {
boolean hadStar = false;
if(wouldAccept(UNDERSCORE)) {
if(args.size() > parameters.size()) {
throw syntaxError("Cannot use _ for argument #" + args.size() + " when there are only " + parameters.size() + " parameters");
}
nextToken();
args.add(new Variable(parameters.get(args.size()).getName()));
} else if(wouldAccept(STAR, COMMA.or(RPAREN))) {
hadStar = true;
nextToken();
for(var param : parameters) {
args.add(new Variable(param.getName()));
}
} else {
args.add(parseArgument());
}
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
if(wouldAccept(UNDERSCORE)) {
if(args.size() >= parameters.size()) {
throw syntaxError("Cannot use _ for argument #" + (args.size()+1) + " when there are only " + parameters.size() + " parameters");
}
nextToken();
args.add(new Variable(parameters.get(args.size()).getName()));
} else if(wouldAccept(STAR, COMMA.or(RPAREN))) {
if(hadStar) {
throw syntaxError("Cannot use * more than once in explicit constructor call");
} else {
hadStar = true;
}
nextToken();
for(var param : parameters) {
args.add(new Variable(param.getName()));
}
} else {
args.add(parseArgument());
}
}
}
require(RPAREN);
if(enabled(LAST_LAMBDA_ARGUMENT) && wouldAccept(LBRACE)) {
args.add(new Lambda(Either.second(emptyList()), Either.first(parseBlock())));
}
return args;
}
@Override
public Optional<Block> parseMethodBody(boolean isVoidMethod, List<FormalParameter> parameters) {
if(accept(SEMI)) {
return Optional.empty();
} else {
try(var $ = functionParameters.enter(parameters)) {
if(enabled(SIMPLE_METHOD_BODIES) && accept(ARROW)) {
var expr = parseExpression();
endStatement();
return Optional.of(new Block(isVoidMethod? new ExpressionStmt(expr) : new ReturnStmt(expr)));
} else {
return Optional.of(parseBlock());
}
}
}
}
@Override
public Pair<Optional<ThisParameter>,List<FormalParameter>> parseConstructorParameters(ArrayList<Statement> bodyStmts) {
Supplier<Name> nameParser;
if(enabled(CONSTRUCTOR_FIELDS)) {
nameParser = () -> {
if(accept(THIS, DOT)) {
var name = parseName();
bodyStmts.add(new ExpressionStmt(new AssignExpr(new MemberAccess(new This(), name), new Variable(name))));
return name;
} else {
return parseName();
}
};
} else {
nameParser = this::parseName;
}
return parseParameters(nameParser);
}
@Override
public ArrayList<FormalParameter> parseFormalParameterList(Supplier<Name> parseName) {
var params = new ArrayList<FormalParameter>();
var eitherParam = parseFormalParameterWithOptDefault(parseName);
while(eitherParam.isSecond()) {
FormalParameter param = eitherParam.second();
params.add(param);
if(param.isVariadic()) {
break;
}
if(!accept(COMMA)) {
break;
}
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
eitherParam = parseFormalParameterWithOptDefault(parseName, param);
}
if(eitherParam.isFirst()) {
FormalParameter param = eitherParam.first();
params.add(param);
while(!param.isVariadic() && accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
params.add(param = parseFormalParameterWithDefault(parseName, param));
}
}
return params;
}
public Either<DefaultFormalParameter,FormalParameter> parseFormalParameterWithOptDefault() {
return parseFormalParameterWithOptDefault(this::parseName);
}
public Either<DefaultFormalParameter,FormalParameter> parseFormalParameterWithOptDefault(Supplier<Name> parseName) {
return parseFormalParameterWithOptDefault(parseName, parseFinalAndAnnotations());
}
public Either<DefaultFormalParameter,FormalParameter> parseFormalParameterWithOptDefault(Supplier<Name> parseName, FormalParameter prevParam) {
return parseFormalParameterWithOptDefault(parseName, Optional.ofNullable(prevParam));
}
public Either<DefaultFormalParameter,FormalParameter> parseFormalParameterWithOptDefault(Supplier<Name> parseName, Optional<FormalParameter> prevParam) {
return parseFormalParameterWithOptDefault(parseName, parseFinalAndAnnotations(), prevParam);
}
public Either<DefaultFormalParameter, FormalParameter> parseFormalParameterWithOptDefault(Supplier<Name> parseName, ModsAndAnnotations modsAndAnnos) {
return parseFormalParameterWithOptDefault(parseName, modsAndAnnos, Optional.empty());
}
@SuppressWarnings("unchecked")
public Either<DefaultFormalParameter,FormalParameter> parseFormalParameterWithOptDefault(Supplier<Name> parseName, ModsAndAnnotations modsAndAnnos, Optional<FormalParameter> prevParam) {
assert modsAndAnnos.canBeLocalVarMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
Type type;
boolean variadic;
Name name;
var predicate = enabled(DEFAULT_ARGUMENTS)? (enabled(SIZED_ARRAY_INITIALIZER)? RPAREN.or(COMMA).or(EQ).or(AT).or(LBRACKET) : RPAREN.or(COMMA).or(EQ)) : RPAREN.or(COMMA);
if(modsAndAnnos.isEmpty() && enabled(IMPLICIT_PARAMETER_TYPES) && prevParam.isPresent() && (wouldAccept(Tag.NAMED, predicate) || wouldAccept(Tag.NAMED, ELLIPSIS, predicate) || wouldAccept(THIS, DOT, Tag.NAMED, predicate) || wouldAccept(THIS, DOT, Tag.NAMED, ELLIPSIS, predicate))) {
var prev = prevParam.get();
modifiers = Node.clone(prev.getModifiers());
annotations = Node.clone(prev.getAnnotations());
type = prev.getType().clone();
name = parseName.get();
variadic = accept(ELLIPSIS);
} else {
type = parseType();
variadic = accept(ELLIPSIS);
name = parseName.get();
}
var dimensions = parseDimensions();
if(enabled(DEFAULT_ARGUMENTS) && (wouldAccept(EQ) || enabled(SIZED_ARRAY_INITIALIZER) && wouldAccept(AT.or(LBRACKET)))) {
Type initType;
if(variadic) {
if(type instanceof ArrayType) {
initType = type.clone();
((ArrayType)initType).getDimensions().add(0, new Dimension());
} else {
initType = new ArrayType(type);
}
} else {
initType = type;
}
boolean arraySizeInit = wouldAccept(AT.or(LBRACKET));
var initializer = parseVariableInitializer(initType, dimensions);
if(variadic && arraySizeInit) {
dimensions.remove(0);
((ArrayCreator)initializer).getDimensions().remove(0);
if(type instanceof ArrayType) {
((ArrayType)type).getDimensions().addAll(dimensions);
} else {
type = new ArrayType(type, dimensions);
}
dimensions.clear();
}
if(variadic && !arraySizeInit && accept(COMMA)) {
if(!enabled(TRAILING_COMMAS) || !wouldAccept(RPAREN)) {
var elements = new ArrayList<Initializer>();
elements.add(initializer);
elements.add(parseInitializer(dimensionCount(type, dimensions)));
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
elements.add(parseInitializer(dimensionCount(type, dimensions)));
}
initializer = new ArrayInitializer<>(elements);
}
}
Expression defaultValue;
if(initializer instanceof ArrayInitializer) {
var dimensions2 = dimensions.stream().map(Dimension::clone).collect(Collectors.toCollection(ArrayList<Dimension>::new));
Type baseType;
if(type instanceof ArrayType) {
var arrayType = (ArrayType)type;
baseType = arrayType.getBaseType();
dimensions2.addAll(0, arrayType.getDimensions().stream().map(Dimension::clone).collect(Collectors.toList()));
} else {
baseType = type;
}
if(variadic) {
dimensions2.add(new Dimension());
}
if(baseType instanceof GenericType) {
var genericType = (GenericType)baseType;
if(!genericType.getTypeArguments().isEmpty()) {
baseType = genericType.clone();
((GenericType)baseType).getTypeArguments().clear();
Type castType;
if(type instanceof ArrayType) {
castType = type.clone();
((GenericType)baseType).getTypeArguments().clear();
} else {
castType = new ArrayType(genericType);
}
defaultValue = new CastExpr(castType, new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2));
} else {
defaultValue = new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2);
}
} else {
defaultValue = new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2);
}
} else {
defaultValue = (Expression)initializer;
}
return Either.first(new DefaultFormalParameter(type, name, variadic, dimensions, defaultValue, modifiers, annotations));
} else {
return Either.second(new FormalParameter(type, name, variadic, dimensions, modifiers, annotations));
}
}
public FormalParameter parseFormalParameterWithDefault() {
return parseFormalParameterWithDefault(this::parseName);
}
public FormalParameter parseFormalParameterWithDefault(Supplier<Name> parseName) {
return parseFormalParameterWithDefault(parseName, parseFinalAndAnnotations());
}
public FormalParameter parseFormalParameterWithDefault(Supplier<Name> parseName, FormalParameter prevParam) {
return parseFormalParameterWithDefault(parseName, Optional.ofNullable(prevParam));
}
public FormalParameter parseFormalParameterWithDefault(Supplier<Name> parseName, Optional<FormalParameter> prevParam) {
return parseFormalParameterWithDefault(parseName, parseFinalAndAnnotations(), prevParam);
}
public FormalParameter parseFormalParameterWithDefault(Supplier<Name> parseName, ModsAndAnnotations modsAndAnnos) {
return parseFormalParameterWithDefault(parseName, modsAndAnnos, Optional.empty());
}
@SuppressWarnings("unchecked")
public FormalParameter parseFormalParameterWithDefault(Supplier<Name> parseName, ModsAndAnnotations modsAndAnnos, Optional<FormalParameter> prevParam) {
assert modsAndAnnos.canBeLocalVarMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
Type type;
boolean variadic;
Name name;
var predicate = enabled(SIZED_ARRAY_INITIALIZER)? RPAREN.or(COMMA).or(EQ).or(AT).or(LBRACKET) : RPAREN.or(COMMA).or(EQ);
if(modsAndAnnos.isEmpty() && enabled(IMPLICIT_PARAMETER_TYPES) && prevParam.isPresent() && (wouldAccept(Tag.NAMED, predicate) || wouldAccept(Tag.NAMED, ELLIPSIS, predicate) || wouldAccept(THIS, DOT, Tag.NAMED, predicate) || wouldAccept(THIS, DOT, Tag.NAMED, ELLIPSIS, predicate))) {
var prev = prevParam.get();
modifiers = Node.clone(prev.getModifiers());
annotations = Node.clone(prev.getAnnotations());
type = prev.getType().clone();
name = parseName.get();
variadic = accept(ELLIPSIS);
} else {
type = parseType();
variadic = accept(ELLIPSIS);
name = parseName.get();
}
var dimensions = parseDimensions();
if(variadic) {
if(!wouldAccept(EQ) && (!enabled(SIZED_ARRAY_INITIALIZER) || !wouldAccept(LBRACKET))) {
return new FormalParameter(type, name, variadic, dimensions, modifiers, annotations);
}
}
boolean arraySizeInit = wouldAccept(AT.or(LBRACKET));
var initializer = parseVariableInitializer(type, dimensions);
if(variadic && arraySizeInit) {
dimensions.remove(0);
((ArrayCreator)initializer).getDimensions().remove(0);
if(type instanceof ArrayType) {
((ArrayType)type).getDimensions().addAll(dimensions);
} else {
type = new ArrayType(type, dimensions);
}
dimensions.clear();
}
if(variadic && !arraySizeInit && accept(COMMA)) {
if(!enabled(TRAILING_COMMAS) || !wouldAccept(RPAREN)) {
var elements = new ArrayList<Initializer>();
elements.add(initializer);
elements.add(parseInitializer(dimensionCount(type, dimensions)));
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
elements.add(parseInitializer(dimensionCount(type, dimensions)));
}
initializer = new ArrayInitializer<>(elements);
}
}
Expression defaultValue;
if(initializer instanceof ArrayInitializer) {
var dimensions2 = dimensions.stream().map(Dimension::clone).collect(Collectors.toCollection(ArrayList<Dimension>::new));
Type baseType;
if(type instanceof ArrayType) {
var arrayType = (ArrayType)type;
baseType = arrayType.getBaseType();
dimensions2.addAll(0, arrayType.getDimensions().stream().map(Dimension::clone).collect(Collectors.toList()));
} else {
baseType = type;
}
if(variadic) {
dimensions2.add(new Dimension());
}
if(baseType instanceof GenericType) {
var genericType = (GenericType)baseType;
if(!genericType.getTypeArguments().isEmpty()) {
baseType = genericType.clone();
((GenericType)baseType).getTypeArguments().clear();
Type castType;
if(type instanceof ArrayType) {
castType = type.clone();
((GenericType)baseType).getTypeArguments().clear();
} else {
castType = new ArrayType(genericType);
}
defaultValue = new CastExpr(castType, new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2));
} else {
defaultValue = new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2);
}
} else {
defaultValue = new ArrayCreator(baseType, (ArrayInitializer<? extends Initializer>)initializer, dimensions2);
}
} else {
defaultValue = (Expression)initializer;
}
return new DefaultFormalParameter(type, name, variadic, dimensions, defaultValue, modifiers, annotations);
}
protected int firstDefaultIndex(List<FormalParameter> parameters) {
for(int firstDefaultIndex = 0; firstDefaultIndex < parameters.size(); firstDefaultIndex++) {
if(parameters.get(firstDefaultIndex) instanceof DefaultFormalParameter) {
return firstDefaultIndex;
}
}
return -1;
}
@Override
public List<Member> parseMethod(boolean inInterface, Type returnType, List<TypeParameter> typeParameters,
Name name, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
var methods = super.parseMethod(inInterface, returnType, typeParameters, name, docComment, modsAndAnnos);
if(methods.size() == 1) {
var method = (FunctionDecl)methods.get(0);
if(inInterface && enabled(AUTO_DEFAULT_MODIFIER) && method.getBody().isPresent() && !method.hasModifier("static") && !method.hasModifier("default") && !method.hasModifier("non-default") && !method.hasModifier("abstract")) {
method.getModifiers().add(createModifier("default"));
}
var parameters = method.getParameters();
int firstDefaultIndex = firstDefaultIndex(parameters);
if(firstDefaultIndex >= 0) {
methods = new ArrayList<>();
methods.add(method);
var lastParam = parameters.get(parameters.size()-1);
if(firstDefaultIndex + 1 < parameters.size() && !(lastParam instanceof DefaultFormalParameter)) {
assert lastParam.isVariadic();
for(int i = firstDefaultIndex; i < parameters.size()-1; i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size()-1; j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
newparams.add(lastParam.clone());
args.add(new Variable(lastParam.getName()));
methods.add(makeDelegateCall(inInterface, method, newparams, args));
}
} else {
for(int i = firstDefaultIndex; i < parameters.size(); i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size(); j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
methods.add(makeDelegateCall(inInterface, method, newparams, args));
}
if(lastParam.isVariadic()) {
for(int i = firstDefaultIndex; i < parameters.size()-1; i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size()-1; j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
newparams.add(((DefaultFormalParameter)lastParam).toFormalParameter());
args.add(new Variable(lastParam.getName()));
methods.add(makeDelegateCall(inInterface, method, newparams, args));
}
}
}
method.setParameters(parameters.stream().map(param -> param instanceof DefaultFormalParameter? ((DefaultFormalParameter)param).toFormalParameter() : param).collect(Collectors.toList()));
}
}
return methods;
}
protected FunctionDecl makeDelegateCall(boolean inInterface, FunctionDecl base, List<FormalParameter> parameters,
List<Expression> arguments) {
var funcCall = new FunctionCall(base.getName(), arguments);
var result = new FunctionDecl(base.getName(), Node.clone(base.getTypeParameters()), base.getReturnType().clone(),
Node.clone(base.getThisParameter()), parameters, Node.clone(base.getDimensions()),
Node.clone(base.getExceptions()),
new Block(base.getReturnType() instanceof VoidType? new ExpressionStmt(funcCall) : new ReturnStmt(funcCall)),
Node.clone(base.getModifiers()), Node.clone(base.getAnnotations()), base.getDocComment());
if(inInterface && !result.hasModifier("default")) {
result.getModifiers().add(createModifier("default"));
}
return result;
}
@Override
public List<Member> parseConstructor(Name name, List<TypeParameter> typeParameters,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
var methods = super.parseConstructor(name, typeParameters, docComment, modsAndAnnos);
if(methods.size() == 1) {
var method = (ConstructorDecl)methods.get(0);
var parameters = method.getParameters();
int firstDefaultIndex = firstDefaultIndex(parameters);
if(firstDefaultIndex >= 0) {
methods = new ArrayList<>();
methods.add(method);
var lastParam = parameters.get(parameters.size()-1);
if(firstDefaultIndex + 1 < parameters.size() && !(lastParam instanceof DefaultFormalParameter)) {
assert lastParam.isVariadic();
for(int i = firstDefaultIndex; i < parameters.size()-1; i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size()-1; j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
newparams.add(lastParam.clone());
args.add(new Variable(lastParam.getName()));
methods.add(makeDelegateCall(method, newparams, args));
}
} else {
for(int i = firstDefaultIndex; i < parameters.size(); i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size(); j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
methods.add(makeDelegateCall(method, newparams, args));
}
if(lastParam.isVariadic()) {
for(int i = firstDefaultIndex; i < parameters.size()-1; i++) {
var newparams = new ArrayList<FormalParameter>();
var args = new ArrayList<Expression>();
for(int j = 0; j < i; j++) {
var param = parameters.get(j);
if(param instanceof DefaultFormalParameter) {
newparams.add(((DefaultFormalParameter)param).toFormalParameter());
} else {
newparams.add(param.clone());
}
args.add(new Variable(param.getName()));
}
for(int j = i; j < parameters.size()-1; j++) {
args.add(((DefaultFormalParameter)parameters.get(j)).getDefaultValue());
}
newparams.add(((DefaultFormalParameter)lastParam).toFormalParameter());
args.add(new Variable(lastParam.getName()));
methods.add(makeDelegateCall(method, newparams, args));
}
}
}
method.setParameters(parameters.stream().map(param -> param instanceof DefaultFormalParameter? ((DefaultFormalParameter)param).toFormalParameter() : param).collect(Collectors.toList()));
}
}
return methods;
}
protected ConstructorDecl makeDelegateCall(ConstructorDecl base, List<FormalParameter> parameters,
List<Expression> arguments) {
return new ConstructorDecl(base.getName(), Node.clone(base.getTypeParameters()),
Node.clone(base.getThisParameter()), parameters, Node.clone(base.getExceptions()),
new Block(new ConstructorCall(ConstructorCall.Type.THIS, arguments)), Node.clone(base.getModifiers()),
Node.clone(base.getAnnotations()), base.getDocComment());
}
@Override
public List<Member> parseFieldDecl() {
var docComment = getDocComment();
var modsAndAnnos = parseFieldModsAndAnnotations();
try(var $ = context.enter(modsAndAnnos.hasModifier("static")? Context.STATIC : Context.DYNAMIC)) {
return parseFieldDecl(docComment, modsAndAnnos);
}
}
@Override
public List<Member> parseFieldDecl(Type type, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
try(var $ = preStmts.enter()) {
var members = new ArrayList<Member>();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var declarators = new ArrayList<VariableDeclarator>();
var declarator = parseVariableDeclarator(type);
declarators.add(declarator);
if(enabled(GETTERS_AND_SETTERS) && wouldAccept(LBRACE)) {
members.addAll(parseGetterAndSetters(type, declarator));
}
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && !wouldAccept(Tag.NAMED)) {
break;
}
declarators.add(declarator = parseVariableDeclarator(type));
if(enabled(GETTERS_AND_SETTERS) && wouldAccept(LBRACE)) {
members.addAll(parseGetterAndSetters(type, declarator));
}
}
endStatement();
var decl = new VariableDecl(type, declarators, modifiers, annotations, docComment);
if(preStmts.isEmpty()) {
members.add(decl);
} else {
for(var stmt : preStmts) {
if(stmt instanceof VariableDecl) {
var varDecl = (VariableDecl)stmt;
if(!varDecl.hasVisibilityModifier()) {
varDecl.getModifiers().add(createModifier(PRIVATE));
}
members.add(varDecl);
} else {
if(members.isEmpty()) {
members.add(new ClassInitializer(context.current() == Context.STATIC, stmt instanceof Block? (Block)stmt : new Block(stmt)));
} else {
var lastMember = members.get(members.size()-1);
if(lastMember instanceof ClassInitializer) {
var classInitializer = (ClassInitializer)lastMember;
if(classInitializer.isStatic() == (context.current() == Context.STATIC)) {
classInitializer.getBlock().getStatements().add(stmt);
} else {
members.add(new ClassInitializer(context.current() == Context.STATIC, stmt instanceof Block? (Block)stmt : new Block(stmt)));
}
} else {
members.add(new ClassInitializer(context.current() == Context.STATIC, stmt instanceof Block? (Block)stmt : new Block(stmt)));
}
}
}
}
members.add(decl);
}
return members;
}
}
private final List<Modifier> defaultGetterSetterModifiers = List.of(createModifier(PUBLIC));
public List<Member> parseGetterAndSetters(Type fieldType, VariableDeclarator declarator) {
require(LBRACE);
String suffix = declarator.getName().toCode();
suffix = Character.toUpperCase(suffix.charAt(0)) + suffix.substring(1);
final Name fieldName = declarator.getName(),
getterName = fieldType instanceof PrimitiveType && ((PrimitiveType)fieldType).getName().equals(PrimitiveType.BOOLEAN)? declarator.getName().toCode().startsWith("is") && declarator.getName().length() > 2 && (declarator.getName().charAt(2) == '_' || Character.isUpperCase(declarator.getName().charAt(2)))? declarator.getName() : Name("is" + suffix) : Name("get" + suffix),
setterName = Name("set" + suffix);
var members = new ArrayList<Member>();
var docComment = getDocComment();
var modsAndAnnos = parseMethodModsAndAnnotations();
if(!modsAndAnnos.hasModifier("final") && !modsAndAnnos.hasModifier("non-final")) {
modsAndAnnos.mods.add(createModifier("non-final"));
}
if(context.currentOrElse(Context.DYNAMIC) == Context.STATIC && !modsAndAnnos.hasModifier("static") && !modsAndAnnos.hasModifier("non-static")) {
modsAndAnnos.mods.add(createModifier("static"));
}
var typeParameters = parseTypeParametersOpt();
Type returnType;
if(wouldAccept(GET.or(SET), LPAREN.or(ARROW).or(LBRACE).or(SEMI))) {
if(wouldAccept(GET)) {
returnType = fieldType.clone();
} else {
returnType = new VoidType();
}
} else if(wouldAccept(VOID, SET)) {
nextToken();
returnType = new VoidType();
} else {
returnType = parseType();
}
if(wouldAccept(GET)) {
parseGetter(members, fieldType, fieldName, getterName, typeParameters, returnType, docComment, modsAndAnnos);
while(wouldNotAccept(RBRACE)) {
docComment = getDocComment();
modsAndAnnos = parseMethodModsAndAnnotations();
if(!modsAndAnnos.hasModifier("final") && !modsAndAnnos.hasModifier("non-final")) {
modsAndAnnos.mods.add(createModifier("non-final"));
}
if(context.currentOrElse(Context.DYNAMIC) == Context.STATIC && !modsAndAnnos.hasModifier("static") && !modsAndAnnos.hasModifier("non-static")) {
modsAndAnnos.mods.add(createModifier("static"));
}
typeParameters = parseTypeParametersOpt();
if(wouldAccept(GET.or(SET), LPAREN.or(ARROW).or(LBRACE).or(SEMI))) {
returnType = new VoidType();
} else if(accept(VOID)) {
returnType = new VoidType();
} else {
returnType = parseType();
}
parseSetter(members, fieldType, fieldName, setterName, typeParameters, returnType, docComment, modsAndAnnos);
}
} else {
parseSetter(members, fieldType, fieldName, setterName, typeParameters, returnType, docComment, modsAndAnnos);
while(wouldNotAccept(RBRACE)) {
docComment = getDocComment();
modsAndAnnos = parseMethodModsAndAnnotations();
if(!modsAndAnnos.hasModifier("final") && !modsAndAnnos.hasModifier("non-final")) {
modsAndAnnos.mods.add(createModifier("non-final"));
}
if(context.currentOrElse(Context.DYNAMIC) == Context.STATIC && !modsAndAnnos.hasModifier("static") && !modsAndAnnos.hasModifier("non-static")) {
modsAndAnnos.mods.add(createModifier("static"));
}
typeParameters = parseTypeParametersOpt();
if(wouldAccept(GET.or(SET), LPAREN.or(ARROW).or(LBRACE).or(SEMI))) {
returnType = new VoidType();
} else if(accept(VOID)) {
returnType = new VoidType();
} else {
returnType = parseType();
}
if(wouldAccept(GET)) {
parseGetter(members, fieldType, fieldName, getterName, typeParameters, returnType, docComment, modsAndAnnos);
while(wouldNotAccept(RBRACE)) {
docComment = getDocComment();
modsAndAnnos = parseMethodModsAndAnnotations();
if(!modsAndAnnos.hasModifier("final") && !modsAndAnnos.hasModifier("non-final")) {
modsAndAnnos.mods.add(createModifier("non-final"));
}
if(context.currentOrElse(Context.DYNAMIC) == Context.STATIC && !modsAndAnnos.hasModifier("static") && !modsAndAnnos.hasModifier("non-static")) {
modsAndAnnos.mods.add(createModifier("static"));
}
typeParameters = parseTypeParametersOpt();
if(wouldAccept(GET.or(SET), LPAREN.or(ARROW).or(LBRACE).or(SEMI))) {
returnType = new VoidType();
} else if(accept(VOID)) {
returnType = new VoidType();
} else {
returnType = parseType();
}
parseSetter(members, fieldType, fieldName, setterName, typeParameters, returnType, docComment, modsAndAnnos);
}
} else {
parseSetter(members, fieldType, fieldName, setterName, typeParameters, returnType, docComment, modsAndAnnos);
}
}
}
require(RBRACE);
return members;
}
protected void parseGetter(ArrayList<Member> members, Type fieldType, Name fieldName, Name getterName, List<TypeParameter> typeParameters, Type returnType, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
require(GET);
Optional<ThisParameter> thisParameter;
if(accept(LPAREN)) {
if(!accept(RPAREN)) {
thisParameter = Optional.of(parseThisParameter());
require(RPAREN);
} else {
thisParameter = Optional.empty();
}
} else {
thisParameter = Optional.empty();
}
List<Dimension> dimensions = returnType instanceof VoidType? emptyList() : parseDimensions();
List<GenericType> exceptions;
if(accept(THROWS)) {
exceptions = parseGenericTypeList();
} else {
exceptions = emptyList();
}
var body = parseMethodBody(returnType instanceof VoidType, emptyList());
var method = new FunctionDecl(getterName, typeParameters, returnType, thisParameter, emptyList(), dimensions, exceptions, body, modsAndAnnos.mods, modsAndAnnos.annos, docComment);
if(!body.isPresent() && !method.hasModifier(Modifiers.ABSTRACT)) {
method.setBody(new Block(new ReturnStmt(new MemberAccess(context.isEmpty() || context.current() == Context.DYNAMIC || typeNames.isEmpty()? new This() : new Variable(typeNames.current()), fieldName))));
}
mergeModifiers(method, defaultGetterSetterModifiers);
members.add(method);
}
protected void parseSetter(ArrayList<Member> members, Type fieldType, Name fieldName, Name setterName, List<TypeParameter> typeParameters, Type returnType, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
require(SET);
ArrayList<Member> methods;
if(wouldAccept(LPAREN, Tag.NAMED, RPAREN)) {
methods = new ArrayList<>();
require(LPAREN);
var parameters = List.of(new FormalParameter(fieldType.clone(), parseName()));
require(RPAREN);
List<Dimension> dimensions = returnType instanceof VoidType? emptyList() : parseDimensions();
List<GenericType> exceptions;
if(accept(THROWS)) {
exceptions = parseGenericTypeList();
} else {
exceptions = emptyList();
}
var body = parseMethodBody(returnType instanceof VoidType, parameters);
methods.add(new FunctionDecl(setterName, typeParameters, returnType, Optional.empty(), parameters, dimensions, exceptions, body, modsAndAnnos.mods, modsAndAnnos.annos, docComment));
} else if(wouldAccept(LPAREN)) {
methods = new ArrayList<>(parseMethod(false, returnType, typeParameters, setterName, docComment, modsAndAnnos));
} else {
methods = new ArrayList<>();
var parameters = List.of(new FormalParameter(fieldType.clone(), Names.value));
List<Dimension> dimensions = returnType instanceof VoidType? emptyList() : parseDimensions();
List<GenericType> exceptions;
if(accept(THROWS)) {
exceptions = parseGenericTypeList();
} else {
exceptions = emptyList();
}
var body = parseMethodBody(returnType instanceof VoidType, parameters);
methods.add(new FunctionDecl(setterName, typeParameters, returnType, Optional.empty(), parameters, dimensions, exceptions, body, modsAndAnnos.mods, modsAndAnnos.annos, docComment));
}
int index;
if(methods.size() == 1) {
index = 0;
} else {
index = -1;
for(int i = 0; i < methods.size(); i++) {
var member = methods.get(i);
if(member instanceof FunctionDecl) {
var decl = (FunctionDecl)member;
if(decl.getName().equals(setterName) && decl.getParameters().size() == 1) {
index = i;
break;
}
}
}
}
var method = (FunctionDecl)methods.get(index);
if(method.getBody().isEmpty() && !method.hasModifier(Modifiers.ABSTRACT) && method.getParameters().size() == 1) {
var param = method.getParameters().get(0);
if(param.getType() instanceof GenericType && ((GenericType)param.getType()).getName().equals("var")) {
param.setType(fieldType.clone());
}
Block newBody;
if(returnType instanceof VoidType) {
newBody = new Block(new ExpressionStmt(new AssignExpr(new MemberAccess(context.isEmpty() || context.current() == Context.DYNAMIC || typeNames.isEmpty()? new This() : new Variable(typeNames.current()), fieldName), new Variable(param.getName()))));
} else {
newBody = new Block(new ReturnStmt(new AssignExpr(new MemberAccess(context.isEmpty() || context.current() == Context.DYNAMIC || typeNames.isEmpty()? new This() : new Variable(typeNames.current()), fieldName), new Variable(param.getName()))));
}
method.setBody(newBody);
}
for(var member : methods) {
if(member instanceof Modified) {
mergeModifiers((Modified)member, defaultGetterSetterModifiers);
}
}
members.addAll(methods);
}
@Override
public VariableDecl parseVariableDecl(Type type, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeFieldMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var declarators = new ArrayList<VariableDeclarator>();
declarators.add(parseVariableDeclarator(type));
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && !wouldAccept(Tag.NAMED)) {
break;
}
declarators.add(parseVariableDeclarator(type));
}
endStatement();
return new VariableDecl(type, declarators, modifiers, annotations, docComment);
}
protected Expression wrapInNot(Expression expr) {
/*if(expr instanceof TypeTest || expr instanceof BinaryExpr || expr instanceof AssignExpr
|| expr instanceof UnaryExpr || expr instanceof Lambda) {
expr = new ParensExpr(expr);
}*/
if(expr.precedence().isGreaterThan(Precedence.UNARY_AND_CAST)) {
expr = new ParensExpr(expr);
}
return new UnaryExpr(UnaryExpr.Op.NOT, expr);
/*if(expr instanceof UnaryExpr && ((UnaryExpr)expr).getOperation() == UnaryExpr.Op.NOT) {
return ((UnaryExpr)expr).getOperand();
} else {
return new UnaryExpr(UnaryExpr.Op.NOT, expr);
}*/
}
@Override
public void endStatement() {
if(enabled(IMPLICIT_SEMICOLONS) && (wouldAccept(RBRACE.or(ENDMARKER)) || tokens.look(-2).getType() == RBRACE)) {
accept(SEMI);
} else {
requireSemi();
}
}
protected Expression makeQualifier(String fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES)) {
return makeMemberAccess(fullyQualifiedName);
} else {
return new Variable(fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf('.')+1));
}
}
protected Expression makeQualifier(QualifiedName fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES)) {
return makeMemberAccess(fullyQualifiedName);
} else {
return new Variable(fullyQualifiedName.lastName());
}
}
protected QualifiedName makeQualifiedName(QualifiedName fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES)) {
return fullyQualifiedName;
} else {
return fullyQualifiedName.lastName().toQualifiedName();
}
}
protected Expression makeImportedQualifier(String fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES) && !imported(fullyQualifiedName)) {
return makeMemberAccess(fullyQualifiedName);
} else {
if(importedNameOtherThan(fullyQualifiedName)) {
return makeMemberAccess(fullyQualifiedName);
} else {
imports.add(new ImportDecl(QualifiedName(fullyQualifiedName)));
return new Variable(fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf('.')+1));
}
}
}
protected Expression makeImportedQualifier(QualifiedName fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES) && !imported(fullyQualifiedName)) {
return makeMemberAccess(fullyQualifiedName);
} else {
if(importedNameOtherThan(fullyQualifiedName)) {
return makeMemberAccess(fullyQualifiedName);
} else {
imports.add(new ImportDecl(fullyQualifiedName));
return new Variable(fullyQualifiedName.lastName());
}
}
}
protected QualifiedName makeImportedQualifiedName(QualifiedName fullyQualifiedName) {
if(enabled(FULLY_QUALIFIED_NAMES) && !imported(fullyQualifiedName)) {
return fullyQualifiedName;
} else {
if(importedNameOtherThan(fullyQualifiedName)) {
return fullyQualifiedName;
} else {
imports.add(new ImportDecl(fullyQualifiedName));
return fullyQualifiedName.lastName().toQualifiedName();
}
}
}
@Override
public Type parseType(List<Annotation> annotations) {
var base = parseNonArrayType(annotations);
if(wouldAccept(AT.or(LBRACKET))) {
var dimensions = parseDimensions();
base.setAnnotations(emptyList());
Type type = new ArrayType(base, dimensions, annotations);
if(enabled(OPTIONAL_LITERALS) && wouldAccept(QUES)) {
base = type;
var qualifier = makeImportedQualifiedName(QualNames.java_util_Optional);
for(;;) {
while(accept(QUES)) {
type = new GenericType(qualifier, List.of(type));
}
if(wouldAccept(AT.or(LBRACKET))) {
base.setAnnotations(emptyList());
dimensions = parseDimensions();
type = base = new ArrayType(type, dimensions, annotations);
if(!wouldAccept(QUES)) {
break;
}
} else {
break;
}
}
}
return type;
} else {
return base;
}
}
@Override
public Type parseNonArrayType(List<Annotation> annotations) {
if(enabled(OPTIONAL_LITERALS)) {
Type type;
if(accept(INT, QUES)) {
type = new GenericType(makeImportedQualifiedName(QualNames.java_util_OptionalInt), emptyList(), annotations);
} else if(accept(DOUBLE, QUES)) {
type = new GenericType(makeImportedQualifiedName(QualNames.java_util_OptionalDouble), emptyList(), annotations);
} else if(accept(LONG, QUES)) {
type = new GenericType(makeImportedQualifiedName(QualNames.java_util_OptionalLong), emptyList(), annotations);
} else if(wouldAccept(PRIMITIVE_TYPES)) {
var name = token.getString();
nextToken();
return new PrimitiveType(name, annotations);
} else {
type = parseGenericType(annotations);
}
if(wouldAccept(QUES)) {
var qualifier = makeImportedQualifiedName(QualNames.java_util_Optional);
while(accept(QUES)) {
type = new GenericType(qualifier, List.of(type));
}
}
return type;
} else {
return super.parseNonArrayType(annotations);
}
}
@Override
public ReferenceType parseReferenceType(List<Annotation> annotations) {
var base = parseNonArrayType(annotations);
ReferenceType type;
if(base instanceof PrimitiveType) {
base.setAnnotations(emptyList());
var dimension = parseDimension();
var dimensions = parseDimensions();
dimensions.add(0, dimension);
type = new ArrayType(base, dimensions, annotations);
} else if(wouldAccept(AT.or(LBRACKET))) {
var dimensions = parseDimensions();
base.setAnnotations(emptyList());
type = new ArrayType(base, dimensions, annotations);
} else {
type = (GenericType)base;
}
base = type;
if(enabled(OPTIONAL_LITERALS) && wouldAccept(QUES)) {
var qualifier = makeImportedQualifiedName(QualNames.java_util_Optional);
for(;;) {
while(accept(QUES)) {
type = new GenericType(qualifier, List.of(type));
}
if(wouldAccept(AT.or(LBRACKET))) {
base.setAnnotations(emptyList());
var dimensions = parseDimensions();
base = type = new ArrayType(type, dimensions, annotations);
if(!wouldAccept(QUES)) {
break;
}
} else {
break;
}
}
}
return type;
}
protected boolean isMultiVarDecl(Statement stmt) {
if(!(stmt instanceof VariableDecl)) {
return false;
}
var varDecl = (VariableDecl)stmt;
if(varDecl.getDeclarators().size() == 1) {
return false;
}
var type = varDecl.getType();
return type instanceof GenericType && ((GenericType)type).getName().equals(QualNames.var);
}
@Override
public Block parseBlock() {
try(var $1 = preStmts.enter(); var $2 = scope.enter(Scope.NORMAL)) {
require(LBRACE);
var stmts = new ArrayList<Statement>();
while(wouldNotAccept(RBRACE)) {
var stmt = parseBlockStatement();
if(enabled(MULTIPLE_VAR_DECLARATIONS) && isMultiVarDecl(stmt)) {
var varDecl = (VariableDecl)stmt;
for(var declarator : varDecl.getDeclarators()) {
stmts.add(new VariableDecl(varDecl.getType().clone(), declarator, Node.clone(varDecl.getModifiers()), Node.clone(varDecl.getAnnotations()), varDecl.getDocComment()));
}
} else {
stmts.add(stmt);
}
}
require(RBRACE);
return preStmts.apply(new Block(stmts));
}
}
@Override
public Block parseBodyAsBlock() {
if(enabled(IMPLICIT_BLOCKS)) {
var stmt = parseBlockStatement();
if(stmt instanceof Block) {
return (Block)stmt;
} else if(enabled(MULTIPLE_VAR_DECLARATIONS) && isMultiVarDecl(stmt)) {
var varDecl = (VariableDecl)stmt;
return new Block(varDecl.getDeclarators().stream()
.map(declarator -> new VariableDecl(varDecl.getType().clone(), declarator, Node.clone(varDecl.getModifiers()), Node.clone(varDecl.getAnnotations()), varDecl.getDocComment()))
.collect(Collectors.toList()));
} else {
return new Block(stmt);
}
} else {
return parseBlock();
}
}
@Override
public Statement parseBlockStatement() {
switch(token.getType()) {
case PRINT, PRINTLN, PRINTF, PRINTFLN -> {
if(enabled(PRINT_STATEMENT)) {
return parseStatement();
} else {
return super.parseBlockStatement();
}
}
case WITH -> {
if(enabled(WITH_STATEMENT)) {
return parseWithStmt();
} else {
return super.parseBlockStatement();
}
}
default -> {
return super.parseBlockStatement();
}
}
}
@Override
public Statement parseStatement() {
try(var $ = preStmts.enter()) {
switch(token.getType()) {
case WITH -> {
if(enabled(WITH_STATEMENT)) {
return preStmts.apply(parseWithStmt());
}
}
case PRINT -> {
if(enabled(PRINT_STATEMENT)) {
return preStmts.apply(parsePrintStmt());
}
}
case PRINTLN -> {
if(enabled(PRINT_STATEMENT)) {
return preStmts.apply(parsePrintlnStmt());
}
}
case PRINTF -> {
if(enabled(PRINT_STATEMENT)) {
return preStmts.apply(parsePrintfStmt(false));
}
}
case PRINTFLN -> {
if(enabled(PRINT_STATEMENT)) {
return preStmts.apply(parsePrintfStmt(true));
}
}
case EXIT -> {
if(enabled(EXIT_STATEMENT)) {
return preStmts.apply(parseExitStmt());
}
}
default -> {}
}
}
return super.parseStatement();
}
public Statement parsePrintStmt() {
require(PRINT);
var args = parsePrintStmtArgs();
var qualifier = new MemberAccess(makeQualifier(QualNames.java_lang_System), Names.out);
var funcName = Names.print;
switch(args.size()) {
case 0:
return new EmptyStmt();
case 1:
return new ExpressionStmt(new FunctionCall(qualifier, funcName, args));
default:
var stmts = new ArrayList<Statement>();
for(int i = 0; i < args.size(); i++) {
if(i != 0) {
stmts.add(new ExpressionStmt(new FunctionCall(qualifier, funcName, new Literal(' '))));
}
stmts.add(new ExpressionStmt(new FunctionCall(qualifier, funcName, args.get(i))));
}
return new Block(stmts);
}
}
public Statement parsePrintlnStmt() {
require(PRINTLN);
var args = parsePrintStmtArgs();
var qualifier = new MemberAccess(makeQualifier(QualNames.java_lang_System), Names.out);
var funcName = Names.println;
switch(args.size()) {
case 0:
return new EmptyStmt();
case 1:
var arg = args.get(0);
if(arg instanceof ParensExpr) {
arg = ((ParensExpr)arg).getExpression();
}
return new ExpressionStmt(new FunctionCall(qualifier, funcName, arg));
default:
var funcName2 = Names.print;
var stmts = new ArrayList<Statement>();
for(int i = 0; i < args.size(); i++) {
if(i != 0) {
stmts.add(new ExpressionStmt(new FunctionCall(qualifier, funcName2, new Literal(' '))));
}
stmts.add(new ExpressionStmt(new FunctionCall(qualifier, i+1 == args.size()? funcName : funcName2, args.get(i))));
}
return new Block(stmts);
}
}
protected List<Expression> parsePrintStmtArgs() {
if(accept(SEMI)) {
return emptyList();
} else {
var args = new ArrayList<Expression>();
args.add(parseExpression());
if(accept(COMMA)) {
do {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
args.add(parseExpression());
} while(accept(COMMA));
} else if(!wouldAccept(SEMI) && (!enabled(IMPLICIT_SEMICOLONS) || tokens.look(-2).getType() != RBRACE)) {
do {
args.add(parseExpression());
} while(!wouldAccept(SEMI) && (!enabled(IMPLICIT_SEMICOLONS) || tokens.look(-2).getType() != RBRACE));
}
endStatement();
return args;
}
}
public Statement parsePrintfStmt(boolean isPrintfln) {
require(isPrintfln? PRINTFLN : PRINTF);
var qualifier = new MemberAccess(makeQualifier(java_lang_System), Names.out);
var args = new ArrayList<Expression>();
var format = parseExpression();
if(isPrintfln) {
if(!(format instanceof Variable || format instanceof MemberAccess || format instanceof ParensExpr
|| format instanceof Literal || format instanceof ClassLiteral || format instanceof ArrayCreator
|| format instanceof ClassCreator)) {
format = new ParensExpr(format);
}
format = new BinaryExpr(format, BinaryExpr.Op.PLUS, new Literal("%n"));
}
args.add(format);
if(accept(COMMA)) {
do {
if(enabled(TRAILING_COMMAS) && wouldAccept(SEMI)) {
break;
}
args.add(parseExpression());
} while(accept(COMMA));
} else if(!wouldAccept(SEMI) && (!enabled(IMPLICIT_SEMICOLONS) || tokens.look(-2).getType() != RBRACE)) {
do {
args.add(parseExpression());
} while(!wouldAccept(SEMI) && (!enabled(IMPLICIT_SEMICOLONS) || tokens.look(-2).getType() != RBRACE));
}
endStatement();
return new ExpressionStmt(new FunctionCall(qualifier, Names.printf, args));
}
public Statement parseExitStmt() {
require(EXIT);
var qualifier = makeQualifier(QualNames.java_lang_System);
Expression argument;
if(accept(SEMI) || enabled(IMPLICIT_SEMICOLONS) && wouldAccept(RBRACE.or(ENDMARKER))) {
argument = new Literal(0);
} else {
argument = parseExpression();
endStatement();
if(argument instanceof ParensExpr) {
argument = ((ParensExpr)argument).getExpression();
}
}
return new ExpressionStmt(new FunctionCall(qualifier, Names.exit, argument));
}
public Statement parseWithStmt() {
require(WITH);
var resources = new ArrayList<ResourceSpecifier>();
if(enabled(OPTIONAL_STATEMENT_PARENTHESIS) && !wouldAccept(LPAREN)) {
try(var $ = scope.enter(Scope.CONDITION)) {
resources.add(parseWithResource(false, 0));
}
} else {
require(LPAREN);
resources.add(parseWithResource(true, 0));
while(wouldNotAccept(RPAREN)) {
resources.add(parseWithResource(true, resources.size()));
}
require(RPAREN);
}
var body = parseBodyAsBlock();
return new TryStmt(resources, body);
}
public ResourceSpecifier parseWithResource(boolean inParens, int count) {
if(wouldAccept(AT.or(Tag.NAMED).or(Tag.PRIMITIVE_TYPE).or(Tag.LOCAL_VAR_MODIFIER))) {
vardecl:
try(var state = tokens.enter()) {
var modsAndAnnos = parseFinalAndAnnotations();
Type type;
Name name;
try {
type = parseType();
name = parseName();
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
var dimensions = parseDimensions();
require(EQ);
var init = Optional.of(parseInitializer(dimensionCount(type, dimensions)));
if(inParens && !wouldAccept(RPAREN)) {
endStatement();
}
return new VariableDecl(type, name, dimensions, init, modsAndAnnos.mods, modsAndAnnos.annos, Optional.empty());
}
}
var expr = parseExpression();
if(inParens && !wouldAccept(RPAREN)) {
endStatement();
}
if(expr instanceof MemberAccess || expr instanceof Variable) {
return new ExpressionStmt(expr);
} else {
return new VariableDecl(new GenericType(QualNames.var), Name(syntheticName("with" + count, expr)), expr);
}
}
@Override
public IfStmt parseIfStmt() {
require(IF);
Expression condition;
if(enabled(IF_NOT) && !enabled(OPTIONAL_STATEMENT_PARENTHESIS) && accept(BANG)) {
condition = wrapInNot(parseCondition());
} else {
condition = parseCondition();
}
var body = parseBody();
Optional<Statement> elseBody;
if(accept(ELSE)) {
elseBody = Optional.of(parseBody());
} else {
elseBody = Optional.empty();
}
return new IfStmt(condition, body, elseBody);
}
@Override
public WhileStmt parseWhileStmt() {
require(WHILE);
Expression condition;
if(enabled(IF_NOT) && !enabled(OPTIONAL_STATEMENT_PARENTHESIS) && accept(BANG)) {
condition = wrapInNot(parseCondition());
} else {
condition = parseCondition();
}
var body = parseBody();
return new WhileStmt(condition, body);
}
@Override
public DoStmt parseDoStmt() {
require(DO);
var body = parseBody();
require(WHILE);
Expression condition;
if(enabled(IF_NOT) && !enabled(OPTIONAL_STATEMENT_PARENTHESIS) && accept(BANG)) {
condition = wrapInNot(parseCondition());
} else {
condition = parseCondition();
}
endStatement();
return new DoStmt(body, condition);
}
@Override
public Statement parseForStmt() {
require(FOR);
if(enabled(EMPTY_FOR) && wouldAccept(enabled(OPTIONAL_STATEMENT_PARENTHESIS)? LBRACE : not(LPAREN))) {
var body = parseStatement();
return new ForStmt(Optional.empty(), Optional.empty(), emptyList(), body);
} else {
require(LPAREN);
}
final TokenPredicate<JavaTokenType> _COLON, _IN;
if(enabled(FOR_IN)) {
_COLON = _IN = IN.or(COLON);
} else {
_COLON = COLON;
_IN = IN;
}
if(enabled(SIMPLER_FOR) && (wouldAccept(Tag.NAMED, _IN) || enabled(FOR_ENTRIES) && (wouldAccept(Tag.NAMED, COMMA, Tag.NAMED, _IN) || wouldAccept(Tag.NAMED, LPAREN, Tag.NAMED, COMMA, Tag.NAMED, RPAREN, _IN)))) {
Name name = parseName(),
entryName = null;
if(enabled(FOR_ENTRIES) && accept(LPAREN)) {
entryName = name;
name = parseName();
}
FormalParameter param = new FormalParameter(new GenericType(QualNames.var), name),
param2 = null;
if(enabled(FOR_ENTRIES) && accept(COMMA)) {
name = parseName();
param2 = new FormalParameter(new GenericType(QualNames.var), name);
if(entryName != null) {
require(RPAREN);
}
}
require(_IN);
var iterable = parseExpression();
require(RPAREN);
var body = parseStatement();
if(param2 == null) {
return new ForEachStmt(param, iterable, body);
} else {
if(entryName == null) {
entryName = Name(syntheticName("entry", iterable));
}
iterable = new FunctionCall(iterable, Names.entrySet);
var entryDecl = new FormalParameter(new GenericType(QualNames.var), entryName);
var decl1 = new VariableDecl(param.getType(), param.getName(), new FunctionCall(new Variable(entryName), Names.getKey));
var decl2 = new VariableDecl(param2.getType(), param2.getName(), new FunctionCall(new Variable(entryName), Names.getValue));
if(body instanceof Block) {
var stmts = ((Block)body).getStatements();
stmts.add(0, decl1);
stmts.add(1, decl2);
} else {
body = new Block(decl1, decl2, body);
}
return new ForEachStmt(entryDecl, iterable, body);
}
}
boolean mayHaveVariable = wouldAccept(AT.or(Tag.NAMED).or(Tag.PRIMITIVE_TYPE).or(Tag.LOCAL_VAR_MODIFIER));
if(mayHaveVariable) {
foreach:
try(var state = tokens.enter()) {
FormalParameter param, param2 = null, entryDecl = null;
try {
var modsAndAnnos = parseFinalAndAnnotations();
var type = parseType();
var name = parseName();
var dimensions = parseDimensions();
if(enabled(FOR_ENTRIES) && accept(LPAREN)) {
entryDecl = new FormalParameter(type, name, dimensions, modsAndAnnos.mods, modsAndAnnos.annos);
modsAndAnnos = parseFinalAndAnnotations();
type = parseType();
name = parseName();
dimensions = parseDimensions();
if(!wouldAccept(COMMA)) {
require(COMMA);
}
}
param = new FormalParameter(type, name, dimensions, modsAndAnnos.mods, modsAndAnnos.annos);
if(enabled(FOR_ENTRIES) && accept(COMMA)) {
modsAndAnnos = parseFinalAndAnnotations();
type = parseType();
name = parseName();
dimensions = parseDimensions();
param2 = new FormalParameter(type, name, dimensions, modsAndAnnos.mods, modsAndAnnos.annos);
if(entryDecl != null) {
require(RPAREN);
}
}
require(_COLON);
} catch(SyntaxError e) {
state.reset();
break foreach;
}
var iterable = parseExpression();
require(RPAREN);
var body = parseBody();
if(param2 == null) {
return new ForEachStmt(param, iterable, body);
} else {
Name entryName;
if(entryDecl == null) {
entryName = Name(syntheticName("entry", iterable));
entryDecl = new FormalParameter(new GenericType(QualNames.var), entryName);
} else {
entryName = entryDecl.getName();
}
iterable = new FunctionCall(iterable, Names.entrySet);
var decl1 = new VariableDecl(param.getType(), param.getName(), param.getDimensions(), new FunctionCall(new Variable(entryName), Names.getKey), param.getModifiers(), param.getAnnotations());
var decl2 = new VariableDecl(param2.getType(), param2.getName(), param2.getDimensions(), new FunctionCall(new Variable(entryName), Names.getValue), param2.getModifiers(), param2.getAnnotations());
if(body instanceof Block) {
var stmts = ((Block)body).getStatements();
stmts.add(0, decl1);
stmts.add(1, decl2);
} else {
body = new Block(decl1, decl2, body);
}
return new ForEachStmt(entryDecl, iterable, body);
}
}
}
Optional<Either<VariableDecl,ExpressionStmt>> initializer = Optional.empty();
if(mayHaveVariable) {
vardecl:
try(var state = tokens.enter()) {
var modsAndAnnos = parseFinalAndAnnotations();
Type type;
Name name;
ArrayList<Dimension> dimensions;
try {
type = parseType();
name = parseName();
dimensions = parseDimensions();
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
Optional<? extends Initializer> init = parseVariableInitializerOpt(type, dimensions);
var declarators = new ArrayList<VariableDeclarator>();
declarators.add(new VariableDeclarator(name, dimensions, init));
while(accept(COMMA)) {
declarators.add(parseVariableDeclarator(type));
}
endStatement();
initializer = Optional.of(Either.first(new VariableDecl(type, declarators, modsAndAnnos.mods, modsAndAnnos.annos, Optional.empty())));
}
if(initializer.isEmpty()) {
initializer = Optional.of(Either.second(parseExpressionStmt()));
}
} else if(!accept(SEMI)) {
initializer = Optional.of(Either.second(parseExpressionStmt()));
}
Optional<? extends Expression> condition;
if(accept(SEMI)) {
condition = Optional.empty();
} else {
condition = Optional.of(parseExpression());
endStatement();
}
List<? extends Expression> updates;
if(wouldAccept(RPAREN)) {
updates = emptyList();
} else {
updates = listOf(this::parseExpression);
}
require(RPAREN);
var body = parseBody();
return new ForStmt(initializer, condition, updates, body);
}
@Override
public SynchronizedStmt parseSynchronizedStmt() {
if(wouldAccept(SYNCHRONIZED, LBRACE) || enabled(IMPLICIT_BLOCKS) && !enabled(OPTIONAL_STATEMENT_PARENTHESIS) && wouldAccept(SYNCHRONIZED, not(LPAREN)) || wouldAccept(SYNCHRONIZED, Tag.STATEMENT_KW.and(not(Tag.NAMED)))) {
require(SYNCHRONIZED);
var lock = context.current() == Context.STATIC && !typeNames.isEmpty()? new ClassLiteral(new GenericType(typeNames.current().toQualifiedName())) : new This();
var body = parseBodyAsBlock();
return new SynchronizedStmt(lock, body);
} else {
return super.parseSynchronizedStmt();
}
}
@Override
public EmptyStmt parseEmptyStmt() {
if(enabled(EMPTY_STATEMENTS)) {
require(SEMI);
return new EmptyStmt();
} else {
throw syntaxError("Use {} for empty statements");
}
}
@Override
public Statement parseTryStmt() {
require(TRY);
List<ResourceSpecifier> resources;
if(accept(LPAREN)) {
resources = new ArrayList<>();
resources.add(parseResourceSpecifier());
while(wouldNotAccept(RPAREN)) {
endStatement();
if(wouldAccept(RPAREN)) {
break;
}
resources.add(parseResourceSpecifier());
}
require(RPAREN);
} else {
resources = emptyList();
}
var body = parseBodyAsBlock();
var catches = parseCatches();
var lastToken = tokens.look(-2);
if(lastToken.getType() != RBRACE) {
lastToken = null;
}
if(enabled(TRY_ELSE) && wouldAccept(ELSE) && lastToken != null && token.getStart().getLine() == lastToken.getEnd().getLine()) {
elsebody:
try(var state = tokens.enter()) {
require(ELSE);
Block elseBlock;
try {
elseBlock = parseBodyAsBlock();
} catch(SyntaxError e) {
state.reset();
break elsebody;
}
Optional<Block> finallyBody = parseFinally();
var successName = Name(syntheticName("trysuccess", elseBlock));
if(catches.isEmpty()) {
catches.add(new Catch(new FormalParameter(new GenericType(QualifiedName(enabled(FULLY_QUALIFIED_NAMES)? "java.lang.Throwable" : "Throwable")), successName), new Block(new ExpressionStmt(new AssignExpr(new Variable(successName), new Literal(false))))));
} else {
for(var catchClause : catches) {
catchClause.getBody().getStatements().add(0, new ExpressionStmt(new AssignExpr(new Variable(successName), new Literal(false))));
}
}
if(finallyBody.isEmpty()) {
var tryStmt = new TryStmt(resources, body, catches, finallyBody);
return new Block(new VariableDecl(new PrimitiveType(PrimitiveType.BOOLEAN), successName, new Literal(true)), tryStmt, new IfStmt(new Variable(successName), elseBlock));
} else {
var tryStmt = new TryStmt(resources, body, catches, Optional.empty());
var block = new Block(new VariableDecl(new PrimitiveType(PrimitiveType.BOOLEAN), successName, new Literal(true)), tryStmt, new IfStmt(new Variable(successName), elseBlock));
return new TryStmt(block, emptyList(), finallyBody);
//finallyBody = Optional.of(new Block(new TryStmt(emptyList(), new Block(new IfStmt(new Variable(successName), elseBlock)), emptyList(), finallyBody)));
//var tryStmt = new TryStmt(resources, body, catches, finallyBody);
//return new Block(new VariableDecl(new PrimitiveType(PrimitiveType.BOOLEAN), successName, new Literal(true)), tryStmt);
}
}
}
Optional<Block> finallyBody = parseFinally();
if(resources.isEmpty() && catches.isEmpty() && finallyBody.isEmpty()) {
throw syntaxError("expected 'catch' or 'finally' here, got " + token);
}
return new TryStmt(resources, body, catches, finallyBody);
}
@Override
public List<Catch> parseCatches() {
var catches = new ArrayList<Catch>();
while(wouldAccept(CATCH)) {
if(enabled(DEFAULT_CATCH) && wouldAccept(CATCH, not(LPAREN))) {
require(CATCH);
var body = parseBodyAsBlock();
var param = new FormalParameter(new GenericType(QualifiedName(enabled(FULLY_QUALIFIED_NAMES)? "java.lang.Throwable" : "Throwable")), Name(syntheticName("defaultException", body)));
catches.add(new Catch(param, body));
if(wouldAccept(CATCH)) {
throw syntaxError("default catch must be the last catch");
}
break;
} else {
catches.add(parseCatch());
}
}
return catches;
}
@Override
public Statement parseArrowCaseBody() {
if(wouldAccept(THROW)) {
return parseThrowStmt();
} else if(wouldAccept(LBRACE)) {
return parseBlock();
} else {
if(enabled(IMPLICIT_BLOCKS)) {
var stmt = parseStatement();
if(!(stmt instanceof ExpressionStmt)) {
stmt = new Block(stmt);
}
return stmt;
} else if(enabled(BETTER_ARROW_CASE_BODIES)) {
switch(token.getType()) {
case IF, RETURN, TRY, SYNCHRONIZED -> {
return new Block(parseStatement());
}
case WITH -> {
if(enabled(WITH_STATEMENT)) {
try(var $ = preStmts.enter()) {
return preStmts.apply(new Block(parseWithStmt()));
}
}
}
default -> {}
}
}
return parseExpressionStmt();
}
}
@Override
public ReturnStmt parseReturnStmt() {
require(RETURN);
if(accept(SEMI) || enabled(IMPLICIT_SEMICOLONS) && wouldAccept(RBRACE.or(ENDMARKER))) {
return new ReturnStmt();
} else {
var expr = parseExpression();
endStatement();
return new ReturnStmt(expr);
}
}
@Override
public ArrayList<GenericType> parseGenericTypeList() {
var types = new ArrayList<GenericType>();
types.add(parseGenericType());
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && !wouldAccept(Tag.NAMED)) {
break;
}
types.add(parseGenericType());
}
return types;
}
protected Expression makeMemberAccess(String qualifier) {
if(qualifier.indexOf('.') < 0) {
return new Variable(Name(qualifier));
} else {
return makeMemberAccess(QualifiedName(qualifier));
}
}
protected Expression makeMemberAccess(QualifiedName qualifier) {
Expression result = null;
for(var name : qualifier) {
if(result == null) {
result = new Variable(name);
} else {
result = new MemberAccess(result, name);
}
}
return result;
}
@Override
public Initializer parseVariableInitializer(Type type, ArrayList<Dimension> dimensions) {
if(enabled(SIZED_ARRAY_INITIALIZER) && dimensions.isEmpty() && wouldAccept(AT.or(LBRACKET))) {
var sizes = new ArrayList<Size>();
var newdimensions = new ArrayList<Dimension>();
var annotations = parseAnnotations();
require(LBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
if(accept(RBRACKET)) {
newdimensions.add(new Dimension(annotations));
break;
} else {
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
}
}
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET, RBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
newdimensions.add(new Dimension(annotations));
}
Type baseType;
if(type instanceof ArrayType) {
var arrayType = (ArrayType)type;
newdimensions.addAll(0, Node.clone(arrayType.getDimensions()));
baseType = arrayType.getBaseType();
} else {
baseType = type;
}
if(baseType instanceof GenericType) {
var genericType = (GenericType)baseType;
if(!genericType.getTypeArguments().isEmpty()) {
baseType = genericType.clone();
((GenericType)baseType).getTypeArguments().clear();
Type castType;
if(type instanceof ArrayType) {
castType = type.clone();
((GenericType)((ArrayType)castType).getBaseType()).getTypeArguments().clear();
} else {
castType = new ArrayType(genericType);
}
return new CastExpr(castType, new ArrayCreator(baseType, sizes, newdimensions));
}
}
return new ArrayCreator(baseType, sizes, newdimensions);
} else {
require(EQ);
return parseInitializer(dimensionCount(type, dimensions));
}
}
@Override
public Optional<? extends Initializer> parseVariableInitializerOpt(Type type, ArrayList<Dimension> dimensions) {
if(accept(EQ)) {
return Optional.of(parseInitializer(dimensionCount(type, dimensions)));
} else if(enabled(SIZED_ARRAY_INITIALIZER) && dimensions.isEmpty() && wouldAccept(AT.or(LBRACKET))) {
var sizes = new ArrayList<Size>();
var newdimensions = new ArrayList<Dimension>();
var annotations = parseAnnotations();
require(LBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
if(accept(RBRACKET)) {
newdimensions.add(new Dimension(annotations));
break;
} else {
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
}
}
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET, RBRACKET);
dimensions.add(new Dimension(Node.clone(annotations)));
newdimensions.add(new Dimension(annotations));
}
Type baseType;
if(type instanceof ArrayType) {
var arrayType = (ArrayType)type;
newdimensions.addAll(0, Node.clone(arrayType.getDimensions()));
baseType = arrayType.getBaseType();
} else {
baseType = type;
}
if(baseType instanceof GenericType) {
var genericType = (GenericType)baseType;
if(!genericType.getTypeArguments().isEmpty()) {
baseType = genericType.clone();
((GenericType)baseType).getTypeArguments().clear();
Type castType;
if(type instanceof ArrayType) {
castType = type.clone();
((GenericType)((ArrayType)castType).getBaseType()).getTypeArguments().clear();
} else {
castType = new ArrayType(genericType);
}
return Optional.of(new CastExpr(castType, new ArrayCreator(baseType, sizes, newdimensions)));
}
}
return Optional.of(new ArrayCreator(baseType, sizes, newdimensions));
} else {
return Optional.empty();
}
}
@Override
public ArrayList<Dimension> parseDimensions() {
var dimensions = new ArrayList<Dimension>();
while(wouldAccept(AT.or(LBRACKET))) {
if(wouldAccept(AT)) {
try(var state = tokens.enter()) {
var annotations = parseAnnotations();
if(accept(LBRACKET, RBRACKET)) {
dimensions.add(new Dimension(annotations));
} else {
state.reset();
break;
}
}
} else {
if(accept(LBRACKET, RBRACKET)) {
dimensions.add(new Dimension());
} else {
break;
}
}
}
return dimensions;
}
@Override
public Expression parseCondition() {
if(enabled(OPTIONAL_STATEMENT_PARENTHESIS)) {
try(var $ = scope.enter(Scope.CONDITION)) {
return super.parseExpression();
}
} else {
try(var $ = scope.enter(Scope.NORMAL)) {
require(LPAREN);
Expression expr;
expr = parseExpression();
require(RPAREN);
return expr;
}
}
}
@Override
public Expression parseConditionalExpr() {
var expr = parseLogicalOrExpr();
if(enabled(NULL_SAFE_EXPRESSIONS) && acceptPseudoOp(QUES, COLON)) {
var expr2 = parseLambdaOr(this::parseConditionalExpr);
if(isSimple(expr)) {
return new ConditionalExpr(new BinaryExpr(expr.clone(), BinaryExpr.Op.EQUAL, new Literal(/*null*/)), expr2, expr);
} else if(preStmts.isWithinContext() && !functionParameters.isEmpty()) {
var name = Name(syntheticName("nullSafe", expr));
var varDecl = new VariableDecl(new GenericType(QualNames.var), name, new ConditionalExpr(new Literal(false), expr.clone(), new Literal(/*null*/)));
preStmts.append(varDecl);
return new ConditionalExpr(new BinaryExpr(new ParensExpr(new AssignExpr(new Variable(name), expr)), BinaryExpr.Op.EQUAL, new Literal(/*null*/)), expr2, new Variable(name));
} else {
var qualifier = makeImportedQualifier(QualNames.java_util_Objects);
if(isSimple(expr2)) {
return new FunctionCall(qualifier, Names.requireNonNullElse, expr, expr2);
} else {
return new FunctionCall(qualifier, Names.requireNonNullElseGet, expr, new Lambda(emptyList(), expr2));
}
}
}
if(accept(QUES)) {
if(enabled(OPTIONAL_LITERALS)) {
try(var state = tokens.enter()) {
if(accept(LT)) {
var annotations = parseAnnotations();
if(accept(INT, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalInt);
return new FunctionCall(qualifier, Names.of, expr);
} else if(accept(LONG, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalLong);
return new FunctionCall(qualifier, Names.of, expr);
} else if(accept(DOUBLE, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalDouble);
return new FunctionCall(qualifier, Names.of, expr);
} else {
var type = parseTypeArgument(annotations);
require(GT);
var qualifier = makeImportedQualifier(QualNames.java_util_Optional);
boolean hasNonNullAnnotation = false;
for(var annotation : annotations) {
if(annotation.getType().getName().endsWith(Names.NonNull)) {
hasNonNullAnnotation = true;
}
}
return new FunctionCall(qualifier, hasNonNullAnnotation? Names.of : Names.ofNullable, List.of(type), expr);
}
} else if(wouldAccept(RPAREN.or(RBRACE).or(RBRACKET).or(COMMA).or(SEMI))) {
var qualifier = makeImportedQualifier(QualNames.java_util_Optional);
return new FunctionCall(qualifier, Names.ofNullable, expr);
} else {
state.reset();
}
}
}
var truepart = parseExpression();
require(COLON);
var falsepart = parseLambdaOr(this::parseConditionalExpr);
return new ConditionalExpr(expr, truepart, falsepart);
} else {
return expr;
}
}
protected boolean isInvalidDeepEqualsArgument(Expression expr) {
if(expr instanceof Literal) {
var literal = (Literal)expr;
return literal.getValue() == null || literal.getValue().getClass() != String.class;
} else if(expr instanceof ParensExpr) {
return isInvalidDeepEqualsArgument(((ParensExpr)expr).getExpression());
} else {
return expr instanceof ClassLiteral;
}
}
@Override
public Expression parseEqualityExpr() {
var expr = parseRelExpr();
for(;;) {
if(accept(EQEQ)) {
var arg = parseRelExpr();
if(enabled(EQUALITY_OPERATOR) && !isInvalidDeepEqualsArgument(expr) && !isInvalidDeepEqualsArgument(arg)) {
var qualifier = makeImportedQualifier(QualNames.java_util_Objects);
expr = new FunctionCall(qualifier, Names.deepEquals, expr, arg);
} else {
expr = new BinaryExpr(expr, BinaryExpr.Op.EQUAL, arg);
}
} else if(accept(BANGEQ)) {
var arg = parseRelExpr();
if(enabled(EQUALITY_OPERATOR) && !isInvalidDeepEqualsArgument(expr) && !isInvalidDeepEqualsArgument(arg)) {
var qualifier = makeImportedQualifier(QualNames.java_util_Objects);
expr = wrapInNot(new FunctionCall(qualifier, Names.deepEquals, expr, arg));
} else {
expr = new BinaryExpr(expr, BinaryExpr.Op.NEQUAL, arg);
}
} else if(enabled(EQUALITY_OPERATOR) && acceptPseudoOp(IS, BANG)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.NEQUAL, parseRelExpr());
} else if(enabled(EQUALITY_OPERATOR) && accept(IS)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.EQUAL, parseRelExpr());
} else if(enabled(DEEP_EQUALS_OPERATOR) && acceptPseudoOp(QUES, EQ)) {
var arg = parseRelExpr();
if(!isInvalidDeepEqualsArgument(expr) && !isInvalidDeepEqualsArgument(arg)) {
var qualifier = makeImportedQualifier(QualNames.java_util_Objects);
expr = new FunctionCall(qualifier, Names.deepEquals, expr, arg);
} else {
expr = new BinaryExpr(expr, BinaryExpr.Op.EQUAL, arg);
}
} else if(enabled(DEEP_EQUALS_OPERATOR) && acceptPseudoOp(BANG, QUES, EQ)) {
var arg = parseRelExpr();
if(!isInvalidDeepEqualsArgument(expr) && !isInvalidDeepEqualsArgument(arg)) {
var qualifier = makeImportedQualifier(QualNames.java_util_Objects);
expr = wrapInNot(new FunctionCall(qualifier, Names.deepEquals, expr, arg));
} else {
expr = new BinaryExpr(expr, BinaryExpr.Op.NEQUAL, arg);
}
} else {
return expr;
}
}
}
@Override
public Expression parseRelExpr() {
var expr = parseAsExpr();
for(;;) {
if(enabled(COMPARE_TO_OPERATOR) && acceptPseudoOp(LTEQ, GT)) {
var arg = parseAsExpr();
var qualifier1 = makeImportedQualifier(QualNames.java_util_Objects);
var qualifier2 = makeImportedQualifier(QualNames.java_util_Comparator);
expr = new FunctionCall(qualifier1, Names.compare, expr, arg, new FunctionCall(qualifier2, Names.naturalOrder));
} else {
if(accept(LT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.LTHAN, parseAsExpr());
} else if(accept(GT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.GTHAN, parseAsExpr());
} else if(accept(LTEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.LEQUAL, parseAsExpr());
} else if(accept(GTEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.GEQUAL, parseAsExpr());
} else if(accept(INSTANCEOF)) {
var type = parseReferenceType();
if(enabled(VARDECL_EXPRESSIONS) && wouldAccept(Tag.NAMED)) {
var name = parseName();
preStmts.append(new VariableDecl(type.clone(), name));
if(isSimple(expr)) {
expr = new ParensExpr(new BinaryExpr(new TypeTest(expr, type), BinaryExpr.Op.AND, new BinaryExpr(new ParensExpr(new AssignExpr(new Variable(name), new CastExpr(type, expr.clone()))), BinaryExpr.Op.NEQUAL, new Literal(/*null*/))));
} else {
var synthname = Name(syntheticName("typeTest", expr));
preStmts.append(new VariableDecl(new GenericType(makeQualifiedName(QualNames.java_lang_Object)), synthname));
expr = new ParensExpr(new BinaryExpr(new TypeTest(new ParensExpr(new AssignExpr(new Variable(synthname), expr)), type), BinaryExpr.Op.AND, new BinaryExpr(new ParensExpr(new AssignExpr(new Variable(name), new CastExpr(type, new Variable(synthname)))), BinaryExpr.Op.NEQUAL, new Literal(/*null*/))));
}
} else {
expr = new TypeTest(expr, type);
}
} else if(enabled(NOT_INSTANCEOF) && acceptPseudoOp(BANG, INSTANCEOF)) {
expr = wrapInNot(new TypeTest(expr, parseReferenceType()));
}
return expr;
}
}
}
public Expression parseAsExpr() {
var expr = parseShiftExpr();
if(enabled(AS_CAST)) {
while(accept(AS)) {
var type = parseType();
expr = new CastExpr(type, expr);
}
}
return expr;
}
@SuppressWarnings("unchecked")
@Override
public Expression parseParens() {
try(var $ = scope.enter(Scope.NORMAL)) {
require(LPAREN);
Expression expr;
if(enabled(VARDECL_EXPRESSIONS) && wouldAccept(AT.or(Tag.LOCAL_VAR_MODIFIER).or(Tag.NAMED).or(Tag.PRIMITIVE_TYPE))) {
expr = null;
vardecl:
try(var state = tokens.enter()) {
List<Modifier> modifiers;
List<Annotation> annotations;
Type type;
Name name;
ArrayList<Dimension> dimensions;
try {
var modsAndAnnos = parseFinalAndAnnotations();
modifiers = modsAndAnnos.mods;
annotations = modsAndAnnos.annos;
type = parseType();
if(type instanceof GenericType && ((GenericType)type).getName().equals("var")) {
throw syntaxError("'var' not allowed in variable declaration expressions");
}
name = parseName();
dimensions = parseDimensions();
if(!wouldAccept(EQ)) {
state.reset();
break vardecl;
}
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
var declarator = parseVariableDeclarator(type, name, dimensions);
if(preStmts.isWithoutContext()) {
throw syntaxError("variable declaration expressions are not allowed here");
}
var init = declarator.getInitializer().orElseThrow();
Expression value;
if(init instanceof ArrayInitializer) {
Type baseType;
if(type instanceof ArrayType) {
var arrayType = (ArrayType)type;
baseType = arrayType.getBaseType();
dimensions.addAll(0, arrayType.getDimensions());
} else {
baseType = type;
}
value = new ArrayCreator(baseType, (ArrayInitializer<Initializer>)init, dimensions);
} else {
value = (Expression)init;
}
declarator.setInitializer();
preStmts.append(new VariableDecl(type, declarator, modifiers, annotations));
expr = new AssignExpr(new Variable(name), value);
}
if(expr == null) {
expr = parseExpression();
}
} else {
expr = parseExpression();
}
require(RPAREN);
return new ParensExpr(expr);
}
}
@Override
public <T extends AnnotationValue> ArrayInitializer<? extends T> parseArrayInitializer(Supplier<? extends T> elementParser) {
try(var $ = scope.enter(Scope.NORMAL)) {
return super.parseArrayInitializer(elementParser);
}
}
@Override
public List<Expression> parseArguments(boolean classCreatorArguments) {
require(LPAREN);
if(accept(RPAREN)) {
if(!classCreatorArguments && enabled(LAST_LAMBDA_ARGUMENT) && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
return List.of(new Lambda(Either.second(emptyList()), Either.first(parseBlock())));
} else {
return emptyList();
}
} else {
var args = new ArrayList<Expression>();
args.add(parseExpression());
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
args.add(parseExpression());
}
require(RPAREN);
if(!classCreatorArguments && enabled(LAST_LAMBDA_ARGUMENT) && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
args.add(new Lambda(Either.second(emptyList()), Either.first(parseBlock())));
}
return args;
}
}
@Override
public Expression parseArgument() {
if(enabled(ARGUMENT_ANNOTATIONS)) {
accept(NAME, COLON);
}
return super.parseArgument();
}
public String syntheticName(String hint, Object hint2) {
return String.format("__%s$%08x", hint, System.identityHashCode(hint2));
}
@Override
public Expression parseSuffix() {
var expr = parsePrimary();
for(;;) {
if(wouldAccept(COLCOL)) {
expr = parseMethodReferenceRest(expr);
} else if(wouldAccept(DOT)
&& (!wouldAccept(DOT, SUPER.or(THIS)) || wouldAccept(DOT, SUPER.or(THIS), not(LPAREN.or(SEMI))))) {
List<? extends TypeArgument> typeArguments;
if(wouldAccept(DOT, LT)) {
try(var state = tokens.enter()) {
require(DOT);
typeArguments = parseTypeArguments();
if(wouldAccept(SUPER.or(THIS), LPAREN)) {
state.reset();
return expr;
}
}
} else {
require(DOT);
typeArguments = emptyList();
}
expr = parseMemberAccessRest(expr, typeArguments);
} else if(enabled(NULL_SAFE_EXPRESSIONS) && acceptPseudoOp(QUES, DOT)) {
var expr2 = parseMemberAccessRest(expr, parseTypeArgumentsOpt());
if(expr instanceof This) {
expr = expr2;
} else {
if(isSimple(expr)) {
expr = new ParensExpr(new ConditionalExpr(new BinaryExpr(expr.clone(), BinaryExpr.Op.EQUAL, new Literal(/*null*/)), new Literal(/*null*/), expr2));
} else if(preStmts.isWithinContext() && !functionParameters.isEmpty()) {
var name = Name(syntheticName("nullSafeDot", expr));
var varDecl = new VariableDecl(new GenericType(QualNames.var), name, new ConditionalExpr(new Literal(false), new Literal(/*null*/), expr.clone()));
preStmts.append(varDecl);
expr = new ConditionalExpr(new BinaryExpr(new ParensExpr(new AssignExpr(new Variable(name), expr.clone())), BinaryExpr.Op.EQUAL, new Literal(/*null*/)), new Variable(name), expr2);
} else {
var qualifier = makeImportedQualifier(QualNames.java_util_Optional);
var object = new FunctionCall(qualifier, Names.ofNullable, expr.clone());
var name = Name(syntheticName("nullSafeDot", expr));
var result = expr2.clone();
if(result instanceof ClassCreator) {
((ClassCreator)result).setObject(new Variable(name));
} else if(result instanceof FunctionCall) {
((FunctionCall)result).setObject(new Variable(name));
} else {
((MemberAccess)result).setExpression(new Variable(name));
}
var mapped = new FunctionCall(object, Names.map, new Lambda(List.of(new InformalParameter(name)), result));
expr = new FunctionCall(mapped, Names.orElse, new Literal(/*null*/));
}
}
} else if(wouldAccept(LBRACKET)) {
expr = parseIndexRest(expr);
} else if(enabled(OPTIONAL_LITERALS) && wouldAccept(BANG, not(INSTANCEOF)) && !wouldAcceptPseudoOp(BANG, QUES, EQ)) {
nextToken();
if(accept(ELSE)) {
if(accept(THROW)) {
if(wouldAccept(LBRACE)) {
var body = parseBlock();
return new FunctionCall(expr, Names.orElseThrow, new Lambda(emptyList(), body));
} else {
Expression body;
if(wouldAccept(NEW)) {
body = parseClassCreator();
} else if(accept(LPAREN)) {
body = parseExpression();
require(RPAREN);
} else {
body = parseSuffix();
}
return new FunctionCall(expr, Names.orElseThrow, new Lambda(emptyList(), body));
}
} else {
if(wouldAccept(LBRACE)) {
var body = parseBlock();
return new FunctionCall(expr, Names.orElseGet, new Lambda(emptyList(), body));
} else {
Expression body;
if(wouldAccept(NEW)) {
body = parseClassCreator();
} else if(accept(LPAREN)) {
body = parseExpression();
require(RPAREN);
} else {
body = parseSuffix();
}
if(isSimple(body)) {
return new FunctionCall(expr, Names.orElse, body);
} else {
return new FunctionCall(expr, Names.orElseGet, new Lambda(emptyList(), body));
}
}
}
} else {
return new FunctionCall(expr, Names.orElseThrow);
}
} else {
return expr;
}
}
}
protected boolean isSimple(Expression expr) {
while(expr instanceof ParensExpr) {
expr = ((ParensExpr)expr).getExpression();
}
return expr instanceof Literal || expr instanceof ClassLiteral || expr instanceof Variable
|| expr instanceof This || expr instanceof MethodReference || expr instanceof SuperMethodReference;
}
@Override
public Expression parseIndexRest(Expression indexed) {
try(var $ = scope.enter(Scope.NORMAL)) {
return super.parseIndexRest(indexed);
}
}
@Override
public Expression parseExpressionMethodReferenceRest(Expression object, List<? extends TypeArgument> typeArguments, Name name) {
return parseExpressionMethodReferenceRest(Optional.ofNullable(object), typeArguments, name);
}
public Expression parseExpressionMethodReferenceRest(Optional<? extends Expression> object, List<? extends TypeArgument> typeArguments, Name name) {
if(enabled(PARTIAL_METHOD_REFERENCES) && accept(LPAREN)) {
var params = new ArrayList<InformalParameter>();
var args = new ArrayList<Expression>();
if(!wouldAccept(RPAREN)) {
try(var $ = scope.enter(Scope.NORMAL)) {
parsePartialMethodReferenceArgument(params, args);
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
parsePartialMethodReferenceArgument(params, args);
}
}
}
require(RPAREN);
if(enabled(LAST_LAMBDA_ARGUMENT) && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
args.add(new Lambda(Either.second(emptyList()), Either.first(parseBlock())));
}
if(object.isEmpty() && !typeArguments.isEmpty()) {
if(context.isEmpty() || context.current() == Context.DYNAMIC || typeNames.isEmpty()) {
object = Optional.of(new This());
} else {
object = Optional.of(new Variable(typeNames.current()));
}
}
Expression functionCall = new FunctionCall(object, name, typeArguments, args);
return new ParensExpr(new Lambda(Either.second(params), Either.second(functionCall)));
}
if(object.isPresent()) {
return super.parseExpressionMethodReferenceRest(object.get(), typeArguments, name);
} else {
/*if(typeArguments.isEmpty()) {
return new ParensExpr(new Lambda(emptyList(), new FunctionCall(name)));
} else {*/
Expression object2;
if(context.isEmpty() || context.current() == Context.DYNAMIC || typeNames.isEmpty()) {
object2 = new This();
} else {
object2 = new Variable(typeNames.current());
}
return super.parseExpressionMethodReferenceRest(object2, typeArguments, name);
//}
}
}
@Override
public Expression parseTypeMethodReferenceRest(Either<ArrayType,GenericType> type, List<? extends TypeArgument> typeArguments) {
if(enabled(PARTIAL_METHOD_REFERENCES)) {
if(accept(LPAREN)) {
var params = new ArrayList<InformalParameter>();
var args = new ArrayList<Expression>();
var comma = token;
if(!wouldAccept(RPAREN)) {
try(var $ = scope.enter(Scope.NORMAL)) {
parsePartialMethodReferenceArgument(params, args);
comma = token;
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
parsePartialMethodReferenceArgument(params, args);
}
}
}
require(RPAREN);
Expression functionCall;
if(type.isFirst()) {
var arrayType = type.first();
if(args.size() != arrayType.getDimensions().size()) {
if(args.size() == 0 && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
var initializer = parseArrayInitializer(() -> parseInitializer(dimensionCount(arrayType)-1));
functionCall = new ArrayCreator(arrayType.getBaseType(), initializer, arrayType.getDimensions());
} else {
throw new SyntaxError("array[]::new can only accept exactly 1 argument", filename,
comma.getStart().getLine(), comma.getStart().getColumn(), comma.getLine());
}
} else {
functionCall = new ArrayCreator(arrayType.getBaseType(), args.stream().map(Size::new).collect(Collectors.toList()), emptyList());
}
} else {
Optional<List<Member>> members;
if(wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
members = Optional.of(parseClassBody(() -> parseClassMember(false)));
} else {
members = Optional.empty();
}
functionCall = new ClassCreator(typeArguments, type.second(), args, members);
}
return new ParensExpr(new Lambda(Either.second(params), Either.second(functionCall)));
} else if(scope.current() != Scope.CONDITION && wouldAccept(LBRACE) && (type.isFirst() || enabled(OPTIONAL_CONSTRUCTOR_ARGUMENTS))) {
Expression functionCall;
if(type.isFirst()) {
var arrayType = type.first();
var initializer = parseArrayInitializer(() -> parseInitializer(dimensionCount(arrayType)-1));
functionCall = new ArrayCreator(arrayType.getBaseType(), initializer, arrayType.getDimensions());
} else {
var members = Optional.of(parseClassBody(() -> parseClassMember(false)));
functionCall = new ClassCreator(typeArguments, type.second(), emptyList(), members);
}
return new ParensExpr(new Lambda(Either.second(emptyList()), Either.second(functionCall)));
}
}
return super.parseTypeMethodReferenceRest(type, typeArguments);
}
@Override
public Expression parseSuperMethodReferenceRest(Optional<QualifiedName> qualifier, List<? extends TypeArgument> typeArguments, Name name) {
if(enabled(PARTIAL_METHOD_REFERENCES) && accept(LPAREN)) {
var params = new ArrayList<InformalParameter>();
var args = new ArrayList<Expression>();
if(!wouldAccept(RPAREN)) {
try(var $ = scope.enter(Scope.NORMAL)) {
parsePartialMethodReferenceArgument(params, args);
while(accept(COMMA)) {
if(enabled(TRAILING_COMMAS) && wouldAccept(RPAREN)) {
break;
}
parsePartialMethodReferenceArgument(params, args);
}
}
}
require(RPAREN);
if(enabled(LAST_LAMBDA_ARGUMENT) && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
args.add(new Lambda(Either.second(emptyList()), Either.first(parseBlock())));
}
Expression functionCall = new SuperFunctionCall(qualifier, name, typeArguments, args);
return new ParensExpr(new Lambda(Either.second(params), Either.second(functionCall)));
}
return super.parseSuperMethodReferenceRest(qualifier, typeArguments, name);
}
protected void parsePartialMethodReferenceArgument(ArrayList<InformalParameter> params, ArrayList<Expression> args) {
if(accept(UNDERSCORE)) {
var name = Name(syntheticName("arg" + args.size(), args.isEmpty()? args : args.get(args.size()-1)));
params.add(new InformalParameter(name));
args.add(new Variable(name));
} else {
args.add(parseExpression());
}
}
@Override
public Expression parsePrimary() {
return switch(token.getType()) {
case LBRACKET -> parseListLiteral();
case LBRACE -> parseMapOrSetLiteral();
case HASHTAG -> parseParameterLiteral();
case QUES -> parseEmptyOptionalLiteral();
case COLCOL -> {
if(enabled(PARTIAL_METHOD_REFERENCES)) {
nextToken();
var typeArguments = parseTypeArgumentsOpt();
if(accept(NEW)) {
if(typeNames.isEmpty()) {
throw syntaxError("::new not allowed here");
} else {
return parseTypeMethodReferenceRest(Either.second(new GenericType(typeNames.current().toQualifiedName())), typeArguments);
}
} else {
return parseExpressionMethodReferenceRest(Optional.empty(), typeArguments, parseName());
}
} else {
throw syntaxError("invalid start of expression");
}
}
default -> super.parsePrimary();
};
}
public Expression parseEmptyOptionalLiteral() {
if(enabled(OPTIONAL_LITERALS)) {
require(QUES);
if(accept(LT)) {
var annotations = parseAnnotations();
if(accept(INT, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalInt);
return new FunctionCall(qualifier, Names.empty);
} else if(accept(LONG, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalLong);
return new FunctionCall(qualifier, Names.empty);
} else if(accept(DOUBLE, GT)) {
var qualifier = makeImportedQualifier(QualNames.java_util_OptionalDouble);
return new FunctionCall(qualifier, Names.empty);
} else {
var type = parseTypeArgument(annotations);
require(GT);
var qualifier = makeImportedQualifier(QualNames.java_util_Optional);
return new FunctionCall(qualifier, Names.empty, List.of(type));
}
} else {
var qualifier = makeImportedQualifier(QualNames.java_util_Optional);
return new FunctionCall(qualifier, Names.empty);
}
} else {
throw syntaxError("invalid start of expression");
}
}
public Expression parseParameterLiteral() {
if(functionParameters.isEmpty() || !enabled(PARAMETER_LITERALS)) {
throw syntaxError("invalid start of expression");
} else {
require(HASHTAG);
var parameters = functionParameters.current();
if(!wouldAccept(NUMBER) || !token.getString().matches("\\d+(_+\\d+)*")) {
throw syntaxError("Expected argument index after #, got " + token);
}
var argIndex = Integer.parseUnsignedInt(token.getString().replace("_", ""));
if(argIndex == 0 || argIndex > parameters.size()) {
throw syntaxError("Invalid argument index " + argIndex + ", valid indices range from 1 to " + parameters.size());
}
nextToken();
return new Variable(parameters.get(argIndex-1).getName());
}
}
protected boolean hasNumPrefix(String str, String prefix) {
if(str.isEmpty()) {
return false;
}
int start = switch(str.charAt(0)) {
case '+', '-' -> 1;
default -> 0;
};
return str.regionMatches(true, start, prefix, 0, prefix.length());
}
protected String removeNumPrefix(String str, int prefixLen) {
if(str.isEmpty()) {
return str;
}
return switch(str.charAt(0)) {
case '+', '-' -> str.charAt(0) + str.substring(1+prefixLen);
default -> str.substring(prefixLen);
};
}
protected boolean hasNumSuffix(String str, String suffix) {
return str.regionMatches(true, str.length()-suffix.length(), suffix, 0, suffix.length());
}
protected String removeNumSuffix(String str) {
return str.substring(0, str.length()-1);
}
protected String removeNumPrefixAndSuffix(String str, int prefixLen) {
if(str.isEmpty()) {
return str;
}
return switch(str.charAt(0)) {
case '+', '-' -> str.charAt(0) + str.substring(1+prefixLen, str.length()-1);
default -> str.substring(prefixLen, str.length()-1);
};
}
@Override
public Expression parseNumberLiteral() {
var token = this.token;
var str = token.getString();
require(NUMBER);
assert !token.equals(this.token);
try {
str = str.replace("_", "");
if(hasNumSuffix(str, "f")) {
if(hasNumPrefix(str, "0x") && !str.contains(".") && !str.contains("p")
&& !str.contains("P")) {
return new Literal(Integer.parseInt(removeNumPrefix(str, 2), 16), token.getString());
} else if(enabled(MORE_NUMBER_LITERALS) && hasNumPrefix(str, "0b")) {
return new CastExpr(new PrimitiveType(PrimitiveType.FLOAT), new Literal(Integer.parseInt(removeNumPrefixAndSuffix(str, 2), 2), removeNumSuffix(token.getString())));
} else if(enabled(MORE_NUMBER_LITERALS) && hasNumPrefix(str, "0o")) {
return new CastExpr(new PrimitiveType(PrimitiveType.FLOAT), new Literal(Integer.parseInt(removeNumPrefixAndSuffix(str, 2), 8), removeNumSuffix(token.getString())));
}
return new Literal(Float.parseFloat(removeNumSuffix(str)), token.getString());
}
if(hasNumSuffix(str, "D")) {
if(hasNumPrefix(str, "0x") && !str.contains(".") && !str.contains("p")
&& !str.contains("P")) {
return new Literal(Integer.parseInt(removeNumPrefix(str, 2), 16), token.getString());
} else if(enabled(MORE_NUMBER_LITERALS) && hasNumPrefix(str, "0b")) {
return new CastExpr(new PrimitiveType(PrimitiveType.DOUBLE), new Literal(Integer.parseInt(removeNumPrefixAndSuffix(str, 2), 2), removeNumSuffix(token.getString())));
} else if(enabled(MORE_NUMBER_LITERALS) && hasNumPrefix(str, "0o")) {
return new CastExpr(new PrimitiveType(PrimitiveType.DOUBLE), new Literal(Integer.parseInt(removeNumPrefixAndSuffix(str, 2), 2), removeNumSuffix(token.getString())));
}
return new Literal(Double.parseDouble(removeNumSuffix(str)), token.getString());
}
if(str.contains(".")) {
return new Literal(Double.parseDouble(str), token.getString());
}
String repr = token.getString();
int base = 10;
if(hasNumPrefix(str, "0x")) {
base = 16;
str = removeNumPrefix(str, 2);
} else if(hasNumPrefix(str, "0b")) {
base = 2;
str = removeNumPrefix(str, 2);
} else {
if(enabled(MORE_NUMBER_LITERALS)) {
if(hasNumPrefix(str, "0o")) {
base = 8;
str = removeNumPrefix(str, 2);
switch(repr.charAt(0)) {
case '+', '-' -> repr = repr.charAt(0) + "0" + repr.substring(3);
default -> repr = "0" + repr.substring(2);
}
} else if(str.length() > 1 && hasNumPrefix(str, "0")) {
repr = repr.replaceFirst("(?<=^[-+]?)(0(?!$))+", "");
}
} else if(str.length() > 1 && str.startsWith("0")) {
base = 8;
}
}
if(hasNumSuffix(str, "L")) {
return new Literal(Long.parseLong(removeNumSuffix(str), base), token.getString());
} else {
if(enabled(MORE_NUMBER_LITERALS)) {
if(hasNumSuffix(str, "b")) {
return new CastExpr(new PrimitiveType(PrimitiveType.BYTE), new Literal(Byte.parseByte(removeNumSuffix(str), base), removeNumSuffix(repr)));
} else if(hasNumSuffix(str, "s")) {
return new CastExpr(new PrimitiveType(PrimitiveType.SHORT), new Literal(Short.parseShort(removeNumSuffix(str), base), removeNumSuffix(repr)));
} else if(hasNumSuffix(str, "c")) {
int value = Integer.parseInt(removeNumSuffix(str), base);
if(!Character.isValidCodePoint(value)) {
throw new SyntaxError("invalid number literal", filename, token.getStart().getLine(),
token.getStart().getColumn(), token.getLine());
}
return new CastExpr(new PrimitiveType(PrimitiveType.CHAR), new Literal(value, removeNumSuffix(repr)));
}
}
return new Literal(Integer.parseInt(str, base), repr);
}
} catch(NumberFormatException e) {
throw new SyntaxError("invalid number literal", filename, token.getStart().getLine(),
token.getStart().getColumn(), token.getLine());
}
}
protected Expression makeListCall(List<Expression> elements) {
return new FunctionCall(makeImportedQualifier(QualNames.java_util_List), Names.of, elements);
}
protected Expression parseListLiteral() {
if(enabled(COLLECTION_LITERALS)) {
require(LBRACKET);
var elements = new ArrayList<Expression>();
if(!wouldAccept(RBRACKET)) {
try(var $ = scope.enter(Scope.NORMAL)) {
elements.add(parseExpression());
while(accept(COMMA)) {
if(wouldAccept(RBRACKET)) {
break;
}
elements.add(parseExpression());
}
}
}
require(RBRACKET);
return makeListCall(elements);
} else {
throw syntaxError("invalid start of expression");
}
}
protected Expression makeSetCall(List<Expression> elements) {
return new FunctionCall(makeImportedQualifier(QualNames.java_util_Set), Names.of, elements);
}
protected Expression makeMapCall(List<Pair<Expression, Expression>> pairs) {
var qualifier = makeImportedQualifier(QualNames.java_util_Map);
if(pairs.size() <= 10) {
var args = new ArrayList<Expression>(pairs.size()*2);
for(var pair : pairs) {
args.add(pair.getLeft());
args.add(pair.getRight());
}
return new FunctionCall(qualifier, Names.of, args);
} else {
return new FunctionCall(qualifier, Names.ofEntries, pairs.stream().map(pair -> new FunctionCall(qualifier, Names.entry, pair.getLeft(), pair.getRight())).collect(Collectors.toList()));
}
}
protected Expression parseMapOrSetLiteral() {
if(enabled(COLLECTION_LITERALS)) {
require(LBRACE);
if(accept(RBRACE)) {
return makeMapCall(emptyList());
} else {
Expression expr;
try(var $ = scope.enter(Scope.NORMAL)) {
expr = parseExpression();
}
if(accept(COLON)) {
var pairs = new ArrayList<Pair<Expression,Expression>>();
try(var $ = scope.enter(Scope.NORMAL)) {
pairs.add(Pair.of(expr, parseExpression()));
while(accept(COMMA)) {
if(wouldAccept(RBRACE)) {
break;
}
expr = parseExpression();
require(COLON);
pairs.add(Pair.of(expr, parseExpression()));
}
}
require(RBRACE);
return makeMapCall(pairs);
} else {
var elements = new ArrayList<Expression>();
elements.add(expr);
try(var $ = scope.enter(Scope.NORMAL)) {
while(accept(COMMA)) {
if(wouldAccept(RBRACE)) {
break;
}
elements.add(parseExpression());
}
}
require(RBRACE);
return makeSetCall(elements);
}
}
} else {
throw syntaxError("invalid start of expression");
}
}
protected Expression makeFStringExpression(String format, List<Expression> args, boolean isRaw) {
if(args.isEmpty() && format.indexOf('%') == -1) {
try {
return new Literal(isRaw? format : StringEscapeUtils.unescapeJava(format));
} catch(Exception e) {
throw new SyntaxError("invalid string literal", filename, token.getStart().getLine(), token.getStart().getColumn(), token.getLine());
}
} else {
var qualifier = makeQualifier(QualNames.java_lang_String);
try {
args.add(0, new Literal(isRaw? format : StringEscapeUtils.unescapeJava(format)));
} catch(Exception e) {
var error = new SyntaxError("invalid string literal", filename, token.getStart().getLine(), token.getStart().getColumn(), token.getLine());
error.addSuppressed(e);
throw error;
}
return new FunctionCall(qualifier, Names.format, args);
}
}
private static final Pattern formatFlagsRegex = Pattern.compile("^(?<flags>[-+# 0,(]{0,7})([1-9]\\d*)?(\\.\\d+)?([bBhHsScCdoxXeEfgGaA%n]|[tT][HIklMSLNpzZsQBbhAaCYyjmdeRTrDFc])");
private static final Set<Character> formatFlags = Set.of('+', '-', '#', ' ', '0', '(', ',');
private static final Pattern rawStringRegex = Pattern.compile("^[fF]?[rR]");
@Override
public Expression parseStringLiteral() {
var startToken = this.token;
var str = startToken.getString();
require(STRING);
if(enabled(RAW_STRING_LITERALS) && rawStringRegex.matcher(str).find()) {
if(str.startsWith("f") || str.startsWith("F") || "fF".indexOf(str.charAt(1)) >= 0) {
if(enabled(FORMAT_STRINGS)) {
return parseFormatStringLiteral(startToken, str);
} else {
throw syntaxError("invalid string literal", startToken);
}
} else {
if(str.endsWith("\"\"\"")) {
if(enabled(TEXT_BLOCKS)) {
str = str.substring(4, str.length()-3);
} else {
throw syntaxError("invalid string literal", startToken);
}
} else {
str = str.substring(2, str.length()-1);
}
try {
return new Literal(str);
} catch(Exception e) {
throw syntaxError("invalid string literal", startToken);
}
}
} else if(enabled(FORMAT_STRINGS) && (str.startsWith("f") || str.startsWith("F"))) {
return parseFormatStringLiteral(startToken, str);
} else if(enabled(REGEX_LITERALS) && str.startsWith("/")) {
return parseRegexLiteral(startToken, str);
} else {
if(!str.startsWith("\"")) {
throw syntaxError("invalid start of expression");
}
if(str.startsWith("\"\"\"")) {
if(enabled(TEXT_BLOCKS)) {
str = str.substring(3, str.length()-3).replace("\r\n", "\\n").replace("\n", "\\n");
try {
return new Literal(StringEscapeUtils.unescapeJava(str));
} catch(Exception e) {
throw syntaxError("invalid string literal", startToken);
}
} else {
throw syntaxError("invalid string literal", startToken);
}
} else {
str = str.substring(1, str.length()-1);
try {
return new Literal(StringEscapeUtils.unescapeJava(str), startToken.getString());
} catch(Exception e) {
throw syntaxError("invalid string literal", startToken);
}
}
}
}
protected Expression parseRegexLiteral(Token<JavaTokenType> startToken, String str) {
var sb = new StringBuilder();
boolean escape = false;
for(int i = 1; i < str.length() - 1; i++) {
char c = str.charAt(i);
if(escape) {
if(c != '/') {
sb.append('\\');
}
sb.append(c);
escape = false;
} else if(c == '\\') {
escape = true;
} else {
sb.append(c);
}
}
str = sb.toString();
Literal literal;
try {
literal = new Literal(str);
} catch(Exception e) {
throw syntaxError("invalid string literal", startToken);
}
return new FunctionCall(makeImportedQualifier(QualNames.java_util_regex_Pattern), Names.compile, literal);
}
protected Expression parseFormatStringLiteral(Token<JavaTokenType> startToken, String str) {
var args = new ArrayList<Expression>();
String format;
boolean isRaw = "rR".indexOf(str.charAt(1)) >= 0 || str.startsWith("r") || str.startsWith("R");
if(str.endsWith("\"\"\"")) {
if(!enabled(TEXT_BLOCKS)) {
throw syntaxError("invalid string literal", startToken);
}
format = str.substring(isRaw? 5 : 4, str.length()-3).replace("%", "%%").replaceAll("\r?\n", "%n");
} else if(str.endsWith("\"")) {
format = str.substring(isRaw? 3 : 2, str.length()-1).replace("%", "%%");
} else {
assert str.endsWith("%");
//var formatBuilder = new StringBuilder();
var elements = new ArrayList<String>();
boolean isMultiline = str.startsWith("\"\"\"", isRaw? 2 : 1);
if(isMultiline && !enabled(TEXT_BLOCKS)) {
throw syntaxError("invalid string literal", startToken);
}
elements.add(str.substring(isMultiline? isRaw? 5 : 4 : isRaw ? 3 : 2, str.length()-1).replace("%", "%%") + "%");
if(accept(LBRACE)) {
try(var $ = scope.enter(Scope.NORMAL)) {
args.add(parseExpression());
}
require(RBRACE);
elements.add(args.size() + "$");
elements.add(null);
} else {
args.add(new Variable(parseName()));
elements.add(args.size() + "$s");
}
String endStr = isMultiline? "\"\"\"" : "\"";
while(wouldAccept(STRING) && !token.getString().endsWith(endStr) && switch(token.getString().charAt(0)) { case '"' -> token.getString().equals(endStr); case 'r', 'R', 'f', 'F' -> token.getString().length() == 1 || token.getString().charAt(1) != '"'; default -> true; }) {
str = token.getString();
nextToken();
assert str.endsWith("%");
elements.add(str.substring(0, str.length()-1).replace("%", "%%") + "%");
if(accept(LBRACE)) {
try(var $ = scope.enter(Scope.NORMAL)) {
args.add(parseExpression());
}
require(RBRACE);
elements.add(args.size() + "$");
elements.add(null);
} else {
args.add(new Variable(parseName()));
elements.add(args.size() + "$s");
}
}
if(!wouldAccept(STRING) || !token.getString().endsWith("\"") || switch(token.getString().charAt(0)) { case '"' -> !token.getString().equals(endStr); case 'r', 'R', 'f', 'F' -> token.getString().length() == 1 || token.getString().charAt(1) == '"'; default -> false; }) {
throw syntaxError("expected format string end here, got " + token);
}
str = token.getString();
elements.add(str.substring(0, str.length()-endStr.length()).replace("%", "%%"));
nextToken();
var formatBuilder = new StringBuilder();
for(int i = 0; i < elements.size(); i++) {
String element = elements.get(i);
if(element == null) {
var matcher = formatFlagsRegex.matcher(elements.get(i+1));
if(!matcher.find()) {
formatBuilder.append('s');
} else {
String flags = matcher.group("flags");
if(!flags.isEmpty()) {
var remainingFlags = new HashSet<>(formatFlags);
for(int j = 0; j < flags.length(); j++) {
if(!remainingFlags.remove(flags.charAt(j))) {
formatBuilder.append('s');
break;
}
}
}
}
} else {
formatBuilder.append(element);
}
}
format = formatBuilder.toString();
if(isMultiline) {
format = format.replaceAll("\r?\n", "%n");
}
}
return makeFStringExpression(format, args, false);
}
@Override
public Expression parseCreator() {
try(var state = tokens.enter()) {
require(NEW);
if(wouldAccept(LT)) {
var typeArguments = parseTypeArguments();
GenericType type;
if(enabled(OPTIONAL_CONSTRUCTOR_TYPE) && !typeNames.isEmpty() && wouldAccept(LPAREN)) {
List<? extends TypeArgument> typeTypeArguments = emptyList();
if(!typeArguments.isEmpty()) {
if(wouldAccept(LT)) {
if(!wouldAccept(LT, GT)) {
typeTypeArguments = parseTypeArguments();
}
} else {
typeTypeArguments = typeArguments;
typeArguments = emptyList();
}
}
type = new GenericType(typeNames.current().toQualifiedName(), typeTypeArguments);
} else {
type = parseGenericType();
}
return parseClassCreatorRest(typeArguments, type);
}
if(enabled(OPTIONAL_CONSTRUCTOR_TYPE) && !typeNames.isEmpty() && wouldAccept(LPAREN)) {
var type = new GenericType(typeNames.current().toQualifiedName());
return parseClassCreatorRest(emptyList(), type);
}
state.reset();
}
return super.parseCreator();
}
@Override
public ClassCreator parseClassCreator() {
require(NEW);
var typeArguments = parseTypeArgumentsOpt();
GenericType type;
if(enabled(OPTIONAL_CONSTRUCTOR_TYPE) && !typeNames.isEmpty() && wouldAccept(LPAREN)) {
List<? extends TypeArgument> typeTypeArguments = emptyList();
if(!typeArguments.isEmpty()) {
if(wouldAccept(LT)) {
if(!wouldAccept(LT, GT)) {
typeTypeArguments = parseTypeArguments();
}
} else {
typeTypeArguments = typeArguments;
typeArguments = emptyList();
}
}
type = new GenericType(typeNames.current().toQualifiedName(), typeTypeArguments);
} else {
type = parseGenericType();
}
return parseClassCreatorRest(typeArguments, type);
}
@Override
public ClassCreator parseClassCreatorRest(List<? extends TypeArgument> typeArguments, GenericType type) {
boolean hasDiamond = type.getTypeArguments().isEmpty() && accept(LT, GT);
if(enabled(COLLECTION_LITERALS) && wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
Expression arg;
require(LBRACE);
if(accept(RBRACE)) {
arg = makeMapCall(emptyList());
} else {
var expr = parseExpression();
if(accept(COLON)) {
var pairs = new ArrayList<Pair<Expression,Expression>>();
pairs.add(Pair.of(expr, parseExpression()));
while(accept(COMMA)) {
if(wouldAccept(RBRACE)) {
break;
}
expr = parseExpression();
require(COLON);
pairs.add(Pair.of(expr, parseExpression()));
}
require(RBRACE);
arg = makeMapCall(pairs);
} else {
var elements = new ArrayList<Expression>();
elements.add(expr);
while(accept(COMMA)) {
if(wouldAccept(RBRACE)) {
break;
}
elements.add(parseExpression());
}
require(RBRACE);
arg = makeListCall(elements);
}
}
return new ClassCreator(typeArguments, type, hasDiamond, arg);
}
var args = enabled(OPTIONAL_CONSTRUCTOR_ARGUMENTS)? parseArgumentsOpt(true) : parseArguments(true);
Optional<? extends List<Member>> members;
if(wouldAccept(LBRACE) && scope.current() != Scope.CONDITION) {
members = Optional.of(parseClassBody(() -> parseClassMember(false)));
} else {
members = Optional.empty();
}
return new ClassCreator(typeArguments, type, hasDiamond, args, members);
}
}
| 163,401 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
JavaPlusPlusTokenizer.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/parser/JavaPlusPlusTokenizer.java | package jpp.parser;
import static java.lang.Character.*;
import static jpp.parser.JavaPlusPlusParser.Feature.*;
import static jtree.parser.JavaTokenType.*;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import jpp.parser.JavaPlusPlusParser.Feature;
import jtree.parser.JavaTokenType;
import jtree.parser.JavaTokenType.Tag;
import jtree.parser.JavaTokenizer;
import jtree.parser.Position;
import jtree.parser.SyntaxError;
import jtree.parser.Token;
import lombok.NonNull;
public class JavaPlusPlusTokenizer extends JavaTokenizer<JavaTokenType> {
protected JavaTokenType regexType;
protected Token<JavaTokenType> last;
protected int braceDepth;
protected Stack<Scope> scope = new Stack<>();
{
scope.push(Scope.NORMAL);
}
protected final EnumSet<Feature> enabledFeatures, initialEnabledFeatures;
public JavaPlusPlusTokenizer(CharSequence str, String filename) {
this(str, filename, Feature.enabledByDefault());
}
public JavaPlusPlusTokenizer(CharSequence str) {
this(str, Feature.enabledByDefault());
}
public JavaPlusPlusTokenizer(@NonNull CharSequence str, @NonNull String filename, @NonNull EnumSet<Feature> enabledFeatures) {
super(str, filename, ENDMARKER, ERRORTOKEN, STRING, CHARACTER, NUMBER, NAME, COMMENT,
JavaTokenType.NORMAL_TOKENS.stream()
.collect(Collectors.toMap(token -> token.getSymbol().orElseThrow(), token -> token)));
this.regexType = STRING;
this.enabledFeatures = enabledFeatures;
this.initialEnabledFeatures = enabledFeatures.clone();
}
public JavaPlusPlusTokenizer(@NonNull CharSequence str, @NonNull EnumSet<Feature> enabledFeatures) {
super(str, ENDMARKER, ERRORTOKEN, STRING, CHARACTER, NUMBER, NAME, COMMENT,
JavaTokenType.NORMAL_TOKENS.stream()
.collect(Collectors.toMap(token -> token.getSymbol().orElseThrow(), token -> token)));
this.regexType = STRING;
this.enabledFeatures = enabledFeatures;
this.initialEnabledFeatures = enabledFeatures.clone();
}
protected boolean enabled(Feature feature) {
return enabledFeatures.contains(feature);
}
protected void setEnabled(String featureId, boolean enabled) {
if(featureId.equals("*")) {
if(enabled) {
enabledFeatures.addAll(Feature.VALUES);
} else {
enabledFeatures.clear();
}
} else if(featureId.endsWith(".*") && featureId.length() > 2) {
String prefix = featureId.substring(0, featureId.length()-1); // removes the *
boolean found = false;
for(var feature : Feature.VALUES) {
if(feature.id.startsWith(prefix)) {
found = true;
if(enabled) {
enabledFeatures.add(feature);
} else {
enabledFeatures.remove(feature);
}
}
}
if(!found) {
throw new IllegalArgumentException("No feature found matching '" + featureId + "'");
}
} else {
for(var feature : Feature.VALUES) {
if(feature.id.equals(featureId)) {
if(enabled) {
enabledFeatures.add(feature);
} else {
enabledFeatures.remove(feature);
}
return;
}
}
throw new IllegalArgumentException("No feature found matching '" + featureId + "'");
}
}
protected static enum Scope {
NORMAL,
FSTRING_END,
FSTRING_BRACES,
FSTRING_BEGIN(FSTRING_END, FSTRING_BRACES),
RAW_FSTRING_END,
RAW_FSTRING_BRACES,
RAW_FSTRING_BEGIN(RAW_FSTRING_END, RAW_FSTRING_BRACES),
ML_FSTRING_END,
ML_FSTRING_BRACES,
ML_FSTRING_BEGIN(ML_FSTRING_END, ML_FSTRING_BRACES),
RAW_ML_FSTRING_END,
RAW_ML_FSTRING_BRACES,
RAW_ML_FSTRING_BEGIN(RAW_ML_FSTRING_END, RAW_ML_FSTRING_BRACES);
private Supplier<Scope> fstringEndScopeSupplier, fstringBracesScopeSupplier;
Scope() {
this.fstringEndScopeSupplier = this.fstringBracesScopeSupplier = () -> {throw new NoSuchElementException();};
}
Scope(Scope fstringEnd, Scope fstringBraces) {
this.fstringEndScopeSupplier = () -> fstringEnd;
this.fstringBracesScopeSupplier = () -> fstringBraces;
}
public Scope getFStringEndScope() {
return fstringEndScopeSupplier.get();
}
public Scope getFStringBracesScope() {
return fstringBracesScopeSupplier.get();
}
}
protected ArrayList<Pair<Token<JavaTokenType>, String>> importsToBeAdded = new ArrayList<>();
protected Token<JavaTokenType> firstImportNameToken;
protected StringBuilder importNameBuilder;
protected boolean disable;
protected void doFeatureImports() {
boolean enabled = !disable;
for(var pair : importsToBeAdded) {
try {
setEnabled(pair.getRight(), enabled);
} catch(IllegalArgumentException e) {
var token = pair.getLeft();
throw new SyntaxError(e.getMessage(), filename, token.getStart().getLine(), token.getStart().getColumn(), token.getLine());
}
}
importsToBeAdded.clear();
}
protected class States {
protected Consumer<Token<JavaTokenType>> PrePackage = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case PACKAGE -> state = WaitUntilSemiAfterPackage;
case ENABLE -> {
disable = false;
state = ParseName0;
}
case DISABLE -> {
disable = true;
state = ParseName0;
}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "PrePackage";
}
};
protected Consumer<Token<JavaTokenType>> WaitUntilSemiAfterPackage = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case SEMI -> state = TryAcceptEnableDisable;
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "WaitUntilSemiAfterPackage";
}
};
protected Consumer<Token<JavaTokenType>> TryAcceptEnableDisable = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case ENABLE -> {
disable = false;
state = ParseName0;
}
case DISABLE -> {
disable = true;
state = ParseName0;
}
case COMMENT -> {}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "TryAcceptEnableDisable";
}
};
protected Consumer<Token<JavaTokenType>> ParseName0 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
firstImportNameToken = token;
importNameBuilder = new StringBuilder(token.getString());
state = ParseDotName;
} else {
switch(token.getType()) {
case STAR -> {
importsToBeAdded.add(Pair.of(token, "*"));
state = ParsePostStar;
}
case SEMI -> state = TryAcceptEnableDisable;
case COMMENT -> {}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
}
public String toString() {
return "ParseName0";
}
};
protected Consumer<Token<JavaTokenType>> ParseDotName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case DOT -> state = ParseNameRest;
case COMMA -> {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseName1;
}
case SEMI -> {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
doFeatureImports();
state = TryAcceptEnableDisable;
}
case COMMENT -> {}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "";
}
};
protected Consumer<Token<JavaTokenType>> ParseNameRest = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
importNameBuilder.append('.').append(token.getString());
state = ParseDotName;
} else {
switch(token.getType()) {
case SEMI -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
case STAR -> {
importNameBuilder.append(".*");
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseCommaName;
}
case COMMENT -> {}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
}
public String toString() {
return "ParseNameRest";
}
};
protected Consumer<Token<JavaTokenType>> ParseName1 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
firstImportNameToken = token;
importNameBuilder = new StringBuilder(token.getString());
state = ParseDotName;
} else {
switch(token.getType()) {
case SEMI -> {
if(enabled(TRAILING_COMMAS)) {
doFeatureImports();
state = TryAcceptEnableDisable;
} else {
state = Normal;
}
}
case COMMENT -> {}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
}
public String toString() {
return "ParseName1";
}
};
protected Consumer<Token<JavaTokenType>> ParseCommaName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case SEMI -> {
doFeatureImports();
state = TryAcceptEnableDisable;
}
case COMMA -> state = ParseName1;
case COMMENT -> {}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "ParseCommaName";
}
};
protected Consumer<Token<JavaTokenType>> ParsePostStar = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case SEMI -> {
doFeatureImports();
state = TryAcceptEnableDisable;
}
default -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
state = Normal;
}
}
}
public String toString() {
return "ParsePostStar";
}
};
protected Consumer<Token<JavaTokenType>> Normal = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType() == ENDMARKER) {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
}
public String toString() {
return "Normal";
}
};
}
/*protected class States {
protected Consumer<Token<JavaTokenType>> PrePackage = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case PACKAGE -> state = WaitUntilSemiAfterPackage;
case FROM -> state = ParseFromImport_Java;
case IMPORT -> {
disable = false;
state = ParseNormalImport_Java0;
}
case UNIMPORT -> {
disable = true;
state = ParseNormalImport_Java0;
}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {}
}
}
public String toString() {
return "PrePackage";
}
};
protected Consumer<Token<JavaTokenType>> WaitUntilSemiAfterPackage = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case SEMI -> state = TryAcceptImport;
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {}
}
}
public String toString() {
return "WaitUntilSemiAfterPackage";
}
};
protected Consumer<Token<JavaTokenType>> TryAcceptImport = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case FROM -> {
if(enabled(FROM_IMPORTS)) {
state = ParseFromImport_Java;
} else {
state = Normal;
}
}
case IMPORT -> {
disable = false;
state = ParseNormalImport_Java0;
}
case UNIMPORT -> {
disable = true;
state = ParseNormalImport_Java0;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = Normal;
}
}
public String toString() {
return "TryAcceptImport";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_Java = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType() == NAME && token.getString().equals("java")) {
state = ParseFromImport_PlusPlus;
} else {
switch(token.getType()) {
case SEMI -> state = TryAcceptImport;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseFromImport_Java";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_PlusPlus = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case PLUSPLUS -> state = ParseFromImport_Import;
case SEMI -> state = TryAcceptImport;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
public String toString() {
return "ParseFromImport_PlusPlus";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_Import = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case IMPORT -> {
disable = false;
state = ParseFromImport_Name0;
}
case UNIMPORT -> {
disable = true;
state = ParseFromImport_Name0;
}
case SEMI -> state = TryAcceptImport;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
public String toString() {
return "ParseFromImport_Import";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_Name0 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
firstImportNameToken = token;
importNameBuilder = new StringBuilder(token.getString());
state = ParseFromImport_DotName;
} else {
switch(token.getType()) {
case STAR -> {
importsToBeAdded.add(Pair.of(token, "*"));
state = ParseFromImport_CommaName;
}
case SEMI -> state = TryAcceptImport;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseFromImport_Name0";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_DotName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case DOT -> state = ParseFromImport_NameRest;
case COMMA -> {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseFromImport_Name1;
}
case SEMI -> {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
doFeatureImports();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseFromImport_DotName";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_Name1 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
firstImportNameToken = token;
importNameBuilder = new StringBuilder();
state = ParseFromImport_DotName;
} else {
switch(token.getType()) {
case SEMI -> {
if(enabled(TRAILING_COMMAS)) {
doFeatureImports();
state = TryAcceptImport;
} else {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = TryAcceptImport;
}
}
case STAR -> {
importsToBeAdded.add(Pair.of(token, "*"));
state = ParseFromImport_CommaName;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
}
public String toString() {
return "ParseFromImport_Name1";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_NameRest = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
importNameBuilder.append('.').append(token.getString());
state = ParseFromImport_DotName;
} else {
switch(token.getType()) {
case STAR -> {
importNameBuilder.append(".*");
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseFromImport_CommaName;
}
case SEMI -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
}
public String toString() {
return "ParseFromImport_NameRest";
}
};
protected Consumer<Token<JavaTokenType>> ParseFromImport_CommaName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case COMMA -> state = ParseFromImport_Name1;
case SEMI -> {
doFeatureImports();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseFromImport_CommaName";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_Java0 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType() == NAME && token.getString().equals("java")) {
state = ParseNormalImport_PlusPlus;
} else if(token.getType().hasTag(Tag.NAMED)) {
state = ParseRegularImport_DotName;
} else {
switch(token.getType()) {
case SEMI -> state = TryAcceptImport;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseNormalImport_Java0";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_PlusPlus = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case PLUSPLUS -> state = ParseNormalImport_DotName0;
case DOT -> state = ParseRegularImport_Name1;
case SEMI -> {
doFeatureImports();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> state = WaitUntilSemiAfterImport;
}
}
public String toString() {
return "ParseNormalImport_PlusPlus";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_DotName0 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case DOT -> state = ParseNormalImport_Name0;
case SEMI -> {
importsToBeAdded.clear();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseNormalImport_DotName0";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_Name0 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
firstImportNameToken = token;
importNameBuilder = new StringBuilder(token.getString());
state = ParseNormalImport_DotName;
} else {
switch(token.getType()) {
case STAR -> {
importsToBeAdded.add(Pair.of(token, "*"));
state = ParseNormalImport_CommaName;
}
case SEMI -> {
importsToBeAdded.clear();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
}
public String toString() {
return "ParseNormalImport_Name0";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_DotName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case COMMA -> {
if(enabled(COMMA_IMPORTS)) {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseNormalImport_Java1;
} else {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
case SEMI -> {
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
doFeatureImports();
state = TryAcceptImport;
}
case DOT -> state = ParseNormalImport_Name1;
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
firstImportNameToken = null;
importNameBuilder = null;
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseNormalImport_DotName";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_Name1 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
importNameBuilder.append('.').append(token.getString());
state = ParseNormalImport_DotName;
} else {
switch(token.getType()) {
case SEMI -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = TryAcceptImport;
}
case STAR -> {
importNameBuilder.append(".*");
importsToBeAdded.add(Pair.of(firstImportNameToken, importNameBuilder.toString()));
firstImportNameToken = null;
importNameBuilder = null;
state = ParseNormalImport_CommaName;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
firstImportNameToken = null;
importNameBuilder = null;
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
}
public String toString() {
return "ParseNormalImport_Name1";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_CommaName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case COMMA -> {
if(enabled(COMMA_IMPORTS)) {
state = ParseNormalImport_Java1;
} else {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
case SEMI -> {
doFeatureImports();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseNormalImport_CommaName";
}
};
protected Consumer<Token<JavaTokenType>> ParseNormalImport_Java1 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType() == NAME && token.getString().equals("java")) {
state = ParseNormalImport_PlusPlus;
} else if(token.getType().hasTag(Tag.NAMED)) {
state = ParseRegularImport_DotName;
} else {
switch(token.getType()) {
case SEMI -> {
if(enabled(TRAILING_COMMAS)) {
doFeatureImports();
} else {
importsToBeAdded.clear();
}
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = TryAcceptImport;
}
}
}
}
public String toString() {
return "ParseNormalImport_Java1";
}
};
protected Consumer<Token<JavaTokenType>> ParseRegularImport_Name1 = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType().hasTag(Tag.NAMED)) {
state = ParseRegularImport_DotName;
} else {
switch(token.getType()) {
case SEMI -> {
importsToBeAdded.clear();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
}
public String toString() {
return "ParseRegularImport_Name1";
}
};
protected Consumer<Token<JavaTokenType>> ParseRegularImport_DotName = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case DOT -> state = ParseRegularImport_Name1;
case COMMA -> {
if(enabled(COMMA_IMPORTS)) {
state = ParseNormalImport_Java1;
} else {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
case SEMI -> {
doFeatureImports();
state = TryAcceptImport;
}
case COMMENT -> {}
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {
importsToBeAdded.clear();
state = WaitUntilSemiAfterImport;
}
}
}
public String toString() {
return "ParseRegularImport_DotName";
}
};
protected Consumer<Token<JavaTokenType>> WaitUntilSemiAfterImport = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
switch(token.getType()) {
case SEMI -> state = TryAcceptImport;
case ENDMARKER -> {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
default -> {}
}
}
public String toString() {
return "WaitUntilSemiAfterImport";
}
};
protected Consumer<Token<JavaTokenType>> Normal = new Consumer<>() {
public void accept(Token<JavaTokenType> token) {
if(token.getType() == ENDMARKER) {
enabledFeatures.clear();
enabledFeatures.addAll(initialEnabledFeatures);
}
}
public String toString() {
return "Normal";
}
};
}*/
//protected States states = new States();
protected States states = new States();
protected Consumer<Token<JavaTokenType>> state = states.PrePackage;
@Override
public Token<JavaTokenType> next() {
var token = next0();
state.accept(token);
return token;
}
protected Token<JavaTokenType> next0() {
if(pos >= str.length()) {
if(returnedEndmarker) {
throw new NoSuchElementException();
} else {
returnedEndmarker = true;
var start = new Position(line, column);
var end = new Position(line, column);
return last = new Token<>(defaultType, "", start, end, currentLine);
}
}
Scope peeked = scope.peek();
switch(peeked) {
case FSTRING_BEGIN, ML_FSTRING_BEGIN, RAW_FSTRING_BEGIN, RAW_ML_FSTRING_BEGIN -> {
if(Character.isJavaIdentifierStart(ch)) {
scope.pop();
scope.push(peeked.getFStringEndScope());
return defaultNext();
} else if(ch == '{') {
scope.pop();
scope.push(peeked.getFStringBracesScope());
var start = new Position(line, column);
nextChar();
var end = new Position(line, column);
eatWhite();
return new Token<>(tokens.get("{"), "{", start, end, currentLine);
} else {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
}
case FSTRING_BRACES, ML_FSTRING_BRACES, RAW_FSTRING_BRACES, RAW_ML_FSTRING_BRACES -> {
if(ch == '}') {
if(braceDepth == 0) {
scope.pop();
scope.push(peeked.getFStringEndScope());
var start = new Position(line, column);
nextChar();
var end = new Position(line, column);
return new Token<>(tokens.get("}"), "}", start, end, currentLine);
} else {
braceDepth--;
}
} else if(ch == '{') {
braceDepth++;
}
}
case FSTRING_END -> {
Token<JavaTokenType> result = eatFStringRest();
eatWhite();
return result;
}
case ML_FSTRING_END -> {
Token<JavaTokenType> result = eatMultilineFStringRest();
eatWhite();
return result;
}
case RAW_FSTRING_END -> {
Token<JavaTokenType> result = eatRawFStringRest();
eatWhite();
return result;
}
case RAW_ML_FSTRING_END -> {
Token<JavaTokenType> result = eatMultilineRawFStringRest();
eatWhite();
return result;
}
default -> {}
}
Token<JavaTokenType> result = switch(ch) {
case '"' -> eatString();
case '\'' -> eatChar();
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> eatNumber();
case '/' -> eatRegexLiteralOrCommentOrDefault();
case 'r', 'R', 'f', 'F' -> {
if(hasNextString()) {
break eatString();
} else {
break defaultNext();
}
}
case '-', '+' -> {
if(pos + 1 < str.length() && (isDigit(str.charAt(pos+1)) || pos+2 < str.length() && str.charAt(pos+1) == '.' && isDigit(str.charAt(pos+2)))) {
char c = lastNonWhitespaceChar();
if(Character.isWhitespace(c)) {
break eatNumber();
} else {
break switch(c) {
case ')', '}', ']', '.' -> defaultNext();
default -> Character.isJavaIdentifierPart(c)? defaultNext() : eatNumber();
};
}
} else {
break defaultNext();
}
}
default -> defaultNext();
};
eatWhite();
return last = result;
}
@Override
protected Token<JavaTokenType> eatNumber() {
// assert ch == '.' || isDigit(ch);
int startPos = pos;
var start = new Position(line, column);
if(!eat('-')) {
eat('+');
}
if(eat("0x") || eat("0X")) {
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
boolean first = false;
while(isHexDigit(ch)) {
first = true;
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(ch == '.' && (!first || pos+1 < str.length() && isHexDigit(str.charAt(pos+1)))) {
nextChar();
if(!first && !isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isHexDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(eat('p') || eat('P')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
} else {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
} else {
if(!first) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
if(eat('p') || eat('P')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(!(eat('f') || eat('F') || eat('d'))) {
eat('D');
}
} else if(!(eat('l') || eat('L'))) {
if(enabled(MORE_NUMBER_LITERALS)) {
if(!eat('s')) {
eat('S');
}
}
}
}
} else if(eat("0b") || eat("0B")) {
if(!enabled(MORE_NUMBER_LITERALS) || isDigit(ch)) {
do {
if(ch != '1' && ch != '0') {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
} while(isDigit(ch));
if(!(eat('l') || eat('L'))) {
if(enabled(MORE_NUMBER_LITERALS)) {
if(!(eat('f') || eat('F') || eat('d') || eat('D') || eat('s') || eat('S') || eat('c') || eat('C') || eat('b'))) {
eat('B');
}
}
}
}
} else if(enabled(MORE_NUMBER_LITERALS) && (eat("0o") || eat("0O"))) {
do {
if(!isOctalDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
} while(isDigit(ch));
if(!(eat('l') || eat('L') || eat('f') || eat('F') || eat('d') || eat('D') || eat('s') || eat('S') || eat('c') || eat('C') || eat('b'))) {
eat('B');
}
} else {
boolean first = false;
while(isDigit(ch)) {
first = true;
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(ch == '.' && (!first || pos+1 < str.length() && isDigit(str.charAt(pos+1)))) {
nextChar();
if(!first && !isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(eat('e') || eat('E')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
} else if(!(eat('f') || eat('F') || eat('d'))) {
eat('D');
}
} else {
if(!first) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
if(eat('e') || eat('E')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(!(eat('f') || eat('F') || eat('d'))) {
eat('D');
}
} else if(!(eat('F') || eat('d') || eat('D') || eat('l') || eat('L'))) {
if(enabled(MORE_NUMBER_LITERALS)) {
if(!(eat('s') || eat('S') || eat('c') || eat('C') || eat('b'))) {
eat('B');
}
}
}
}
}
var end = new Position(line, column);
return new Token<>(numberType, str.subSequence(startPos, pos).toString(), start, end, currentLine);
}
protected boolean hasNextString() {
switch(ch) {
case 'f', 'F':
if(enabled(FORMAT_STRINGS)) {
int npos = pos+1;
if(npos < str.length()) {
switch(str.charAt(npos)) {
case '"':
return true;
case 'r', 'R':
if(enabled(RAW_STRING_LITERALS)) {
npos++;
return npos < str.length() && str.charAt(npos) == '"';
}
default:
return false;
}
}
} else {
return false;
}
case 'r', 'R':
if(enabled(RAW_STRING_LITERALS)) {
int npos = pos+1;
if(npos < str.length()) {
switch(str.charAt(npos)) {
case '"':
return true;
case 'f', 'F':
if(enabled(FORMAT_STRINGS)) {
npos++;
return npos < str.length() && str.charAt(npos) == '"';
}
default:
return false;
}
}
} else {
return false;
}
case '"':
return true;
default:
return false;
}
}
protected char lastNonWhitespaceChar() {
if(pos == 0) {
return ch;
} else {
int i = pos-1;
while(i > 0 && Character.isWhitespace(str.charAt(i))) {
i--;
}
return str.charAt(i);
}
}
protected Token<JavaTokenType> eatRegexLiteralOrCommentOrDefault() {
boolean valid;
if(enabled(REGEX_LITERALS)) {
char lastChar = lastNonWhitespaceChar();
if(Character.isWhitespace(lastChar)) {
valid = true;
} else {
valid = switch(lastChar) {
case ')', ']', '}', '.' -> false;
default -> !Character.isJavaIdentifierPart(lastChar);
};
}
} else {
valid = false;
}
if(valid) {
if(pos + 1 < str.length() && "/*".indexOf(str.charAt(pos+1)) >= 0) {
return eatCommentOrDefault();
}
int temp = pos;
try {
return eatString('/', regexType);
} catch(SyntaxError e) {
if(e.getMessage().startsWith("unterminated string")) {
setPos(temp);
return eatCommentOrDefault();
} else {
throw e;
}
}
} else {
return eatCommentOrDefault();
}
}
@Override
protected Token<JavaTokenType> eatString() {
if(enabled(RAW_STRING_LITERALS) && (ch == 'r' || ch == 'R')) {
char startChar = ch;
var start = new Position(line, column);
int startPos = pos - column + 1;
nextChar();
var sb = new StringBuilder();
sb.append(startChar);
if(enabled(FORMAT_STRINGS) && (ch == 'f' || ch == 'F')) {
sb.append(ch);
nextChar();
if(!eat('"')) {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
sb.append('"');
if(eat('"')) {
sb.append('"');
if(enabled(TEXT_BLOCKS) && eat('"')) {
sb.append('"');
parseMultilineRawFStringContents(sb);
}
} else {
parseRawFStringContents(sb);
}
} else {
if(!eat('"')) {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
sb.append('"');
if(eat('"')) {
sb.append('"');
if(enabled(TEXT_BLOCKS) && eat('"')) {
sb.append('"');
parseMultilineRawStringContents(sb);
}
} else {
parseRawStringContents(sb);
}
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
} else if(enabled(FORMAT_STRINGS) && (ch == 'f' || ch == 'F')) {
char startChar = ch;
var start = new Position(line, column);
int startPos = pos - column + 1;
nextChar();
var sb = new StringBuilder();
sb.append(startChar);
if(enabled(RAW_STRING_LITERALS) && (ch == 'r' || ch == 'R')) {
sb.append(ch);
nextChar();
if(!eat('"')) {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
sb.append('"');
if(eat('"')) {
sb.append('"');
if(enabled(TEXT_BLOCKS) && eat('"')) {
sb.append('"');
parseMultilineRawFStringContents(sb);
}
} else {
parseRawFStringContents(sb);
}
} else {
if(!eat('"')) {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
sb.append('"');
if(eat('"')) {
sb.append('"');
if(enabled(TEXT_BLOCKS) && eat('"')) {
sb.append('"');
parseMultilineFStringContents(sb);
}
} else {
parseFStringContents(sb);
}
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
} else {
var start = new Position(line, column);
int startPos = pos - column + 1;
var sb = new StringBuilder();
if(!eat('"')) {
throw new SyntaxError("invalid string literal", filename, line, column, currentLine);
}
sb.append('"');
if(eat('"')) {
sb.append('"');
if(enabled(TEXT_BLOCKS) && eat('"')) {
sb.append('"');
parseMultilineStringContents(sb);
}
} else {
parseStringContents(sb);
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
}
protected void parseRawFStringContents(StringBuilder sb) {
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
scope.push(Scope.RAW_FSTRING_BEGIN);
} else {
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
}
}
protected void parseMultilineRawFStringContents(StringBuilder sb) {
int endCounter = 0;
boolean escape = false;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
scope.push(Scope.RAW_ML_FSTRING_BEGIN);
} else {
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
}
}
protected void parseRawStringContents(StringBuilder sb) {
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
}
nextChar();
}
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
}
protected void parseMultilineRawStringContents(StringBuilder sb) {
int endCounter = 0;
boolean escape = false;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
}
}
nextChar();
}
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
}
protected void parseFStringContents(StringBuilder sb) {
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
scope.push(Scope.FSTRING_BEGIN);
} else {
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
}
}
protected void parseMultilineFStringContents(StringBuilder sb) {
int endCounter = 0;
boolean escape = false;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
scope.push(Scope.ML_FSTRING_BEGIN);
} else {
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
}
}
protected void parseStringContents(StringBuilder sb) {
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
}
nextChar();
}
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
}
protected void parseMultilineStringContents(StringBuilder sb) {
int endCounter = 0;
boolean escape = false;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
}
}
nextChar();
}
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
}
protected Token<JavaTokenType> eatFStringRest() {
var start = new Position(line, column);
int startPos = pos - column + 1;
var sb = new StringBuilder();
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
assert scope.peek() == Scope.FSTRING_END;
scope.pop();
scope.push(Scope.FSTRING_BEGIN);
} else {
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
assert scope.peek() == Scope.FSTRING_END;
scope.pop();
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
protected Token<JavaTokenType> eatMultilineFStringRest() {
var start = new Position(line, column);
int startPos = pos - column + 1;
var sb = new StringBuilder();
boolean escape = false;
int endCounter = 0;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
assert scope.peek() == Scope.ML_FSTRING_END;
scope.pop();
scope.push(Scope.ML_FSTRING_BEGIN);
} else {
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
assert scope.peek() == Scope.ML_FSTRING_END;
scope.pop();
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
protected Token<JavaTokenType> eatRawFStringRest() {
var start = new Position(line, column);
int startPos = pos - column + 1;
var sb = new StringBuilder();
boolean escape = false;
while(pos < str.length() && (ch != '"' && ch != '\n' || escape)) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
assert scope.peek() == Scope.RAW_FSTRING_END;
scope.pop();
scope.push(Scope.RAW_FSTRING_BEGIN);
} else {
if(!eat('"')) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append('"');
assert scope.peek() == Scope.RAW_FSTRING_END;
scope.pop();
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
protected Token<JavaTokenType> eatMultilineRawFStringRest() {
var start = new Position(line, column);
int startPos = pos - column + 1;
var sb = new StringBuilder();
boolean escape = false;
int endCounter = 0;
while(pos < str.length() && endCounter < 3) {
if(escape) {
escape = false;
/*if(isWhitespace(ch)) {
nextChar();
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
continue;
} else*/ {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
endCounter = 0;
} else {
sb.append(ch);
if(ch == '"') {
endCounter++;
} else {
endCounter = 0;
if(ch == '%') {
if(pos + 1 < str.length()) {
char next = str.charAt(pos+1);
if(next == '{' || Character.isJavaIdentifierStart(next)) {
break;
}
}
}
}
}
nextChar();
}
if(eat('%')) {
assert ch == '{' || Character.isJavaIdentifierStart(ch);
assert scope.peek() == Scope.RAW_ML_FSTRING_END;
scope.pop();
scope.push(Scope.RAW_ML_FSTRING_BEGIN);
} else {
if(endCounter != 3) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
assert scope.peek() == Scope.RAW_ML_FSTRING_END;
scope.pop();
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(stringType, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
}
| 58,378 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
QualNames.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/parser/QualNames.java | package jpp.parser;
import java.util.HashMap;
import jtree.nodes.QualifiedName;
import lombok.experimental.UtilityClass;
@UtilityClass
public class QualNames {
private static final HashMap<String,QualifiedName> qualNameMap = new HashMap<>();
public static final QualifiedName // @formatter:off
java_util_Optional = QualifiedName("java.util.Optional"),
java_util_OptionalInt = QualifiedName("java.util.OptionalInt"),
java_util_OptionalLong = QualifiedName("java.util.OptionalLong"),
java_util_OptionalDouble = QualifiedName("java.util.OptionalDouble"),
java_lang_System = QualifiedName("java.lang.System"),
java_util_List = QualifiedName("java.util.List"),
java_util_Set = QualifiedName("java.util.Set"),
java_util_Map = QualifiedName("java.util.Map"),
java_lang_String = QualifiedName("java.lang.String"),
java_util_regex_Pattern = QualifiedName("java.util.regex.Pattern"),
var = QualifiedName("var"),
java_util_Objects = QualifiedName("java.util.Objects"),
java_util_Comparator = QualifiedName("java.util.Comparator"),
java_lang_Object = QualifiedName("java.lang.Object");
// @formatter:on
public static QualifiedName QualifiedName(String str) {
return qualNameMap.computeIfAbsent(str, QualifiedName::new);
}
}
| 1,340 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
JPPModifier.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/nodes/JPPModifier.java | package jpp.nodes;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import jtree.nodes.Modifier;
import lombok.Getter;
import lombok.experimental.Accessors;
public class JPPModifier extends Modifier {
public static enum Modifiers implements CharSequence {
PUBLIC,
PRIVATE,
PROTECTED,
PACKAGE,
STATIC, NON_STATIC,
FINAL, NON_FINAL,
TRANSIENT, NON_TRANSIENT,
VOLATILE, NON_VOLATILE,
STRICTFP, NON_STRICTFP,
NATIVE, NON_NATIVE,
SYNCHRONIZED, NON_SYNCHRONIZED,
DEFAULT, NON_DEFAULT,
ABSTRACT, NON_ABSTRACT,
TRANSITIVE;
@Getter @Accessors(fluent = true)
private final String toString = name().toLowerCase().replace('_', '-');
@Override
public int length() {
return toString.length();
}
@Override
public char charAt(int index) {
return toString.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return toString.subSequence(start, end);
}
private static final Map<String, Modifiers> NAME_TO_MODIFIER = Arrays.stream(values()).collect(Collectors.toMap(Modifiers::toString, m -> m));
public static Modifiers fromString(String str) {
var result = NAME_TO_MODIFIER.get(str);
if(result == null) {
throw new IllegalArgumentException("'" + str + "' is not a valid Modifier");
}
return result;
}
}
public JPPModifier(Modifiers value) {
super(value.toString());
}
}
| 1,422 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
EnableDisableStmt.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/nodes/EnableDisableStmt.java | package jpp.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.function.Consumer;
import jtree.nodes.INode;
import jtree.nodes.Node;
import jtree.nodes.QualifiedName;
import jtree.nodes.REPLEntry;
import jtree.nodes.TreeVisitor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@EqualsAndHashCode(callSuper = true)
@Getter @Setter
public class EnableDisableStmt extends Node implements REPLEntry {
protected boolean isDisable;
protected @NonNull List<FeatureId> features;
public EnableDisableStmt(boolean isDisable, List<FeatureId> features) {
setDisable(isDisable);
setFeatures(features);
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitNode(this, parent, cast(replacer))) {
visitList(visitor, getFeatures());
}
}
@Override
public EnableDisableStmt clone() {
return new EnableDisableStmt(isDisable(), clone(getFeatures()));
}
@Override
public String toCode() {
var features = getFeatures();
return (isDisable()? "disable " : "enable ") + (features.isEmpty()? "*" : joinNodes(", ", features)) + ";";
}
public boolean isEnable() {
return !isDisable();
}
public void setFeatures(@NonNull List<FeatureId> features) {
this.features = newList(features);
}
public final void setFeatures(FeatureId... features) {
setFeatures(List.of(features));
}
@EqualsAndHashCode(callSuper = true)
@Getter @Setter
public static class FeatureId extends Node {
protected @NonNull QualifiedName name;
protected boolean wildcard;
public FeatureId(QualifiedName name, boolean wildcard) {
setName(name);
setWildcard(wildcard);
}
@Override
public FeatureId clone() {
return new FeatureId(getName(), isWildcard());
}
@Override
public String toCode() {
return isWildcard()? getName().toCode() + ".*" : getName().toCode();
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitNode(this, parent, cast(replacer))) {
getName().accept(visitor, this, this::setName);
}
}
}
}
| 2,187 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
DefaultFormalParameter.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/nodes/DefaultFormalParameter.java | package jpp.nodes;
import java.util.List;
import java.util.function.Consumer;
import jtree.nodes.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@EqualsAndHashCode(callSuper = true)
@Getter @Setter
public class DefaultFormalParameter extends FormalParameter {
private @NonNull Expression defaultValue;
public DefaultFormalParameter(Type type, Name name, boolean variadic, List<Dimension> dimensions, Expression defaultValue,
List<Modifier> modifiers, List<Annotation> annotations) {
super(type, name, variadic, dimensions, modifiers, annotations);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, boolean variadic, List<Dimension> dimensions, Expression defaultValue) {
super(type, name, variadic, dimensions);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, boolean variadic, Expression defaultValue) {
super(type, name, variadic);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, List<Dimension> dimensions, Expression defaultValue, List<Modifier> modifiers,
List<Annotation> annotations) {
super(type, name, dimensions, modifiers, annotations);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, List<Dimension> dimensions, Expression defaultValue) {
super(type, name, dimensions);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, Expression defaultValue, List<Modifier> modifiers, List<Annotation> annotations) {
super(type, name, modifiers, annotations);
setDefaultValue(defaultValue);
}
public DefaultFormalParameter(Type type, Name name, Expression defaultValue) {
super(type, name);
setDefaultValue(defaultValue);
}
@Override
public DefaultFormalParameter clone() {
return new DefaultFormalParameter(getType().clone(), getName(), isVariadic(), clone(getDimensions()), getDefaultValue().clone(), clone(getModifiers()), clone(getAnnotations()));
}
@Override
public String toCode() {
return super.toCode() + " = " + getDefaultValue().toCode();
}
public FormalParameter toFormalParameter() {
return new FormalParameter(getType().clone(), getName(), isVariadic(), clone(getDimensions()), clone(getModifiers()), clone(getAnnotations()));
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitFormalParameter(this, parent, cast(replacer))) {
getType().accept(visitor, this, this::setType);
getName().accept(visitor, this, this::setName);
visitList(visitor, getDimensions());
getDefaultValue().accept(visitor, this, this::setDefaultValue);
visitList(visitor, getModifiers());
visitList(visitor, getAnnotations());
}
}
}
| 2,844 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
NonVanillaModifierRemover.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/util/NonVanillaModifierRemover.java | package jpp.util;
import java.util.function.Consumer;
import jtree.nodes.AbstractTreeVisitor;
import jtree.nodes.Modifier;
import jtree.nodes.Node;
public class NonVanillaModifierRemover extends AbstractTreeVisitor {
@Override
public boolean visitNode(Node node, Node parent, Consumer<Node> replacer) {
return true;
}
@Override
public boolean visitModifier(Modifier node, Node parent, Consumer<Modifier> replacer) {
if(node.toCode().startsWith("non-") || node.equals("package")) {
replacer.accept(null); // removes it
}
return true;
}
}
| 562 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Tester.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/Java++Parser/src/jpp/util/Tester.java | package jpp.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
import jpp.nodes.EnableDisableStmt;
import jpp.nodes.EnableDisableStmt.FeatureId;
import jpp.parser.JavaPlusPlusParser;
import jpp.parser.JavaPlusPlusParser.Feature;
import jpp.parser.JavaPlusPlusTokenizer;
import jtree.nodes.REPLEntry;
import jtree.parser.JavaParser;
import jtree.parser.JavaTokenType;
import jtree.parser.JavaTokenizer;
public class Tester extends jtree.parser.Tester {
public static void main(String[] args) {
new Tester().run();
}
protected EnumSet<Feature> enabledFeatures = Feature.enabledByDefault();
@Override
protected void dispatchCommand(String command, String[] args) {
switch(command) {
case "enable", "Enable", "ENABLE" -> enable(args);
case "disable", "Disable", "DISABLE" -> disable(args);
case "features", "Features", "FEATURES" -> features(args);
default -> super.dispatchCommand(command, args);
}
}
protected void features(String[] args) {
if(args.length == 0) {
printFeatures();
} else {
System.out.println("Too many arguments to command 'features'");
}
}
protected void printFeatures() {
System.out.println("Features:");
for(var feature : Feature.VALUES.stream().sorted((feature1, feature2) -> feature1.id.compareTo(feature2.id)).collect(Collectors.toList())) {
System.out.println(feature.id);
}
}
protected void enable(String[] args) {
if(args.length == 0) {
if(enabledFeatures.isEmpty()) {
System.out.println("All features are currently disabled");
} else {
System.out.println("Enabled features:");
for(var feature : enabledFeatures.stream().sorted((feature1, feature2) -> feature1.id.compareTo(feature2.id)).collect(Collectors.toList())) {
System.out.println(feature.id);
}
}
} else {
setEnabled(args, true);
}
}
protected void disable(String[] args) {
if(args.length == 0) {
if(enabledFeatures.size() == Feature.VALUES.size()) {
System.out.print("All features are currently enabled");
} else {
System.out.println("Disabled features:");
for(var feature : EnumSet.complementOf(enabledFeatures).stream().sorted((feature1, feature2) -> feature1.id.compareTo(feature2.id)).collect(Collectors.toList())) {
System.out.println(feature.id);
}
}
} else {
setEnabled(args, false);
}
}
protected final void setEnabled(String[] features, boolean enabled) {
setEnabled(Arrays.asList(features), enabled);
}
protected void setEnabled(Collection<String> features, boolean enabled) {
outer:
for(String featureId : features) {
if(featureId.equals("*")) {
if(enabled) {
enabledFeatures.addAll(Feature.VALUES);
System.out.println("Enabled all features");
} else {
enabledFeatures.clear();
System.out.println("Disabled all features");
}
} else if(featureId.endsWith(".*") && featureId.length() > 2) {
String prefix = featureId.substring(0, featureId.length()-1); // removes the *
boolean found = false;
for(var feature : Feature.VALUES) {
if(feature.id.startsWith(prefix)) {
found = true;
if(enabled) {
if(enabledFeatures.add(feature)) {
System.out.println("Enabled " + feature.id);
}
} else {
if(enabledFeatures.remove(feature)) {
System.out.println("Disabled " + feature.id);
}
}
}
}
if(!found) {
System.out.println("No feature found matching '" + featureId + "'");
}
} else {
for(var feature : Feature.VALUES) {
if(feature.id.equals(featureId)) {
if(enabled) {
if(enabledFeatures.add(feature)) {
System.out.println("Enabled " + feature.id);
}
} else {
if(enabledFeatures.remove(feature)) {
System.out.println("Disabled " + feature.id);
}
}
continue outer;
}
}
System.out.println("No feature found matching '" + featureId + "'");
}
}
}
@Override
protected void printJshellEntries(List<REPLEntry> jshellEntries) {
boolean first = true;
for(var elem : jshellEntries) {
if(first) {
first = false;
} else {
System.out.println();
}
if(elem instanceof EnableDisableStmt) {
var stmt = (EnableDisableStmt)elem;
setEnabled(stmt.getFeatures().stream().map(FeatureId::toCode).collect(Collectors.toList()), stmt.isEnable());
} else {
printNodeString(elem);
}
}
}
@Override
protected void printHelp() {
super.printHelp();
System.out.println(
"/enable [<features>]\n"
+ "/disable [<features>]\n"
+ "/features"
);
}
@Override
protected JavaParser createParser(CharSequence text, String filename) {
return new JavaPlusPlusParser(text, filename, enabledFeatures);
}
@Override
@SuppressWarnings("unchecked")
protected Class<? extends JavaParser>[] getParserClasses() {
return new Class[] { JavaParser.class, JavaPlusPlusParser.class };
}
@Override
protected JavaTokenizer<JavaTokenType> createTokenizer(CharSequence text, String filename) {
return new JavaPlusPlusTokenizer(text, filename, enabledFeatures);
}
}
| 5,169 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
IUserDao.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/dao/IUserDao.java | package com.ansel.dao;
import com.ansel.bean.User;
public interface IUserDao {
int insert(User record);
User selectByPrimaryKey(Integer id);
User checkByUserName(String username);
} | 193 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
User.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/bean/User.java | package com.ansel.bean;
import java.io.Serializable;
import javax.validation.constraints.Email;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6551106323558516531L;
@Size(min = 4, max = 20, message = "用户名长度应该在4-20字符之间")
private String username;
@Email
private String email;
@Pattern(regexp = "^[0-9]{3,14}$", message = "密码长度为3-14,仅包含数字")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String email, String password) {
// TODO Auto-generated constructor stub
this.username = username;
this.email = email;
this.password = password;
}
public User() {
// TODO Auto-generated constructor stub
}
@Override
public String toString()
{
return "[user: " + username + "]";
}
}
| 1,279 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
Login.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/controller/Login.java | package com.ansel.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ansel.bean.User;
import com.ansel.service.IUserService;
@Controller
public class Login {
@Resource
private IUserService userService;
@RequestMapping(value = "/login")
public ModelAndView UserLogin(Model model, HttpServletRequest request, HttpServletResponse response)
throws IOException {
ModelAndView mv = new ModelAndView();
String username = String.valueOf(request.getParameter("username"));
String password = String.valueOf(request.getParameter("password"));
User user = this.userService.checkUser(username);
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
if (user == null) {
// 该用户不存在
request.setAttribute("username", username);
out.println("<script language='javascript'>");
out.println("alert('该用户不存在!')");
out.println("</script>");
out.flush();
mv.setViewName("login");
} else if (user.getPassword().equals(password)) {
// 该用户存在且用户名和密码匹配
mv.setViewName("login_success");
} else {
// 用户名或密码错误
request.setAttribute("username", username);
out.println("<script language='javascript'>");
out.println("alert('用户名或密码不正确!')");
out.println("</script>");
out.flush();
mv.setViewName("login");
}
return mv;
}
}
| 1,757 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
Register.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/controller/Register.java | package com.ansel.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ansel.bean.User;
import com.ansel.service.IUserService;
@Controller
public class Register {
@Resource
private IUserService userService;
@RequestMapping(value = "/register")
public ModelAndView UserRegister() {
ModelAndView mv = new ModelAndView();
mv.addObject("user", new User());
mv.setViewName("register");
return mv;
}
@RequestMapping("/verify")
public ModelAndView processUser(HttpServletRequest request, HttpServletResponse response, @Valid User user,
BindingResult result) throws IOException {
ModelAndView mv = new ModelAndView();
mv.addObject("user", user);
if (result.hasErrors()) {
// 表单验证有误
mv.setViewName("register");
} else {
String username = request.getParameter("username");
String email = request.getParameter("email");
String password = request.getParameter("password");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
if (this.userService.checkUser(username) != null) {
// 用户名存在
out.println("<script language='javascript'>");
out.println("alert('用户名存在!')");
out.println("</script>");
out.flush();
mv = new ModelAndView("forward:/register");
} else {
// 插入成功
User newUser = new User(username, email, password);
this.userService.insertNewUser(newUser);
mv.setViewName("register_success");
}
}
return mv;
}
}
| 1,893 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
IUserService.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/service/IUserService.java | package com.ansel.service;
import com.ansel.bean.User;
public interface IUserService {
public User checkUser(String username);
public int insertNewUser(User user);
}
| 177 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
UserServiceImpl.java | /FileExtraction/Java_unseen/anselleeyy_SSM-Login/src/main/java/com/ansel/service/impl/UserServiceImpl.java | package com.ansel.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ansel.bean.User;
import com.ansel.dao.IUserDao;
import com.ansel.service.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
@Override
public User checkUser(String username) {
// TODO Auto-generated method stub
return this.userDao.checkByUserName(username);
}
@Override
public int insertNewUser(User user) {
// TODO Auto-generated method stub
return this.userDao.insert(user);
}
} | 606 | Java | .java | anselleeyy/SSM-Login | 16 | 3 | 0 | 2017-10-16T10:44:10Z | 2018-02-06T08:05:20Z |
CsvDictionaryTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/utils/CsvDictionaryTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.utils;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.supercsv.io.CsvListWriter;
import org.supercsv.prefs.CsvPreference;
public class CsvDictionaryTest {
@Test
public void test() throws IOException, TransformationException {
File tempDir = Files.createTempDirectory("CsvDictionaryTest").toFile();
tempDir.createNewFile();
File dictFile = new File(tempDir, "dictFile.txt");
CsvPreference customCsvPref = new CsvPreference.Builder('"', '\t', "\n").build();
try (CsvListWriter writer = new CsvListWriter(new OutputStreamWriter(new FileOutputStream(dictFile.toString()), "UTF-8"), customCsvPref)) {
writer.write(new String[] {"a", "b"});
writer.write(new String[] {"c", "d"});
}
CsvDictionary dict = new CsvDictionary();
dict.setFilePath(dictFile.toString());
dict.setFileDelimiter("\t");
dict.afterPropertiesSet();
DictionaryTransformer transformer = new DictionaryTransformer();
transformer.setDictionary(dict);
assertEquals("b", transformer.transform("a"));
assertEquals("b", transformer.transform("b"));
assertEquals("d", transformer.transform("c"));
assertEquals("d", transformer.transform("d"));
assertEquals("e", transformer.transform("e"));
}
}
| 2,261 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NumberInRangeMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/NumberInRangeMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NumberInRangeMatcherTest {
@Test
public void testMatches() throws Exception {
NumberInRangeMatcher matcher = new NumberInRangeMatcher();
assertTrue(matcher.matches("32", "32"));
assertTrue(matcher.matches("32", "12 32"));
assertTrue(matcher.matches("32", "32 9"));
assertTrue(matcher.matches("32", "12 32-33 89"));
assertTrue(matcher.matches("32", "12 31-32 89"));
assertTrue(matcher.matches("32", "12 31-33 89"));
assertTrue(matcher.matches("32", "12-18 30-35 45-90"));
assertTrue(matcher.matches("1854", "Vols. 1-7, 1848-1868 etc."));
assertFalse(matcher.matches("29", "32"));
assertFalse(matcher.matches("29", "12 32"));
assertFalse(matcher.matches("29", "32 9"));
assertFalse(matcher.matches("29", "12 32-33 89"));
assertFalse(matcher.matches("29", "12 31-32 89"));
assertFalse(matcher.matches("29", "12 31-33 89"));
assertFalse(matcher.matches("29", "12-18 30-35 45-90"));
assertFalse(matcher.matches("1829", "Vols. 1-7, 1848-1868 etc."));
assertTrue(matcher.matches("32", "12 32/33 89"));
assertTrue(matcher.matches("33", "12 32/33 89"));
assertTrue(matcher.matches("32", "12 31-3 89"));
assertTrue(matcher.matches("1332", "12 1331-3 89"));
assertTrue(matcher.matches("1332", "12 1331-33 89"));
assertTrue(matcher.matches("1332", "12 1331-333 89"));
assertFalse(matcher.matches("33", "12 32/34 89"));
assertTrue(matcher.matches("31", "88 12+ 32/33 89"));
assertTrue(matcher.matches("1888", "88 12+ 1832+ 89"));
}
}
| 2,389 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LevenshteinMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/LevenshteinMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import org.kew.rmf.utils.Dictionary;
public class LevenshteinMatcherTest {
private Dictionary dict = new TestDictionary();
public class TestDictionary extends HashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("hinz", "kunz");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test
public void test() throws MatchException {
LevenshteinMatcher matcher = new LevenshteinMatcher();
matcher.setMaxDistance(2);
assertTrue(matcher.matches("hallo", "haaallo"));
matcher.setMaxDistance(1);
assertFalse(matcher.matches("hallo", "haaallo"));
}
@Test
public void testFalsePositives() throws IOException, MatchException {
LevenshteinMatcher matcher = new LevenshteinMatcher();
matcher.setMaxDistance(3);
assertTrue(matcher.matches("hinz", "kunz"));
matcher.setDictionary(dict);
assertFalse(matcher.matches("hinz", "kunz"));
}
@Test
public void blankMatchesBlank() throws MatchException {
LevenshteinMatcher matcher = new LevenshteinMatcher();
assertTrue(matcher.matches("", ""));
}
}
| 2,197 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NumberMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/NumberMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NumberMatcherTest {
@Test
public void testMatchesExactly () throws Exception {
NumberMatcher matcher = new NumberMatcher();
assertTrue(matcher.matches("Abraham Lincoln came 1834 to Ealing, 4 times in a row, riding 23 horses",
"Abraham Lincoln came 1934 to Ealing, 4 times in a row, riding 23 horses"));
// Also true would be:
assertTrue(matcher.matches("Abraham Lincoln came 1834 to Ealing, 4 times in a row",
"1834 was the year of the goose in Chinese calendar. 4 geese where beatified."));
}
@Test
public void noNumbersButRestMatchesExactly () throws Exception {
NumberMatcher matcher = new NumberMatcher();
assertTrue(matcher.matches("No numbers at all here!", "No numbers at all here!"));
}
@Test
public void noNumbersButRestMatchesNotExactly () throws Exception {
NumberMatcher matcher = new NumberMatcher();
assertFalse(matcher.matches("No numbers at all here!", "No numbers at all here neither!"));
}
@Test
public void testMatchesWhitespaceTest () throws Exception {
NumberMatcher matcher = new NumberMatcher();
assertFalse(matcher.matches("123", "1 2 3"));
assertTrue(matcher.matches("1a2b3", "1 2 3"));
}
@Test
public void testChangeMinRatio () throws Exception {
NumberMatcher matcher = new NumberMatcher();
// minRatio expected to be (1)/1+(1+2) == 0.25, which is below the allowed limit (default==0.5)
assertFalse(matcher.matches("1 23", "1 2 3"));
matcher.setMinRatio(0.25);
assertTrue(matcher.matches("1 23", "1 2 3"));
}
}
| 2,405 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
AuthorCommonTokensMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/AuthorCommonTokensMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AuthorCommonTokensMatcherTest {
@Test
public void testMatchesExactly () throws Exception {
AuthorCommonTokensMatcher matcher = new AuthorCommonTokensMatcher();
assertTrue(matcher.matches("Hans D.", "Hans D."));
}
@Test
public void testMatchesWithpunctuation () throws Exception {
AuthorCommonTokensMatcher matcher = new AuthorCommonTokensMatcher();
assertFalse(matcher.matches("Hans Delafontaine", "Hans De-la-fointaine"));
}
@Test
public void testMatchesWithDiacrits () throws Exception {
AuthorCommonTokensMatcher matcher = new AuthorCommonTokensMatcher();
assertTrue(matcher.matches("Jaques Leblée", "Jaques Leblee"));
}
}
| 1,559 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CapitalLettersMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/CapitalLettersMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CapitalLettersMatcherTest {
@Test
public void testMatchesExactly () throws Exception {
CapitalLettersMatcher matcher = new CapitalLettersMatcher();
matcher.setMinRatio(1);
assertTrue(matcher.matches("Abraham Lincoln came to Ealing", "Abraham Lincoln came to Ealing"));
// Also true would be:
assertTrue(matcher.matches("Abraham Lincoln came to Ealing", "After Laughter comes the End"));
}
@Test
public void testSameWordsDifferentCapitals () throws Exception {
CapitalLettersMatcher matcher = new CapitalLettersMatcher();
assertTrue(matcher.matches("My horse has MANY big teeth!", "My horse has many big teeth!"));
matcher.setDelimiter("");
assertFalse(matcher.matches("My horse has MANY big teeth!", "My horse has many big teeth!"));
assertTrue(matcher.matches("A A A A B C", "A A A A D E"));
matcher.setDeduplicateTokens(true);
assertFalse(matcher.matches("A A A A B C", "A A A A D E"));
}
@Test
public void testHm () throws Exception {
CapitalLettersMatcher matcher = new CapitalLettersMatcher();
assertTrue(matcher.matches("AbCdEEfG", "Ab Cd Eef G"));
matcher.setMinRatio(1);
assertFalse(matcher.matches("AbCdEEfG", "Ab Cd Eef G"));
}
@Test
public void testAboutDots() throws Exception {
CapitalLettersMatcher matcher = new CapitalLettersMatcher();
assertFalse(matcher.matches("USA", "U.S.A"));
matcher.setDelimiter("");
assertTrue(matcher.matches("USA", "U.S.A"));
}
}
| 2,338 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
ExactMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/ExactMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
public class ExactMatcherTest {
@Test
public void testNullMatches() {
ExactMatcher matcher = new ExactMatcher();
matcher.setNullToBlank(false);
try {
matcher.matches(null, null);
fail("Expected NPE");
}
catch (NullPointerException e) {
}
catch (Exception e) {
fail("Unexpected exception "+e);
}
matcher.setNullToBlank(true);
try {
assertTrue(matcher.matches(null, null));
assertTrue(matcher.matches("", null));
assertTrue(matcher.matches(null, ""));
}
catch (Exception e) {
fail("Unexpected exception "+e);
}
}
@Test
public void testBlankMatches() {
ExactMatcher matcher = new ExactMatcher();
assertTrue(matcher.matches("", ""));
assertFalse(matcher.matches("", "x"));
assertFalse(matcher.matches("x", ""));
}
@Test
public void testStringMatches() {
ExactMatcher matcher = new ExactMatcher();
assertTrue(matcher.matches("one", "one"));
}
@Test
public void testStringCaseMatches() {
ExactMatcher matcher = new ExactMatcher();
assertFalse(matcher.matches("one", "One"));
}
@Test
public void testStringTrimMatches() {
ExactMatcher matcher = new ExactMatcher();
assertFalse(matcher.matches("one", "one "));
}
@Test
public void testStringWithWhitespaces () {
ExactMatcher matcher = new ExactMatcher();
assertTrue(matcher.matches("hello kitty", "hello kitty"));
}
}
| 2,288 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
IntegerMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/IntegerMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IntegerMatcherTest {
@Test
public void test() {
IntegerMatcher matcher = new IntegerMatcher();
assertTrue(matcher.matches("10", "15"));
assertFalse(matcher.matches("10", "16"));
matcher.setMaxDiff(6);
assertTrue(matcher.matches("10", "16"));
}
}
| 1,168 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
AlwaysMatchingMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/AlwaysMatchingMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AlwaysMatchingMatcherTest {
@Test
public void testNullMatches() throws Exception {
Matcher matcher = new AlwaysMatchingMatcher();
assertTrue(matcher.matches(null, null));
}
public void testBlankMatches() throws Exception {
Matcher matcher = new AlwaysMatchingMatcher();
assertTrue(matcher.matches("", ""));
}
public void testNullBlankMatches() throws Exception {
Matcher matcher = new AlwaysMatchingMatcher();
assertTrue(matcher.matches("", null));
}
public void testStringMatches() throws Exception {
Matcher matcher = new AlwaysMatchingMatcher();
assertTrue(matcher.matches("one", "two"));
}
} | 1,488 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CommonTokensMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/CommonTokensMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CommonTokensMatcherTest {
@Test
public void testMatchesExactly() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
assertTrue("Exact match", matcher.matches("abc 123!", "abc 123!"));
}
@Test
public void testCommonTokens() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
// default acceptance is a ratio of 0.5
assertTrue("Common tokens", matcher.matches("first sec third", "first sec diff"));
assertTrue("Common tokens", matcher.matches("first sec third", "diff first sec"));
assertFalse("Common tokens", matcher.matches("first sec third", "first diff diff"));
matcher.setMinRatio(0.2);
assertTrue("Common tokens", matcher.matches("first sec third", "first diff diff"));
}
@Test
public void testDelimiter() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
assertFalse("Delimiter", matcher.matches("USA", "U.S.A."));
matcher.setDelimiter("");
assertTrue("Delimiter", matcher.matches("USA", "U.S.A."));
assertTrue("Delimiter", matcher.matches("abc", "abcd"));
}
@Test
public void testVaryingTokenNumbers() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
matcher.setMinRatio(1);
assertTrue("Varying token numbers 1", matcher.matches("a b c", "a b c"));
matcher.setMinRatio(0.5);
// ratio == 1 still matches
assertTrue("Varying token numbers 2", matcher.matches("a b c", "a b c"));
assertTrue("Varying token numbers 3", matcher.matches("a b", "a b c")); // 5 tokens, 4 common, ratio = ⅘
assertTrue("Varying token numbers 4", matcher.matches("a", "a b c")); // 4 tokens, 2 common, ratio = ½
assertTrue("Varying token numbers 5", matcher.matches("a b c", "a b")); // 5 tokens, 4 common, ratio = ⅘
assertTrue("Varying token numbers 6", matcher.matches("a b d", "a b c")); // 6 tokens, 4 common, ratio = ⅔
assertTrue("Varying token numbers 7", matcher.matches("a b c", "a b d")); // 6 tokens, 4 common, ratio = ⅔
assertTrue("Varying token numbers 8", matcher.matches("a b d e", "a b c")); // 7 tokens, 4 common, ratio = ⁴⁄₇
assertTrue("Varying token numbers 9", matcher.matches("a b c", "a b d e")); // 7 tokens, 4 common, ratio = ⁴⁄₇
// The total number of tokens (for the denominator of the ratio) is the sum of the number of tokens on each side.
matcher.setMinRatio(0.2500000001);
assertFalse("Varying token numbers 10", matcher.matches("a b", "a b c d e f g h i j k l m n")); // 16 tokens, 4 common, ratio = ¼
assertFalse("Varying token numbers 11", matcher.matches("a b c d e f g h i j k l m n", "a b")); // 16 tokens, 4 common, ratio = ¼
matcher.setMinRatio(0.25);
assertTrue("Varying token numbers 12", matcher.matches("a b", "a b c d e f g h i j k l m n")); // 16 tokens, 4 common, ratio = ¼
assertTrue("Varying token numbers 13", matcher.matches("a b c d e f g h i j k l m n", "a b")); // 16 tokens, 4 common, ratio = ¼
}
@Test
public void testDuplicateTokens() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
// Default is that duplicate tokens must each be matched
matcher.setMinRatio(0.4);
assertTrue("Duplicate tokens 1", matcher.matches("a a", "a b c")); // 5 tokens, 2 are common, ratio = ⅖
assertFalse("Duplicate tokens 2", matcher.matches("a a", "a b c d")); // 6 tokens, 2 are common, ratio = ⅓
assertTrue("Duplicate tokens 3", matcher.matches("a a", "a a c d")); // 6 tokens, 4 are common, ratio = ⅔
// Tokens can be deduplicated within each side first
matcher.setDeduplicateTokens(true);
assertTrue("Deduplicate tokens 1", matcher.matches("a a", "a b c")); // 1+3 unique tokens, 2 are common, ratio = ½
assertTrue("Deduplicate tokens 2", matcher.matches("c c", "a b c d")); // 1+4 unique tokens, 2 are common, ratio = ⅖
assertTrue("Deduplicate tokens 3", matcher.matches("e e", "c e e d")); // 1+3 unique tokens, 2 are common, ratio = ½
assertFalse("Deduplicate tokens 4", matcher.matches("b a b a", "d d c c a a a a x x x x x x x x")); // 2+4 unique tokens, 2 are common, ratio = ⅓
assertTrue("Deduplicate tokens 5", matcher.matches("b a b a", "d d c c b a a a x x x x x x x x")); // 2+5 unique tokens, 4 are common, ratio = ⁴⁄₇
}
@Test
public void testIgnoreEmptyTokens() {
CommonTokensMatcher matcher = new CommonTokensMatcher();
matcher.setMinRatio(0.3);
// Extra tokens from double spaces should be ignored
assertTrue("Ignore empty tokens 1", matcher.matches("J Str Bra Roy Asi Soc", "J Str Bra Roy Asi Soc")); // 6+6 tokens, 6+6 are common, ratio 1
assertFalse("Ignore empty tokens 2", matcher.matches("J Bot", "J Str Bra Roy Asi Soc")); // 2+6 tokens, 2 are common, ratio ¼
assertFalse("Ignore empty tokens 3", matcher.matches("J Str Bra Roy Asi Soc", "J Bot")); // 6+2 tokens, 2 are common, ratio ¼
}
}
| 5,690 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
InitialSubstringMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/InitialSubstringMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class InitialSubstringMatcherTest {
@Test
public void matchBlanks() {
InitialSubstringMatcher matcher = new InitialSubstringMatcher();
// prefixSize is null and hence 0..
// in no case blanks would match here
assertFalse(matcher.matches("", ""));
assertFalse(matcher.matches("", "hello"));
}
@Test
public void exactMatch () throws Exception {
Matcher matcher = new InitialSubstringMatcher();
assertTrue(matcher.matches("2012", "2012"));
}
@Test
public void PrefixSize () {
InitialSubstringMatcher matcher = new InitialSubstringMatcher();
assertTrue(matcher.matches("2012", "201something else"));
assertTrue(matcher.matches("2012", "2013"));
matcher.setPrefixSize(4);
assertFalse(matcher.matches("2012", "2013"));
}
}
| 1,654 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
TokeniserMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/TokeniserMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TokeniserMatcherTest extends TokeniserMatcher {
private static final Logger logger = LoggerFactory.getLogger(TokeniserMatcherTest.class);
/**
* Test that various delimiters and minimum lengths work as expected.
*/
@Test
public void testConvToArray() {
String[] r;
// Defaults (set to ensure test is OK).
setDelimiter(" ");
setMinLength(1);
// Default delimiter (" ") and min length (1)
r = convToArray("AA BBB CC");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(3));
r = convToArray("AA BBB CC ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(3));
// Min length 0, so blank tokens should be included, including those at the end
setMinLength(0);
r = convToArray("AA BBB CC ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(10));
// Change delimiter
setDelimiter("B");
r = convToArray("AA BBB CC ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(4));
setDelimiter("BBB");
r = convToArray("AA BBB CC ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(2));
setDelimiter("A");
r = convToArray("AA BBB CC ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(3));
}
@Test
public void testConvEmptyToArray() {
String[] r;
// Defaults
setDelimiter(" ");
setMinLength(1);
// Default delimiter (" ") and min length (1)
r = convToArray("");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(0));
r = convToArray(" ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(0));
r = convToArray(null);
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(0));
// Min length 0, so blank tokens should be included.
setMinLength(0);
r = convToArray("");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(1));
r = convToArray(" ");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(4));
r = convToArray(null);
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(0));
}
@Test
public void testBlankDelimiter() {
String[] r;
setDelimiter("");
setMinLength(1);
// Blank delimiter ("") and min length 1
r = convToArray("ABCD");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(4));
// Min length 0
setMinLength(0);
r = convToArray("ABCD");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(4));
// Min length 2
setMinLength(2);
r = convToArray("ABCD");
logger.trace("{} tokens; {} {}", r.length, (Object)r);
assertThat("Wrong number of tokens", r.length, CoreMatchers.equalTo(0));
}
@Override public boolean matches(String s1, String s2) throws MatchException { fail("Not tested here"); return false; }
@Override public boolean isExact() { fail("Not tested here"); return false; }
@Override public int getCost() { fail("Not tested here"); return 0; }
@Override public String getExecutionReport() { fail("Not tested here"); return null; }
}
| 4,860 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NeverMatchingMatcherTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/matchers/NeverMatchingMatcherTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class NeverMatchingMatcherTest {
@Test
public void testNullMatches() throws Exception {
Matcher matcher = new NeverMatchingMatcher();
assertFalse(matcher.matches(null, null));
}
@Test
public void testBlankMatches() throws Exception {
Matcher matcher = new NeverMatchingMatcher();
assertFalse(matcher.matches("", ""));
}
@Test
public void testNullBlankMatches() throws Exception {
Matcher matcher = new NeverMatchingMatcher();
assertFalse(matcher.matches("", null));
}
@Test
public void testStringMatches() throws Exception {
Matcher matcher = new NeverMatchingMatcher();
assertFalse(matcher.matches("one", "one"));
}
}
| 1,511 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchReporterTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/reporters/MatchReporterTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2015 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.io.CsvMapReader;
import org.supercsv.prefs.CsvPreference;
public class MatchReporterTest {
private static final Logger logger = LoggerFactory.getLogger(MatchReporterTest.class);
@Test
public void testQuotedCsv() throws Exception {
File tempFile = File.createTempFile("MatchReporterTest-", ".tsv");
MatchReporter reporter = new MatchReporter();
reporter.setName("MatchReporter");
reporter.setConfigName("Test_Config");
reporter.setDelimiter("\t");
reporter.setIdDelimiter("|");
reporter.setFile(tempFile);
reporter.setWriter();
reporter.setDefinedOutputFields(new String[]{"property", "quote-test"});
reporter.writeHeader();
Map<String,String> fromRecord = new HashMap<>();
List<Map<String,String>> matches = new ArrayList<>();
String[][] records = new String[][]{
new String[]{"test-id", "test-value", "ABC 'DEF' GHI"},
new String[]{"id2", "value2", "ABC \"DEF\" GHI"},
new String[]{"id3", "value3", "ABC \"\"DEF\"\" GHI"},
new String[]{"id4", "value4", "\"ABC DEF GHI\""},
new String[]{"id2", "value2", "\"ABC DEF GHI"},
new String[]{"id2", "value2", "\"\"ABC DEF GHI"},
new String[]{"id2", "value2", "\""},
new String[]{"id2", "value2", "\"\""},
new String[]{"id2", "value2", "\"\"\""}
};
for (String[] r : records) {
fromRecord.put("id", r[0]);
fromRecord.put("property", r[1]);
fromRecord.put("quote-test", r[2]);
reporter.reportResults(fromRecord, matches);
}
reporter.close();
// Read in file and check it's the same
CsvPreference customCsvPref = new CsvPreference.Builder('"', '\t', "\n").build();
int i = 0;
try (CsvMapReader mr = new CsvMapReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8"), customCsvPref)) {
final String[] header = mr.getHeader(true);
logger.info("CSV header is {}", (Object[])header);
Map<String, String> record;
record = mr.read(header);
while (record != null) {
logger.info("Expecting record {}, {}, {}", records[i][0], records[i][1], records[i][2]);
logger.info("Read record {}", record);
assertTrue(record.get("id").equals(records[i][0]));
assertTrue(record.get("property").equals(records[i][1]));
assertTrue(record.get("quote-test").equals(records[i][2]));
// Read next record from CSV/datasource
record = mr.read(header);
i++;
}
}
catch (Exception e) {
Assert.fail(e.toString());
}
}
}
| 3,551 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DedupStepDefs.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/core/DedupStepDefs.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cucumber.api.DataTable;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class DedupStepDefs {
private final static Logger log = LoggerFactory.getLogger(DedupStepDefs.class);
// define input and output files; like this we make them available as variables for the scope
// of all steps in the scenario, but we actually create and delete them in a controlled way
Path tempDir;
Path tempConfigFile;
Path tempQueryFile;
Path tempAuthorityFile;
Path tempOutputFile;
Path tempOutputMultilineFile;
Path dictFile;
@Before
public void before() throws Exception {
tempDir = Files.createTempDirectory("dedup-dir");
tempConfigFile = new File(tempDir + File.separator + "config.xml").toPath();
tempQueryFile = new File(tempDir + File.separator + "query.txt").toPath();
// tempAuthorityFile shall be used additionally for matching tasks..
tempAuthorityFile = new File(tempDir + File.separator + "authority.txt").toPath();
tempOutputFile = new File(tempDir + File.separator + "output.txt").toPath();
tempOutputMultilineFile = new File(tempDir + File.separator + "output_multiline.txt").toPath();
dictFile = new File(tempDir + File.separator + "funkyDict.txt").toPath();
}
@After
public void after() throws Exception {
try{
// Force a system gc to release lucene files so can delete
System.gc();
FileDeleteStrategy.FORCE.delete(tempDir.toFile());
File dir = new File("target");
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("deduplicator");
}
});
for (File indexFile : files) {
FileDeleteStrategy.FORCE.delete(indexFile); // removes the lucene index after scenario
}
}
catch(Exception e){
log.error("Problem clearing up temp files / lucene index");
}
}
private void writeDataTableToFile(DataTable dataTable, Path path) throws Exception {
Writer w = new OutputStreamWriter(new FileOutputStream(path.toFile()), "UTF-8");
for (List<String> rows : dataTable.cells(0)) {
for (String cell : rows) {
w.write(cell);
w.write("\t");
}
w.write("\n");
}
w.close();
}
@Given("^(?:.*) has created an? (?:input|query)-file(?:.*)$")
public void x_has_created_an_y_file(DataTable fileContent) throws Exception {
writeDataTableToFile(fileContent, tempQueryFile);
}
@Given("^(?:he|she) has created an authority-file to match against$")
public void has_created_a_authorityfile_to_match_against(DataTable fileContent) throws Exception {
writeDataTableToFile(fileContent, tempAuthorityFile);
}
@Given("^(?:he|she) has access to a tab-separated dictionary$")
public void has_access_to_a_tabseparated_dictionary(DataTable dictContent) throws Exception {
writeDataTableToFile(dictContent, dictFile);
}
@Given("^Alecs has set up a (?:.*)configuration file(?:.*)$")
public void alecs_has_set_up_a_configuration_file(String configXML) throws Exception {
String escapedTempPath = tempDir.toString().replace("\\", "\\\\");
Writer w = new OutputStreamWriter(new FileOutputStream(tempConfigFile.toFile()), "UTF-8");
w.write(configXML.replaceAll("REPLACE_WITH_TMPDIR", escapedTempPath));
w.close();
}
@When("^this config is run through the deduplicator$")
public void this_config_is_run_through_the_deduplicator() throws Exception {
String[] args = {"-d", tempDir.toString() + "/"};
CoreApp.main(args);
}
private void checkDataInFile(DataTable expectedOutput, Path path) throws Exception {
List<List<String>> expectedOutputList = expectedOutput.cells(0);
List<String> lines = FileUtils.readLines(path.toFile(), "UTF-8");
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
List<String> expectedLine = expectedOutputList.get(i);
List<String> lineList = Arrays.asList(line.split("\t", expectedLine.size()));
Assert.assertArrayEquals("Error occurred in record "+i, expectedLine.toArray(), lineList.toArray());
}
}
@Then("^a file should have been created in the same folder with the following data:$")
public void a_file_should_have_been_created_in_the_same_folder_with_the_following_data(DataTable expectedOutput) throws Exception {
checkDataInFile(expectedOutput, tempOutputFile);
}
@Then("^a file for the multiline output should have been created in the same folder with the following data:$")
public void a_file_for_the_multiline_output_should_have_been_created_in_the_same_folder_with_the_following_data(DataTable expectedOutput) throws Exception {
checkDataInFile(expectedOutput, tempOutputMultilineFile);
}
}
| 5,908 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchConfigurationTestingStepdefs.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/core/MatchConfigurationTestingStepdefs.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.exception.MatchExecutionException;
import org.kew.rmf.core.exception.TooManyMatchesException;
import org.kew.rmf.core.lucene.LuceneMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class MatchConfigurationTestingStepdefs {
private final static Logger logger = LoggerFactory.getLogger(MatchConfigurationTestingStepdefs.class);
LuceneMatcher currentMatcher;
List<Map<String,String>> queryResults;
@Given("^I have loaded the \"(.*?)\" configuration$")
public void i_have_loaded_the_configuration(String fileName) throws Throwable {
currentMatcher = getConfiguration(fileName);
Assert.assertNotNull("Failed to load matcher", currentMatcher);
}
@When("^I query for$")
public void i_query_for(List<Map<String,String>> queries) throws Throwable {
Assert.assertNotNull("No matcher selected", currentMatcher);
// Go through the list of queries one at a time, execute the query, store the result in a new key "result".
queryResults = new ArrayList<>();
for (Map<String,String> testQuery : queries) {
Map<String,String> result = doSingleTestQuery(testQuery);
logger.debug("Query result: {}", result);
queryResults.add(result);
}
}
@Then("^the results are$")
public void the_results_are(List<Map<String,String>> expectedResults) throws Throwable {
for (Map<String,String> expectedResult : expectedResults) {
checkResult(expectedResult);
}
}
private void checkResult(Map<String,String> expectedResult) {
String targetId = expectedResult.get("queryId");
Map<String,String> actualResult = null;
for (Map<String,String> result : queryResults) {
if (targetId.equals(result.get("queryId"))) {
actualResult = result;
break;
}
}
Assert.assertNotNull("No result found for query "+targetId, actualResult);
Assert.assertThat("Match results not correct for query "+expectedResult.get("queryId"), actualResult.get("results"), Matchers.equalTo(expectedResult.get("results")));
}
private Map<String,String> doSingleTestQuery(Map<String,String> origQuery) throws TooManyMatchesException, MatchExecutionException {
// Copy the map, as Cucumber supplies an UnmodifiableMap
Map<String,String> query = new HashMap<>();
query.putAll(origQuery);
query.put("id", query.get("queryId")); // Means the id can show up in the debug output.
List<Map<String,String>> matches = currentMatcher.getMatches(query);
logger.debug("Found some matches: {}", matches.size());
if (matches.size() < 4) {
logger.debug("Matches for {} are {}", query, matches);
}
// Construct result string (list of ids)
ArrayList<String> matchedIds = new ArrayList<>();
for (Map<String,String> match : matches) {
String r = match.get("id") + "[" + match.get(Configuration.MATCH_SCORE) + "]";
matchedIds.add(r);
}
Collections.sort(matchedIds);
query.put("results", StringUtils.join(matchedIds, " "));
return query;
}
private static final Map<String, LuceneMatcher> matchers = new HashMap<String, LuceneMatcher>();
private LuceneMatcher getConfiguration(String config) throws Throwable {
logger.debug("Considering initialising match controller with configuration {}", config);
// Load up the matchers from the specified files
if (!matchers.containsKey(config)){
String configurationFile = "/META-INF/spring/reconciliation-service/" + config + ".xml";
logger.debug("Loading configuration {} from {}", config, configurationFile);
ConfigurableApplicationContext context = new GenericXmlApplicationContext(configurationFile);
LuceneMatcher matcher = context.getBean("engine", LuceneMatcher.class);
matcher.loadData();
logger.debug("Loaded data for configuration {}", config);
matchers.put(config, matcher);
logger.debug("Stored matcher with name {} from configuration {}", matcher.getConfig().getName(), config);
}
return matchers.get(config);
}
}
| 5,193 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
HighLevelTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/core/HighLevelTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
public class HighLevelTest {
}
| 905 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
JavaScriptEnvTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/core/script/JavaScriptEnvTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.script;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptException;
import org.junit.Test;
public class JavaScriptEnvTest {
@Test
public void testBooleanBehaviourSimple() throws ScriptException {
JavaScriptEnv jsEnv = new JavaScriptEnv();
Map<String, String> record = new HashMap<>();
assertTrue(jsEnv.evalFilter("true", record));
assertFalse(jsEnv.evalFilter("false", record));
}
@Test(expected = ScriptException.class)
public void testWrongStuffReturned() throws ScriptException {
JavaScriptEnv jsEnv = new JavaScriptEnv();
Map<String, String> record = new HashMap<>();
jsEnv.evalFilter("something else", record);
}
@Test(expected = NullPointerException.class)
public void testAlsoFailIfEmpty() throws ScriptException {
JavaScriptEnv jsEnv = new JavaScriptEnv();
Map<String, String> record = new HashMap<>();
jsEnv.evalFilter("", record);
}
@Test
public void testRealJavaScriptExampleSimple() throws ScriptException {
JavaScriptEnv jsEnv = new JavaScriptEnv();
Map<String, String> record = new HashMap<>();
assertTrue(jsEnv.evalFilter("true === true", record));
assertFalse(jsEnv.evalFilter("true === false", record));
}
@Test
public void testRealJavaScriptExampleWithRecord() throws ScriptException {
JavaScriptEnv jsEnv = new JavaScriptEnv();
Map<String, String> record = new HashMap<>();
record.put("fieldA", "value1");
record.put("fieldB", "value2");
record.put("fieldC", "value1");
assertTrue(jsEnv.evalFilter("record.fieldA == 'value1'", record));
assertTrue(jsEnv.evalFilter("record.fieldA == record['fieldC']", record));
assertFalse(jsEnv.evalFilter("record.fieldA == record.fieldB", record));
}
}
| 2,743 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneUtilsTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/test/java/org/kew/rmf/core/lucene/LuceneUtilsTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.configuration.Property;
import org.kew.rmf.matchers.AlwaysMatchingMatcher;
import org.kew.rmf.matchers.ExactMatcher;
import org.kew.rmf.matchers.MatchException;
import org.kew.rmf.transformers.StripNonAlphabeticCharactersTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.WeightedTransformer;
import org.kew.rmf.transformers.authors.ShrunkAuthors;
import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer;
import org.kew.rmf.transformers.botany.EpithetTransformer;
import org.kew.rmf.transformers.botany.FakeHybridSignCleaner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuceneUtilsTest {
private static Logger logger = LoggerFactory.getLogger(LuceneUtils.class);
List<Property> genusOnly;
List<Property> genusAndAuthor;
List<Property> fullNameBlanksMatchOnly;
List<Property> fullNameBlanksDifferOnly;
@Before
public void setUpConfigurations() {
// Configure transformers
Transformer fakeHybridSignCleaner = new FakeHybridSignCleaner();
StripNonAlphabeticCharactersTransformer stripNonAlphabetic = new StripNonAlphabeticCharactersTransformer();
stripNonAlphabetic.setReplacement("");
Transformer epithetTransformer = new EpithetTransformer();
Transformer stripBasionymAuthor = new StripBasionymAuthorTransformer();
ShrunkAuthors shrunkAuthor = new ShrunkAuthors();
shrunkAuthor.setShrinkTo(4);
// Configure genus property
List<Transformer> genusQueryTransformers = new ArrayList<>();
genusQueryTransformers.add(new WeightedTransformer(fakeHybridSignCleaner, 0.1, 1));
genusQueryTransformers.add(new WeightedTransformer(stripNonAlphabetic, 0.05, 3));
genusQueryTransformers.add(new WeightedTransformer(epithetTransformer, 0.4, 5));
List<Transformer> genusAuthorityTransformers = new ArrayList<>();
genusAuthorityTransformers.add(new WeightedTransformer(stripNonAlphabetic, 0.15, 2));
genusAuthorityTransformers.add(new WeightedTransformer(epithetTransformer, 0.3, 4));
Property genus = new Property();
genus.setQueryColumnName("genus");
genus.setAuthorityColumnName("genus");
genus.setMatcher(new ExactMatcher());
genus.setQueryTransformers(genusQueryTransformers);
genus.setAuthorityTransformers(genusAuthorityTransformers);
// Configure author property
List<Transformer> authorQueryTransformers = new ArrayList<>();
authorQueryTransformers.add(new WeightedTransformer(stripBasionymAuthor, 0.0, -1));
authorQueryTransformers.add(new WeightedTransformer(shrunkAuthor, 0.5, 1));
List<Transformer> authorAuthorityTransformers = new ArrayList<>();
authorAuthorityTransformers.add(new WeightedTransformer(stripBasionymAuthor, 0.0, -1));
authorAuthorityTransformers.add(new WeightedTransformer(shrunkAuthor, 0.5, 1));
Property authors = new Property();
authors.setQueryColumnName("authors");
authors.setAuthorityColumnName("authors");
authors.setMatcher(new ExactMatcher());
authors.setBlanksMatch(true);
authors.setQueryTransformers(authorQueryTransformers);
authors.setAuthorityTransformers(authorAuthorityTransformers);
// Configure fullName property
Property fullNameBlanksMatch = new Property();
fullNameBlanksMatch.setQueryColumnName("full_name");
fullNameBlanksMatch.setAuthorityColumnName("full_name");
fullNameBlanksMatch.setMatcher(new AlwaysMatchingMatcher());
fullNameBlanksMatch.setBlanksMatch(true);
Property fullNameBlanksDiffer = new Property();
fullNameBlanksDiffer.setQueryColumnName("full_name");
fullNameBlanksDiffer.setAuthorityColumnName("full_name");
fullNameBlanksDiffer.setMatcher(new AlwaysMatchingMatcher());
fullNameBlanksDiffer.setBlanksMatch(false);
// Set up configurations
genusOnly = new ArrayList<>();
genusOnly.add(genus);
genusAndAuthor = new ArrayList<>();
genusAndAuthor.add(genus);
genusAndAuthor.add(authors);
fullNameBlanksMatchOnly = new ArrayList<>();
fullNameBlanksMatchOnly.add(fullNameBlanksMatch);
fullNameBlanksDifferOnly = new ArrayList<>();
fullNameBlanksDifferOnly.add(fullNameBlanksDiffer);
}
@Test
public void checkSinglePropertyScores() {
// Set up test records
Map<String,String> queryRecord = new HashMap<>();
Map<String,String> authorityRecord = new HashMap<>();
queryRecord.put("id", "q");
authorityRecord.put("id", "a");
// Check a non-match is flagged as such, score 0.
queryRecord.put("genus", "Ilex");
authorityRecord.put("genus", "Quercus");
test(false, queryRecord, authorityRecord, genusOnly);
test(0.0, queryRecord, authorityRecord, genusOnly);
// Check an exact match has a score of 1.
queryRecord.put("genus", "Quercus");
authorityRecord.put("genus", "Quercus");
test(true, queryRecord, authorityRecord, genusOnly);
test(1.0, queryRecord, authorityRecord, genusOnly);
// This needs transformers up to and including strip non alphabetic, costing 0.3. Score should be 0.7.
queryRecord.put("genus", "Quer5c5us");
authorityRecord.put("genus", "Quer6cus");
test(true, queryRecord, authorityRecord, genusOnly);
test(0.7, queryRecord, authorityRecord, genusOnly);
// This has the same score, since the fake hybrid sign cleaner comes before the strip non alphabetic transformer.
queryRecord.put("genus", "x Quer5c5us");
authorityRecord.put("genus", "Quer7cus");
test(true, queryRecord, authorityRecord, genusOnly);
test(0.7, queryRecord, authorityRecord, genusOnly);
// This also needs the epithet transformer, which brings the required cost up to 1.0.
queryRecord.put("genus", "x Quer5c5us");
authorityRecord.put("genus", "Quer8ca");
test(true, queryRecord, authorityRecord, genusOnly);
test(0.0, queryRecord, authorityRecord, genusOnly);
}
@Test
public void checkTwoPropertyMatchScores() {
// Set up test records
Map<String,String> queryRecord = new HashMap<>();
Map<String,String> authorityRecord = new HashMap<>();
queryRecord.put("id", "q");
authorityRecord.put("id", "a");
// Both match exactly, score is 1.0
queryRecord.put("genus", "Quercus");
authorityRecord.put("genus", "Quercus");
queryRecord.put("authors", "L.");
authorityRecord.put("authors", "L.");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(1.0, queryRecord, authorityRecord, genusAndAuthor);
// Genus is a poor match (0.0), author is a perfect match (1), so score is 0.5.
queryRecord.put("genus", "x Quer5cus");
authorityRecord.put("genus", "Querca");
queryRecord.put("authors", "L.");
authorityRecord.put("authors", "L.");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.5, queryRecord, authorityRecord, genusAndAuthor);
// Genus is a perfect match (1), author is a terrible match (0), so score is 0.5.
queryRecord.put("genus", "Quercus");
authorityRecord.put("genus", "Quercus");
queryRecord.put("authors", "A.B.Otherelse");
authorityRecord.put("authors", "A.B.Otherwise");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.5, queryRecord, authorityRecord, genusAndAuthor);
// Genus is an imperfect match (0.9), author is a perfect match (1), so score is 0.95.
queryRecord.put("genus", "x Quercus");
authorityRecord.put("genus", "Quercus");
queryRecord.put("authors", "A.B.Other");
authorityRecord.put("authors", "A.B.Other");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.95, queryRecord, authorityRecord, genusAndAuthor);
}
@Test
public void checkWithBlankPropertyMatchScores() {
// Set up test records
Map<String,String> queryRecord = new HashMap<>();
Map<String,String> authorityRecord = new HashMap<>();
queryRecord.put("id", "q");
authorityRecord.put("id", "a");
queryRecord.put("genus", "Quercus");
authorityRecord.put("genus", "Quercus");
// Exact author in the query
authorityRecord.put("authors", "L.");
queryRecord.put("authors", "L.");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(1.0, queryRecord, authorityRecord, genusAndAuthor);
// Close author in the query
authorityRecord.put("authors", "L.");
queryRecord.put("authors", "l");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.5, queryRecord, authorityRecord, genusAndAuthor);
// Blank author in the query
authorityRecord.put("authors", "L.");
queryRecord.put("authors", "");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.75, queryRecord, authorityRecord, genusAndAuthor);
// Blank author in the authority
authorityRecord.put("authors", "");
queryRecord.put("authors", "L.");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.75, queryRecord, authorityRecord, genusAndAuthor);
// Blank author on both sides
queryRecord.put("authors", "");
authorityRecord.put("authors", "");
test(true, queryRecord, authorityRecord, genusAndAuthor);
test(0.875, queryRecord, authorityRecord, genusAndAuthor);
}
@Test
public void noDetrimentForBlankIfItMatchesAnyway() {
// Set up test records
Map<String,String> queryRecord = new HashMap<>();
Map<String,String> authorityRecord = new HashMap<>();
queryRecord.put("id", "q");
authorityRecord.put("id", "a");
authorityRecord.put("full_name", "Quercus alba L.");
// Non-blank, but always matches
queryRecord.put("full_name", "Anything");
test(true, queryRecord, authorityRecord, fullNameBlanksMatchOnly);
test(1.0, queryRecord, authorityRecord, fullNameBlanksMatchOnly);
// Blank, so blanksMatch catches it and reduces the score
queryRecord.put("full_name", "");
test(true, queryRecord, authorityRecord, fullNameBlanksMatchOnly);
test(0.5, queryRecord, authorityRecord, fullNameBlanksMatchOnly);
// Non-blank, but always matches
queryRecord.put("full_name", "Anything");
test(true, queryRecord, authorityRecord, fullNameBlanksDifferOnly);
test(1.0, queryRecord, authorityRecord, fullNameBlanksDifferOnly);
// Blank, but !blanksMatch so the AlwaysMatcher gets this and maintains the score
queryRecord.put("full_name", "");
test(true, queryRecord, authorityRecord, fullNameBlanksDifferOnly);
test(1.0, queryRecord, authorityRecord, fullNameBlanksDifferOnly);
}
private void test(boolean expectedResult, Map<String,String> queryRecord, Map<String,String> authorityRecord, List<Property> properties) {
logger.info("Testing Q:{} and A:{}, expecting {}", queryRecord, authorityRecord, expectedResult);
try {
// transform query and authority properties
for (Property prop : properties) {
String qfName = prop.getQueryColumnName();
String qfValue = queryRecord.get(qfName);
String afName = prop.getAuthorityColumnName();
String afValue = authorityRecord.get(afName);
qfValue = (qfValue == null) ? "" : qfValue; // super-csv treats blank as null, we don't for now
afValue = (afValue == null) ? "" : afValue;
// transform the field-value..
for (Transformer t : prop.getQueryTransformers()) {
qfValue = t.transform(qfValue);
}
for (Transformer t : prop.getAuthorityTransformers()) {
afValue = t.transform(afValue);
}
// ..and put it into the record
queryRecord.put(qfName + Configuration.TRANSFORMED_SUFFIX, qfValue);
authorityRecord.put(afName + Configuration.TRANSFORMED_SUFFIX, afValue);
}
boolean actualResult = LuceneUtils.recordsMatch(queryRecord, LuceneUtils.map2Doc(authorityRecord), properties);
logger.info("Result was {} ({})", actualResult, (expectedResult == actualResult) ? "Passed" : "Failed");
Assert.assertTrue(expectedResult == actualResult);
}
catch (MatchException | TransformationException e) {
Assert.fail(e.getMessage());
}
}
private void test(double expectedResult, Map<String,String> queryRecord, Map<String,String> authorityRecord, List<Property> properties) {
logger.info("Testing Q:{} and A:{}, expecting {}", queryRecord, authorityRecord, expectedResult);
try {
double actualResult = LuceneUtils.recordsMatchScore(queryRecord, LuceneUtils.map2Doc(authorityRecord), properties);
logger.info("Result was {} ({})", actualResult, (Math.abs(expectedResult - actualResult) < 0.00001) ? "Passed" : "Failed");
Assert.assertTrue(Math.abs(expectedResult - actualResult) < 0.00001);
}
catch (MatchException | TransformationException e) {
Assert.fail(e.getMessage());
}
}
}
| 13,348 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Version.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/Version.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Holds version information.
*/
public class Version {
private static Logger logger = LoggerFactory.getLogger(Version.class);
private static String VERSION;
static {
try {
InputStream is = Version.class.getResourceAsStream("/META-INF/maven/org.kew.rmf/rmf-core/pom.properties");
if (is == null) {
logger.info("Could not load Maven properties file — probably a development execution.");
VERSION = "UNKNOWN";
}
else {
Properties prop = new Properties();
prop.load(is);
VERSION = prop.get("version").toString();
}
}
catch (Exception e) {
logger.error("Could not determine application version", e);
VERSION = "UNKNOWN";
}
logger.info("Reconciliation service version: {}", VERSION);
}
/* Getters and setters */
public static String getVersion() {
return VERSION;
}
}
| 1,724 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CsvOrderedDictionary.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/utils/CsvOrderedDictionary.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.utils;
import java.util.LinkedHashMap;
/**
* Same as a {@link CsvDictionary}, but maintains order of insertion.
*/
public class CsvOrderedDictionary extends CsvDictionary {
public CsvOrderedDictionary() {
map = new LinkedHashMap<>();
}
}
| 1,017 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CsvDictionary.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/utils/CsvDictionary.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.utils;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.InitializingBean;
import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;
/**
* A CsvDictionary is a HashMap of Strings that is created from the first two
* columns (key, value) of a CSV file.
*/
public class CsvDictionary implements Dictionary, InitializingBean {
Map<String, String> map;
private String fileDelimiter;
private String filePath;
public CsvDictionary() {
map = new HashMap<>();
}
@Override
public void afterPropertiesSet() throws IOException {
CsvPreference customCsvPref = new CsvPreference.Builder('"', this.getFileDelimiter().charAt(0), "\n").build();
try (CsvListReader reader = new CsvListReader(new FileReader(this.getFilePath()), customCsvPref)) {
List<String> miniMap;
while ((miniMap = reader.read()) != null) {
map.put(miniMap.get(0), miniMap.get(1));
}
}
}
@Override
public String get(String key) {
return map.get(key);
}
@Override
public Set<Entry<String, String>> entrySet() {
return map.entrySet();
}
@Override
public String toString() {
return getFilePath().substring(getFilePath().lastIndexOf('/')+1) + " (" + entrySet().size() + " entries)";
}
// • Getters and setters • //
public String getFileDelimiter() {
return fileDelimiter;
}
public void setFileDelimiter(String fileDelimiter) {
this.fileDelimiter = fileDelimiter;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) throws IOException {
this.filePath = filePath;
}
}
| 2,495 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
IntegerMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/IntegerMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* A simple number matcher that compares two Integers and accepts a maximal difference of
* `maxDiff` to match.
*
*/
public class IntegerMatcher implements Matcher {
public static int COST = 1;
private int maxDiff = 5;
@Override
public boolean matches(String s1, String s2) {
return Math.abs((Integer.parseInt(s1) - Integer.parseInt(s2))) <= this.maxDiff;
}
@Override
public boolean isExact() {
return false;
}
@Override
public int getCost() {
return COST;
}
@Override
public String getExecutionReport() {
// TODO Auto-generated method stub
return null;
}
public int getMaxDiff() {
return maxDiff;
}
public void setMaxDiff(int maxDiff) {
this.maxDiff = maxDiff;
}
}
| 1,495 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
EmptyStringMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/EmptyStringMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher returns true if either of the strings is null
* @author nn00kg
*
*/
public class EmptyStringMatcher implements Matcher {
public static int COST = 0;
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
boolean match = false;
if (s1 == null || s2 == null)
match = true;
return match;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
}
| 1,296 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchException.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/MatchException.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
public class MatchException extends Exception {
private static final long serialVersionUID = 1L;
public MatchException() {
super();
}
public MatchException(String message) {
super(message);
}
public MatchException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,074 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NumberMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/NumberMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import org.kew.rmf.transformers.StripNonNumericCharactersTransformer;
/**
* This matcher tests for common tokens using only the numeric tokens in the strings supplied.
*
* If noNumbersRequireRestMatch == true and both strings don't contain any numbers,
* they are matched for exact string equality.
*/
public class NumberMatcher extends CommonTokensMatcher {
public static int COST = 5;
public boolean noNumbersRequireRestMatch = true;
StripNonNumericCharactersTransformer removeNumbers = new StripNonNumericCharactersTransformer();
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
if (s1 == null && s2 == null) return true;
String no1 = removeNumbers.transform(s1);
String no2 = removeNumbers.transform(s2);
if (noNumbersRequireRestMatch && no1.length() == 0 && no2.length() == 0) {
return (s1.equals(s2));
}
else {
return super.matches(no1, no2);
}
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
public boolean isNoNumbersRequireRestMatch() {
return noNumbersRequireRestMatch;
}
public void setNoNumbersRequireRestMatch(boolean noNumbersRequireRestMatch) {
this.noNumbersRequireRestMatch = noNumbersRequireRestMatch;
}
}
| 2,093 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
OcrCanonicaliserMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/OcrCanonicaliserMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher tests for equality between the two inputs (exact matches).
* @author nn00kg
*
*/
public class OcrCanonicaliserMatcher implements Matcher {
public static int COST = 0;
@Override
public int getCost() {
return COST;
}
private static final String[][] ocr_pairs = {
{"a","c"}
,{"a","d"}
,{"a","e"}
,{"a","f"}
,{"an","m"}
,{"a","o"}
,{"a","s"}
,{"a","z"}
,{"b","g"}
,{"b","h"}
,{"b","p"}
,{"c","e"}
,{"c","f"}
,{"ch","oli"}
,{"c","o"}
,{"d","l"}
,{"e","o"}
,{"e","r"}
,{"ff","f"}
,{"fi","fr"}
,{"fii","fi"}
,{"f","l"}
,{"fl","f"}
,{"g","h"}
,{"g","p"}
,{"g","q"}
,{"h","i"}
,{"h","li"}
,{"h","ll"}
,{"id","k"}
,{"i","l"}
,{"il","u"}
,{"in","lm"}
,{"in","m"}
,{"i","r"}
,{"i","t"}
,{"li","k"}
,{"ll","k"}
,{"ln","n"}
,{"l","t"}
,{"lt","k"}
,{"mc","rne"}
,{"m","n"}
,{"mn","rm"}
,{"m","o"}
,{"m","rn"}
,{"m","ru"}
,{"m","tn"}
,{"m","tu"}
,{"m","u"}
,{"ni","m"}
,{"nm","rm"}
,{"n","o"}
,{"n","r"}
,{"n","ra"}
,{"n","s"}
,{"n","u"}
,{"rn","m"}
,{"ro","m"}
,{"r","u"}
,{"s","z"}
,{"t","f"}
,{"tr","u"}
,{"t","u"}
,{"v","y"}
,{"x","z"}
,{"y","u"}
};
private static final String CANONICAL = "#";
@Override
public boolean matches(String s1, String s2) {
boolean matches = false;
if (s1 == null && s2 == null)
matches = true;
else{
try{
matches = s1.equals(s2);
if (!matches){
for (int i = 0; i < ocr_pairs.length; i++) {
String[] pair = ocr_pairs[i];
matches = s1.replaceAll(pair[0], CANONICAL).matches(s2.replaceAll(pair[1], CANONICAL));
if (matches)
break;
}
}
}
catch (Exception e) {
;
}
}
return matches;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
public static void main(String[] args) {
OcrCanonicaliserMatcher m = new OcrCanonicaliserMatcher();
System.out.println(m.matches("hirsuta", "liirsuta"));
}
}
| 2,825 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
ExactMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/ExactMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher tests for equality between the two inputs (exact matches).
* @author nn00kg
*
*/
public class ExactMatcher implements Matcher {
public static int COST = 0;
private boolean nullToBlank = true;
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
if (nullToBlank && s1 == null) s1 = "";
if (nullToBlank && s2 == null) s2 = "";
return s1.equals(s2);
}
@Override
public boolean isExact() {
return true;
}
@Override
public String getExecutionReport() {
return null;
}
/* ••• Getters and setters ••• */
public boolean isNullToBlank() {
return nullToBlank;
}
public void setNullToBlank(boolean nullToBlank) {
this.nullToBlank = nullToBlank;
}
}
| 1,550 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NeverMatchingMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/NeverMatchingMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher returns false in all cases.
* @author nn00kg
*
*/
public class NeverMatchingMatcher implements Matcher {
public static int COST = 0;
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
return false;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
} | 1,201 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NGramMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/NGramMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* This matcher tests for common tokens after splitting the input strings into a sequence of ngrams.
* The ngram length ("n") is configurable.
* @author nn00kg
*
*/
public class NGramMatcher extends CommonTokensMatcher{
private int nGramLength;
public static int COST = 10;
@Override
public boolean matches(String s1, String s2){
boolean matches = false;
if (StringUtils.isNotEmpty(s1) && StringUtils.isNotEmpty(s2)){
matches = s1.equals(s2);
if (!matches){
String[] a1 = extract(s1, nGramLength);
String[] a2 = extract(s2, nGramLength);
matches = calculateTokensInCommon(a1, a2);
}
}
return matches;
}
public static String[] extract(String input, int n){
List<String> ngramlist = new ArrayList<String>();;
if (input != null){
input = "_" + input + "_";
if (input.length() > n){
for (int i = 0; i < input.length() - n; i++){
ngramlist.add(input.substring(i, i+n));
}
}
else{
ngramlist.add(input);
}
}
String[] ngrams = new String[ngramlist.size()];
return (String[])ngramlist.toArray(ngrams);
}
public int getnGramLength() {
return nGramLength;
}
public void setnGramLength(int nGramLength) {
this.nGramLength = nGramLength;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
public static void main(String[] args) {
NGramMatcher nGramMatcher = new NGramMatcher();
nGramMatcher.setMinRatio(0.5);
nGramMatcher.setnGramLength(2);
System.out.println(nGramMatcher.matches("lofgreniana", "loefgreniana"));
}
}
| 2,476 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CompositeAnyMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/CompositeAnyMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher is wrapper for multiple matchers,
* at least one of which must match.
* @author nn00kg
*
*/
public class CompositeAnyMatcher extends CompositeMatcher{
@Override
public boolean matches(String s1, String s2) throws MatchException {
boolean matches = false;
for (Matcher m : matchers)
if (m.matches(s1, s2)){
matches = true;
break;
}
return matches;
}
}
| 1,184 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CommonTokensMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/CommonTokensMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Two strings match with this Matcher if they have more than {@link #minRatio} tokens in common.
* <br/>
* By default the ratio is calculated by "pairing off" common tokens. "A B" and "A B B" have two pairs (4 tokens)
* in common, out of 5 tokens. The ratio is ⅘.
* <br/>
* Setting {@link #setDeduplicateTokens(boolean)} to <code>true</code> causes duplicates to be ignored, so
* "A A B C" and "A B B D" have two pairs (4 tokens) out of 3+3 deduplicated tokens, so the ration is ⅔.
*/
public class CommonTokensMatcher extends TokeniserMatcher {
private static Logger logger = LoggerFactory.getLogger(CommonTokensMatcher.class);
public static int COST = 5;
protected double minRatio = 0.5;
private boolean deduplicateTokens = false;
@Override
public boolean matches(String s1, String s2) {
logger.trace("s1 {}; s2 {}", s1, s2);
if (s1 == null && s2 == null) return true;
String[] a1 = convToArray(s1);
String[] a2 = convToArray(s2);
return calculateTokensInCommon(a1,a2);
}
protected boolean calculateTokensInCommon(String[] s1, String[] s2) {
//logger.info("Comparing {} and {}", s1, s2);
// Sort both arrays.
Arrays.sort(s1); // Complexity less than n₁·ln n₁
Arrays.sort(s2); // Complexity less than n₂·ln n₂
//logger.info("Sorted {} and {}", s1, s2);
// Set an index s1i to s1 to 0
int s1i = 0;
int s2i = 0;
int matches = 0;
int c;
int duplicates = 0;
// With each element of s1, go through s2 (from where we left off last time) to find that element.
while (true) { // Complexity n₁ + n₂ ?
// Stop if we've reached the end of either array
if (s1i >= s1.length) {
if (deduplicateTokens) {
while (s2i+1 < s2.length) {
if (s2[s2i].equals(s2[s2i+1])) {
duplicates++;
//logger.info("Skipping s2[{}] {}, {} duplicates", s2i, s2[s2i], duplicates);
}
s2i++;
}
}
break;
}
if (s2i >= s2.length) {
if (deduplicateTokens) {
while (s1i+1 < s1.length) {
if (s1[s1i].equals(s1[s1i+1])) {
duplicates++;
//logger.info("Skipping s1[{}] {}, {} duplicates", s1i, s1[s1i], duplicates);
}
s1i++;
}
}
break;
}
// Skip to the last of successive duplicates if required
if (deduplicateTokens) {
while (s1i+1 < s1.length && s1[s1i].equals(s1[s1i+1])) {
duplicates++;
//logger.info("Skipping s1[{}] {}, {} duplicates", s1i, s1[s1i], duplicates);
s1i++;
}
while (s2i+1 < s2.length && s2[s2i].equals(s2[s2i+1])) {
duplicates++;
//logger.info("Skipping s2[{}] {}, {} duplicates", s2i, s2[s2i], duplicates);
s2i++;
}
}
c = s1[s1i].compareTo(s2[s2i]);
//logger.info("Comparing s1[{}] {} with s2[{}] {}, result {}", s1i, s1[s1i], s2i, s2[s2i], c);
if (c == 0) {
matches += 2;
// If they're the same increment both counters.
s1i++;
s2i++;
}
else if (c > 0) {
// If s1's element is larger continue with the next in s2
s2i++;
}
else {
// If s1's element is smaller continue with the next s1
s1i++;
}
}
int combinedLength = s1.length + s2.length - duplicates;
double ratio = ((double)matches) / ((double)combinedLength);
logger.trace("{} matches {}? Counted {} paired tokens from {} combined (deduplicated) length, ratio {}", s1, s2, matches, combinedLength, ratio);
return ratio >= this.minRatio;
}
public double getMinRatio() {
return this.minRatio;
}
/**
* The minimum ratio for the match to be true.
*/
public void setMinRatio(double minRatio) {
this.minRatio = minRatio;
}
public boolean isDeduplicateTokens() {
return deduplicateTokens;
}
/**
* If true, each set of tokens is deduplicated so repeats are only counted once (as either in a matched pair, or as part of the total number of tokens).
*/
public void setDeduplicateTokens(boolean deduplicateTokens) {
this.deduplicateTokens = deduplicateTokens;
}
@Override
public int getCost() {
return COST;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
}
| 4,991 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LevenshteinMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/LevenshteinMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import org.apache.commons.lang.StringUtils;
import org.kew.rmf.utils.Dictionary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This matcher uses the Levenshtein edit distance algorithm
* (provided by the Apache StringUtils class).
* It is computationally expensive, so has a cost of 10.
* The maximum distance is configurable.
* @author nn00kg
*/
public class LevenshteinMatcher implements Matcher {
public static int COST = 10;
private int maxDistance = 2;
private int numCalls = 0;
private int numExecutions = 0;
private static Logger logger = LoggerFactory.getLogger(LevenshteinMatcher.class);
private Dictionary dictionary;
public Dictionary getDictionary() {
return dictionary;
}
public void setDictionary(Dictionary dictionary) {
this.dictionary = dictionary;
}
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) throws MatchException {
boolean matches = false;
numCalls++;
if (StringUtils.isEmpty(s1) && StringUtils.isEmpty(s2)) return true;
if (StringUtils.isNotEmpty(s1) && StringUtils.isNotEmpty(s2)) {
matches = s1.equals(s2);
if (!matches){
logger.trace("Testing ld({}, {})", s1, s2);
int shorter = Math.min(s1.length(), s2.length());
int longer = Math.max(s1.length(), s2.length());
if ((longer - shorter) > maxDistance)
matches = false;
else {
int distance = calculateLevenshtein(s1, s2).intValue();
matches = (distance <= maxDistance);
}
}
}
if (this.getDictionary() != null && matches) {
matches = doFalsePositiveCheck(s1,s2);
}
return matches;
}
private boolean doFalsePositiveCheck(String s1, String s2) {
logger.info("FALSE_POSITIVES_CHECK");
boolean passed = true;
Dictionary falsePositives = this.getDictionary();
if (falsePositives.get(s1) != null && falsePositives.get(s1).equals(s2)) {
passed = false;
}
else if (falsePositives.get(s2) != null && falsePositives.get(s2).equals(s1)) {
passed = false;
}
if (!passed) {
logger.info("Rejected match (" + s1 + ", " + s2 + ") as false positive");
}
return passed;
}
public Integer calculateLevenshtein(String s1, String s2){
numExecutions++;
return new Integer(StringUtils.getLevenshteinDistance(s1, s2));
}
@Override
public boolean isExact() {
return false;
}
public int getMaxDistance() {
return maxDistance;
}
public void setMaxDistance(int maxDistance) {
this.maxDistance = maxDistance;
}
@Override
public String getExecutionReport(){
return "Number of calls: "+ numCalls + ", num executions: " + numExecutions;
}
}
| 3,742 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
AuthorAbbreviationsMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/AuthorAbbreviationsMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.List;
import org.kew.rmf.transformers.Transformer;
/**
* This matcher tests for common author abbreviations in two authorship strings
* It takes two input files - one is for a standard set of author abbreviations and the other is for any author misspellings-
* that are specific to the data-set being compared. e.g variations of 'Linnaeus'.
* @author nb00kg
*
*/
public class AuthorAbbreviationsMatcher extends AuthorCommonTokensMatcher{
public static int COST = 1;
private List<Transformer> transformers;
public List<Transformer> getTransformers() {
return transformers;
}
public void setTransformers(List<Transformer> transformers){
this.transformers = transformers;
}
@Override
public int getCost() {
return COST;
}
private static String IN_MARKER = " in ";
private static String EX_MARKER = " ex ";
private static String AMP_MARKER = " & ";
private static String ET_MARKER = ".et ";
private static String FORMA_MARKER = " forma ";
private static final String FILE_DELIMETER = "%";
private static HashMap<String, String> authorAbbreviations;
private static HashMap<String, String> authorSpecialCases;
AuthorAbbreviationsMatcher() {}
AuthorAbbreviationsMatcher(FileInputStream abbreviationsFile, FileInputStream specialCasesFile) {
authorAbbreviations = loadAbbreviationsList(abbreviationsFile,FILE_DELIMETER);
authorSpecialCases = loadAbbreviationsList(specialCasesFile,FILE_DELIMETER);
}
boolean storeAndReuseTransformations;
public boolean matches_new(String s1, String s2) throws Exception {
// First check for match w/out transform
boolean matches = match_inner(s1, s2);
if (!matches){
String s1_transformed = s1;
String s2_transformed = s2;
for (Transformer t : transformers){
// First attempt to match uses the results of this transformer standalone
matches = match_inner(t.transform(s1),t.transform(s2));
if (matches) break;
if (storeAndReuseTransformations){
// Apply transformer to results of previous run and store the results
s1_transformed = t.transform(s1_transformed);
s2_transformed = t.transform(s2_transformed);
matches = match_inner(s1_transformed,s2_transformed);
}
if (matches) break;
}
}
return matches;
}
public boolean match_inner(String s1, String s2) {
boolean matches = false;
matches = new ExactMatcher().matches(s1, s2);
if (!matches){
// TODO : do the common substring calc etc here
}
return matches;
}
@Override
public boolean matches(String s1, String s2) {
boolean matches = false;
if (s1 == null && s2 == null)
matches = true;
else{
try{
//are strings equal
matches = s1.equals(s2);
if (!matches) {
//clean the input Strings
s1 = clean(s1);
s2 = clean(s2);
//correct any author misspellings specific to the dataset being compared. e.g. change 'Linn.;' to 'L.'
s1 = translateMisspellings(s1);
s2 = translateMisspellings(s2);
//split author strings by space
String[] str1 = s1.split(" ");
String[] str2 = s2.split(" ");
//check for any abbreviated author strings in each string array and translate them
String [] transString1 = translateAbbreviation(str1);
String [] transString2 = translateAbbreviation(str2);
//merge author components back into a single string
s1 = singleString(transString1);
s2 = singleString(transString2);
//replace any full stops with spaces now abbreviations have been translated
s1 = s1.replaceAll("\\.", " ");
s2 = s2.replaceAll("\\.", " ");
//split by space again to prevent unwanted author initials corrupting the comparison results
str1 = s1.split(" ");
str2 = s2.split(" ");
//compare the common tokens now
matches = super.calculateTokensInCommon(str1, str2);
if (!matches) {
//compare the two arrays and see if any element from one appears as a substring in the other.
//only substrings of 3 or more characters are compared
matches = commonSubString(str1, str2);
if (!matches)
matches = commonSubString(str2, str1);
}
if (!matches) {
//Finally try the Ngram matcher on the two cleaned and translated author strings
s1 = singleString(str1);
s2 = singleString(str2);
NGramMatcher gram = new NGramMatcher();
gram.setMinRatio(0.5);
gram.setnGramLength(2);
matches = gram.matches(s1,s2);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return matches;
}
public String translateMisspellings(String str1) {
String misspell = null;
misspell = authorSpecialCases.get(str1);
if (misspell == null)
misspell = str1;
return misspell;
}
public String[] translateAbbreviation(String[] str1) {
String abbrev = null;
String transl = null;
String[] trans = str1;
for (int x=0; x < trans.length; x++) {
abbrev = trans[x];
transl = authorSpecialCases.get(abbrev);
if (transl != null) {
abbrev = transl;
}
transl = authorAbbreviations.get(abbrev);
if (transl != null)
trans[x] = transl;
}
return trans;
}
/*
public boolean compareStandardAbbeviations(String s1, String s2) {
boolean abbrevMatch = false;
//is one string a standard abbreviation.
if (authorAbbreviations != null) {
String abbrev = null;
if (s1.matches("\\S*\\.")) {
abbrev = authorAbbreviations.get(s1);
if (abbrev != null) {
abbrevMatch = s2.equals(abbrev);
//clean the latin characters
}
}
else if (s2.matches("\\S*\\.")) {
abbrev = authorAbbreviations.get(s2);
if (abbrev != null) {
abbrevMatch = s1.equals(abbrev);
}
}
}
return abbrevMatch;
}
*/
public String clean(String strIn) {
//replace any diacritical mark characters with 'a-z' characters and replace any 'in', 'ex', '&', 'forma' with space.
//replace '.et ' with '. '
String str1 = strIn;
try {
str1 = Normalizer.normalize(strIn, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
str1 = cleanAmp(cleanEx(cleanIn(cleanEt(cleanForma(str1)))));
}
catch (Exception e) {
}
return str1;
}
private String cleanEx(String s){
String cleaned = s;
if (s != null){
if (s.indexOf(EX_MARKER) != -1){
cleaned = s.replaceAll(EX_MARKER, " ");
}
}
return cleaned;
}
private String cleanIn(String s){
String cleaned = s;
if (s != null){
if (s.indexOf(IN_MARKER) != -1){
cleaned = s.replaceAll(IN_MARKER, " ");
}
}
return cleaned;
}
private String cleanAmp(String s){
String cleaned = s;
if (s != null){
if (s.indexOf(AMP_MARKER) != -1){
cleaned = s.replaceAll(AMP_MARKER, " ");
}
}
return cleaned;
}
private String cleanEt(String s){
String cleaned = s;
if (s != null){
if (s.indexOf(ET_MARKER) != -1){
cleaned = s.replaceAll(ET_MARKER, "\\. ");
}
}
return cleaned;
}
private String cleanForma(String s){
String cleaned = s;
if (s != null){
if (s.indexOf(FORMA_MARKER) != -1){
cleaned = s.replaceAll(FORMA_MARKER, " ");
}
}
return cleaned;
}
/*
public boolean matchAbbreviationPattern(String s1,String s2) {
boolean abbrevPatternMatch = false;
String[] splitS1 = null;
String[] splitS2 = null;
try {
splitS1 = s1.toLowerCase().replaceAll("\\.", "").split("\\s");
splitS2 = s2.toLowerCase().replaceAll("\\.", "").split("\\s");
if ((splitS1[0].startsWith(splitS2[0])) || (splitS2[0].startsWith(splitS1[0]))) {
abbrevPatternMatch = true;
}
}
catch (Exception e) {
e.printStackTrace();
}
return abbrevPatternMatch;
}
*/
public String singleString(String[] strArr) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < strArr.length; i++) {
result.append(strArr[i]).append(" ");
}
return result.toString().trim();
}
public boolean commonSubString(String[] strArr1, String[] strArr2) {
//check if any element (3 characters or greater) form one array is found as a substring in the other
String findString = null;
boolean StringMatch = false;
for (int i = 0; i < strArr1.length; i++) {
findString = strArr1[i].replaceAll("\\.", "");
if (findString.length() < 3)
continue;
for (int x = 0; x < strArr2.length; x++) {
if (strArr2[x].indexOf(findString) > -1) {
StringMatch = true;
break;
}
}
if (StringMatch)
break;
}
return StringMatch;
}
public HashMap<String, String> loadAbbreviationsList(FileInputStream abbreviationsFile, String fileSeparator) {
//load the supplied author abbreviations file into a hash map.
//as the file is loaded all diacritical marks are replaced with a-z characters and strings are stored as lower case
HashMap<String, String> map = new HashMap<String, String>();
try {
InputStreamReader streamReader = new InputStreamReader(abbreviationsFile, "UTF-8");
BufferedReader br = new BufferedReader(streamReader);
String line = null;
String sKey;
String sValue;
while ((line = br.readLine()) != null) {
String[] elem = line.split(fileSeparator);
sKey = elem[0];
sValue = elem[1];
//System.out.println(sKey + "----" + sValue);
sKey = Normalizer.normalize(sKey, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
sValue = Normalizer.normalize(sValue, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
//System.out.println(sKey + "----" + sValue);
map.put(sKey.toLowerCase(), sValue.toLowerCase());
}
}
catch (Exception e) {
e.printStackTrace();
}
return map;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
/*
* TODO: This should be moved into a unit test.
*/
public static void main(String[] args) {
//test this matcher using a test file of author pairs to match. File layout example = 'authorID%author1%author2'
//The output file shows each author pair after they are cleaned, any abbreviation translated and finally if they match.
try {
FileInputStream authorAbbs = new FileInputStream("T:/Development/Medicinal Plants/name-matching/JavaApp/data/ipni-author-abbreviations.txt");
FileInputStream specialAbbs = new FileInputStream("T:/Development/Medicinal Plants/name-matching/JavaApp/data/uwe-author-misspellings.txt");
AuthorAbbreviationsMatcher n = new AuthorAbbreviationsMatcher(authorAbbs,specialAbbs);
FileOutputStream out = new FileOutputStream("data/author-abbreviations-matcher-test-output.txt");
OutputStreamWriter streamWriter = new OutputStreamWriter(out,"UTF-8");
FileInputStream authTestFile = new FileInputStream("T:/Development/Medicinal Plants/name-matching/JavaApp/data/author-abbreviations-matcher-test-file.txt");
InputStreamReader streamReader = new InputStreamReader(authTestFile,"UTF-8");
BufferedReader br = new BufferedReader(streamReader);
String id;
String line = null;
String s1;
String s2;
String s1orig;
String s2orig;
String[] str1;
String[] str2;
StringBuffer outLn = new StringBuffer();
while ((line = br.readLine()) != null) {
String[] elem = line.split("%");
id = elem[0];
s1orig = elem[1];
s2orig = elem[2];
s1 = s1orig;
s2 = s2orig;
outLn.append(id+"%"+s1+"%"+s2+"%");
s1 = n.translateMisspellings(s1);
s2 = n.translateMisspellings(s2);
outLn.append(s1+"%"+s2+"%");
s1 = n.clean(s1);
s2 = n.clean(s2);
outLn.append(s1+"%"+s2+"%");
str1 = s1.split(" ");
str2 = s2.split(" ");
str1 = n.translateAbbreviation(str1);
str2 = n.translateAbbreviation(str2);
s1 = n.singleString(str1);
s2 = n.singleString(str2);
outLn.append(s1+"%"+s2+"%");
outLn.append(n.matches(s1orig, s2orig)+"\r\n");
streamWriter.write(outLn.toString());
outLn.setLength(0);
}
streamWriter.flush();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| 13,663 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
InitialSubstringMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/InitialSubstringMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import org.kew.rmf.transformers.ZeroToBlankTransformer;
/**
* This matcher tests for initial substring equality between the two inputs.
* @author nn00kg
*
*/
public class InitialSubstringMatcher implements Matcher {
public static int COST = 0;
public int prefixSize = 3;
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
if (s1 == null && s2 == null) return true;
if ((s1.length() > prefixSize) && (s2.length() > prefixSize )){
return s1.substring(0, prefixSize).equals(s2.substring(0, prefixSize));
}
return false;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
public int getPrefixSize() {
return prefixSize;
}
public void setPrefixSize(int prefixSize) {
this.prefixSize = prefixSize;
}
public static void main(String[] args) {
ZeroToBlankTransformer z = new ZeroToBlankTransformer();
InitialSubstringMatcher ism = new InitialSubstringMatcher();
ism.setPrefixSize(3);
System.out.println(ism.matches(z.transform("1794"), z.transform("1802")));
}
}
| 1,921 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
TokensInSequenceMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/TokensInSequenceMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.kew.rmf.transformers.StripNonNumericCharactersTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This matcher returns a match if the shorter list of tokens occurs in order
* in the longer list of tokens - e.g. "10 2 140" and "10 140" will match, but
* "10 2 140" and "10 141" will not.
* @author nn00kg
*/
public class TokensInSequenceMatcher extends TokeniserMatcher {
public static int COST = 5;
private static Logger logger = LoggerFactory.getLogger(TokensInSequenceMatcher.class);
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
logger.trace("s1: {}", s1);
logger.trace("s2: {}", s2);
if (s1 == null && s2 == null) return true;
String[] a1 = convToArray(s1);
logger.trace("{}", (Object[]) a1);
String[] a2 = convToArray(s2);
logger.trace("{}", (Object[]) a2);
return calculateTokensInSequence(a1,a2);
}
public Boolean calculateTokensInSequence(String[] s1, String[] s2){
List<String> superset = null;
List<String> subset = null;
if (s1.length > s2.length){
superset = new ArrayList<String>(Arrays.asList(s1));
subset = new ArrayList<String>(Arrays.asList(s2));;
}
else{
superset = new ArrayList<String>(Arrays.asList(s2));;
subset = new ArrayList<String>(Arrays.asList(s1));
}
boolean tokensInSeq = false;
for (String s : superset){
if (subset.size() > 0){
if (s.equals(subset.get(0)))
subset.remove(0);
}
}
tokensInSeq = (subset.size() == 0);
return tokensInSeq;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
/*
* TODO: Looks like this should be in a test.
*/
public static void main(String[] args) {
TokensInSequenceMatcher tsm = new TokensInSequenceMatcher();
StripNonNumericCharactersTransformer stripper = new StripNonNumericCharactersTransformer();
tsm.setDelimiter(" ");
try{
System.out.println(tsm.matches(stripper.transform("10(1): 121"), stripper.transform("10: 121")));
System.out.println(tsm.matches(stripper.transform("10(1): 122"), stripper.transform("10: 122")));
System.out.println(tsm.matches(stripper.transform("10(2): 122"), stripper.transform("10: 122")));
System.out.println(tsm.matches(stripper.transform("10(2): 122"), stripper.transform("10: 124")));
System.out.println(tsm.matches("1 3", "1 2 3"));
System.out.println(tsm.matches("1", "1 2 3"));
System.out.println(tsm.matches("", "1 2 3"));
}
catch(Exception e){
e.printStackTrace();
}
}
}
| 3,640 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
AuthorCommonTokensMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/AuthorCommonTokensMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.authors.StripExAuthorTransformer;
import org.kew.rmf.transformers.authors.StripInAuthorTransformer;
/**
* This matcher tests for common tokens in two authorship strings
* @author nn00kg
*/
public class AuthorCommonTokensMatcher extends CommonTokensMatcher{
public static int COST = 1;
final private StripInAuthorTransformer inCleaner = new StripInAuthorTransformer();
final private StripExAuthorTransformer exCleaner = new StripExAuthorTransformer();
final private StripNonAlphanumericCharactersTransformer stripNonDs = new StripNonAlphanumericCharactersTransformer();
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
boolean matches = false;
if (s1 == null && s2 == null)
matches = true;
else{
matches = super.matches(clean(s1),clean(s2));
}
return matches;
}
private String clean(String s) {
return this.inCleaner.transform(this.exCleaner.transform(this.stripNonDs.transform(s)));
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
}
| 2,126 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
AlwaysMatchingMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/AlwaysMatchingMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher returns true in all cases.
* @author nn00kg
*/
public class AlwaysMatchingMatcher implements Matcher {
public static int COST = 0;
@Override
public int getCost() {
return COST;
}
@Override
public boolean matches(String s1, String s2) {
return true;
}
@Override
public boolean isExact() {
return true;
}
@Override
public String getExecutionReport() {
return null;
}
}
| 1,197 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Matcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/Matcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This interface defines the behaviour expected of Matchers.
* Some matches are expensive to calculate, so matchers have a cost:
* zero - low, higher int values = higher cost.
* When multiple matchers are defined, it is expected that they will be
* evaluated in order of cost (lowest first).
*
* @author nn00kg
*/
public interface Matcher {
public boolean matches(String s1, String s2) throws MatchException;
public boolean isExact();
public int getCost();
public String getExecutionReport();
}
| 1,296 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CompositeAllMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/CompositeAllMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
/**
* This matcher is wrapper for multiple matchers,
* all of which must match.
* @author nn00kg
*
*/
public class CompositeAllMatcher extends CompositeMatcher{
@Override
public boolean matches(String s1, String s2) throws MatchException {
boolean matches = true;
for (Matcher m : matchers)
if (!m.matches(s1, s2)){
matches = false;
break;
}
return matches;
}
}
| 1,176 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CapitalLettersMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/CapitalLettersMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import org.kew.rmf.transformers.CapitalLettersExtractor;
/**
* This matcher tests for common tokens using only the capital letters in the strings supplied.
*/
public class CapitalLettersMatcher extends CommonTokensMatcher{
CapitalLettersExtractor removeNonCaps = new CapitalLettersExtractor();
public CapitalLettersMatcher() {
this.removeNonCaps.setReplacement(this.getDelimiter());
}
@Override
public boolean matches(String s1, String s2) {
if (s1 == null && s2 == null) return true;
return super.matches(this.removeNonCaps.transform(s1), this.removeNonCaps.transform(s2));
}
@Override
public void setDelimiter(String delimiter) {
super.setDelimiter(delimiter);
this.removeNonCaps.setReplacement(this.getDelimiter());
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
}
| 1,659 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
NumberInRangeMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/NumberInRangeMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* This matcher tests for a number appearing in a number range, e.g. "34" ? "12-18 30-36" is true.
*/
public class NumberInRangeMatcher implements Matcher {
private static final String rangesRegex = "\\b(\\d+)([-–—+]?|\\b)(\\d*\\b?)";
private static final Pattern rangesPattern = Pattern.compile(rangesRegex);
@Override
public boolean matches(String s1, String s2) {
// Search for ranges
if (s1 == null && s2 == null) return true;
if (s1 == null || s1.length() == 0) return false;
int n;
try {
n = Integer.parseInt(s1);
}
catch (NumberFormatException e) {
return false;
}
// Find ranges
for (int[] range : findRanges(s2)) {
if (range[0] <= n && n <= range[1]) {
return true;
}
}
return false;
}
private ArrayList<int[]> findRanges(String s) {
ArrayList<int[]> ranges = new ArrayList<>();
if (s != null) {
java.util.regex.Matcher m = rangesPattern.matcher(s);
while (m.find()) {
int[] r = new int[2];
try {
// Start of range
r[0] = Integer.parseInt(m.group(1));
if (m.group(3).isEmpty()) {
// + and no end means open ended
if ("+".equals(m.group(2))) {
r[1] = Integer.MAX_VALUE;
}
else {
r[1] = r[0];
}
}
else {
r[1] = Integer.parseInt(m.group(3));
}
// Check for ranges like "32-5", "1843-88", which really mean "32-35", "1843-1888"
if (r[1] < r[0]) {
int magEnd = r[1] / 10 + 1;
r[1] = (r[0] / magEnd) * magEnd + r[1];
}
}
catch (NumberFormatException e) {
continue;
}
ranges.add(r);
}
}
return ranges;
}
@Override
public boolean isExact() {
return false;
}
@Override
public String getExecutionReport() {
return null;
}
@Override
public int getCost() {
return 3;
}
}
| 2,646 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
TokeniserMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/TokeniserMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.Arrays;
/**
* Abstract {@link Matcher} to split a string into delimited tokens before matching.
* <br/>
* By default with {@link #minLength} <code>1</code>, empty tokens are ignored.
*/
public abstract class TokeniserMatcher implements Matcher {
private String delimiter = " ";
protected int minLength = 1;
protected String[] convToArray(String s) {
if (s == null) { return new String[0]; }
String[] a = s.split(this.delimiter, -1);
// if delimiter is blank we want every element to be represented as one item in the array;
// however, the first and last element swould be blank, which we correct here.
if (this.getDelimiter().isEmpty()) a = Arrays.copyOfRange(a, 1, a.length -1);
// remove elements that are too short
if (minLength > 0) {
int bi = 0;
String[] b = new String[a.length];
for (int ai = 0; ai < a.length; ai++) {
if (a[ai].length() >= minLength) {
b[bi++] = a[ai];
}
}
a = Arrays.copyOf(b, bi);
}
return a;
}
public String getDelimiter() {
return delimiter;
}
/**
* Set the delimiter. The default is " " (a space).
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public int getMinLength() {
return minLength;
}
/**
* Set the minimum token length. To preserve empty tokens (caused by adjacent delimiters)
* set this to zero.
*/
public void setMinLength(int minLength) {
this.minLength = minLength;
}
}
| 2,236 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CompositeMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/matchers/CompositeMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchers;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This abstract class defines a composite matcher, a wrapper for multiple matchers
* @author nn00kg
*
*/
public abstract class CompositeMatcher implements Matcher{
protected List<Matcher> matchers;
@Override
public abstract boolean matches(String s1, String s2) throws MatchException;
public List<Matcher> getMatchers() {
return matchers;
}
public void setMatchers(List<Matcher> matchers) {
this.matchers = matchers;
Collections.sort(matchers, new Comparator<Matcher>() {
@Override
public int compare(Matcher m1,Matcher m2) {
return Integer.valueOf(m1.getCost()).compareTo(Integer.valueOf(m2.getCost()));
}
});
}
@Override
public boolean isExact() {
boolean exact = true;
for (Matcher m : matchers){
exact = m.isExact();
if (!exact)
break;
}
return exact;
}
@Override
public int getCost() {
int cost = 0;
for (Matcher m : matchers)
cost += m.getCost();
return cost;
}
@Override
public String getExecutionReport() {
StringBuffer sb = new StringBuffer();
for (Matcher m : matchers)
sb.append(m.getExecutionReport()).append("\n");
return sb.toString();
}
} | 2,029 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneReporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/LuceneReporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.kew.rmf.core.lucene.DocList;
public abstract class LuceneReporter extends Reporter {
protected static String[] AVAILABLE_FIELDS = new String[] {};
@Override
protected String[] getAvailableFields () {
return (String[]) ArrayUtils.addAll(super.getAvailableFields(), LuceneReporter.AVAILABLE_FIELDS);
}
protected void writeHeader(DocList docs) throws IOException {
this.writeHeader();
}
public void report (DocList docs) throws Exception {
docs.sort();
this.report(docs.getFromDocAsMap(), docs.storeToMapList());
}
protected String getIDsInCluster(Map<String, String> fromRecord, List<Map<String, String>> cluster, String delimiter) {
List<String> ids = new ArrayList<>();
for (Map<String, String> record:cluster) {
ids.add(record.get(this.idFieldName));
}
return StringUtils.join(ids, " " + this.idDelimiter + " ");
}
protected String getFromId(Map<String, String> fromRecord, List<Map<String, String>> cluster) {
return fromRecord.get(this.idFieldName);
}
// TODO: For now only ranked according to scoreField values, no match-specific ranking!
protected String getRank(Map<String, String> fromRecord, List<Map<String, String>> cluster) {
int i = 1;
for (Map<String, String> rec:cluster) {
if (fromRecord.get(this.getIdFieldName()).equals(rec.get(this.getIdFieldName()))) {
break;
}
i++;
}
return Integer.toString(i);
}
protected String getConfigLog() {
return this.configName;
}
protected String getBestRecordId(List<Map<String, String>> cluster) {
return cluster.get(0).get(this.idFieldName);
}
}
| 2,556 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchReporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/MatchReporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class MatchReporter extends LuceneReporter {
protected static String[] AVAILABLE_FIELDS = new String[] {"configLog", "total_matches", "matching_ids"};
public MatchReporter() {
logger.info("I will be creating an enhanced output file for you with additional fields: " +
this.getAvailableFieldsAsString());
}
@Override
protected String[] getAvailableFields () {
return (String[]) ArrayUtils.addAll(super.getAvailableFields(), MatchReporter.AVAILABLE_FIELDS);
}
/**
* Returns one line for one identified cluster containing the stored fields for
* the 'best' record + additional info
*/
@Override
public void reportResults (Map<String, String> fromRecord, List<Map<String, String>> matches) throws IOException {
String namespace = this.getNameSpacePrefix();
fromRecord.put("configLog", this.getConfigLog());
fromRecord.put(namespace + "total_matches", this.getClusterSize(fromRecord, matches));
fromRecord.put(namespace + "matching_ids", this.getIDsInCluster(fromRecord, matches, this.getIdDelimiter()));
// add the authority values of the best match
if (matches.size() > 0) fromRecord.putAll(Reporter.getNamespacedCopy(matches.get(0), namespace + "authority_"));
this.writer.write(fromRecord, this.header);
}
}
| 2,262 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Reporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/Reporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.prefs.CsvPreference;
/**
* This is a CsvReporter really.
*
* Its subclasses manage the output of the deduplication/matching process,
* receive it row by row and write it wherever they are configured to do so.
*
* TODO: design and implement the Reporter subclass to be more generic than
* csv-focused.
*/
public abstract class Reporter implements AutoCloseable {
protected static String[] AVAILABLE_FIELDS = new String[] {};
protected String name;
protected String nameSpacePrefix = "";
protected String configName;
protected String delimiter;
protected String idDelimiter;
protected File file;
protected CsvMapWriter writer;
protected String sortFieldName;
protected String idFieldName;
protected Logger logger;
protected boolean wantHeader = true; // TODO: make configurable
protected boolean isStart = true;
protected String[] definedOutputFields;
protected String[] header;
protected Reporter () {
this.logger = LoggerFactory.getLogger(this.getClass());
}
protected String[] getAvailableFields () {
return Reporter.AVAILABLE_FIELDS;
}
protected String getAvailableFieldsAsString() {
return StringUtils.join(this.getAvailableFields(), ", ");
}
protected void writeHeader() throws IOException {
String[] fields = this.getAvailableFields();
// name-space the field names
for (int i=0;i<fields.length;i++) {
fields[i] = this.getNameSpacePrefix() + fields[i];
}
this.header = (String[]) ArrayUtils.addAll(new String[] {"id"}, ArrayUtils.addAll(this.definedOutputFields, fields));
this.writer.writeHeader(header);
}
public abstract void reportResults (Map<String, String> record, List<Map<String, String>> results) throws Exception;
/**
* Meta method to deal with a 'main' record and a list of attached maps, the
* results of a deduplication/matching process.
*
* 'Meta' means it only writes a header if wanted and no header is written yet,
* and then passes the objects back to the method reportResults by the calling subclass
* If there is any meaning in the order of the results, it will be preserved
* but is expected to be already sorted.
*
* @param record
* @param results
* @throws IOException
*/
public void report (Map<String, String> record, List<Map<String, String>> results) throws Exception {
if (this.isStart) {
this.setWriter();
if (this.wantHeader) this.writeHeader();
this.setStart(false);
}
logger.debug("Reporting record {} with results {}", record, results);
this.reportResults(record, results);
}
protected static Map<String, String> getNamespacedCopy(Map<String, String> record, String namespace) {
Map<String, String> copy = new HashMap<>();
for (String key:record.keySet()) copy.put(namespace + key, record.get(key));
return copy;
}
@Override
public void close() throws IOException {
this.writer.flush();
this.writer.close();
}
protected String getClusterSize(Map<String, String> fromRecord, List<Map<String, String>> cluster){
return Integer.toString(cluster.size());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setFile(File file) throws IOException {
this.file = file;
}
public void setWriter() throws IOException {
// TODO: either make quote characters and line break characters configurable or simplify even more?
CsvPreference customCsvPref = new CsvPreference.Builder('"', this.getDelimiter().charAt(0), "\n").build();
this.writer = new CsvMapWriter(new OutputStreamWriter(new FileOutputStream(this.file), "UTF-8"), customCsvPref);
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public String getIdDelimiter() {
return idDelimiter;
}
public void setIdDelimiter(String idDelimiter) {
this.idDelimiter = idDelimiter;
}
public String getSortFieldName() {
return sortFieldName;
}
public void setSortFieldName(String sortFieldName) {
this.sortFieldName = sortFieldName;
}
public String getIdFieldName() {
return idFieldName;
}
public void setIdFieldName(String idFieldName) {
this.idFieldName = idFieldName;
}
public boolean isWantHeader() {
return wantHeader;
}
public void setWantHeader(boolean wantHeader) {
this.wantHeader = wantHeader;
}
public boolean isStart() {
return isStart;
}
public void setStart(boolean isStart) {
this.isStart = isStart;
}
public String[] getDefinedOutputFields() {
return definedOutputFields;
}
public void setDefinedOutputFields(String[] definedOutputFields) {
this.definedOutputFields = definedOutputFields;
}
public String getNameSpacePrefix() {
return nameSpacePrefix;
}
public void setNameSpacePrefix(String nameSpacePrefix) {
this.nameSpacePrefix = nameSpacePrefix;
}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName;
}
}
| 6,670 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DedupReporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/DedupReporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class DedupReporter extends LuceneReporter {
protected static String[] AVAILABLE_FIELDS = new String[] {"cluster_size", "from_id", "ids_in_cluster"};
public DedupReporter() {
logger.info("I will be creating an enhanced output file for you with additional fields: " +
this.getAvailableFieldsAsString());
}
@Override
protected String[] getAvailableFields () {
return (String[]) ArrayUtils.addAll(super.getAvailableFields(), DedupReporter.AVAILABLE_FIELDS);
}
/*
* Returns one line for one identified cluster containing the stored fields for
* the 'best' record + additional info
*
*/
@Override
public void reportResults(Map<String, String> fromRecord, List<Map<String, String>> cluster) throws Exception {
String namespace = this.getNameSpacePrefix();
Map<String, String> topCopy = cluster.get(0);
topCopy.put(namespace + "cluster_size", this.getClusterSize(fromRecord, cluster));
topCopy.put(namespace + "from_id", this.getFromId(fromRecord, cluster));
topCopy.put(namespace + "ids_in_cluster", this.getIDsInCluster(fromRecord, cluster, this.getIdDelimiter()));
this.writer.write(topCopy, this.header);
}
}
| 2,035 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Piper.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/Piper.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.IOException;
import java.util.Map;
/**
* A piper is a reporter used for immediately writing out a record without
* calling all the special bits and bobs methods; it basically represents the
* 'continue' statement in the reporting logic, without swallowing the record
* itself away
*/
public class Piper {
private Reporter reporter;
public Piper(Reporter reporter) {
this.reporter = reporter;
}
public void pipe(Map<String, String> record) throws IOException {
Reporter rep = this.getReporter();
if (rep.isStart()) {
rep.setWriter();
if (rep.wantHeader) rep.writeHeader();
rep.setStart(false);
}
rep.writer.write(record, rep.header);
}
public Reporter getReporter() {
return reporter;
}
}
| 1,609 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DarwinCoreArchiveExtensionReporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/DarwinCoreArchiveExtensionReporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
public class DarwinCoreArchiveExtensionReporter extends LuceneReporter {
protected static String[] AVAILABLE_FIELDS = new String[] {"id", "matching_ids"};
public DarwinCoreArchiveExtensionReporter() {
logger.info("I will be creating an enhanced output file for you with additional fields: " +
this.getAvailableFieldsAsString());
}
@Override
protected String[] getAvailableFields () {
return new String[0];
}
@Override
protected void writeHeader() throws IOException {
this.header = AVAILABLE_FIELDS;
this.writer.writeHeader(header);
}
/**
* Returns one line for one identified cluster containing the stored fields for
* the 'best' record + additional info
*/
@Override
public void reportResults (Map<String, String> fromRecord, List<Map<String, String>> matches) throws IOException {
String namespace = this.getNameSpacePrefix();
// fromRecord.put("configLog", this.getConfigLog());
// fromRecord.put(namespace + "total_matches", this.getClusterSize(fromRecord, matches));
this.getIDsInCluster(fromRecord, matches, this.getIdDelimiter());
String highestScoringMatch = getHighestScoringMatch(fromRecord, matches, this.getIdDelimiter());
fromRecord.put(namespace + "matching_ids", highestScoringMatch);
// add the authority values of the best match
//if (matches.size() > 0) fromRecord.putAll(Reporter.getNamespacedCopy(matches.get(0), namespace + "authority_"));
if (highestScoringMatch != null) this.writer.write(fromRecord, this.header);
}
protected String getHighestScoringMatch(Map<String, String> fromRecord, List<Map<String, String>> cluster, String delimiter) {
double bestScore = -1;
double s;
String bestId = null;
for (Map<String, String> record : cluster) {
s = Double.parseDouble(record.get("_score"));
if (s > bestScore) {
bestId = record.get(this.idFieldName);
bestScore = s;
}
}
return bestId;
}
}
| 3,023 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DedupReporterMultiline.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/reporters/DedupReporterMultiline.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.reporters;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class DedupReporterMultiline extends LuceneReporter {
protected static String[] AVAILABLE_FIELDS = new String[] {"cluster_size", "best_record_id", "rank"};
public DedupReporterMultiline() {
logger.info("I will be creating a file containing a row for each record in a cluster; additional fields: " +
this.getAvailableFieldsAsString());
}
@Override
protected String[] getAvailableFields () {
return (String[]) ArrayUtils.addAll(super.getAvailableFields(), DedupReporterMultiline.AVAILABLE_FIELDS);
}
@Override
public void reportResults(Map<String, String> fromRecord, List<Map<String, String>> cluster) throws IOException {
String namespace = this.getNameSpacePrefix();
// TODO: make sure the fromRecord is in the cluster (should be!)
for (Map<String, String> record:cluster) {
record.put(namespace + "cluster_size", this.getClusterSize(fromRecord, cluster));
record.put(namespace + "best_record_id", this.getBestRecordId(cluster));
record.put(namespace + "rank", this.getRank(record, cluster));
this.writer.write(record, this.header);
}
}
}
| 2,008 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DataHandler.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/DataHandler.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import org.kew.rmf.core.configuration.Configuration;
/**
* The DataHandler does all the work.
* It loads the data and runs a process as defined in the provided configuration.
*
* @param <Config>
*/
public interface DataHandler<Config extends Configuration> {
public void setConfig(Config config);
public void setDataLoader(DataLoader dataLoader);
public void loadData() throws Exception;
public void run() throws Exception;
}
| 1,217 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DatabaseRecordSource.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/DatabaseRecordSource.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Reads records from a database.
*/
public interface DatabaseRecordSource {
public ResultSet getResultSet() throws SQLException;
public int count() throws SQLException;
public void close() throws SQLException;
}
| 1,057 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CoreApp.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/CoreApp.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
/**
* Everything begins here.
*/
public class CoreApp {
private static final Logger logger = LoggerFactory.getLogger(CoreApp.class);
public static void main(String[] args) throws Exception {
// Some arguments possibly want to be picked up from the command-line
CommandLine line = getParsedCommandLine(args);
// where is the work directory that contains the design configuration as well
// as the data files?
String workDir = ".";
if (line.hasOption("d")) workDir = line.getOptionValue("d").trim();
// the name of the core configuration file that contains the dedup/match design
// NOTE this is relative to the working directory
String configFileName = "config.xml";
if (line.hasOption("c")) configFileName = line.getOptionValue("c").trim();
String dedupDesign = "file:" + new File(new File(workDir), configFileName).toPath();
runEngineAndCache(new GenericXmlApplicationContext(dedupDesign));
}
protected static CommandLine getParsedCommandLine(String[] args) throws ParseException {
CommandLineParser argParser = new GnuParser();
final Options options = new Options();
options.addOption("d", "data-dir", true,
"location of the directory containing the config and the input and output files");
options.addOption("c", "config-file", true,
"name of the config file (default: 'config.xml')");
CommandLine line = argParser.parse( options, args );
return line;
}
/**
* Get the "engine" bean from the Spring config - Spring has instantiated it
* with the values set in the application-context file, which defaults to
* deduplication mode. If the context provided is a matching one, the bean
* definition will be changed prior to its initialisation.
* @param context
* @throws Exception
*/
protected static void runEngineAndCache (ConfigurableApplicationContext context) throws Exception {
DataHandler<?> engine = (DataHandler<?>) context.getBean("engine");
// Call the run method
engine.run();
}
}
| 3,188 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DataLoader.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/DataLoader.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.exception.DataLoadException;
public interface DataLoader{
public void load() throws DataLoadException, InterruptedException;
public void setConfig(Configuration config);
}
| 1,030 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
JavaScriptEnv.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/script/JavaScriptEnv.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.script;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.google.gson.Gson;
/**
* This boxed javascript environment is able to evaluate a string as javascript.
*
* The available data to evaluate on is provided in form of a map of strings, hence
* a typical task would be "record['columnA'] > 10 && record['columnB'] != 'jumpOverMe'"
*/
public class JavaScriptEnv {
private ScriptEngineManager factory;
public JavaScriptEnv() {
this.factory = new ScriptEngineManager();
}
public boolean evalFilter(String s, Map<String, String> record) throws ScriptException {
Gson gson = new Gson();
ScriptEngine engine = this.factory.getEngineByName("JavaScript");
String recordJson = gson.toJson(record);
engine.put("record_json", recordJson);
try {
s = "var record = new Object(JSON.parse(record_json));" + s;
return (boolean) engine.eval(s);
} catch (NullPointerException e) {
throw new NullPointerException("The record filter should return either true or false! -- " + e.toString());
}
}
}
| 1,984 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneDataLoader.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/LuceneDataLoader.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.kew.rmf.core.DataLoader;
import org.kew.rmf.core.DatabaseRecordSource;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.configuration.Property;
import org.kew.rmf.core.exception.DataLoadException;
import org.kew.rmf.transformers.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.io.CsvMapReader;
import org.supercsv.prefs.CsvPreference;
/**
* This implementation reads a file and stores its content in a Lucene index.
* The rules for this are defined in the corresponding Configuration.
*/
public class LuceneDataLoader implements DataLoader {
/**
* RAM buffer to use for loading data into Lucene.
*/
private static final double RAM_BUFFER_SIZE = 64;
private org.apache.lucene.util.Version luceneVersion;
/**
* The IndexWriter is set in {@link #openIndex()}, and closed at the end of {@link #load()}.
*/
private IndexWriter indexWriter;
private FSDirectory directory;
private Analyzer luceneAnalyzer;
private Configuration config;
private String configName;
private static Logger logger = LoggerFactory.getLogger(LuceneDataLoader.class);
/**
* Load the authority data into Lucene.
*/
@Override
public void load() throws DataLoadException, InterruptedException {
try {
int count = -1;
/*
* In case no file is specified we (assuming a de-duplication task) use the
* queryFile also for index creation.
*
* This is why we copy over the query-related properties to the
* authority-related ones
*/
if (config.getAuthorityRecords() == null) {
if (config.getAuthorityFile() == null) {
for (Property p : config.getProperties()) {
p.setAuthorityTransformers(p.getQueryTransformers());
p.setAddOriginalAuthorityValue(p.isAddOriginalQueryValue());
p.setAddTransformedAuthorityValue(p.isAddTransformedQueryValue());
p.setAuthorityColumnName(p.getQueryColumnName());
}
config.setAuthorityFile(config.getQueryFile());
config.setAuthorityFileEncoding(config.getQueryFileEncoding());
config.setAuthorityFileDelimiter(config.getQueryFileDelimiter());
config.setAuthorityFileQuoteChar(config.getQueryFileQuoteChar());
}
// Count file
try {
count = this.count(config.getAuthorityFile());
}
catch (Exception e) {
logger.error("Error counting records in authority file", e);
count = -1;
}
}
else {
// Count file
try {
count = this.count(config.getAuthorityRecords());
}
catch (Exception e) {
logger.error("Error counting records in authority database", e);
count = -1;
}
}
indexWriter = openIndex();
// Reuse index if configured, and if it contains the expected number of records.
if (getConfig().isReuseIndex()) {
if (count < 0) {
logger.info("{}: Cannot reuse index as required size is unknown", configName);
}
else {
logger.debug("{}: Checking whether to reuse index, expecting {} records", configName, count);
int numDocs = indexWriter.numDocs();
if (numDocs == count) {
logger.warn("{}: Reusing index, since it contains {} entries as expected", configName, numDocs);
return;
}
else {
logger.info("{}: Wiping incomplete ({}/{} records) index", configName, numDocs, count);
indexWriter.deleteAll();
indexWriter.commit();
}
}
}
logger.info("{}: Starting data load", configName);
if (config.getAuthorityRecords() == null) {
this.load(config.getAuthorityFile(), count);
}
else {
this.load(config.getAuthorityRecords(), count);
}
int numDocs = indexWriter.numDocs();
logger.info("{}: Completed index contains {} records", configName, numDocs);
}
catch (IOException e) {
throw new DataLoadException(configName + ": Problem creating/opening Lucene index", e);
}
finally {
// Close the index, no matter what happened.
try {
if (indexWriter != null) {
indexWriter.close();
logger.info("{}: IndexWriter {} closed", configName, indexWriter.getDirectory());
}
}
catch (IOException e) {
throw new DataLoadException(configName + ": Error closing Lucene index for "+configName, e);
}
}
}
/**
* Opens an IndexWriter, reusing or wiping an existing index according to the configuration.
*/
private IndexWriter openIndex() throws IOException {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(getLuceneVersion(), luceneAnalyzer);
indexWriterConfig.setRAMBufferSizeMB(RAM_BUFFER_SIZE);
if (getConfig().isReuseIndex()) {
// Reuse the index if it exists, otherwise create a new one.
logger.debug("{}: Reusing existing index, if it exists", configName);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
}
else {
// Create a new index, overwriting any that already exists.
logger.debug("{}: Overwriting existing index, if it exists", configName);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
}
IndexWriter indexWriter;
try {
indexWriter = new IndexWriter(directory, indexWriterConfig);
}
catch (IOException e) {
logger.warn("Exception while creating index, removing index directory and retrying", e);
// Try deleting the index directory.
File dir = directory.getDirectory();
if (dir.isDirectory() && dir.listFiles() != null) {
logger.warn("{}: Wiping existing index directory {}", configName, dir);
FileUtils.deleteDirectory(dir);
}
indexWriter = new IndexWriter(directory, indexWriterConfig);
}
return indexWriter;
}
/**
* Count the number of records in a file.
*/
private int count(File file) throws DataLoadException, InterruptedException {
int i = 0;
int errors = 0;
logger.info("{}: Counting records in {}", configName, file);
char delimiter = this.config.getAuthorityFileDelimiter().charAt(0);
char quote = this.config.getAuthorityFileQuoteChar().charAt(0);
CsvPreference customCsvPref = new CsvPreference.Builder(quote, delimiter, "\n").build();
try (CsvMapReader mr = new CsvMapReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), customCsvPref)) {
final String[] header = mr.getHeader(true);
Map<String, String> record;
record = mr.read(header);
while (record != null) {
// Read next record from CSV/datasource
try {
i++;
record = mr.read(header);
}
catch (Exception e) {
errors++;
String message = configName + ": Problem reading record " + i + " «" + mr.getUntokenizedRow() + "»";
if (errors < config.getMaximumLoadErrors()) {
logger.warn(message, e);
}
else{
throw new DataLoadException(message, e);
}
}
}
logger.info("{}: Counted {} records ({} errors)", configName, i, errors);
return i;
}
catch (Exception e) {
throw new DataLoadException(configName + ": Error "+e.getMessage()+" loading records at line " + i, e);
}
}
/**
* Count the number of records in a file.
*/
private int count(DatabaseRecordSource recordSource) throws DataLoadException {
try {
return recordSource.count();
}
catch (SQLException e) {
throw new DataLoadException(this.config.getName() + ": Unable to count records", e);
}
}
private void load(DatabaseRecordSource recordSource, int total) throws DataLoadException, InterruptedException {
int i = 0;
int errors = 0;
ResultSet resultSet;
try {
resultSet = recordSource.getResultSet();
}
catch (SQLException e) {
throw new DataLoadException(configName + ": Problem reading data from database "+recordSource, e);
}
try {
// check whether the necessary column names are present in the ResultSet
for (String headerName : this.config.getPropertyAuthorityColumnNames()) {
try {
resultSet.findColumn(headerName);
}
catch (SQLException se) {
throw new DataLoadException(String.format("%s: Database result doesn't contain field name «%s» as defined in config.", this.config.getName(), headerName));
}
}
// same for the id-field
try {
resultSet.findColumn(Configuration.ID_FIELD_NAME);
}
catch (SQLException se) {
throw new DataLoadException(String.format("%s: Database result doesn't contain field name «%s» as defined in config.", this.config.getName(), Configuration.ID_FIELD_NAME));
}
Document doc = null;
while (resultSet.next()) {
// Index record
try{
doc = this.indexRecord(resultSet);
}
catch (Exception e) {
errors++;
String message = configName + ": Problem indexing record " + i + ", " + resultSet;
if (errors < config.getMaximumLoadErrors()) {
logger.warn(message, e);
}
else {
throw new DataLoadException(message, e);
}
}
// Log progress
if (i++ % this.config.getLoadReportFrequency() == 0) {
logger.info("{}: Indexed {} records ({}%, {} errors)", configName, i-errors, total > 0 ? ((float)i)/total*100 : "?", errors);
logger.debug("{}: Most recent indexed document was {}", configName, doc);
}
// Check for interrupt
if (i % 10000 == 0 && Thread.interrupted()) {
recordSource.close();
indexWriter.commit();
logger.info("{}: Loader interrupted after indexing {}th record", configName, i);
throw new InterruptedException("Interrupted while loading data");
}
}
recordSource.close();
indexWriter.commit();
}
catch (InterruptedException e) {
throw e;
}
catch (Exception e) {
throw new DataLoadException(configName + ": Error "+e.getMessage()+" loading records at row " + i, e);
}
logger.info("{}: Indexed {} records", configName, i);
}
private void load(File file, int total) throws DataLoadException, InterruptedException {
int i = 0;
int errors = 0;
char delimiter = this.config.getAuthorityFileDelimiter().charAt(0);
char quote = this.config.getAuthorityFileQuoteChar().charAt(0);
CsvPreference customCsvPref = new CsvPreference.Builder(quote, delimiter, "\n").build();
logger.info("Reading CSV from {} with delimiter {} and quote {}", file, delimiter, quote);
try (CsvMapReader mr = new CsvMapReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), customCsvPref)) {
final String[] header = mr.getHeader(true);
// check whether the header column names fit to the ones specified in the configuration
List<String> headerList = Arrays.asList(header);
for (String name:this.config.getPropertyAuthorityColumnNames()) {
if (!headerList.contains(name)) throw new DataLoadException(String.format("%s: Header doesn't contain field name < %s > as defined in config.", this.config.getAuthorityFile().getPath(), name));
}
// same for the id-field
String idFieldName = Configuration.ID_FIELD_NAME;
if (!headerList.contains(idFieldName)) throw new DataLoadException(String.format("%s: Id field name not found in header, should be %s!", this.config.getAuthorityFile().getPath(), idFieldName));
Map<String, String> record;
record = mr.read(header);
logger.debug("{}: First read record is {}", configName, record);
Document doc = null;
while (record != null) {
// Index record
try {
doc = this.indexRecord(record);
}
catch (Exception e) {
errors++;
String message = configName + ": Problem indexing record " + i + ", " + record;
if (errors < config.getMaximumLoadErrors()) {
logger.warn(message, e);
}
else{
throw new DataLoadException(message, e);
}
}
// Log process
if (i++ % this.config.getLoadReportFrequency() == 0){
logger.info("{}: Indexed {} records ({}%, {} errors)", configName, i-errors, total > 0 ? ((float)i)/total*100 : "?", errors);
logger.debug("{}: Most recent indexed document was {}", configName, doc);
}
// Check for interrupt
if (i % 10000 == 0 && Thread.interrupted()) {
indexWriter.commit();
logger.info("{}: Loader interrupted after indexing {}th record", configName, i);
throw new InterruptedException("Interrupted while loading data");
}
// Read next record from CSV/datasource
try {
record = mr.read(header);
}
catch (Exception e) {
errors++;
String message = configName + ": Problem reading record " + i + " «" + mr.getUntokenizedRow() + "»";
if (errors < config.getMaximumLoadErrors()) {
logger.warn(message, e);
}
else{
throw new DataLoadException(message, e);
}
}
}
indexWriter.commit();
}
catch (InterruptedException e) {
throw e;
}
catch (Exception e) {
throw new DataLoadException(configName + ": Error "+e.getMessage()+" loading records at line " + i, e);
}
logger.info("{}: Read {} records, indexed {}, {} errors", configName, i, i-errors, errors);
}
/**
* Adds a single record to the Lucene index
* @param record
* @throws Exception
*/
private Document indexRecord(ResultSet record) throws Exception {
Document doc = new Document();
String idFieldName = Configuration.ID_FIELD_NAME;
logger.trace("rawRecord: {}", record.toString());
doc.add(new StringField(idFieldName, record.getString(idFieldName), Field.Store.YES));
// The remainder of the columns are added as specified in the properties
for (Property p : this.config.getProperties()) {
String authorityName = p.getAuthorityColumnName() + Configuration.TRANSFORMED_SUFFIX;
String value = record.getString(p.getAuthorityColumnName());
if (value == null) value = "";
// Index the value in its original state, pre transformation
Field f = new TextField(p.getAuthorityColumnName(), value, Field.Store.YES);
doc.add(f);
// then transform the value if necessary
for (Transformer t:p.getAuthorityTransformers()) {
value = t.transform(value);
}
// and add this one to the index
Field fTransformed = new TextField(authorityName, value, Field.Store.YES);
doc.add(fTransformed);
// For some fields (those which will be passed into a fuzzy matcher like Levenshtein), we index the length
if (p.isIndexLength()){
Field fLength = new StringField(authorityName + Configuration.LENGTH_SUFFIX, String.format("%02d", value.length()), Field.Store.YES);
doc.add(fLength);
}
if (p.isIndexInitial() & StringUtils.isNotBlank(value)){
Field finit = new TextField(authorityName + Configuration.INITIAL_SUFFIX, value.substring(0, 1), Field.Store.YES);
doc.add(finit);
}
}
logger.trace("Document to be indexed: {}", doc.toString());
this.indexWriter.addDocument(doc);
return doc;
}
private Document indexRecord(Map<String, String> record) throws Exception {
Document doc = new Document();
String idFieldName = Configuration.ID_FIELD_NAME;
logger.trace("rawRecord: {}", record.toString());
doc.add(new StringField(idFieldName, record.get(idFieldName), Field.Store.YES));
// The remainder of the columns are added as specified in the properties
for (Property p : this.config.getProperties()) {
String authorityName = p.getAuthorityColumnName() + Configuration.TRANSFORMED_SUFFIX;
String value = record.get(p.getAuthorityColumnName());
// super-csv treats blank as null, we don't for now
value = (value != null) ? value: "";
// Index the value in its original state, pre transformation..
Field f = new TextField(p.getAuthorityColumnName(), value, Field.Store.YES);
doc.add(f);
// ..*then* transform the value if necessary..
for (Transformer t:p.getAuthorityTransformers()) {
value = t.transform(value);
}
//.. and add this one to the index
Field f1 = new TextField(authorityName, value, Field.Store.YES);
doc.add(f1);
// For some fields (those which will be passed into a fuzzy matcher like Levenshtein), we index the length
if (p.isIndexLength()){
int length = 0;
if (value != null)
length = value.length();
Field fl = new StringField(authorityName + Configuration.LENGTH_SUFFIX, String.format("%02d", length), Field.Store.YES);
doc.add(fl);
}
if (p.isIndexInitial() & StringUtils.isNotBlank(value)){
Field finit = new TextField(authorityName + Configuration.INITIAL_SUFFIX, value.substring(0, 1), Field.Store.YES);
doc.add(finit);
}
}
logger.trace("Document to be indexed: {}", doc.toString());
this.indexWriter.addDocument(doc);
return doc;
}
/* • Getters and setters • */
public org.apache.lucene.util.Version getLuceneVersion() {
return luceneVersion;
}
public void setLuceneVersion(org.apache.lucene.util.Version luceneVersion) {
this.luceneVersion = luceneVersion;
}
public FSDirectory getDirectory() {
return directory;
}
public void setDirectory(FSDirectory directory) {
this.directory = directory;
}
public Analyzer getLuceneAnalyzer() {
return luceneAnalyzer;
}
public void setLuceneAnalyzer(Analyzer luceneAnalyzer) {
this.luceneAnalyzer = luceneAnalyzer;
}
public Configuration getConfig() {
return this.config;
}
@Override
public void setConfig(Configuration config) {
this.config = config;
this.configName = config.getName();
}
}
| 20,749 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneUtils.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/LuceneUtils.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexableField;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.configuration.Property;
import org.kew.rmf.matchers.MatchException;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.WeightedTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper class to
* → map from Maps to Lucene Documents and vice versa
* → build a query string that lucene understands
* → check whether two strings match according to the configured
* {@link org.kew.rmf.matchers.Matcher}
*/
public class LuceneUtils {
private static Logger logger = LoggerFactory.getLogger(LuceneUtils.class);
public static String doc2String(Document doc){
return doc2String(doc, "");
}
public static Map<String,String> doc2Map(Document doc){
Map<String,String> map = new HashMap<String, String>();
for (IndexableField f : doc.getFields()){
map.put(f.name(), f.stringValue());
}
return map;
}
public static Document map2Doc(Map<String, String> map) {
Document doc = new Document();
for (String key:map.keySet()) {
String value = map.get(key);
value = (value != null) ? value: "";
doc.add(new TextField(key, value, Field.Store.YES));
}
return doc;
}
public static String doc2String(Document doc, String prefix){
StringBuffer sb = new StringBuffer();
for (IndexableField f : doc.getFields()){
sb.append(prefix)
.append(f.name()).append(" : " ).append(doc.getField(f.name()).stringValue())
.append("\n");
}
return sb.toString();
}
public static String doc2Line(Document doc, String fieldSeparator){
StringBuffer sb = new StringBuffer();
for (IndexableField f : doc.getFields()){
if (sb.length() > 0)
sb.append(fieldSeparator);
sb.append(doc.getField(f.name()).stringValue());
}
return sb.toString();
}
public static String buildQuery(List<Property> properties, Document doc, boolean dedupl){
Map<String,String> map = doc2Map(doc);
return buildQuery(properties, map, dedupl);
}
public static String buildQuery(List<Property> properties, Map<String,String> map, boolean dedupl){
StringBuffer sb = new StringBuffer();
if (dedupl){
// Be sure not to return self:
sb.append("NOT " + Configuration.ID_FIELD_NAME + ":" + map.get(Configuration.ID_FIELD_NAME));
}
for (Property p : properties){
if (p.isUseInSelect() || p.isUseInNegativeSelect()) {
String authorityName = p.getAuthorityColumnName() + Configuration.TRANSFORMED_SUFFIX;
String value = map.get(p.getQueryColumnName() + Configuration.TRANSFORMED_SUFFIX);
// super-csv treats blank as null, we don't for now
value = (value != null) ? value: "";
String quotedValue = "\"" + value + "\"";
if (p.isUseInSelect()){
if (StringUtils.isNotBlank(value)){
if(p.getMatcher().isExact()){
if (sb.length() > 0) sb.append(" AND ");
sb.append(authorityName + ":" + quotedValue);
}
if (p.isIndexLength()){
int low = Math.max(0, value.length()-2);
int high = value.length()+2;
if (sb.length() > 0) sb.append(" AND ");
sb.append(authorityName).append(Configuration.LENGTH_SUFFIX);
sb.append(String.format(":[%02d TO %02d]", low, high));
}
if (p.isIndexInitial()){
if (sb.length() > 0) sb.append(" AND ");
sb.append(authorityName).append(Configuration.INITIAL_SUFFIX).append(':').append(quotedValue.substring(0, 2)).append('"');
}
if (p.isUseWildcard()){
if (sb.length() > 0) sb.append(" AND ");
sb.append(authorityName).append(":").append(quotedValue.subSequence(0, quotedValue.length()-1)).append("~0.5\"");
}
}
}
else { // isUseInNegativeSelect
if (StringUtils.isNotBlank(value)){
if (sb.length() > 0) {
sb.append(" AND");
}
sb.append(" NOT " + authorityName + ":" + quotedValue);
}
}
}
}
return sb.toString();
}
public static boolean recordsMatch(Document from, Document to, List<Property> properties) throws Exception{
Map<String,String> map = doc2Map(from);
return recordsMatch(map, to, properties);
}
public static boolean recordsMatch(Map<String,String> queryRecord, Document authorityRecord, List<Property> properties) throws MatchException {
if (logger.isTraceEnabled()) {
logger.trace("Comparing records: Q:{} A:{}", queryRecord.get(Configuration.ID_FIELD_NAME), authorityRecord.get(Configuration.ID_FIELD_NAME));
}
boolean recordMatch = false;
for (Property p : properties) {
String queryName = p.getQueryColumnName() + Configuration.TRANSFORMED_SUFFIX;
String authorityName = p.getAuthorityColumnName() + Configuration.TRANSFORMED_SUFFIX;
String query = queryRecord.get(queryName);
query = (query != null) ? query : "";
String authority = authorityRecord.get(authorityName);
authority= (authority != null) ? authority : "";
boolean fieldMatch = false;
if (p.isBlanksMatch()){
if (StringUtils.isBlank(query)) {
fieldMatch = true;
logger.trace("Q:'' ? A:'{}' → true (blank query)", authority);
}
else if (StringUtils.isBlank(authority)) {
fieldMatch = true;
logger.trace("Q:'{}' ? A:'' → true (blank authority)", query);
}
}
if (!fieldMatch) {
fieldMatch = p.getMatcher().matches(query, authority);
if (logger.isTraceEnabled()) {
logger.trace("{} Q:'{}' ? A:'{}' → {}", p.getMatcher().getClass().getSimpleName(), query, authority, fieldMatch);
}
}
recordMatch = fieldMatch;
if (!recordMatch) {
logger.trace("Failed on {}", queryName);
break;
}
}
return recordMatch;
}
public static double recordsMatchScore(Map<String,String> queryRecord, Document authorityRecord, List<Property> properties) throws MatchException, TransformationException {
if (logger.isTraceEnabled()) {
logger.trace("Scoring comparison of records: Q:{} A:{}", queryRecord.get(Configuration.ID_FIELD_NAME), authorityRecord.get(Configuration.ID_FIELD_NAME));
}
double recordScore = 0.0;
// Need to go through each property.
// To calculate the score for a property match, start from 1.0 and reduce by the weight of each transformer
// as it needs to be applied (in order).
for (Property p : properties) {
String queryName = p.getQueryColumnName();
String authorityName = p.getAuthorityColumnName();
String query = queryRecord.get(queryName);
query = (query != null) ? query : "";
String authority = authorityRecord.get(authorityName);
authority = (authority != null) ? authority : "";
if (logger.isTraceEnabled()) {
logger.trace("Calculating score for property {}: Q:{}, A:{}", p.getQueryColumnName(), query, authority);
}
boolean fieldMatch = false;
double fieldScore = 1.0;
// Apply each transformation in order, compare the match after that.
// Decrease current score as necessary.
Iterator<Transformer> queryTransformers = p.getQueryTransformers().iterator();
Transformer nextQueryTransformer = queryTransformers.hasNext() ? queryTransformers.next() : null;
Iterator<Transformer> authorityTransformers = p.getAuthorityTransformers().iterator();
Transformer nextAuthorityTransformer = authorityTransformers.hasNext() ? authorityTransformers.next() : null;
int transformerIndex = 0;
while (transformerIndex == 0 || // Must still go once through the loop even if there are no transformers
nextQueryTransformer != null ||
nextAuthorityTransformer != null) {
//logger.trace("Applying transforms with order < {}", transformerIndex);
// Apply query transformers
while (nextQueryTransformer != null
&& (nextQueryTransformer instanceof WeightedTransformer
&& ((WeightedTransformer)nextQueryTransformer).getOrder() < transformerIndex
|| !(nextQueryTransformer instanceof WeightedTransformer))) {
query = nextQueryTransformer.transform(query);
// Take account of weight (score cost) of this transformation
if (nextQueryTransformer instanceof WeightedTransformer) {
fieldScore -= ((WeightedTransformer)nextQueryTransformer).getWeight();
}
nextQueryTransformer = queryTransformers.hasNext() ? queryTransformers.next() : null;
}
// Apply authority transformers
while (nextAuthorityTransformer != null
&& (nextAuthorityTransformer instanceof WeightedTransformer
&& ((WeightedTransformer)nextAuthorityTransformer).getOrder() < transformerIndex
|| !(nextAuthorityTransformer instanceof WeightedTransformer))) {
authority = nextAuthorityTransformer.transform(authority);
// Take account of weight (score cost) of this transformation
if (nextAuthorityTransformer instanceof WeightedTransformer) {
fieldScore -= ((WeightedTransformer)nextAuthorityTransformer).getWeight();
}
nextAuthorityTransformer = authorityTransformers.hasNext() ? authorityTransformers.next() : null;
}
transformerIndex++;
// Test for matches
if (p.isBlanksMatch()) {
// Note that a transformation could make the field blank, so it's necessary to test this each time
if (StringUtils.isBlank(query) && StringUtils.isBlank(authority)) {
fieldMatch = true;
fieldScore *= 0.75;
logger.trace("Q:'' ? A:'' → true (blank query and authority)");
}
else if (StringUtils.isBlank(query)) {
fieldMatch = true;
fieldScore *= 0.5;
logger.trace("Q:'' ? A:'{}' → true (blank query)", authority);
}
else if (StringUtils.isBlank(authority)) {
fieldMatch = true;
fieldScore *= 0.5;
logger.trace("Q:'{}' ? A:'' → true (blank authority)", query);
}
}
if (!fieldMatch) {
fieldMatch = p.getMatcher().matches(query, authority);
logger.trace("Q:'{}' ? A:'{}' → {}", query, authority, fieldMatch);
}
if (fieldMatch) {
logger.trace("Matched on {}, score {}", queryName, fieldScore);
break;
}
else {
logger.trace("Failed on {}", queryName);
}
}
recordScore += fieldScore / properties.size();
}
logger.trace("Overall score is {}", recordScore);
return recordScore;
}
}
| 12,255 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneHandler.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/LuceneHandler.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.flexible.standard.QueryParserUtil;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.kew.rmf.core.DataLoader;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.script.JavaScriptEnv;
import org.kew.rmf.reporters.LuceneReporter;
import org.kew.rmf.reporters.Reporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuceneHandler<C extends Configuration> {
private static final Logger logger = LoggerFactory.getLogger(LuceneHandler.class);
private org.apache.lucene.util.Version luceneVersion;
protected FSDirectory directory;
private IndexSearcher indexSearcher;
private IndexReader indexReader;
private QueryParser queryParser;
protected DataLoader dataLoader;
protected C config;
protected LuceneReporter[] reporters;
protected JavaScriptEnv jsEnv = null;
public IndexReader getIndexReader() throws CorruptIndexException, IOException {
if (this.indexReader == null) {
this.indexReader = DirectoryReader.open(this.directory);
}
return this.indexReader;
}
public IndexSearcher getIndexSearcher() throws CorruptIndexException, IOException {
if (this.indexSearcher == null) {
this.indexSearcher = new IndexSearcher(this.getIndexReader());
}
return this.indexSearcher;
}
public Document getFromLucene(int n) throws IOException {
return indexReader.document(n);
}
/**
* Retrieves a record by indexed id from the Lucene datastore.
*/
public Map<String, String> getRecordById(String id) throws IOException {
String queryString = Configuration.ID_FIELD_NAME + ":" + QueryParserUtil.escape(id);
TopDocs resultDoc = null;
try {
resultDoc = queryLucene(queryString, getIndexSearcher(), 1);
}
catch (ParseException e) {
logger.error("Unexpected error parsing query '"+queryString+"'", e);
return null;
}
if (resultDoc.scoreDocs.length > 0) {
return LuceneUtils.doc2Map(getFromLucene(resultDoc.scoreDocs[0].doc));
}
else {
return new HashMap<>();
}
}
public TopDocs queryLucene(String query, IndexSearcher indexSearcher, int maxSearchResults) throws IOException, ParseException {
Query q = queryParser.parse(query);
logger.debug("Querying Lucene with query --> {}", q);
TopDocs td = indexSearcher.search(q, maxSearchResults);
return td;
}
/**
* Asks the config to initialise the Reporters properly and initialises the in-the-box
* javascript environment, if it will be used.
*/
public void prepareEnvs() {
// copy some necessary values to reporters and possibly create pipers if recordFilter is set
config.setupReporting();
// the recordFilter (excludes records from processing if condition fulfilled) needs a JavaScript environment set up
if (!StringUtils.isBlank(config.getRecordFilter())) {
this.jsEnv = new JavaScriptEnv();
logger.debug("Record filter activated, javascript rock'n roll!");
}
}
// Getters and Setters
public C getConfig() {
return this.config;
}
public void setConfig(C config) {
this.config = config;
}
public DataLoader getDataLoader() {
return dataLoader;
}
public void setDataLoader(DataLoader dataLoader) {
this.dataLoader = dataLoader;
}
public org.apache.lucene.util.Version getLuceneVersion() {
return luceneVersion;
}
public void setLuceneVersion(org.apache.lucene.util.Version luceneVersion) {
this.luceneVersion = luceneVersion;
}
public FSDirectory getDirectory() {
return directory;
}
public void setDirectory(FSDirectory directory) {
this.directory = directory;
}
public QueryParser getQueryParser() {
return queryParser;
}
public void setQueryParser(QueryParser queryParser) {
this.queryParser = queryParser;
}
public Reporter[] getReporters() {
return (LuceneReporter[]) reporters;
}
public void setReporters(LuceneReporter[] reporters) {
this.reporters = reporters;
}
}
| 5,261 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneMatcher.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/LuceneMatcher.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.script.ScriptException;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.kew.rmf.core.DataHandler;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.configuration.MatchConfiguration;
import org.kew.rmf.core.configuration.Property;
import org.kew.rmf.core.exception.DataLoadException;
import org.kew.rmf.core.exception.MatchExecutionException;
import org.kew.rmf.core.exception.TooManyMatchesException;
import org.kew.rmf.matchers.MatchException;
import org.kew.rmf.reporters.LuceneReporter;
import org.kew.rmf.reporters.Piper;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.transformers.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.io.CsvMapReader;
import org.supercsv.prefs.CsvPreference;
/**
* Performs the actual match against the Lucene index.
*
* {@link #getMatches(Map, int)} returns a list of matches.
*/
public class LuceneMatcher extends LuceneHandler<MatchConfiguration> implements DataHandler<MatchConfiguration> {
private static final Logger logger = LoggerFactory.getLogger(LuceneMatcher.class);
protected MatchConfiguration matchConfig;
long count = 0;
long time = System.currentTimeMillis();
@Override // from DataHandler
public void loadData() throws DataLoadException, InterruptedException {
this.dataLoader.setConfig(this.getConfig());
this.dataLoader.load();
}
/**
* Performs a match against the Lucene index, and returns a list of matches.
* @param record The record needing to be matched
* @return A list of matched records
* @throws TooManyMatchesException Thrown if more than configured maximum number of matches are found
* @throws MatchExecutionException For other errors finding a match
*/
public List<Map<String,String>> getMatches(Map<String, String> record) throws TooManyMatchesException, MatchExecutionException {
if (++count % 1000 == 0) {
logger.warn("{} match queries processed in {}ms", count, System.currentTimeMillis() - time);
time = System.currentTimeMillis();
}
// pipe everything through to the output where an existing filter evaluates to false;
try {
if (!StringUtils.isBlank(config.getRecordFilter()) && !jsEnv.evalFilter(config.getRecordFilter(), record)) {
logger.debug("All records excluded by record filter");
return new ArrayList<>();
}
}
catch (ScriptException e) {
throw new MatchExecutionException("Error evaluating recordFilter on record "+record, e);
}
// transform query properties
for (Property prop:config.getProperties()) {
String fName = prop.getQueryColumnName();
String fValue = record.get(fName);
// transform the field-value..
fValue = fValue == null ? "" : fValue; // super-csv treats blank as null, we don't for now
for (Transformer t:prop.getQueryTransformers()) {
try {
fValue = t.transform(fValue);
}
catch (TransformationException e) {
throw new MatchExecutionException("Error evaluating transformer "+t+" on record "+record, e);
}
}
// ..and put it into the record
record.put(fName + Configuration.TRANSFORMED_SUFFIX, fValue);
}
// Use the properties to select a set of documents which may contain matches
String fromId = record.get(Configuration.ID_FIELD_NAME);
String querystr = LuceneUtils.buildQuery(config.getProperties(), record, false);
// If the query for some reasons results being empty we pipe the record directly through to the output
if (querystr.equals("")) {
logger.warn("Empty query for record {}", record);
return new ArrayList<>();
}
// Perform the Lucene query
TopDocs td;
try {
td = queryLucene(querystr, this.getIndexSearcher(), config.getMaxSearchResults());
if (td.totalHits >= config.getMaxSearchResults()) {
logger.info("Error querying Lucene with {} ({}/{})", querystr, td.totalHits, config.getMaxSearchResults());
//throw new TooManyMatchesException(String.format("%d potential results (maximum is %d) returned for record %s! You should either tweak your config to bring back less possible results making better use of the \"useInSelect\" switch (recommended) or raise the \"maxSearchResults\" number.", td.totalHits, config.getMaxSearchResults(), record));
return null;
}
logger.debug("Found {} possible record to assess against {}", td.totalHits, fromId);
}
catch (ParseException | IOException e) {
throw new MatchExecutionException("Error querying Lucene on query "+record, e);
}
// Run the detailed match against the possibilities returned by Lucene
List<Map<String, String>> matches = new ArrayList<>();
for (ScoreDoc sd : td.scoreDocs){
try {
Document toDoc = getFromLucene(sd.doc);
if (LuceneUtils.recordsMatch(record, toDoc, config.getProperties())) {
Map<String,String> toDocAsMap = LuceneUtils.doc2Map(toDoc);
double matchScore = LuceneUtils.recordsMatchScore(record, toDoc, config.getProperties());
toDocAsMap.put(Configuration.MATCH_SCORE, String.format("%5.4f", matchScore));
matches.add(toDocAsMap);
logger.info("Match is {}", toDocAsMap);
}
}
catch (TransformationException e) {
throw new MatchExecutionException("Error evaluating transformer while scoring record "+record, e);
}
catch (MatchException e) {
throw new MatchExecutionException("Error running matcher for "+record, e);
}
catch (IOException e) {
throw new MatchExecutionException("Error retrieving match result from Lucene "+sd.doc, e);
}
}
sortMatches(matches);
return matches;
}
public void sortMatches(List<Map<String, String>> matches) {
final String sortOn = config.getSortFieldName();
try {
Collections.sort(matches, Collections.reverseOrder(new Comparator<Map<String, String>>() {
@Override
public int compare(final Map<String, String> m1,final Map<String, String> m2) {
return Integer.valueOf(m1.get(sortOn)).compareTo(Integer.valueOf(m2.get(sortOn)));
}
}));
} catch (NumberFormatException e) {
// if the String can't be converted to an integer we do String comparison
Collections.sort(matches, Collections.reverseOrder(new Comparator<Map<String, String>>() {
@Override
public int compare(final Map<String, String> m1,final Map<String, String> m2) {
return m1.get(sortOn).compareTo(m2.get(sortOn));
}
}));
}
}
/**
* Run the whole matching task.
*
* The iterative flow is:
* - load the data (== write the lucene index)
* - iterate over the query data file
* - for each record, look for matches in the index
* - for each record, report into new fields of this record about matches via reporters
*
* The main difference to a deduplication task as defined by {@link LuceneDeduplicator}
* is that we use two different datasets, one to create the authority index, the other one as
* query file (where we iterate over each record to look up possible matches).
*/
@Override
public void run() throws Exception {
this.loadData(); // writes the index according to the configuration
char delimiter = this.config.getQueryFileDelimiter().charAt(0);
char quote = this.config.getQueryFileQuoteChar().charAt(0);
CsvPreference csvPref = new CsvPreference.Builder(quote, delimiter, "\n").build();
logger.info("Reading CSV from {} with delimiter '{}' and quote '{}'", this.getConfig().getQueryFile(), delimiter, quote);
int i = 0;
try (MatchConfiguration config = this.getConfig();
IndexReader indexReader= this.getIndexReader();
CsvMapReader mr = new CsvMapReader(new InputStreamReader(new FileInputStream(this.getConfig().getQueryFile()), this.getConfig().getQueryFileEncoding()), csvPref)) {
this.prepareEnvs();
// loop over the queryFile
int numMatches = 0;
final String[] header = mr.getHeader(true);
// check whether the header column names fit to the ones specified in the configuration
List<String> headerList = Arrays.asList(header);
for (String name:this.config.getPropertyQueryColumnNames()) {
if (!headerList.contains(name)) throw new Exception(String.format("%s: Header doesn't contain field name < %s > as defined in config.", this.config.getQueryFile().getPath(), name));
}
// same for the id-field
String idFieldName = Configuration.ID_FIELD_NAME;
if (!headerList.contains(idFieldName)) throw new Exception(String.format("%s: Id field name not found in header, should be %s!", this.config.getQueryFile().getPath(), idFieldName));
Map<String, String> record;
while((record = mr.read(header)) != null) {
List<Map<String, String>> matches = getMatches(record);
if (matches == null) {
for (Piper piper:config.getPipers()) piper.pipe(record);
continue;
}
numMatches += matches.size();
if (i++ % config.getAssessReportFrequency() == 0) logger.info("Assessed " + i + " records, found " + numMatches + " matches");
// call each reporter that has a say; all they get is a complete list of duplicates for this record.
for (LuceneReporter reporter : config.getReporters()) {
// TODO: make idFieldName configurable, but not on reporter level
reporter.report(record, matches);
}
}
logger.info("Assessed " + i + " records, found " + numMatches + " matches");
}
}
}
| 11,860 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DocList.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/DocList.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
/**
* A very simple wrapper around an ArrayList specific to Lucene Documents, that knows whether it's sorted or not.
* It can so far only add and get Documents and return its size
*/
public class DocList {
protected boolean sorted = false;
protected String sortOn;
public Document getFromDoc() {
return fromDoc;
}
protected List<Document> store = new ArrayList<Document>();
protected Document fromDoc;
public DocList(Document fromDoc, String sortOn) {
this.fromDoc = fromDoc;
this.store.add(fromDoc); // fromDoc itself is always in the cluster
this.sortOn = sortOn;
}
public DocList(Map<String, String> fromMap, String sortOn) {
// this is for matching; here we don't add the fromDoc
Document docified = LuceneUtils.map2Doc(fromMap);
this.fromDoc = docified;
this.sortOn = sortOn;
}
public Map<String, String> getFromDocAsMap() {
return LuceneUtils.doc2Map(this.fromDoc);
}
public List<Map<String, String>> storeToMapList() {
List<Map<String, String>> maps = new ArrayList<>();
for (Document doc:this.store) {
maps.add(LuceneUtils.doc2Map(doc));
}
return maps;
}
public boolean isSorted() {
return sorted;
}
public void setSorted(boolean sorted) {
this.sorted = sorted;
}
public void sort() {
if (!this.isSorted() && this.store.size() > 0) {
try {
Collections.sort(this.store, Collections.reverseOrder(new Comparator<Document>() {
@Override
public int compare(final Document d1,final Document d2) {
return Integer.valueOf(d1.get(sortOn)).compareTo(Integer.valueOf(d2.get(sortOn)));
}
}));
} catch (NumberFormatException e) {
// if the String can't be converted to an integer we do String comparison
Collections.sort(this.store, Collections.reverseOrder(new Comparator<Document>() {
@Override
public int compare(final Document d1,final Document d2) {
return d1.get(sortOn).compareTo(d2.get(sortOn));
}
}));
}
finally {
this.setSorted(true);
}
}
}
public void add(Document doc) {
this.setSorted(false);
this.store.add(doc);
}
public Document get(int index) {
return this.store.get(index);
}
public String get_attributes(String fieldName, String delimiter) {
String attributes = "";
for (int i = 0; i<this.store.size(); i++) {
Document doc = this.store.get(i);
if (this.store.indexOf(doc) > 0)
attributes += delimiter;
attributes += (doc.get(fieldName));
}
return attributes;
}
public String[] getFieldNames() {
List<IndexableField> fields = fromDoc.getFields();
String[] fieldNames = new String[fields.size()];
for (int i=0; i< fields.size(); i++) {
fieldNames[i] = fields.get(i).name();
}
return fieldNames;
}
public int size () {
return this.store.size();
}
}
| 3,782 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
LuceneDeduplicator.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/lucene/LuceneDeduplicator.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.lucene;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.kew.rmf.core.DataHandler;
import org.kew.rmf.core.DataLoader;
import org.kew.rmf.core.configuration.Configuration;
import org.kew.rmf.core.configuration.DeduplicationConfiguration;
import org.kew.rmf.core.configuration.Property;
import org.kew.rmf.core.exception.DataLoadException;
import org.kew.rmf.reporters.LuceneReporter;
import org.kew.rmf.reporters.Piper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the main handler for any de-duplication.
*/
public class LuceneDeduplicator extends LuceneHandler<DeduplicationConfiguration> implements DataHandler<DeduplicationConfiguration> {
private static final Logger logger = LoggerFactory.getLogger(LuceneDeduplicator.class);
protected DeduplicationConfiguration dedupConfig;
/**
* Uses the {@link DataLoader} in a dedup specific way
*/
@Override // from DataHandler
public void loadData() throws DataLoadException, InterruptedException {
this.dataLoader.setConfig(this.getConfig());
this.dataLoader.load();
}
/**
* Run the whole de-duplication.
*
* The iterative flow is:
* - load the data (== write the index)
* - iterate over the index, using it here as query data
* - for each record, look for matches in the same index, using it now as authority data
* - for each record, report into new fields of this record about matches via reporters
*
* The main difference to a matching task as defined by {@link LuceneMatcher} is that we use
* the lucene index not only as authority but as well as query file iterating over each record.
*/
@Override
public void run() throws Exception {
this.loadData(); // writes the index according to the configuration
Set<String> alreadyProcessed = new HashSet<>();
try (DeduplicationConfiguration config = this.getConfig();
IndexReader indexReader = this.getIndexReader()) {
this.prepareEnvs();
// Loop over all documents in index
int numClusters = 0;
DocList dupls;
for (int i=0; i<indexReader.maxDoc(); i++) {
if (i % config.getAssessReportFrequency() == 0 || i == indexReader.maxDoc() - 1){
logger.info("Assessed {} records, merged to {} duplicate clusters", i, numClusters);
}
Document fromDoc = getFromLucene(i);
Map<String, String> docAsMap = LuceneUtils.doc2Map(fromDoc);
logger.debug("'Query'-Document from index: {}", docAsMap);
// pipe everything through to the output where an existing filter evals to false;
if (!StringUtils.isBlank(config.getRecordFilter()) && !jsEnv.evalFilter(config.getRecordFilter(), docAsMap)) {
for (Piper piper:config.getPipers()) piper.pipe(docAsMap);
continue;
}
dupls = new DocList(fromDoc, config.getSortFieldName()); // each fromDoc has a duplicates cluster
logger.debug(LuceneUtils.doc2String(fromDoc));
String fromId = fromDoc.get(Configuration.ID_FIELD_NAME);
// Keep a record of the records already processed, so as not to return
// matches like id1:id2 *and* id2:id1
if (alreadyProcessed.contains(fromId))
continue;
alreadyProcessed.add(fromId);
// Use the properties to select a set of documents which may contain matches
String querystr = LuceneUtils.buildQuery(config.getProperties(), fromDoc, true);
// If the query for some reasons results being empty we pipe the record directly through to the output
// TODO: create a log-file that stores critical log messages?
if (querystr.equals("")) {
logger.warn("Empty query for record {}", fromDoc);
for (Piper piper:config.getPipers()) piper.pipe(docAsMap);
continue;
}
TopDocs td = queryLucene(querystr, this.getIndexSearcher(), config.getMaxSearchResults());
if (td.totalHits == config.getMaxSearchResults()) {
throw new Exception(String.format("Number of max search results exceeded for record %s! You should either tweak your config to bring back less possible results making better use of the \"useInSelect\" switch (recommended) or raise the \"maxSearchResults\" number.", fromDoc));
}
logger.debug("Found {} possibles to assess against {}", td.totalHits, fromId);
for (ScoreDoc sd : td.scoreDocs){
Document toDoc = getFromLucene(sd.doc);
logger.debug(LuceneUtils.doc2String(toDoc));
String toId = toDoc.get(Configuration.ID_FIELD_NAME);
// Skip the processing if we have already encountered this record in the main loop
if (alreadyProcessed.contains(toId))
continue;
if (LuceneUtils.recordsMatch(fromDoc, toDoc, config.getProperties())){
dupls.add(toDoc);
alreadyProcessed.add(toId);
}
}
// use the DocList's specific sort method to sort on the scoreField.
try {
dupls.sort();
} catch (Exception e) {
throw new Exception ("Could not sort on score-field:" + e.toString());
}
numClusters ++;
// call each reporter that has a say; all they get is a complete list of duplicates for this record.
for (LuceneReporter reporter : config.getReporters()) {
// TODO: make idFieldName configurable, but not on reporter level
reporter.setIdFieldName(Configuration.ID_FIELD_NAME);
reporter.setDefinedOutputFields(config.outputDefs());
reporter.report(dupls);
}
}
// Matchers can output a report on their number of executions:
for (Property p : config.getProperties()){
String executionReport = p.getMatcher().getExecutionReport();
if (executionReport != null)
logger.debug(p.getMatcher().getExecutionReport());
}
}
}
}
| 7,567 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchConfiguration.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/configuration/MatchConfiguration.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.configuration;
import java.util.ArrayList;
import java.util.List;
public class MatchConfiguration extends Configuration {
@Override
public String[] outputDefs() {
List<String> queryOutputDefs = new ArrayList<>();
List<String> authorityOutputDefs = new ArrayList<>();
for (Property prop : this.getProperties()) {
if (prop.isAddOriginalQueryValue()) queryOutputDefs.add(prop.getQueryColumnName());
if (prop.isAddTransformedQueryValue()) queryOutputDefs.add(prop.getQueryColumnName() + "_transf");
if (prop.isAddOriginalAuthorityValue()) authorityOutputDefs.add("authority_" + prop.getAuthorityColumnName());
if (prop.isAddTransformedAuthorityValue()) authorityOutputDefs.add("authority_" + prop.getAuthorityColumnName() + "_transf");
}
queryOutputDefs.addAll(authorityOutputDefs);
return queryOutputDefs.toArray(new String[queryOutputDefs.size()]);
}
}
| 1,657 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Configuration.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/configuration/Configuration.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.configuration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.kew.rmf.core.DatabaseRecordSource;
import org.kew.rmf.reporters.LuceneReporter;
import org.kew.rmf.reporters.Piper;
/**
* A configuration holds all the information, of which the most important is
* <ul>
* <li>how the named columns are mapped to Transformers and Matchers (via {@link #properties})</li>
* <li>where the data to match against ({@link #authorityFile} etc) and the data to match ({@link #queryFile} etc)</li>
* <li>where and in which format to produce output (via {@link #reporters})</li>
* </ul>
* This information is used by the implementation of DataHandler during the process.
*/
public abstract class Configuration implements AutoCloseable {
private String name;
private List<Property> properties;
private File queryFile;
private String queryFileEncoding = "UTF-8";
private String queryFileDelimiter;
private String queryFileQuoteChar;
private String recordFilter = "";
private int maxSearchResults = 10000;
private boolean writeComparisonReport=false;
private boolean writeDelimitedReport=false;
private boolean includeNonMatchesInDelimitedReport=false;
private int maximumLoadErrors = 0;
private int loadReportFrequency=50000;
private int assessReportFrequency=100;
private List<? extends LuceneReporter> reporters;
// a 'piper' is created for each reporter in case recordFilter is not empty
private List<Piper> pipers = new ArrayList<>();
private boolean reuseIndex;
public static String ID_FIELD_NAME ="id";
public static final String LENGTH_SUFFIX="_length";
public static final String TRANSFORMED_SUFFIX="_transf";
public static final String INITIAL_SUFFIX="_init";
public static final String MATCH_SCORE = "_score";
private File authorityFile;
private String authorityFileEncoding = "UTF-8";
private String authorityFileDelimiter;
private String authorityFileQuoteChar;
private DatabaseRecordSource authorityRecords;
private boolean outputAllMatches;
private String sortFieldName;
public abstract String[] outputDefs();
/**
* This does two things:
* (1) copy over some config-wide setting to each reporter
* (2) add a Piper (a dummy reporter that does the basic job for records where no reporter
* needed) for each reporter
*/
public void setupReporting() {
for (LuceneReporter rep:this.getReporters()) {
rep.setIdFieldName(Configuration.ID_FIELD_NAME);
rep.setDefinedOutputFields(this.outputDefs());
// set up a 'piper' for each reporter as a shortcut to output a record immediately (-->'continue'-ish)
this.getPipers().add(new Piper(rep));
}
}
public String[] getPropertyQueryColumnNames() {
String[] propertyNames = new String[this.getProperties().size()];
for (int i=0;i<propertyNames.length;i++) {
propertyNames[i] = (this.getProperties().get(i).getQueryColumnName());
}
return propertyNames;
}
public String[] getPropertyAuthorityColumnNames() {
String[] propertyNames = new String[this.getProperties().size()];
for (int i=0;i<propertyNames.length;i++) {
propertyNames[i] = (this.getProperties().get(i).getAuthorityColumnName());
}
return propertyNames;
}
@Override
public void close() throws Exception {
if (this.reporters != null) {
for (LuceneReporter reporter : this.reporters) {
reporter.close();
}
}
}
// Getters and Setters
public boolean isOutputAllMatches() {
return outputAllMatches;
}
public void setOutputAllMatches(boolean outputAllMatches) {
this.outputAllMatches = outputAllMatches;
}
public String getSortFieldName() {
return sortFieldName;
}
/**
* The field to sort results by.
*/
public void setSortFieldName(String sortFieldName) {
this.sortFieldName = sortFieldName;
}
public File getAuthorityFile() {
return authorityFile;
}
public void setAuthorityFile(File authorityFile) {
this.authorityFile = authorityFile;
}
public String getAuthorityFileEncoding() {
return authorityFileEncoding;
}
public void setAuthorityFileEncoding(String authorityFileEncoding) {
this.authorityFileEncoding = authorityFileEncoding;
}
/**
* The delimiter (usually tab or comma) for delimiter-separated-value authority files.
*/
public String getAuthorityFileDelimiter() {
return authorityFileDelimiter;
}
public void setAuthorityFileDelimiter(String authorityFileDelimiter) {
this.authorityFileDelimiter = authorityFileDelimiter;
}
/**
* The quote character (usually " or nothing) for delimiter-separated-value files.
*/
public String getAuthorityFileQuoteChar() {
return authorityFileQuoteChar;
}
public void setAuthorityFileQuoteChar(String authorityFileQuoteChar) {
this.authorityFileQuoteChar = authorityFileQuoteChar;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public File getQueryFile() {
return queryFile;
}
public String getQueryFileEncoding() {
return queryFileEncoding;
}
public void setQueryFile(File queryFile) {
this.queryFile = queryFile;
}
public void setQueryFileEncoding(String queryFileEncoding) {
this.queryFileEncoding = queryFileEncoding;
}
public int getLoadReportFrequency() {
return loadReportFrequency;
}
public void setLoadReportFrequency(int loadReportFrequency) {
this.loadReportFrequency = loadReportFrequency;
}
public int getAssessReportFrequency() {
return assessReportFrequency;
}
public void setAssessReportFrequency(int assessReportFrequency) {
this.assessReportFrequency = assessReportFrequency;
}
public boolean isWriteComparisonReport() {
return writeComparisonReport;
}
public void setWriteComparisonReport(boolean writeComparisonReport) {
this.writeComparisonReport = writeComparisonReport;
}
/**
* The delimiter (usually tab or comma) for delimiter-separated-value query files.
*/
public String getQueryFileDelimiter() {
return queryFileDelimiter;
}
public void setQueryFileDelimiter(String queryFileDelimiter) {
this.queryFileDelimiter = queryFileDelimiter;
}
/**
* The quote character (usually " or nothing) for delimiter-separated-value files.
*/
public String getQueryFileQuoteChar() {
return queryFileQuoteChar;
}
public void setQueryFileQuoteChar(String queryFileQuoteChar) {
this.queryFileQuoteChar = queryFileQuoteChar;
}
public boolean isWriteDelimitedReport() {
return writeDelimitedReport;
}
public void setWriteDelimitedReport(boolean writeDelimitedReport) {
this.writeDelimitedReport = writeDelimitedReport;
}
public boolean isIncludeNonMatchesInDelimitedReport() {
return includeNonMatchesInDelimitedReport;
}
public void setIncludeNonMatchesInDelimitedReport(boolean includeNonMatchesInDelimitedReport) {
this.includeNonMatchesInDelimitedReport = includeNonMatchesInDelimitedReport;
}
public boolean isReuseIndex() {
return reuseIndex;
}
/**
* Whether to reuse an index, if it already exists.
*/
public void setReuseIndex(boolean reuseIndex) {
this.reuseIndex = reuseIndex;
}
public List<? extends LuceneReporter> getReporters() {
return reporters;
}
public void setReporters(List<? extends LuceneReporter> reporters) {
this.reporters = reporters;
}
public String getRecordFilter() {
return recordFilter;
}
public void setRecordFilter(String recordFilter) {
this.recordFilter = recordFilter;
}
public List<Piper> getPipers() {
return pipers;
}
public void setPipers(List<Piper> pipers) {
this.pipers = pipers;
}
public int getMaxSearchResults() {
return maxSearchResults;
}
public void setMaxSearchResults(int maxSearchResults) {
this.maxSearchResults = maxSearchResults;
}
public int getMaximumLoadErrors() {
return maximumLoadErrors;
}
/**
* The limit of data errors before loading the configuration is aborted.
*/
public void setMaximumLoadErrors(int maximumLoadErrors) {
this.maximumLoadErrors = maximumLoadErrors;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DatabaseRecordSource getAuthorityRecords() {
return authorityRecords;
}
public void setAuthorityRecords(DatabaseRecordSource authorityRecords) {
this.authorityRecords = authorityRecords;
}
}
| 9,630 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DeduplicationConfiguration.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/configuration/DeduplicationConfiguration.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.configuration;
import java.util.ArrayList;
import java.util.List;
/**
* The important aspect of a DeduplicationConfiguration is that for a
* deduplication process there is no real differentiation between query and
* authority as we only have one file that is matched to itself.
*/
public class DeduplicationConfiguration extends Configuration {
@Override
public String[] outputDefs() {
List<String> queryOutputDefs = new ArrayList<>();
for (Property prop : this.getProperties()) {
if (prop.isAddOriginalQueryValue()) queryOutputDefs.add(prop.getQueryColumnName());
if (prop.isAddTransformedQueryValue()) queryOutputDefs.add(prop.getQueryColumnName() + "_transf");
}
return queryOutputDefs.toArray(new String[queryOutputDefs.size()]);
}
}
| 1,538 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Property.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/configuration/Property.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.configuration;
import java.util.ArrayList;
import java.util.List;
import org.kew.rmf.matchers.Matcher;
import org.kew.rmf.transformers.Transformer;
/**
* This is a simple JavaBean that holds configuration options relating
* to how a value is cleaned, stored and matched.
*
* The mapping works via <strong>named</strong> columns.
*/
public class Property {
private String queryColumnName;
private String authorityColumnName;
private Matcher matcher;
private boolean useInSelect=false;
private boolean useInNegativeSelect=false;
private boolean indexLength=false;
private boolean blanksMatch=false;
private boolean indexInitial=false;
private boolean useWildcard=false;
private boolean addOriginalQueryValue = false;
private boolean addTransformedQueryValue = false;
// Matching specific as obsolete for Deduplication tasks
private boolean addOriginalAuthorityValue = false;
private boolean addTransformedAuthorityValue = false;
private List<Transformer> queryTransformers = new ArrayList<>();
private List<Transformer> authorityTransformers = new ArrayList<>();
@Override
public String toString() {
return "Property [name=" + queryColumnName + "_" + authorityColumnName
+ ", matcher=" + matcher + ", useInSelect="
+ useInSelect + ", useInNegativeSelect=" + useInNegativeSelect
+ ", indexLength=" + indexLength + ", blanksMatch="
+ blanksMatch + ", indexInitial=" + indexInitial + ", useWildcard="
+ useWildcard + ", transformers=" + queryTransformers + "_" + authorityTransformers + "]";
}
// Getters and Setters
public Matcher getMatcher() {
return matcher;
}
/**
* The {@link Matcher} to use against the transformed fields.
*/
public void setMatcher(Matcher matcher) {
this.matcher = matcher;
}
public boolean isUseInSelect() {
return useInSelect;
}
/**
* Whether this property should be used in the query to retrieve potential matches.
*/
public void setUseInSelect(boolean useInSelect) {
this.useInSelect = useInSelect;
}
public void setIndexLength(boolean indexLength) {
this.indexLength = indexLength;
}
/**
* Index the length of the record, needed for Lucene Levenshtein matching
* @return
*/
public boolean isIndexLength() {
return indexLength;
}
public boolean isBlanksMatch() {
return blanksMatch;
}
/**
* Whether a blank on either side (authority or query) is a match.
*/
public void setBlanksMatch(boolean blanksMatch) {
this.blanksMatch = blanksMatch;
}
public boolean isIndexInitial() {
return indexInitial;
}
/**
* Index the first letter, used to limit records retrieved as potential matches.
*/
public void setIndexInitial(boolean indexInitial) {
this.indexInitial = indexInitial;
}
public boolean isUseInNegativeSelect() {
return useInNegativeSelect;
}
/**
* Exclude records from query to retrieve potential matches.
*/
public void setUseInNegativeSelect(boolean useInNegativeSelect) {
this.useInNegativeSelect = useInNegativeSelect;
}
public boolean isUseWildcard() {
return useWildcard;
}
/**
* Allow approximate matching when retrieving potential matches.
*/
public void setUseWildcard(boolean useWildcard) {
this.useWildcard = useWildcard;
}
public List<Transformer> getQueryTransformers() {
return queryTransformers;
}
/**
* The {@link Transformer}s used to transform query records before indexing or matching.
*/
public void setQueryTransformers(List<Transformer> queryTransformers) {
this.queryTransformers = queryTransformers;
}
public List<Transformer> getAuthorityTransformers() {
return authorityTransformers;
}
/**
* The {@link Transformer}s used to transform authority records before indexing or matching.
*/
public void setAuthorityTransformers(List<Transformer> authorityTransformers) {
this.authorityTransformers = authorityTransformers;
}
public boolean isAddOriginalAuthorityValue() {
return addOriginalAuthorityValue;
}
/**
* Whether to add the untransformed authority value to result records.
*/
public void setAddOriginalAuthorityValue(boolean addOriginalAuthorityValue) {
this.addOriginalAuthorityValue = addOriginalAuthorityValue;
}
public boolean isAddTransformedAuthorityValue() {
return addTransformedAuthorityValue;
}
/**
* Whether to add the transformed authority value to result records.
*/
public void setAddTransformedAuthorityValue(boolean addTransformedAuthorityValue) {
this.addTransformedAuthorityValue = addTransformedAuthorityValue;
}
public boolean isAddOriginalQueryValue() {
return addOriginalQueryValue;
}
/**
* Whether to add the untransformed query value to result records.
*/
public void setAddOriginalQueryValue(boolean addOriginalQueryValue) {
this.addOriginalQueryValue = addOriginalQueryValue;
}
public boolean isAddTransformedQueryValue() {
return addTransformedQueryValue;
}
/**
* Whether to add the transformed query value to result records.
*/
public void setAddTransformedQueryValue(boolean addTransformedQueryValue) {
this.addTransformedQueryValue = addTransformedQueryValue;
}
public String getQueryColumnName() {
return queryColumnName;
}
/**
* The name of the query column this Property refers to.
*/
public void setQueryColumnName(String queryColumnName) {
this.queryColumnName = queryColumnName;
}
public String getAuthorityColumnName() {
return authorityColumnName;
}
/**
* The name of the authority column this Property refers to.
*/
public void setAuthorityColumnName(String authorityColumnName) {
this.authorityColumnName = authorityColumnName;
}
}
| 6,372 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
TooManyMatchesException.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/exception/TooManyMatchesException.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.exception;
public class TooManyMatchesException extends Exception {
private static final long serialVersionUID = 1L;
public TooManyMatchesException() {
super();
}
public TooManyMatchesException(String message) {
super(message);
}
public TooManyMatchesException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,116 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DataLoadException.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/exception/DataLoadException.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.exception;
public class DataLoadException extends Exception {
private static final long serialVersionUID = 1L;
public DataLoadException() {
super();
}
public DataLoadException(String message) {
super(message);
}
public DataLoadException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,092 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
MatchExecutionException.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/core/exception/MatchExecutionException.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.core.exception;
public class MatchExecutionException extends Exception {
private static final long serialVersionUID = 1L;
public MatchExecutionException() {
super();
}
public MatchExecutionException(String message) {
super(message);
}
public MatchExecutionException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,116 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
WeightedTransformer.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/transformers/WeightedTransformer.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.transformers;
/**
* A WeightedTransformer adds a weight (score value) and an order to a
* {@link Transformer}.
*/
public class WeightedTransformer implements Transformer {
private Transformer transformer;
private int order;
private double weight;
/* ••• Methods in Transformer ••• */
@Override
public String transform(String s) throws TransformationException {
return transformer.transform(s);
}
/* ••• Constructors ••• */
public WeightedTransformer() {
}
public WeightedTransformer(Transformer transformer, double weight, int order) {
this.transformer = transformer;
this.weight = weight;
this.order = order;
}
/* ••• Getters and setters ••• */
public Transformer getTransformer() {
return transformer;
}
public void setTransformer(Transformer transformer) {
this.transformer = transformer;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
| 1,862 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
TokenExtractorTransformer.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/rmf-core/src/main/java/org/kew/rmf/transformers/TokenExtractorTransformer.java | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
/**
TODO
*/
public class TokenExtractorTransformer implements Transformer {
private int index = 0;
private boolean removeMultipleWhitespaces = true;
private boolean trimIt = true;
@Override
public String transform(String s) {
if (s != null) {
if (this.removeMultipleWhitespaces) {
s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
}
if (this.trimIt) {
s = s.trim();
}
String[] tokens = s.split(" ");
if (tokens.length > index) {
return tokens[index];
}
return "";
}
return null;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public boolean isRemoveMultipleWhitespaces() {
return removeMultipleWhitespaces;
}
public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) {
this.removeMultipleWhitespaces = removeMultipleWhitespaces;
}
public boolean isTrimIt() {
return trimIt;
}
public void setTrimIt(boolean trimIt) {
this.trimIt = trimIt;
}
}
| 2,163 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
RunCukesTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/RunCukesTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(monochrome = false)
public class RunCukesTest {
}
| 983 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
FileContentsChecker.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/FileContentsChecker.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class FileContentsChecker {
public static void checkFilesSame(File actualFile, String expectedContents, String replacementText) throws IOException {
assertThat("File exists", actualFile.exists());
@SuppressWarnings("unchecked")
List<String> configFileLines = FileUtils.readLines(actualFile);
String[] configXMLLines =expectedContents.split("\r?\n|\r");
for (int i=0;i<configXMLLines.length;i++) {
String expectedLine = configXMLLines[i];
String actualLine = configFileLines.get(i);
// Replace TMPDIR line, and replace Windows-style backslash separators to forward slashes.
if (expectedLine.contains("REPLACE_WITH_TMPDIR")) {
expectedLine = expectedLine.replace("REPLACE_WITH_TMPDIR", replacementText);
expectedLine = expectedLine.replace("\\", "/");
actualLine = actualLine.replace("\\", "/");
}
try {
assertThat(actualLine, is(expectedLine));
}
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException(String.format("→ line %s not found in calculated output.", expectedLine));
}
}
assertThat(configFileLines.size(), is(configXMLLines.length));
}
}
| 2,130 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CreateSimpleMatchConfig.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/CreateSimpleMatchConfig.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import cucumber.api.DataTable;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
@ContextConfiguration(locations="classpath:/META-INF/spring/applicationContext.xml")
public class CreateSimpleMatchConfig {
Logger logger = LoggerFactory.getLogger(CreateSimpleDedupConfig.class);
File tempDir;
String configName;
String secondColName;
String thirdColName;
Map<String, Transformer> transformers = new HashMap<>();
Map<String, Matcher> matchers = new HashMap<>();
List<Reporter> reporters;
Configuration config;
File workDir;
@Before
public void before (Scenario scenario) throws Throwable {
this.tempDir = Files.createTempDirectory("dedupTestDir").toFile();
}
@After()
public void after (Scenario scenario) {
tempDir.delete();
}
@Given("^Alecs has a query-file containing data in three columns, \\(\"([^\"]*)\", \"([^\"]*)\", \"([^\"]*)\"\\) in a directory \"([^\"]*)\"$")
public void Alecs_has_a_query_file_containing_data_in_three_columns_in_a_directory(String firstColName, String secondColName, String thirdColName, String workDirPath) throws Throwable {
this.workDir = new File(tempDir, workDirPath);
this.workDir.mkdir();
new File(this.workDir, "query.tsv").createNewFile();
}
@Given("^Alecs has an authority-file containing data in three columns \\(\"([^\"]*)\", \"([^\"]*)\", \"([^\"]*)\"\\) in the same directory$")
public void Alecs_has_an_authority_file_containing_data_in_three_columns_in_the_same(String firstColName, String secondColName, String thirdColName) throws Throwable {
new File(this.workDir, "authority.tsv").createNewFile();
}
@Given("^he has created a new match configuration:$")
public void he_has_created_a_new_match_configuration(DataTable colDefTable) throws Throwable {
List<Map<String,String>> colDef = colDefTable.asMaps(String.class, String.class);
this.configName = colDef.get(0).get("name");
config = new Configuration();
config.setName(this.configName);
config.setClassName("MatchConfiguration");
config.setWorkDirPath(new File(this.tempDir, colDef.get(0).get("workDirPath")).getPath());
config.setAuthorityFileName("authority.tsv");
config.persist();
assert (Configuration.findConfiguration(config.getId()) != null);
}
@Given("^he has added the following query- and authorityTransformers$")
public void he_has_added_the_following_query_and_authorityTransformers(DataTable transformerDefTable) throws Throwable {
List<Transformer> transis = new ArrayList<>();
for (Map<String,String> transDef:transformerDefTable.asMaps(String.class, String.class)) {
Transformer transi = new Transformer();
transi.setName(transDef.get("name"));
transi.setPackageName(transDef.get("packageName"));
transi.setClassName(transDef.get("className"));
transi.setParams(transDef.get("params"));
transi.persist();
transis.add(transi);
this.transformers.put(transi.getName(), transi);
}
config.setTransformers(transis);
}
@Given("^he has added two matchers:$")
public void he_has_added_two_matchers(DataTable matcherDefTable) throws Throwable {
for (Map<String,String> matcherDef:matcherDefTable.asMaps(String.class, String.class)) {
Matcher matcher = new Matcher();
matcher.setName(matcherDef.get("name"));
matcher.setPackageName(matcherDef.get("packageName"));
matcher.setClassName(matcherDef.get("className"));
matcher.setParams(matcherDef.get("params"));
matcher.setConfiguration(config);
matcher.persist();
matchers.put(matcher.getName(), matcher);
config.getMatchers().add(matcher);
config.setVersion(config.getVersion() + 1);
assert (Matcher.findMatcher(matcher.getId()) != null);
}
}
@Given("^he has wired them together in the following way:$")
public void he_has_wired_them_together_in_the_following_way(DataTable wireDefTable) throws Throwable {
for (Map<String,String> wireDef:wireDefTable.asMaps(String.class, String.class)) {
Wire wire = new Wire();
wire.setQueryColumnName(wireDef.get("queryColumnName"));
wire.setAuthorityColumnName(wireDef.get("authorityColumnName"));
wire.setUseInSelect(Boolean.parseBoolean(wireDef.get("useInSelect")));
wire.setMatcher(this.matchers.get(wireDef.get("matcher")));
wire.setConfiguration(config);
wire.persist();
int i = 0;
for (String t:wireDef.get("queryTransformers").split(",")) {
i ++;
WiredTransformer wTrans = new WiredTransformer();
// reverse the order to test whether the rank is actually used for sorting
// and not only the auto-generated id
wTrans.setRank(i * - 1);
Transformer transf = this.transformers.get(t.trim());
wTrans.setTransformer(transf);
wTrans.persist();
wire.getQueryTransformers().add(wTrans);
}
i = 0;
for (String t:wireDef.get("authorityTransformers").split(",")) {
i ++;
WiredTransformer wTrans = new WiredTransformer();
// reverse the order to test whether the rank is actually used for sorting
// and not only the auto-generated id
wTrans.setRank(i * - 1);
Transformer transf = this.transformers.get(t.trim());
wTrans.setTransformer(transf);
wTrans.persist();
wire.getAuthorityTransformers().add(wTrans);
}
wire.merge();
assert (Wire.findWire(wire.getId()) != null);
config.getWiring().add(wire);
logger.info("config.getWiring(): {}, wire: {}", config.getWiring(), wire);
}
}
@Given("^he has added the following match-reporters:$")
public void he_has_added_the_following_reporters(DataTable reporterDefTable) throws Throwable {
List<Reporter> reps = new ArrayList<>();
for (Map<String,String> repDef:reporterDefTable.asMaps(String.class, String.class)) {
Reporter rep = new Reporter();
rep.setName(repDef.get("name"));
rep.setFileName(repDef.get("fileName"));
rep.setPackageName(repDef.get("packageName"));
rep.setClassName(repDef.get("className"));
rep.setParams(repDef.get("params"));
rep.setConfig(this.config);
rep.persist();
reps.add(rep);
}
config.setReporters(reps);
}
@When("^he asks to write the match-configuration out to the filesystem$")
public void he_asks_to_write_the_configuration_out_to_the_filesystem() throws Throwable {
ConfigurationEngine configEngine = new ConfigurationEngine(config);
configEngine.write_to_filesystem();
}
@Then("^the following match-config will be written to \"([^\"]*)\":$")
public void the_following_content_will_be_written_to_(String configFilePath, String configXML) throws Throwable {
File configFile = new File(this.tempDir, configFilePath);
FileContentsChecker.checkFilesSame(configFile, configXML, tempDir.toString());
}
}
| 8,730 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
CreateSimpleDedupConfig.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/CreateSimpleDedupConfig.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import cucumber.api.DataTable;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
@ContextConfiguration(locations="classpath:/META-INF/spring/applicationContext.xml")
public class CreateSimpleDedupConfig {
Logger logger = LoggerFactory.getLogger(CreateSimpleDedupConfig.class);
File tempDir;
String configName;
String secondColName;
Matcher matcher;
List<Transformer> transformers;
Configuration config;
@Before
public void before (Scenario scenario) throws Throwable {
this.tempDir = Files.createTempDirectory("dedupTestDir").toFile();
}
@After()
public void after (Scenario scenario) {
tempDir.delete();
}
@Given("^Alecs has a file containing data in two columns, \\(\"([^\"]*)\", \"([^\"]*)\"\\) in a directory \"([^\"]*)\"$")
public void Alecs_has_a_file_containing_data_in_two_columns_in_a_directory(String firstColName, String secondColName, String workDirPath) throws Throwable {
// 'this' is the 'World' class all step-defs in one scenario share
this.secondColName = secondColName;
File workDir = new File(tempDir, workDirPath);
workDir.mkdir();
new File(workDir, "query.tsv").createNewFile();
}
@Given("^he has created a new configuration:$")
public void he_has_created_a_new_configuration(DataTable colDefTable) throws Throwable {
List<Map<String,String>> colDef = colDefTable.asMaps(String.class, String.class);
this.configName = colDef.get(0).get("name");
config = new Configuration();
config.setName(this.configName);
config.setMaxSearchResults(colDef.get(0).get("maxSearchResults"));
config.setRecordFilter(colDef.get(0).get("recordFilter"));
config.setNextConfig(colDef.get(0).get("nextConfig"));
config.setWorkDirPath(new File(this.tempDir, colDef.get(0).get("workDirPath")).getPath());
config.persist();
assert (Configuration.findConfiguration(config.getId()) != null);
}
@Given("^he has added a dictionary \"([^\"]*)\" with the filepath field \"([^\"]*)\"$")
public void he_has_added_a_dictionary_with_the_filepath_field(String name, String filePath) throws Throwable {
Dictionary dict = new Dictionary();
dict.setName(name);
dict.setFilePath(filePath);
dict.persist();
}
@Given("^he has added the following queryTransformers$")
public void he_has_added_the_following_transformers(DataTable transformerDefTable) throws Throwable {
List<Transformer> transis = new ArrayList<>();
for (Map<String,String> transDef:transformerDefTable.asMaps(String.class, String.class)) {
Transformer transi = new Transformer();
transi.setName(transDef.get("name"));
transi.setPackageName(transDef.get("packageName"));
transi.setClassName(transDef.get("className"));
transi.setParams(transDef.get("params"));
transi.persist();
transis.add(transi);
}
config.setTransformers(transis);
this.transformers = new ArrayList<>(transis);
}
@Given("^he has added a matcher for the second column:$")
public void he_has_added_a_matcher_for_the_second_column(DataTable matcherDefTable) throws Throwable {
List<Map<String,String>> matcherDef = matcherDefTable.asMaps(String.class, String.class);
matcher = new Matcher();
matcher.setName(matcherDef.get(0).get("name"));
matcher.setPackageName(matcherDef.get(0).get("packageName"));
matcher.setClassName(matcherDef.get(0).get("className"));
matcher.setParams(matcherDef.get(0).get("params"));
matcher.setConfiguration(config);
matcher.persist();
List<Matcher> matchers = new ArrayList<>();
matchers.add(matcher);
config.getMatchers().add(matcher);
config.setVersion(config.getVersion() + 1);
assert (Matcher.findMatcher(this.matcher.getId()) != null);
}
@Given("^he has wired them together at the second column$")
public void he_has_wired_the_together_at_the_second_column() throws Throwable {
Wire wire = new Wire();
wire.setQueryColumnName(this.secondColName);
wire.setMatcher(this.matcher);
wire.setConfiguration(config);
wire.persist();
int i = 0;
for (Transformer t:this.transformers) {
i ++;
WiredTransformer wTrans = new WiredTransformer();
wTrans.setRank(i);
wTrans.setTransformer(t);
wTrans.persist();
wire.getQueryTransformers().add(wTrans);
}
wire.merge();
assert (Wire.findWire(wire.getId()) != null);
config.getWiring().add(wire);
logger.info("config.getWiring(): {}, wire: {}", config.getWiring(), wire);
// TODO: the following works in STS but not on the command-line, why?
//assert (config.getWiring().toArray(new Wire[1]).equals(new Wire[] {wire}));
}
@Given("^he has added the following reporters:$")
public void he_has_added_the_following_reporters(DataTable reporterDefTable) throws Throwable {
List<Reporter> reps = new ArrayList<>();
for (Map<String,String> repDef:reporterDefTable.asMaps(String.class, String.class)) {
Reporter rep = new Reporter();
rep.setName(repDef.get("name"));
rep.setFileName(repDef.get("fileName"));
rep.setPackageName(repDef.get("packageName"));
rep.setClassName(repDef.get("className"));
rep.setParams(repDef.get("params"));
rep.setConfig(this.config);
rep.persist();
reps.add(rep);
}
config.setReporters(reps);
}
@When("^he asks to write the configuration out to the filesystem$")
public void he_asks_to_write_the_configuration_out_to_the_filesystem() throws Throwable {
ConfigurationEngine configEngine = new ConfigurationEngine(config);
configEngine.write_to_filesystem();
}
@Then("^the following content will be written to \"([^\"]*)\":$")
public void the_following_content_will_be_written_to_(String configFilePath, String configXML) throws Throwable {
File configFile = new File(this.tempDir, configFilePath);
FileContentsChecker.checkFilesSame(configFile, configXML, tempDir.toString());
}
}
| 7,584 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
RunSimpleDedupConfig.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/RunSimpleDedupConfig.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import cucumber.api.DataTable;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
@ContextConfiguration(locations="classpath:/META-INF/spring/applicationContext.xml")
public class RunSimpleDedupConfig {
private static final Logger logger = LoggerFactory.getLogger(RunSimpleDedupConfig.class);
File tempDir;
File workDir;
long configId;
@Before
public void before (Scenario scenario) throws Throwable {
this.tempDir = Files.createTempDirectory("dedupTestDir").toFile();
}
@After()
public void after (Scenario scenario) throws IOException {
tempDir.delete();
FileUtils.deleteDirectory(new File("target/deduplicator")); // removes the lucene index after scenario
}
@Given("^Alecs has set up a simple Configuration resulting in the following config \"([^\"]*)\":$")
public void Alecs_has_set_up_a_simple_Configuration_resulting_in_the_following_config_written_to_(String configFileName, String configXML) throws Throwable {
this.workDir = new File(tempDir.getAbsolutePath(), "workDir");
Configuration config = new Configuration();
config.setName("simple-config-to-run");
config.setWorkDirPath(this.workDir.toString());
config.persist();
this.configId = config.getId();
this.workDir.mkdirs();
File configFile = new File(workDir, configFileName);
configFile.createNewFile();
String correctedConfigXML = configXML.replace("REPLACE_WITH_TMPDIR", workDir.toString().replace("\\", "/"));
try (BufferedWriter br = new BufferedWriter(new FileWriter(configFile))) {
br.write(correctedConfigXML);
}
}
@Given("^some mysterious data-improver has put a file \"([^\"]*)\" in the same directory containing the following data:$")
public void some_mysterious_data_improver_has_put_a_file_in_the_same_directory_containing_the_following_data(String inputFileName, DataTable inputFileContent) throws Throwable {
File inputFile = new File(this.workDir, inputFileName);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(inputFile))) {
for (List<String> line:inputFileContent.raw()) {
bw.write(StringUtils.join(line, "\t") + System.getProperty("line.separator"));
}
}
}
@When("^asking MatchConf to run this configuration$")
public void asking_MatchConf_to_run_this_configuration() throws Throwable {
ConfigurationEngine engine = new ConfigurationEngine(Configuration.findConfiguration(this.configId));
Map<String, List<String>> infoMap = engine.runConfiguration(false);
for (String x : infoMap.get("exception")) {
logger.warn("Exception from running configuration: {}", x);
}
for (String x : infoMap.get("stackTrace")) {
logger.warn("Stack trace from running configuration: {}", x);
}
assertThat("No exceptions from configuration", infoMap.get("exception"), is(empty()));
}
@Then("^the deduplication program should run smoothly and produce the following file \"([^\"]*)\" in the same directory:$")
public void the_deduplication_program_should_run_smoothly_and_produce_the_following_file_at_REPLACE_WITH_TMPDIR_some_path_output_csv_(String outputFileName, DataTable outputFileContent) throws Throwable {
File outputFile = new File(this.workDir, outputFileName);
assertThat("File "+outputFile+"exists", outputFile.exists());
int index = 0;
try (BufferedReader br = new BufferedReader(new FileReader(outputFile))) {
String line;
while ((line = br.readLine()) != null) {
List<String> compareLine = outputFileContent.raw().get(index);
assertThat(line, equalTo(StringUtils.join(compareLine, "\t")));
index += 1;
}
}
}
}
| 5,125 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
DedupConfigTest.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/test/java/org/kew/rmf/matchconf/DedupConfigTest.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration(locations="classpath:/META-INF/spring/applicationContext.xml")
public class DedupConfigTest extends AbstractJUnit4SpringContextTests {
// the entities in our test-config-environment
Configuration config;
Transformer trans1;
Transformer trans2;
WiredTransformer wTrans1;
WiredTransformer wTrans2;
WiredTransformer wTrans3;
Matcher matcher1;
Matcher matcher2;
Wire wire1;
Wire wire2;
Reporter rep1;
Reporter rep2;
public void createTestConfig(String name) {
this.config = new Configuration();
this.config.setName(name);
this.config.setWorkDirPath("/some/file/path");
this.config.setRecordFilter("some_funny_javascript");
this.config.setNextConfig("optional_name_of_the_config_to_run_afterwards");
// trans1 has a parameter
this.trans1 = new Transformer();
this.trans1.setName("poshGuy");
this.trans1.setPackageName("lon.don.people");
this.trans1.setClassName("veryUpperClass");
this.trans1.setParams("hairStyle=uebercrazy");
this.trans1.setConfiguration(this.config);
// trans2 has no parameter set
this.trans2 = new Transformer();
this.trans2.setName("hipsterTransformer");
this.trans2.setPackageName("lon.don.people");
this.trans2.setClassName("lowerMiddleClass");
this.trans2.setConfiguration(this.config);
// matcher1 doesn't have any params set
this.matcher1 = new Matcher();
this.matcher1.setName("Hans");
this.matcher1.setPackageName("a.long.and.funny.javapackagename");
this.matcher1.setClassName("SomeHalfUnreadableCamelCasedName");
this.matcher1.setConfiguration(this.config);
// matcher2 does have params
this.matcher2 = new Matcher();
this.matcher2.setName("Klaus");
this.matcher2.setPackageName("a.long.and.funny.javapackagename");
this.matcher2.setClassName("KlausDieMaus");
this.matcher2.setParams("matchEverything=true");
this.matcher2.setConfiguration(this.config);
this.wire1 = new Wire();
this.wire1.setQueryColumnName("sauceColumn");
this.wire1.setConfiguration(this.config);
// wire1 has blanksMatch set to true
this.wire1.setBlanksMatch(true);
this.wire1.setMatcher(this.matcher1);
this.wTrans1 = new WiredTransformer();
this.wTrans1.setRank(1);
this.wTrans1.setTransformer(this.trans1);
// wire1 has only one transformer
this.wire1.getQueryTransformers().add(this.wTrans1);
this.wire2 = new Wire();
this.wire2.setQueryColumnName("saladColumn");
this.wire2.setConfiguration(this.config);
// wire2 has *not* blanksMatch set to true
this.wire2.setMatcher(this.matcher2);
// wire2 has two transformers
this.wTrans2 = new WiredTransformer();
this.wTrans2.setRank(2);
this.wTrans2.setTransformer(this.trans1);
this.wire2.getQueryTransformers().add(this.wTrans2);
this.wTrans3 = new WiredTransformer();
this.wTrans3.setRank(1);
this.wTrans3.setTransformer(this.trans2);
this.wire2.getQueryTransformers().add(this.wTrans3);
this.rep1 = new Reporter();
this.rep1.setName("karkaKolumna");
this.rep1.setPackageName("lon.don.people.busy");
this.rep1.setClassName("TelegraphReporter");
this.rep1.setFileName("someFunnyFile");
this.rep1.setConfig(this.config);
this.rep2 = new Reporter();
this.rep2.setName("flyingBulldog");
this.rep2.setPackageName("lon.don.people.busy");
this.rep2.setClassName("SunReporter");
this.rep2.setFileName("someOtherFunnyFile");
this.rep2.setConfig(this.config);
this.config.getTransformers().add(this.trans1);
this.config.getTransformers().add(this.trans2);
this.config.getMatchers().add(this.matcher1);
this.config.getMatchers().add(this.matcher2);
this.config.getReporters().add(this.rep1);
this.config.getReporters().add(this.rep2);
this.config.getWiring().add(this.wire1);
this.config.getWiring().add(this.wire2);
this.config.persist();
}
@Test
public void deleteConfig() {
createTestConfig("Igor");
this.config = Configuration.findConfiguration(this.config.getId());
this.config.remove();
}
@Test
public void testSortBots() {
createTestConfig("Zetkin");
List<Transformer> transformers = this.config.getTransformers();
Collections.sort(transformers);
// h comes before p
assertThat(transformers.get(0).getName(), equalTo("hipsterTransformer"));
}
public static String getattr(String method, Configuration aConfig) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
return (String) aConfig.getClass().getMethod(method).invoke(aConfig);
}
@Test
public void testCloneMe() throws Exception {
createTestConfig("Clara");
Configuration clone = this.config.cloneMe();
// config
assertThat(clone.getId(), not(equalTo(this.config.getId())));
assertThat(clone.getName(), equalTo("copy-of_" + this.config.getName()));
for (String fieldName:Configuration.CLONE_STRING_FIELDS) {
assertThat(clone.getattr(fieldName, ""), equalTo(this.config.getattr(fieldName, "")));
}
// bots (transformers and matchers)
assertThat(clone.getTransformers().get(0).getId(), not(equalTo(this.trans1.getId())));
assertThat(clone.getTransformers().get(1).getId(), not(equalTo(this.trans2.getId())));
assertThat(clone.getMatchers().get(0).getId(), not(equalTo(this.matcher1.getId())));
assertThat(clone.getMatchers().get(0).getId(), not(equalTo(this.matcher2.getId())));
for (String fieldName:Bot.CLONE_STRING_FIELDS) {
assertThat(clone.getTransformers().get(0).getattr(fieldName, ""), equalTo(this.trans1.getattr(fieldName, "")));
assertThat(clone.getTransformers().get(1).getattr(fieldName, ""), equalTo(this.trans2.getattr(fieldName, "")));
assertThat(clone.getMatchers().get(0).getattr(fieldName, ""), equalTo(this.matcher1.getattr(fieldName, "")));
assertThat(clone.getMatchers().get(1).getattr(fieldName, ""), equalTo(this.matcher2.getattr(fieldName, "")));
}
// reporters
assertThat(clone.getReporters().get(0).getId(), not(equalTo(this.rep1.getId())));
assertThat(clone.getReporters().get(0).getId(), not(equalTo(this.rep2.getId())));
for (String fieldName:Reporter.CLONE_STRING_FIELDS) {
assertThat(clone.getReporters().get(0).getattr(fieldName, ""), equalTo(this.rep1.getattr(fieldName, "")));
assertThat(clone.getReporters().get(1).getattr(fieldName, ""), equalTo(this.rep2.getattr(fieldName, "")));
}
// wiring
assertThat(clone.getWiring().get(0).getId(), not(equalTo(this.wire1.getId())));
assertThat(clone.getWiring().get(0).getId(), not(equalTo(this.wire2.getId())));
assertThat(clone.getWiring().get(0).getMatcher().getConfiguration().getId(), not(equalTo(this.config.getId())));
assertThat(clone.getWiring().get(1).getMatcher().getConfiguration().getId(), not(equalTo(this.wire1.getMatcher().getConfiguration().getId())));
for (String fieldName:Wire.CLONE_STRING_FIELDS) {
assertThat(clone.getWiring().get(0).getattr(fieldName, ""), equalTo(this.wire1.getattr(fieldName, "")));
assertThat(clone.getWiring().get(1).getattr(fieldName, ""), equalTo(this.wire2.getattr(fieldName, "")));
}
for (String fieldName:Wire.CLONE_BOOL_FIELDS) {
assertThat(clone.getWiring().get(0).getattr(fieldName, true), equalTo(this.wire1.getattr(fieldName, true)));
assertThat(clone.getWiring().get(1).getattr(fieldName, true), equalTo(this.wire2.getattr(fieldName, true)));
}
}
}
| 9,338 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
WiredTransformer.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/WiredTransformer.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import javax.persistence.ManyToOne;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
/**
* A WiredTransformer complicates the whole thing a lot unfortunately; it has
* to exist as it adds an order (by a numeric 'rank') to the {@link Transformer}
* it wires to a column.
*/
@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findWiredTransformersByTransformer" })
public class WiredTransformer implements Comparable<WiredTransformer> {
private int rank;
@ManyToOne
private Transformer transformer;
@Override
public int compareTo(WiredTransformer o) {
return this.rank - o.rank;
}
public WiredTransformer cloneMe(Configuration configClone) throws Exception {
WiredTransformer clone = new WiredTransformer();
clone.setRank(this.rank);
clone.setTransformer(this.getTransformer().cloneMe(configClone));
return clone;
}
public String getName() {
return this.getRank() + "_" + this.getTransformer().getName();
}
@Override
public String toString() {
return String.format("%s: %s", this.getRank(), this.getTransformer().getName());
}
/**
* Helper method to deal with the problem of orphaned WiredTransformers;
* Once this problem is sorted out properly please delete!
* @return
*/
public boolean isWireOrphan() {
for (Wire wire:this.transformer.getConfiguration().getWiring()) {
if (wire.getQueryTransformerForName(this.getName()) != null) return false;
if (wire.getAuthorityTransformerForName(this.getName()) != null) return false;
}
return true;
}
}
| 2,577 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
ConfigurationEngine.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/ConfigurationEngine.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.kew.rmf.core.CoreApp;
/**
* Creates the xml for the whole configuration, and runs the CoreApp of the deduplicator with
* this config file.
*/
public class ConfigurationEngine {
Configuration config;
String luceneDirectory = "/tmp/matchconf/lucene_directory/";
public ConfigurationEngine(Configuration config) {
this.config = config;
}
/**
* Creates the xml for the whole configuration calling all connected <?extends>Bots to write out
* their bit as well.
*
* @return
* @throws Exception
*/
public List<String> toXML() throws Exception {
int shiftWidth = 4;
String shift = String.format("%" + shiftWidth + "s", " ");
ArrayList<String> outXML = new ArrayList<String>();
String queryFilePath = new File(new File(this.config.getWorkDirPath()), this.config.getQueryFileName()).getPath();
// change to unix-style path for convencience, even if on windows..
queryFilePath = queryFilePath.replace("\\\\", "/");
String authorityFilePath = new File(new File(this.config.getWorkDirPath()), this.config.getAuthorityFileName()).getPath();
// change to unix-style path for convencience, even if on windows..
authorityFilePath = authorityFilePath.replace("\\\\", "/");
outXML.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
outXML.add("<beans xmlns=\"http://www.springframework.org/schema/beans\"");
outXML.add(String.format("%sxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", shift));
outXML.add(String.format("%sxmlns:util=\"http://www.springframework.org/schema/util\"", shift));
outXML.add(String.format("%sxmlns:p=\"http://www.springframework.org/schema/p\"", shift));
outXML.add(String.format("%sxmlns:c=\"http://www.springframework.org/schema/c\"", shift));
outXML.add(String.format("%sxsi:schemaLocation=\"", shift));
outXML.add(String.format("%s%shttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd", shift, shift));
outXML.add(String.format("%s%shttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd\">", shift, shift));
outXML.add(String.format("%s<bean id=\"preferencePlaceHolder\" class=\"org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer\">", shift));
outXML.add(String.format("%s%s<property name=\"locations\">", shift, shift));
outXML.add(String.format("%s%s%s<list>", shift, shift, shift));
outXML.add(String.format("%s%s%s</list>", shift, shift, shift));
outXML.add(String.format("%s%s</property>", shift, shift));
outXML.add(String.format("%s</bean>", shift));
outXML.add(String.format("%s<bean id=\"lucene_directory\" class=\"java.lang.String\">", shift, shift));
outXML.add(String.format("%s%s<constructor-arg value=\"%s\"/>", shift, shift, this.luceneDirectory));
outXML.add(String.format("%s</bean>", shift));
outXML.add(String.format("%s<bean id=\"queryfile\" class=\"java.io.File\">", shift, shift));
outXML.add(String.format("%s%s<constructor-arg value=\"%s\" />", shift, shift, queryFilePath));
outXML.add(String.format("%s</bean>", shift));
if (this.config.getClassName().equals("MatchConfiguration")) {
outXML.add(String.format("%s<bean id=\"authorityfile\" class=\"java.io.File\">", shift, shift));
outXML.add(String.format("%s%s<constructor-arg value=\"%s\" />", shift, shift, authorityFilePath));
outXML.add(String.format("%s</bean>", shift));
}
List<Dictionary> usedDicts = this.config.findDictionaries();
if (usedDicts.size() > 0) {
for (Dictionary dict:usedDicts) {
outXML.addAll(new DictionaryEngine(dict).toXML(1));
}
}
List<Matcher> matchers = this.config.getMatchers();
Collections.sort(matchers);
for (Bot bot:matchers) outXML.addAll(new BotEngine(bot).toXML(1));
List<Transformer> transformers = this.config.getTransformers();
Collections.sort(transformers);
for (Bot bot:transformers) outXML.addAll(new BotEngine(bot).toXML(1));
if (this.config.getReporters().size() > 0) {
outXML.add(String.format("%s<util:list id=\"reporters\">", shift));
for (Reporter reporter:this.config.getReporters()) {
outXML.addAll(new ReporterEngine(reporter).toXML(2));
}
outXML.add(String.format("%s</util:list>", shift));
}
outXML.add(String.format("%s<util:list id=\"columnProperties\">", shift));
for (Wire wire:this.config.getWiring()) {
outXML.addAll(new WireEngine(wire).toXML(2));
}
outXML.add(String.format("%s</util:list>", shift));
outXML.add(String.format("%s<bean id=\"config\" class=\"%s.%s\"", shift, this.config.getPackageName(), this.config.getClassName()));
outXML.add(String.format("%s%sp:queryFile-ref=\"queryfile\"", shift, shift));
outXML.add(String.format("%s%sp:queryFileEncoding=\"%s\"", shift, shift, this.config.getQueryFileEncoding()));
outXML.add(String.format("%s%sp:queryFileDelimiter=\"%s\"", shift, shift, this.config.getQueryFileDelimiter()));
outXML.add(String.format("%s%sp:queryFileQuoteChar=\"%s\"", shift, shift, this.config.getQueryFileQuoteChar()));
if (this.config.getClassName().equals("MatchConfiguration")) {
outXML.add(String.format("%s%sp:authorityFile-ref=\"authorityfile\"", shift, shift));
outXML.add(String.format("%s%sp:authorityFileEncoding=\"%s\"", shift, shift, this.config.getAuthorityFileEncoding()));
outXML.add(String.format("%s%sp:authorityFileDelimiter=\"%s\"", shift, shift, this.config.getAuthorityFileDelimiter()));
}
outXML.add(String.format("%s%sp:properties-ref=\"columnProperties\"", shift, shift));
outXML.add(String.format("%s%sp:sortFieldName=\"%s\"", shift, shift, this.config.getSortFieldName()));
outXML.add(String.format("%s%sp:loadReportFrequency=\"%s\"", shift, shift, this.config.getLoadReportFrequency()));
outXML.add(String.format("%s%sp:assessReportFrequency=\"%s\"", shift, shift, this.config.getAssessReportFrequency()));
outXML.add(String.format("%s%sp:maxSearchResults=\"%s\"", shift, shift, this.config.getMaxSearchResults()));
if (this.config.getReporters().size() > 0) {
outXML.add(String.format("%s%sp:recordFilter=\"%s\"", shift, shift, this.config.getRecordFilter()));
outXML.add(String.format("%s%sp:reporters-ref=\"reporters\"/>", shift, shift));
} else outXML.add(String.format("%s%sp:recordFilter=\"%s\"/>", shift, shift, this.config.getRecordFilter()));
outXML.add(String.format("%s<!-- import the generic application-context (equal for dedup/match configurations) -->", shift));
outXML.add(String.format("%s<import resource=\"classpath*:application-context.xml\"/>", shift));
if (this.config.getClassName().equals("DeduplicationConfiguration")) {
outXML.add(String.format("%s<!-- add the deduplication-specific bit -->", shift));
outXML.add(String.format("%s<import resource=\"classpath*:application-context-dedup.xml\"/>", shift));
} else if (this.config.getClassName().equals("MatchConfiguration")) {
outXML.add(String.format("%s<!-- add the matching-specific bit -->", shift));
outXML.add(String.format("%s<import resource=\"classpath*:application-context-match.xml\"/>", shift));
} else throw new Exception("No or wrong Configuration Class Name; this should not happen, contact the developer.");
outXML.add("</beans>");
return outXML;
}
/**
* Writes the configuration to the file system. Takes care not to overwrite existing configs,
* complains in a nice way about not existing input and output files.
*
* @throws Exception
*/
public void write_to_filesystem () throws Exception {
// Perform a few checks:
// 1. does the working directory exist?
File workDir = new File(this.config.getWorkDirPath());
if (!workDir.exists()) {
throw new FileNotFoundException(String.format("The specified working directory %s does not exist! You need to create it and put the query file in it.", config.getWorkDirPath()));
}
// 2a. does the query file exist?
File queryFile = new File(workDir, config.getQueryFileName());
if (!queryFile.exists()) {
throw new FileNotFoundException(String.format("There is no file found at the specified location of the query-file %s. Move the query file there with the specified queryFileName.", queryFile.toPath()));
}
// 2b. if the config is for matching: does the authority file exist?
if (this.config.getClassName().equals("MatchConfiguration")) {
File authorityFile = new File(workDir, config.getAuthorityFileName());
if (!authorityFile.exists()) {
throw new FileNotFoundException(String.format("There is no file found at the specified location of the authority-file %s. Move the authority file there with the specified authorityFileName.", authorityFile.toPath()));
}
}
// 3. write out the xml-configuration file
File configFile = new File(workDir, "config_" + config.getName() + ".xml");
if (configFile.exists()) {
// rename existing config file and save new one under the actual name
configFile.renameTo(new File(configFile.toString() + "_older_than_" + DateTimeFormat.forPattern("yyyy-MM-dd_HH-mm-ss").print(new DateTime())));
configFile = new File(workDir, "config_" + config.getName() + ".xml");
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(configFile))) {
br.write(StringUtils.join(this.toXML(), System.getProperty("line.separator")));
}
}
public Map<String, List<String>> runConfiguration () throws Exception {
return this.runConfiguration(true);
}
/**
* Runs the deduplicator's CoreApp providing the path to the written config. In case of chained
* configs it calls one after the other. Doing this it tries to collect as many Exception types
* as possible and pipes them back to the UI-user.
*
* @param writeBefore
* @return
*/
public Map<String, List<String>> runConfiguration (boolean writeBefore) {
@SuppressWarnings("serial")
Map<String, List<String>> infoMap = new HashMap<String, List<String>>() {{
put("messages", new ArrayList<String>());
put("exception", new ArrayList<String>());
put("stackTrace", new ArrayList<String>());
}};
try {
if (writeBefore) this.write_to_filesystem();
infoMap.get("messages").add(String.format("%s: Written config file to %s..", this.config.getName(), this.config.getWorkDirPath()));
File workDir = new File(this.config.getWorkDirPath());
assert workDir.exists();
// assert the luceneDirectory does NOT exist (we want to overwrite the index for now!)
File luceneDir = new File(this.luceneDirectory);
if (luceneDir.exists()) FileUtils.deleteDirectory(luceneDir);
CoreApp.main(new String[] {"-d " + workDir.toString(), "-c config_" + this.config.getName() + ".xml"});
infoMap.get("messages").add(String.format("%s: Ran without complains.", this.config.getName()));
// Our super-sophisticated ETL functionality:
String next = this.config.getNextConfig();
if (!StringUtils.isBlank(this.config.getNextConfig())) {
ConfigurationEngine nextEngine = new ConfigurationEngine(Configuration.findConfigurationsByNameEquals(next).getSingleResult());
Map<String, List<String>> nextInfoMap = nextEngine.runConfiguration();
infoMap.get("exception").addAll(nextInfoMap.get("exception"));
infoMap.get("stackTrace").addAll(nextInfoMap.get("stackTrace"));
infoMap.get("messages").addAll(nextInfoMap.get("messages"));
}
}
catch (Exception e) {
infoMap.get("exception").add(e.toString());
for (StackTraceElement ste:e.getStackTrace()) infoMap.get("stackTrace").add(ste.toString());
}
File luceneDir = new File(this.luceneDirectory);
try {
if (luceneDir.exists()) FileUtils.deleteDirectory(luceneDir);
}
catch (IOException e) {
System.err.println("Error deleting lucine directory "+luceneDir);
}
return infoMap;
}
}
| 14,142 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Dictionary.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Dictionary.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import javax.persistence.EntityManager;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
/**
* This is the ORM equivalent for {@link org.kew.rmf.utils.Dictionary}.
*
* It knows about a file that is supposed to have two columns which can be used to e.g.
* overwrite deprecated values of columnA with the good values of columnB prior to
* a Matching, or do falsePositives checks.
*/
@RooJavaBean
@RooToString
@Table(uniqueConstraints = @javax.persistence.UniqueConstraint(columnNames= { "name" }))
@RooJpaActiveRecord(finders = { "findDictionarysByNameEquals" })
public class Dictionary {
String name;
String fileDelimiter = "	";
@NotNull
String filePath;
@PrePersist
@PreUpdate
protected void cleanAllPaths() {
// TODO: change the following local setting to a real local setting :-)
String cleanedPath = this.getFilePath().replaceAll("\\\\", "/").replaceAll("T:", "/mnt/t_drive");
this.setFilePath(cleanedPath);
}
public static TypedQuery<Dictionary> findDictionariesByNameEquals(String name) {
if (name == null || name.length() == 0) throw new IllegalArgumentException("The name argument is required");
EntityManager em = Dictionary.entityManager();
TypedQuery<Dictionary> q = em.createQuery("SELECT o FROM Dictionary AS o WHERE o.name = :name", Dictionary.class);
q.setParameter("name", name);
return q;
}
public String getFileDelimiter() {
return fileDelimiter;
}
public void setFileDelimiter(String fileDelimiter) {
this.fileDelimiter = fileDelimiter;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| 3,010 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Reporter.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Reporter.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
/**
*
* This is the ORM equivalent to any heir of {@link org.kew.rmf.reporters.Reporter}.
*
* It can describe any reporter, the provided params are expected to be a comma-separated
* String of key=value pairs.
*/
@RooJavaBean
@RooToString
@RooJpaActiveRecord
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"config", "name"}))
public class Reporter extends CloneMe<Reporter> {
static String[] CLONE_STRING_FIELDS = new String[] {
"className",
"delimiter",
"fileName",
"idDelimiter",
"name",
"packageName",
"params",
};
private String name;
private String delimiter = "	";
private String idDelimiter = "|";
private String fileName;
private String packageName;
private String className;
private String params;
@ManyToOne
private Configuration config;
public String toString() {
return this.name;
}
public Reporter cloneMe(Configuration configClone) throws Exception {
Reporter clone = new Reporter();
// first the string attributes and manytoones
// first the string attributes
for (String method:Reporter.CLONE_STRING_FIELDS) {
clone.setattr(method, this.getattr(method, ""));
}
// then the relational attributes
clone.setConfig(configClone);
return clone;
}
}
| 2,474 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Bot.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Bot.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import java.util.List;
import javax.persistence.MappedSuperclass;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
/**
* A Bot serves as a template for all configurable {@link Matcher} and {@link Transformer}
* entities that have a (instance) name,
* a package- and a className for the class to be identified and accept an arbitrary
* amount of comma-separated 'param=value' parameters.
*/
@RooJavaBean
@RooToString
@MappedSuperclass
@RooJpaActiveRecord(mappedSuperclass=true)
public abstract class Bot extends CloneMe<Bot> implements Comparable<Bot> {
static String[] CLONE_STRING_FIELDS = new String[] {
"name",
"packageName",
"className",
"params",
};
@Override
public int compareTo(Bot o) {
return this.getName().compareTo(o.getName());
}
public abstract String getName();
public abstract String getPackageName();
public abstract String getClassName();
public abstract String getParams();
public abstract List<? extends Bot> getComposedBy();
public abstract String getGroup();
@Override
public String toString () {
return this.getName();
}
}
| 2,077 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |
Configuration.java | /FileExtraction/Java_unseen/RBGKew_Reconciliation-and-Matching-Framework/matchconf/src/main/java/org/kew/rmf/matchconf/Configuration.java | /*
* Reconciliation and Matching Framework
* Copyright © 2014 Royal Botanic Gardens, Kew
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kew.rmf.matchconf;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.TypedQuery;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;
/**
* This is the ORM equivalent to
* {@link org.kew.rmf.core.configuration.Configuration}.
* Further, it offers a sandbox for all entities in MatchConf guaranteeing
* their Uniqueness per configuration instance. This facilitates cloning
* of whole configurations and further tweaking of the clones without messing
* with the original configuration.
*
* NOTE: the uniqueness paradigm is not valid for {@link Dictionary} instances,
* as they are meant to be available to all configurations.
*/
@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findConfigurationsByNameEquals" })
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"name"}))
public class Configuration extends CloneMe<Configuration> {
static String[] CLONE_STRING_FIELDS = new String[] {
"assessReportFrequency",
"className",
"loadReportFrequency",
"authorityFileDelimiter",
"authorityFileEncoding",
"authorityFileName",
"maxSearchResults",
"nextConfig",
"packageName",
"recordFilter",
"sortFieldName",
"queryFileQuoteChar",
"queryFileDelimiter",
"queryFileEncoding",
"queryFileName",
"workDirPath",
};
private String name;
private String workDirPath;
private String queryFileName = "query.tsv";
private String queryFileEncoding = "UTF-8";
private String queryFileDelimiter = "	";
private String queryFileQuoteChar = """;
private String recordFilter = "";
private String nextConfig = "";
// authorityFileName being populated decides over being a MatchConfig
private String authorityFileName = "";
private String authorityFileEncoding = "UTF-8";
private String authorityFileDelimiter = "	";
private String packageName = "org.kew.rmf.core.configuration";
private String className = "DeduplicationConfiguration";
private String loadReportFrequency = "50000";
private String assessReportFrequency = "100";
private String sortFieldName = "id";
private String maxSearchResults = "10000";
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@Sort(type = SortType.NATURAL)
private List<Wire> wiring = new ArrayList<Wire>();
@Sort(type = SortType.NATURAL)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Transformer> transformers = new ArrayList<>();
@Sort(type = SortType.NATURAL)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Matcher> matchers = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Reporter> reporters = new ArrayList<>();
public Configuration cloneMe () throws Exception {
Configuration clone = new Configuration();
// first the string attributes
String newName = "copy-of_" + this.name;
while (Configuration.findConfigurationsByNameEquals(newName).getResultList().size() > 0) {
newName = "copy-of_" + newName;
}
clone.setName(newName);
for (String method:Configuration.CLONE_STRING_FIELDS) {
clone.setattr(method, this.getattr(method, ""));
}
// then the relational attributes
for (Transformer transformer:this.transformers) {
clone.getTransformers().add(transformer.cloneMe(clone));
}
for (Matcher matcher:this.matchers) {
clone.getMatchers().add(matcher.cloneMe(clone));
}
for (Reporter reporter:this.reporters) {
Reporter reporterClone = reporter.cloneMe(clone);
clone.getReporters().add(reporterClone);
}
for (Wire wire:this.wiring) {
clone.getWiring().add(wire.cloneMe(clone));
}
clone.persist();
logger.info("cloned configuration {}", this);
return clone;
}
@PrePersist
@PreUpdate
protected void cleanAllPaths() {
// TODO: change the following local setting to a real local setting :-)
String cleanedPath = this.getWorkDirPath().replaceAll("\\\\", "/").replaceAll("T:", "/mnt/t_drive");
this.setWorkDirPath(cleanedPath);
}
public static TypedQuery<Configuration> findDedupConfigsByNameEquals(String name) {
if (name == null || name.length() == 0) throw new IllegalArgumentException("The name argument is required");
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.name = :name AND o.authorityFileName = :authorityFileName", Configuration.class);
q.setParameter("name", name);
q.setParameter("authorityFileName", "");
return q;
}
public static TypedQuery<Configuration> findMatchConfigsByNameEquals(String name) {
if (name == null || name.length() == 0) throw new IllegalArgumentException("The name argument is required");
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.name = :name AND o.authorityFileName != :authorityFileName", Configuration.class);
q.setParameter("name", name);
q.setParameter("authorityFileName", "");
return q;
}
public static long countDedupConfigs() {
TypedQuery<Long> q = entityManager().createQuery("SELECT COUNT(o) FROM Configuration AS o WHERE o.authorityFileName = :authorityFileName", Long.class);
q.setParameter("authorityFileName", "");
return q.getSingleResult();
}
public static long countMatchConfigs() {
TypedQuery<Long> q = entityManager().createQuery("SELECT COUNT(o) FROM Configuration AS o WHERE o.authorityFileName != :authorityFileName", Long.class);
q.setParameter("authorityFileName", "");
return q.getSingleResult();
}
public static List<Configuration> findAllDedupConfigs() {
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.authorityFileName = :authorityFileName", Configuration.class);
q.setParameter("authorityFileName", "");
return q.getResultList();
}
public static List<Configuration> findAllMatchConfigs() {
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.authorityFileName != :authorityFileName", Configuration.class);
q.setParameter("authorityFileName", "");
return q.getResultList();
}
public static List<Configuration> findDedupConfigEntries(int firstResult, int maxResults) {
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.authorityFileName = :authorityFileName", Configuration.class);
q.setParameter("authorityFileName", "");
return q.setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
public static List<Configuration> findMatchConfigEntries(int firstResult, int maxResults) {
EntityManager em = Configuration.entityManager();
TypedQuery<Configuration> q = em.createQuery("SELECT o FROM Configuration AS o WHERE o.authorityFileName != :authorityFileName", Configuration.class);
q.setParameter("authorityFileName", "");
return q.setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
public Wire getWireForName(String wireName) {
for (Wire wire : this.getWiring()) {
if (wire.getName().equals(wireName)) return wire;
}
return null;
}
public Transformer getTransformerForName(String transformerName) {
for (Transformer transformer : this.getTransformers()) {
if (transformer.getName().equals(transformerName)) return transformer;
}
return null;
}
public Matcher getMatcherForName(String matcherName) {
for (Matcher matcher : this.getMatchers()) {
if (matcher.getName().equals(matcherName)) return matcher;
}
return null;
}
public Reporter getReporterForName(String reporterName) {
for (Reporter reporter: this.getReporters()) {
if (reporter.getName().equals(reporterName)) return reporter;
}
return null;
}
public void removeWire(String wireName) {
this.getWiring().remove(this.getWireForName(wireName));
this.merge();
}
public void removeTransformers() throws Exception {
for (Transformer t : this.getTransformers()) {
this.removeTransformer(t);
}
}
public void removeTransformer(String transformerName) throws Exception {
Transformer toRemove = this.getTransformerForName(transformerName);
this.removeTransformer(toRemove);
}
public void removeTransformer(Transformer toRemove) throws Exception {
Wire stillWired = toRemove.hasWiredTransformers();
if (stillWired != null) {
throw new Exception(String.format("It seems that %s is still being used in a wire (%s), please remove it there first in order to delete it.", toRemove, stillWired));
}
if (this.getTransformers().contains(toRemove)) {
toRemove.removeOrphanedWiredTransformers();
this.getTransformers().remove(toRemove);
}
this.merge();
}
public void removeMatcher(String matcherName) {
this.getMatchers().remove(this.getMatcherForName(matcherName));
this.merge();
}
public void removeReporter(String reporterName) {
this.getReporters().remove(this.getReporterForName(reporterName));
this.merge();
}
public List<Dictionary> findDictionaries() {
List<Dictionary> dicts = new ArrayList<>();
List<Bot> bots = new ArrayList<>();
bots.addAll(this.getTransformers());
bots.addAll(this.getMatchers());
for (Bot bot:bots) {
if (!bot.getParams().contains("dict=")) continue;
for (String param:bot.getParams().split(",")) {
String[] paramTuple = param.split("=");
if (paramTuple[0].equals("dict")) dicts.add(Dictionary.findDictionariesByNameEquals(paramTuple[1]).getSingleResult());
}
}
return dicts;
}
/**
* This method fixes a bug introduced in a very-early-stage migration of the data improvement database. It can possibly be removed
* for any new installations and in near future in general.
*/
public void fixMatchersForAlienWire() {
for (Matcher matcher:this.getMatchers()) {
for (Wire possibleAlienWire:Wire.findWiresByMatcher(matcher).getResultList()) {
Configuration possibleAlienConfig = possibleAlienWire.getConfiguration();
if (!possibleAlienConfig.getId().equals(this.getId())) {
logger.warn("Still found an alien wire ({} from config {}!!! trying to fix that now", possibleAlienWire.getName(), this.getName());
possibleAlienWire.setMatcher(possibleAlienConfig.getMatcherForName(matcher.getName()));
possibleAlienWire.merge();
logger.info("Released alien wire into the void");
}
}
}
}
@Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Configuration attached = Configuration.findConfiguration(this.getId());
this.entityManager.remove(attached);
}
}
}
| 12,048 | Java | .java | RBGKew/Reconciliation-and-Matching-Framework | 28 | 3 | 9 | 2014-09-24T13:39:19Z | 2017-04-18T13:37:52Z |