proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/PatternSymbolDeclarator.java
|
PatternSymbolDeclarator
|
getSymbolDeclarations
|
class PatternSymbolDeclarator extends AbstractSymbolDeclarator<PatternExpr> {
public PatternSymbolDeclarator(PatternExpr wrappedNode, TypeSolver typeSolver) {
super(wrappedNode, typeSolver);
}
@Override
public List<ResolvedValueDeclaration> getSymbolDeclarations() {<FILL_FUNCTION_BODY>}
}
|
List<ResolvedValueDeclaration> symbols = new LinkedList<>();
symbols.add(JavaParserSymbolDeclaration.patternVar(wrappedNode, typeSolver));
return symbols;
| 96
| 46
| 142
|
<methods>public void <init>(com.github.javaparser.ast.expr.PatternExpr, com.github.javaparser.resolution.TypeSolver) <variables>protected com.github.javaparser.resolution.TypeSolver typeSolver,protected com.github.javaparser.ast.expr.PatternExpr wrappedNode
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/declarators/VariableSymbolDeclarator.java
|
VariableSymbolDeclarator
|
getSymbolDeclarations
|
class VariableSymbolDeclarator extends AbstractSymbolDeclarator<VariableDeclarationExpr> {
public VariableSymbolDeclarator(VariableDeclarationExpr wrappedNode, TypeSolver typeSolver) {
super(wrappedNode, typeSolver);
wrappedNode.getParentNode().ifPresent(p -> {
if (p instanceof FieldDeclaration) {
throw new IllegalArgumentException();
}
});
}
@Override
public List<ResolvedValueDeclaration> getSymbolDeclarations() {<FILL_FUNCTION_BODY>}
}
|
List<ResolvedValueDeclaration> variables = wrappedNode.getVariables()
.stream()
.map(v -> JavaParserSymbolDeclaration.localVar(v, typeSolver))
.collect(Collectors.toCollection(ArrayList::new));
// // FIXME: This returns ALL PatternExpr, regardless of whether it is in scope or not.
// List<JavaParserSymbolDeclaration> patterns = wrappedNode.getVariables()
// .stream()
// .filter(variableDeclarator -> variableDeclarator.getInitializer().isPresent())
// .map(variableDeclarator -> variableDeclarator.getInitializer().get())
// .map(expression -> expression.findAll(PatternExpr.class))
// .flatMap(Collection::stream)
// .map(v -> JavaParserSymbolDeclaration.patternVar(v, typeSolver))
// .collect(Collectors.toCollection(ArrayList::new));
List<ResolvedValueDeclaration> all = new ArrayList<>(variables);
// all.addAll(patterns);
return all;
| 136
| 266
| 402
|
<methods>public void <init>(com.github.javaparser.ast.expr.VariableDeclarationExpr, com.github.javaparser.resolution.TypeSolver) <variables>protected com.github.javaparser.resolution.TypeSolver typeSolver,protected com.github.javaparser.ast.expr.VariableDeclarationExpr wrappedNode
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistAnnotationMemberDeclaration.java
|
JavassistAnnotationMemberDeclaration
|
getDefaultValue
|
class JavassistAnnotationMemberDeclaration implements ResolvedAnnotationMemberDeclaration {
private static Map<Class<? extends MemberValue>, Function<MemberValue, ? extends Expression>> memberValueAsExressionConverter = new HashMap<>();
static {
memberValueAsExressionConverter.put(BooleanMemberValue.class, (memberValue) -> new BooleanLiteralExpr(BooleanMemberValue.class.cast(memberValue).getValue()));
memberValueAsExressionConverter.put(CharMemberValue.class, (memberValue) -> new CharLiteralExpr(CharMemberValue.class.cast(memberValue).getValue()));
memberValueAsExressionConverter.put(DoubleMemberValue.class, (memberValue) -> new DoubleLiteralExpr(DoubleMemberValue.class.cast(memberValue).getValue()));
memberValueAsExressionConverter.put(IntegerMemberValue.class, (memberValue) -> new IntegerLiteralExpr(IntegerMemberValue.class.cast(memberValue).getValue()));
memberValueAsExressionConverter.put(LongMemberValue.class, (memberValue) -> new LongLiteralExpr(LongMemberValue.class.cast(memberValue).getValue()));
memberValueAsExressionConverter.put(StringMemberValue.class, (memberValue) -> new StringLiteralExpr(StringMemberValue.class.cast(memberValue).getValue()));
}
private CtMethod annotationMember;
private TypeSolver typeSolver;
public JavassistAnnotationMemberDeclaration(CtMethod annotationMember, TypeSolver typeSolver) {
this.annotationMember = annotationMember;
this.typeSolver = typeSolver;
}
@Override
public Expression getDefaultValue() {<FILL_FUNCTION_BODY>}
@Override
public ResolvedType getType() {
try {
String descriptor = annotationMember.getMethodInfo().getDescriptor();
SignatureAttribute.MethodSignature signature = SignatureAttribute.toMethodSignature(descriptor);
SymbolReference<ResolvedReferenceTypeDeclaration> returnType = typeSolver.tryToSolveType(signature.getReturnType().jvmTypeName());
if (returnType.isSolved()) {
return new ReferenceTypeImpl(returnType.getCorrespondingDeclaration());
}
} catch (BadBytecode e) {
// We don't expect this to happen, but we handle it anyway.
throw new IllegalStateException("An invalid descriptor was received from JavaAssist.", e);
}
throw new UnsupportedOperationException(String.format("Obtaining the type of the annotation member %s is not supported yet.", annotationMember.getLongName()));
}
@Override
public String getName() {
return annotationMember.getName();
}
}
|
AnnotationDefaultAttribute defaultAttribute = (AnnotationDefaultAttribute) annotationMember.getMethodInfo().getAttribute(AnnotationDefaultAttribute.tag);
if (defaultAttribute == null) return null;
MemberValue memberValue = defaultAttribute.getDefaultValue();
Function<MemberValue, ? extends Expression> fn = memberValueAsExressionConverter.get(memberValue.getClass());
if (fn == null) throw new UnsupportedOperationException(String.format("Obtaining the type of the annotation member %s is not supported yet.", annotationMember.getName()));
return fn.apply(memberValue);
| 646
| 137
| 783
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistConstructorDeclaration.java
|
JavassistConstructorDeclaration
|
toString
|
class JavassistConstructorDeclaration implements ResolvedConstructorDeclaration {
private final CtConstructor ctConstructor;
private final TypeSolver typeSolver;
private final JavassistMethodLikeDeclarationAdapter methodLikeAdaper;
public JavassistConstructorDeclaration(CtConstructor ctConstructor, TypeSolver typeSolver) {
this.ctConstructor = ctConstructor;
this.typeSolver = typeSolver;
this.methodLikeAdaper = new JavassistMethodLikeDeclarationAdapter(ctConstructor, typeSolver, this);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return ctConstructor.getName();
}
@Override
public boolean isField() {
return false;
}
@Override
public boolean isParameter() {
return false;
}
@Override
public boolean isType() {
return false;
}
@Override
public ResolvedReferenceTypeDeclaration declaringType() {
return JavassistFactory.toTypeDeclaration(ctConstructor.getDeclaringClass(), typeSolver);
}
@Override
public int getNumberOfParams() {
return methodLikeAdaper.getNumberOfParams();
}
@Override
public ResolvedParameterDeclaration getParam(int i) {
return methodLikeAdaper.getParam(i);
}
@Override
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
return methodLikeAdaper.getTypeParameters();
}
@Override
public AccessSpecifier accessSpecifier() {
return JavassistFactory.modifiersToAccessLevel(ctConstructor.getModifiers());
}
@Override
public int getNumberOfSpecifiedExceptions() {
return methodLikeAdaper.getNumberOfSpecifiedExceptions();
}
@Override
public ResolvedType getSpecifiedException(int index) {
return methodLikeAdaper.getSpecifiedException(index);
}
}
|
return getClass().getSimpleName() + "{" +
"ctConstructor=" + ctConstructor.getName() +
", typeSolver=" + typeSolver +
'}';
| 517
| 50
| 567
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistEnumConstantDeclaration.java
|
JavassistEnumConstantDeclaration
|
toString
|
class JavassistEnumConstantDeclaration implements ResolvedEnumConstantDeclaration {
private CtField ctField;
private TypeSolver typeSolver;
private ResolvedType type;
public JavassistEnumConstantDeclaration(CtField ctField, TypeSolver typeSolver) {
if (ctField == null) {
throw new IllegalArgumentException();
}
if ((ctField.getFieldInfo2().getAccessFlags() & AccessFlag.ENUM) == 0) {
throw new IllegalArgumentException(
"Trying to instantiate a JavassistEnumConstantDeclaration with something which is not an enum field: "
+ ctField.toString());
}
this.ctField = ctField;
this.typeSolver = typeSolver;
}
@Override
public String getName() {
return ctField.getName();
}
@Override
public ResolvedType getType() {
if (type == null) {
type = new ReferenceTypeImpl(new JavassistEnumDeclaration(ctField.getDeclaringClass(), typeSolver));
}
return type;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + "{" +
"ctField=" + ctField.getName() +
", typeSolver=" + typeSolver +
'}';
| 311
| 50
| 361
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFactory.java
|
JavassistFactory
|
toTypeDeclaration
|
class JavassistFactory {
public static ResolvedType typeUsageFor(CtClass ctClazz, TypeSolver typeSolver) {
try {
if (ctClazz.isArray()) {
return new ResolvedArrayType(typeUsageFor(ctClazz.getComponentType(), typeSolver));
}
if (ctClazz.isPrimitive()) {
if (ctClazz.getName().equals("void")) {
return ResolvedVoidType.INSTANCE;
}
return ResolvedPrimitiveType.byName(ctClazz.getName());
}
if (ctClazz.isInterface()) {
return new ReferenceTypeImpl(new JavassistInterfaceDeclaration(ctClazz, typeSolver));
}
if (ctClazz.isEnum()) {
return new ReferenceTypeImpl(new JavassistEnumDeclaration(ctClazz, typeSolver));
}
return new ReferenceTypeImpl(new JavassistClassDeclaration(ctClazz, typeSolver));
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
}
public static ResolvedReferenceTypeDeclaration toTypeDeclaration(CtClass ctClazz, TypeSolver typeSolver) {<FILL_FUNCTION_BODY>}
static AccessSpecifier modifiersToAccessLevel(final int modifiers) {
if (Modifier.isPublic(modifiers)) {
return AccessSpecifier.PUBLIC;
}
if (Modifier.isProtected(modifiers)) {
return AccessSpecifier.PROTECTED;
}
if (Modifier.isPrivate(modifiers)) {
return AccessSpecifier.PRIVATE;
}
return AccessSpecifier.NONE;
}
}
|
if (ctClazz.isAnnotation()) {
return new JavassistAnnotationDeclaration(ctClazz, typeSolver);
}
if (ctClazz.isInterface()) {
return new JavassistInterfaceDeclaration(ctClazz, typeSolver);
}
if (ctClazz.isEnum()) {
return new JavassistEnumDeclaration(ctClazz, typeSolver);
}
if (ctClazz.isArray()) {
throw new IllegalArgumentException("This method should not be called passing an array");
}
return new JavassistClassDeclaration(ctClazz, typeSolver);
| 440
| 156
| 596
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistFieldDeclaration.java
|
JavassistFieldDeclaration
|
getType
|
class JavassistFieldDeclaration implements ResolvedFieldDeclaration {
private CtField ctField;
private TypeSolver typeSolver;
public JavassistFieldDeclaration(CtField ctField, TypeSolver typeSolver) {
this.ctField = ctField;
this.typeSolver = typeSolver;
}
@Override
public ResolvedType getType() {<FILL_FUNCTION_BODY>}
@Override
public boolean isStatic() {
return Modifier.isStatic(ctField.getModifiers());
}
@Override
public boolean isVolatile() {
return Modifier.isVolatile(ctField.getModifiers());
}
@Override
public String getName() {
return ctField.getName();
}
@Override
public boolean isField() {
return true;
}
@Override
public boolean isParameter() {
return false;
}
@Override
public boolean isType() {
return false;
}
@Override
public AccessSpecifier accessSpecifier() {
return JavassistFactory.modifiersToAccessLevel(ctField.getModifiers());
}
@Override
public ResolvedTypeDeclaration declaringType() {
return JavassistFactory.toTypeDeclaration(ctField.getDeclaringClass(), typeSolver);
}
}
|
try {
String signature = ctField.getGenericSignature();
if (signature == null) {
signature = ctField.getSignature();
}
SignatureAttribute.Type genericSignatureType = SignatureAttribute.toTypeSignature(signature);
return JavassistUtils.signatureTypeToType(genericSignatureType, typeSolver, (ResolvedTypeParametrizable) declaringType());
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
| 359
| 122
| 481
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistMethodLikeDeclarationAdapter.java
|
JavassistMethodLikeDeclarationAdapter
|
getSpecifiedException
|
class JavassistMethodLikeDeclarationAdapter {
private CtBehavior ctBehavior;
private TypeSolver typeSolver;
private ResolvedMethodLikeDeclaration declaration;
private SignatureAttribute.MethodSignature methodSignature;
public JavassistMethodLikeDeclarationAdapter(CtBehavior ctBehavior, TypeSolver typeSolver, ResolvedMethodLikeDeclaration declaration) {
this.ctBehavior = ctBehavior;
this.typeSolver = typeSolver;
this.declaration = declaration;
try {
String signature = ctBehavior.getGenericSignature();
if (signature == null) {
signature = ctBehavior.getSignature();
}
methodSignature = SignatureAttribute.toMethodSignature(signature);
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
}
public int getNumberOfParams() {
return methodSignature.getParameterTypes().length;
}
public ResolvedParameterDeclaration getParam(int i) {
boolean variadic = false;
if ((ctBehavior.getModifiers() & javassist.Modifier.VARARGS) > 0) {
variadic = i == (methodSignature.getParameterTypes().length - 1);
}
Optional<String> paramName = JavassistUtils.extractParameterName(ctBehavior, i);
ResolvedType type = JavassistUtils.signatureTypeToType(methodSignature.getParameterTypes()[i], typeSolver, declaration);
return new JavassistParameterDeclaration(type, typeSolver, variadic, paramName.orElse(null));
}
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
if (ctBehavior.getGenericSignature() == null) {
return new ArrayList<>();
}
return Arrays.stream(methodSignature.getTypeParameters())
.map(jasTp -> new JavassistTypeParameter(jasTp, declaration, typeSolver))
.collect(Collectors.toList());
}
public int getNumberOfSpecifiedExceptions() {
ExceptionsAttribute exceptionsAttribute = ctBehavior.getMethodInfo().getExceptionsAttribute();
if (exceptionsAttribute == null) {
return 0;
}
String[] exceptions = exceptionsAttribute.getExceptions();
return exceptions == null ? 0 : exceptions.length;
}
public ResolvedType getSpecifiedException(int index) {<FILL_FUNCTION_BODY>}
public ResolvedType getReturnType() {
return JavassistUtils.signatureTypeToType(methodSignature.getReturnType(), typeSolver, declaration);
}
}
|
if (index < 0) {
throw new IllegalArgumentException(String.format("index < 0: %d", index));
}
ExceptionsAttribute exceptionsAttribute = ctBehavior.getMethodInfo().getExceptionsAttribute();
if (exceptionsAttribute == null) {
throw new IllegalArgumentException(String.format("No exception with index %d. Number of exceptions: 0", index));
}
String[] exceptions = exceptionsAttribute.getExceptions();
if (exceptions == null || index >= exceptions.length) {
throw new IllegalArgumentException(String.format("No exception with index %d. Number of exceptions: %d",
index, getNumberOfSpecifiedExceptions()));
}
ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(exceptions[index]);
return new ReferenceTypeImpl(typeDeclaration, Collections.emptyList());
| 672
| 211
| 883
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistParameterDeclaration.java
|
JavassistParameterDeclaration
|
toString
|
class JavassistParameterDeclaration implements ResolvedParameterDeclaration {
private ResolvedType type;
private TypeSolver typeSolver;
private boolean variadic;
private String name;
public JavassistParameterDeclaration(CtClass type, TypeSolver typeSolver, boolean variadic, String name) {
this(JavassistFactory.typeUsageFor(type, typeSolver), typeSolver, variadic, name);
}
public JavassistParameterDeclaration(ResolvedType type, TypeSolver typeSolver, boolean variadic, String name) {
this.name = name;
this.type = type;
this.typeSolver = typeSolver;
this.variadic = variadic;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean hasName() {
return name != null;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isField() {
return false;
}
@Override
public boolean isParameter() {
return true;
}
@Override
public boolean isVariadic() {
return variadic;
}
@Override
public boolean isType() {
return false;
}
@Override
public ResolvedType getType() {
return type;
}
}
|
return "JavassistParameterDeclaration{" +
"type=" + type +
", typeSolver=" + typeSolver +
", variadic=" + variadic +
'}';
| 364
| 53
| 417
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javassistmodel/JavassistTypeParameter.java
|
JavassistTypeParameter
|
getBounds
|
class JavassistTypeParameter implements ResolvedTypeParameterDeclaration {
private SignatureAttribute.TypeParameter wrapped;
private TypeSolver typeSolver;
private ResolvedTypeParametrizable container;
public JavassistTypeParameter(SignatureAttribute.TypeParameter wrapped, ResolvedTypeParametrizable container, TypeSolver typeSolver) {
this.wrapped = wrapped;
this.typeSolver = typeSolver;
this.container = container;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ResolvedTypeParameterDeclaration)) return false;
ResolvedTypeParameterDeclaration that = (ResolvedTypeParameterDeclaration) o;
if (!getQualifiedName().equals(that.getQualifiedName())) {
return false;
}
if (declaredOnType() == that.declaredOnType()) {
return true;
}
// TODO check bounds
return declaredOnMethod() == that.declaredOnMethod();
}
@Override
public int hashCode() {
return Objects.hash(getQualifiedName(), declaredOnType(), declaredOnMethod());
}
@Override
public String toString() {
return "JavassistTypeParameter{" +
wrapped.getName()
+ '}';
}
@Override
public String getName() {
return wrapped.getName();
}
@Override
public String getContainerQualifiedName() {
if (this.container instanceof ResolvedReferenceTypeDeclaration) {
return ((ResolvedReferenceTypeDeclaration) this.container).getQualifiedName();
}
if (this.container instanceof ResolvedMethodLikeDeclaration) {
return ((ResolvedMethodLikeDeclaration) this.container).getQualifiedName();
}
throw new UnsupportedOperationException();
}
@Override
public String getContainerId() {
return getContainerQualifiedName();
}
@Override
public ResolvedTypeParametrizable getContainer() {
return this.container;
}
@Override
public List<ResolvedTypeParameterDeclaration.Bound> getBounds() {<FILL_FUNCTION_BODY>}
@Override
public Optional<ResolvedReferenceTypeDeclaration> containerType() {
if (container instanceof ResolvedReferenceTypeDeclaration) {
return Optional.of((ResolvedReferenceTypeDeclaration) container);
}
return Optional.empty();
}
@Override
public ResolvedReferenceType object() {
return new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject());
}
}
|
List<Bound> bounds = new ArrayList<>();
SignatureAttribute.ObjectType classBound = wrapped.getClassBound();
if (classBound != null) {
bounds.add(Bound.extendsBound(JavassistUtils.signatureTypeToType(classBound, typeSolver, getContainer())));
}
for (SignatureAttribute.ObjectType ot : wrapped.getInterfaceBound()) {
bounds.add(Bound.extendsBound(JavassistUtils.signatureTypeToType(ot, typeSolver, getContainer())));
}
return bounds;
| 664
| 139
| 803
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/logic/AbstractClassDeclaration.java
|
AbstractClassDeclaration
|
getAllInterfaces
|
class AbstractClassDeclaration extends AbstractTypeDeclaration
implements ResolvedClassDeclaration, MethodResolutionCapability {
///
/// Public
///
@Override
public boolean hasName() {
return getQualifiedName() != null;
}
@Override
public final List<ResolvedReferenceType> getAllSuperClasses() {
List<ResolvedReferenceType> superclasses = new ArrayList<>();
getSuperClass().ifPresent(superClass -> {
superclasses.add(superClass);
superclasses.addAll(superClass.getAllClassesAncestors());
});
if (superclasses.removeIf(ResolvedReferenceType::isJavaLangObject)) {
superclasses.add(object());
}
return superclasses;
}
@Override
public final List<ResolvedReferenceType> getAllInterfaces() {<FILL_FUNCTION_BODY>}
@Override
public final ResolvedClassDeclaration asClass() {
return this;
}
///
/// Protected
///
/**
* An implementation of the Object class.
*/
protected abstract ResolvedReferenceType object();
}
|
List<ResolvedReferenceType> interfaces = new ArrayList<>();
for (ResolvedReferenceType interfaceDeclaration : getInterfaces()) {
interfaces.add(interfaceDeclaration);
interfaces.addAll(interfaceDeclaration.getAllInterfacesAncestors());
}
getSuperClass().ifPresent(superClass -> {
interfaces.addAll(superClass.getAllInterfacesAncestors());
});
return interfaces;
| 297
| 106
| 403
|
<methods>public non-sealed void <init>() ,public final Set<com.github.javaparser.resolution.MethodUsage> getAllMethods() ,public final boolean isFunctionalInterface() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/logic/AbstractTypeDeclaration.java
|
AbstractTypeDeclaration
|
getAllMethods
|
class AbstractTypeDeclaration implements ResolvedReferenceTypeDeclaration {
/*
* Returns all methods which have distinct "enhanced" signature declared in this type and all members.
* An "enhanced" signature include the return type which is used sometimes to identify functional interfaces.
* This is a different implementation from the previous one which returned all methods which have a distinct
* signature (based on method name and qualified parameter types)
*/
@Override
public final Set<MethodUsage> getAllMethods() {<FILL_FUNCTION_BODY>}
@Override
public final boolean isFunctionalInterface() {
return FunctionalInterfaceLogic.getFunctionalMethod(this).isPresent();
}
}
|
Set<MethodUsage> methods = new HashSet<>();
Set<String> methodsSignatures = new HashSet<>();
for (ResolvedMethodDeclaration methodDeclaration : getDeclaredMethods()) {
MethodUsage methodUsage = new MethodUsage(methodDeclaration);
methods.add(methodUsage);
String signature = methodUsage.getSignature();
String returnType = methodUsage.getDeclaration().getReturnType().describe();
String enhancedSignature = String.format("%s %s", returnType, signature);
methodsSignatures.add(enhancedSignature);
}
for (ResolvedReferenceType ancestor : getAllAncestors()) {
List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> typeParametersMap = ancestor.getTypeParametersMap();
for (MethodUsage mu : ancestor.getDeclaredMethods()) {
// replace type parameters to be able to filter away overridden generified methods
MethodUsage methodUsage = mu;
for (Pair<ResolvedTypeParameterDeclaration, ResolvedType> p : typeParametersMap) {
methodUsage = methodUsage.replaceTypeParameter(p.a, p.b);
}
String signature = methodUsage.getSignature();
String returnType = methodUsage.getDeclaration().getReturnType().describe();
String enhancedSignature = String.format("%s %s", returnType, signature);
if (!methodsSignatures.contains(enhancedSignature)) {
methodsSignatures.add(enhancedSignature);
methods.add(mu);
}
}
}
return methods;
| 170
| 380
| 550
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationDeclaration.java
|
ReflectionAnnotationDeclaration
|
solveMethodAsUsage
|
class ReflectionAnnotationDeclaration extends AbstractTypeDeclaration implements ResolvedAnnotationDeclaration,
MethodUsageResolutionCapability,
MethodResolutionCapability {
///
/// Fields
///
private Class<?> clazz;
private TypeSolver typeSolver;
private ReflectionClassAdapter reflectionClassAdapter;
///
/// Constructor
///
public ReflectionAnnotationDeclaration(Class<?> clazz, TypeSolver typeSolver) {
if (!clazz.isAnnotation()) {
throw new IllegalArgumentException("The given type is not an annotation.");
}
this.clazz = clazz;
this.typeSolver = typeSolver;
this.reflectionClassAdapter = new ReflectionClassAdapter(clazz, typeSolver, this);
}
///
/// Public methods
///
@Override
public String getPackageName() {
if (clazz.getPackage() != null) {
return clazz.getPackage().getName();
}
return "";
}
@Override
public String getClassName() {
String qualifiedName = getQualifiedName();
if (qualifiedName.contains(".")) {
return qualifiedName.substring(qualifiedName.lastIndexOf(".") + 1);
}
return qualifiedName;
}
@Override
public String getQualifiedName() {
return clazz.getCanonicalName();
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"clazz=" + clazz.getCanonicalName() +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReflectionAnnotationDeclaration)) return false;
ReflectionAnnotationDeclaration that = (ReflectionAnnotationDeclaration) o;
return clazz.getCanonicalName().equals(that.clazz.getCanonicalName());
}
@Override
public int hashCode() {
return clazz.getCanonicalName().hashCode();
}
@Override
public boolean isAssignableBy(ResolvedType type) {
// TODO #1836
throw new UnsupportedOperationException();
}
@Override
public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasDirectlyAnnotation(String canonicalName) {
return reflectionClassAdapter.hasDirectlyAnnotation(canonicalName);
}
@Override
public List<ResolvedFieldDeclaration> getAllFields() {
return reflectionClassAdapter.getAllFields();
}
@Override
public List<ResolvedReferenceType> getAncestors(boolean acceptIncompleteList) {
// we do not attempt to perform any symbol solving when analyzing ancestors in the reflection model, so we can
// simply ignore the boolean parameter here; an UnsolvedSymbolException cannot occur
return reflectionClassAdapter.getAncestors();
}
@Override
public Set<ResolvedMethodDeclaration> getDeclaredMethods() {
// TODO #1838
throw new UnsupportedOperationException();
}
@Override
public String getName() {
return clazz.getSimpleName();
}
@Override
public Optional<ResolvedReferenceTypeDeclaration> containerType() {
// TODO #1841
throw new UnsupportedOperationException("containerType() is not supported for " + this.getClass().getCanonicalName());
}
/**
* Annotation declarations cannot have type parameters and hence this method always returns an empty list.
*
* @return An empty list.
*/
@Override
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
// Annotation declarations cannot have type parameters - i.e. we can always return an empty list.
return Collections.emptyList();
}
@Override
public Set<ResolvedReferenceTypeDeclaration> internalTypes() {
return Arrays.stream(this.clazz.getDeclaredClasses())
.map(ic -> ReflectionFactory.typeDeclarationFor(ic, typeSolver))
.collect(Collectors.toSet());
}
@Override
public List<ResolvedConstructorDeclaration> getConstructors() {
return Collections.emptyList();
}
@Override
public List<ResolvedAnnotationMemberDeclaration> getAnnotationMembers() {
return Stream.of(clazz.getDeclaredMethods())
.map(m -> new ReflectionAnnotationMemberDeclaration(m, typeSolver))
.collect(Collectors.toList());
}
@Override
public Optional<MethodUsage> solveMethodAsUsage(final String name,
final List<ResolvedType> parameterTypes,
final Context invokationContext,
final List<ResolvedType> typeParameterValues) {<FILL_FUNCTION_BODY>}
@Override
public SymbolReference<ResolvedMethodDeclaration> solveMethod(final String name,
final List<ResolvedType> argumentsTypes,
final boolean staticOnly) {
return ReflectionMethodResolutionLogic.solveMethod(name, argumentsTypes, staticOnly,
typeSolver,this, clazz);
}
@Override
public boolean isInheritable() {
return clazz.getAnnotation(Inherited.class) != null;
}
}
|
Optional<MethodUsage> res = ReflectionMethodResolutionLogic.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext,
typeParameterValues, this, clazz);
if (res.isPresent()) {
// We have to replace method type typeParametersValues here
InferenceContext inferenceContext = new InferenceContext(typeSolver);
MethodUsage methodUsage = res.get();
int i = 0;
List<ResolvedType> parameters = new LinkedList<>();
for (ResolvedType actualType : parameterTypes) {
ResolvedType formalType = methodUsage.getParamType(i);
// We need to replace the class type typeParametersValues (while we derive the method ones)
parameters.add(inferenceContext.addPair(formalType, actualType));
i++;
}
try {
ResolvedType returnType = inferenceContext.addSingle(methodUsage.returnType());
for (int j=0;j<parameters.size();j++) {
methodUsage = methodUsage.replaceParamType(j, inferenceContext.resolve(parameters.get(j)));
}
methodUsage = methodUsage.replaceReturnType(inferenceContext.resolve(returnType));
return Optional.of(methodUsage);
} catch (ConflictingGenericTypesException e) {
return Optional.empty();
}
} else {
return res;
}
| 1,355
| 346
| 1,701
|
<methods>public non-sealed void <init>() ,public final Set<com.github.javaparser.resolution.MethodUsage> getAllMethods() ,public final boolean isFunctionalInterface() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionAnnotationMemberDeclaration.java
|
ReflectionAnnotationMemberDeclaration
|
transformDefaultValue
|
class ReflectionAnnotationMemberDeclaration implements ResolvedAnnotationMemberDeclaration {
private static Map<Class<?>, Function<Object, ? extends Expression>> valueAsExpressionConverters = new HashMap<>();
static {
valueAsExpressionConverters.put(Boolean.class, (value) -> new BooleanLiteralExpr((Boolean) value));
valueAsExpressionConverters.put(Character.class, (value) -> new CharLiteralExpr((Character) value));
valueAsExpressionConverters.put(Double.class, (value) -> new DoubleLiteralExpr((Double) value));
valueAsExpressionConverters.put(Integer.class, (value) -> new IntegerLiteralExpr((Integer) value));
valueAsExpressionConverters.put(Long.class, (value) -> new LongLiteralExpr((Long) value));
valueAsExpressionConverters.put(String.class, (value) -> new StringLiteralExpr((String) value));
valueAsExpressionConverters.put(Class.class, (value) -> {
final ClassOrInterfaceType type = new ClassOrInterfaceType(null, ((Class<?>) value).getSimpleName());
return new ClassExpr(type);
});
}
private Method annotationMember;
private TypeSolver typeSolver;
public ReflectionAnnotationMemberDeclaration(Method annotationMember, TypeSolver typeSolver) {
this.annotationMember = annotationMember;
this.typeSolver = typeSolver;
}
@Override
public Expression getDefaultValue() {
Object value = annotationMember.getDefaultValue();
if (value == null) return null;
if (value.getClass().isArray()) {
Object[] values = (Object[]) value;
final NodeList<Expression> expressions = Arrays.stream(values)
.map(this::transformDefaultValue)
.collect(NodeList.toNodeList());
return new ArrayInitializerExpr(expressions);
}
return transformDefaultValue(value);
}
private Expression transformDefaultValue(Object value) {<FILL_FUNCTION_BODY>}
@Override
public ResolvedType getType() {
Class returnType = annotationMember.getReturnType();
if (returnType.isPrimitive()) {
return ResolvedPrimitiveType.byName(returnType.getName());
}
SymbolReference<ResolvedReferenceTypeDeclaration> rrtd = typeSolver.tryToSolveType(returnType.getName());
if (rrtd.isSolved()) {
return new ReferenceTypeImpl(rrtd.getCorrespondingDeclaration());
}
throw new UnsupportedOperationException(String.format("Obtaining the type of the annotation member %s is not supported yet.", annotationMember.getName()));
}
@Override
public String getName() {
return annotationMember.getName();
}
}
|
if (value instanceof Enum<?>) {
final Class<?> declaringClass = ((Enum<?>) value).getDeclaringClass();
final String name = ((Enum<?>) value).name();
return new FieldAccessExpr(new NameExpr(declaringClass.getSimpleName()), name);
} else if (value instanceof Annotation) {
final Class<? extends Annotation> annotationType = ((Annotation) value).annotationType();
final Method[] declaredMethods = annotationType.getDeclaredMethods();
final NodeList<MemberValuePair> pairs = Arrays.stream(declaredMethods)
.map(m -> {
final ReflectionAnnotationMemberDeclaration nestedMemberDeclaration = new ReflectionAnnotationMemberDeclaration(m, typeSolver);
return new MemberValuePair(m.getName(), nestedMemberDeclaration.getDefaultValue());
})
.collect(NodeList.toNodeList());
return new NormalAnnotationExpr(new Name(annotationType.getSimpleName()), pairs);
}
Function<Object, ? extends Expression> fn = valueAsExpressionConverters.get(value.getClass());
if (fn == null)
throw new UnsupportedOperationException(
String.format("Obtaining the default value of the annotation member %s (of type %s) is not supported yet.",
annotationMember.getName(), value.getClass().getSimpleName())
);
return fn.apply(value);
| 701
| 342
| 1,043
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassAdapter.java
|
ReflectionClassAdapter
|
hasField
|
class ReflectionClassAdapter {
private Class<?> clazz;
private TypeSolver typeSolver;
private ResolvedReferenceTypeDeclaration typeDeclaration;
public ReflectionClassAdapter(Class<?> clazz, TypeSolver typeSolver, ResolvedReferenceTypeDeclaration typeDeclaration) {
this.clazz = clazz;
this.typeSolver = typeSolver;
this.typeDeclaration = typeDeclaration;
}
public Optional<ReferenceTypeImpl> getSuperClass() {
if (clazz.getGenericSuperclass() == null) {
// There isn't a super class (e.g. when this refers to java.lang.Object)
return Optional.empty();
}
java.lang.reflect.Type superType = clazz.getGenericSuperclass();
if (superType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superType;
List<ResolvedType> typeParameters = Arrays.stream(parameterizedType.getActualTypeArguments())
.map((t) -> ReflectionFactory.typeUsageFor(t, typeSolver))
.collect(Collectors.toList());
return Optional.of(new ReferenceTypeImpl(new ReflectionClassDeclaration(clazz.getSuperclass(), typeSolver), typeParameters));
}
return Optional.of(new ReferenceTypeImpl(new ReflectionClassDeclaration(clazz.getSuperclass(), typeSolver)));
}
public List<ResolvedReferenceType> getInterfaces() {
List<ResolvedReferenceType> interfaces = new ArrayList<>();
for (java.lang.reflect.Type superInterface : clazz.getGenericInterfaces()) {
if (superInterface instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superInterface;
List<ResolvedType> typeParameters = Arrays.stream(parameterizedType.getActualTypeArguments())
.map((t) -> ReflectionFactory.typeUsageFor(t, typeSolver))
.collect(Collectors.toList());
interfaces.add(new ReferenceTypeImpl(new ReflectionInterfaceDeclaration((Class<?>) ((ParameterizedType) superInterface).getRawType(), typeSolver), typeParameters));
} else {
interfaces.add(new ReferenceTypeImpl(new ReflectionInterfaceDeclaration((Class<?>) superInterface, typeSolver)));
}
}
return interfaces;
}
public List<ResolvedReferenceType> getAncestors() {
List<ResolvedReferenceType> ancestors = new LinkedList<>();
if (typeDeclaration.isClass() && !Object.class.getCanonicalName().equals(clazz.getCanonicalName())) {
if (getSuperClass().isPresent()) {
ReferenceTypeImpl superClass = getSuperClass().get();
ancestors.add(superClass);
} else {
// Inject the implicitly added extends java.lang.Object
ReferenceTypeImpl object = new ReferenceTypeImpl(
new ReflectionClassDeclaration(Object.class, typeSolver));
ancestors.add(object);
}
}
ancestors.addAll(getInterfaces());
return ancestors;
}
public ResolvedFieldDeclaration getField(String name) {
for (Field field : clazz.getDeclaredFields()) {
if (field.getName().equals(name)) {
return new ReflectionFieldDeclaration(field, typeSolver);
}
}
for (ResolvedReferenceType ancestor : typeDeclaration.getAllAncestors()) {
if (ancestor.getTypeDeclaration().isPresent()) {
ResolvedReferenceTypeDeclaration typeDeclaration = ancestor.getTypeDeclaration().get();
if (typeDeclaration.hasField(name)) {
ReflectionFieldDeclaration reflectionFieldDeclaration = (ReflectionFieldDeclaration) typeDeclaration.getField(name);
return reflectionFieldDeclaration.replaceType(ancestor.getFieldType(name).get());
}
}
}
throw new UnsolvedSymbolException(name, "Field in " + this);
}
public boolean hasField(String name) {<FILL_FUNCTION_BODY>}
public List<ResolvedFieldDeclaration> getAllFields() {
ArrayList<ResolvedFieldDeclaration> fields = new ArrayList<>();
// First consider fields declared on this class
for (Field field : clazz.getDeclaredFields()) {
fields.add(new ReflectionFieldDeclaration(field, typeSolver));
}
// Then consider fields inherited from ancestors
for (ResolvedReferenceType ancestor : typeDeclaration.getAllAncestors()) {
ancestor.getTypeDeclaration().ifPresent(ancestorTypeDeclaration -> {
fields.addAll(ancestorTypeDeclaration.getAllFields());
});
}
return fields;
}
public Set<ResolvedMethodDeclaration> getDeclaredMethods() {
return Arrays.stream(clazz.getDeclaredMethods())
.filter(m -> !m.isSynthetic() && !m.isBridge())
.map(m -> new ReflectionMethodDeclaration(m, typeSolver))
.collect(Collectors.toSet());
}
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
List<ResolvedTypeParameterDeclaration> params = new ArrayList<>();
for (TypeVariable<?> tv : this.clazz.getTypeParameters()) {
params.add(new ReflectionTypeParameter(tv, true, typeSolver));
}
return params;
}
public boolean isAssignableBy(ResolvedType type) {
if (type instanceof NullType) {
return true;
}
if (type instanceof LambdaArgumentTypePlaceholder) {
return isFunctionalInterface();
}
if (type.isArray()) {
return false;
}
if (type.isPrimitive()) {
return false;
}
if (type.describe().equals(typeDeclaration.getQualifiedName())) {
return true;
}
if (type instanceof ReferenceTypeImpl) {
ReferenceTypeImpl otherTypeDeclaration = (ReferenceTypeImpl) type;
if(otherTypeDeclaration.getTypeDeclaration().isPresent()) {
return otherTypeDeclaration.getTypeDeclaration().get().canBeAssignedTo(typeDeclaration);
}
}
return false;
}
public boolean hasDirectlyAnnotation(String canonicalName) {
for (Annotation a : clazz.getDeclaredAnnotations()) {
if (a.annotationType().getCanonicalName().equals(canonicalName)) {
return true;
}
}
return false;
}
private final boolean isFunctionalInterface() {
return FunctionalInterfaceLogic.getFunctionalMethod(typeDeclaration).isPresent();
}
public List<ResolvedConstructorDeclaration> getConstructors() {
return Arrays.stream(clazz.getDeclaredConstructors())
.filter(m -> !m.isSynthetic())
.map(m -> new ReflectionConstructorDeclaration(m, typeSolver))
.collect(Collectors.toList());
}
public Optional<ResolvedReferenceTypeDeclaration> containerType() {
Class<?> declaringClass = clazz.getDeclaringClass();
return declaringClass == null ?
Optional.empty() :
Optional.of(ReflectionFactory.typeDeclarationFor(declaringClass, typeSolver));
}
}
|
// First consider fields declared on this class
for (Field field : clazz.getDeclaredFields()) {
if (field.getName().equals(name)) {
return true;
}
}
// Then consider fields inherited from ancestors
for (ResolvedReferenceType ancestor : typeDeclaration.getAllAncestors()) {
if (ancestor.getTypeDeclaration().isPresent() && ancestor.getTypeDeclaration().get().hasField(name)) {
return true;
}
}
return false;
| 1,830
| 134
| 1,964
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionConstructorDeclaration.java
|
ReflectionConstructorDeclaration
|
getParam
|
class ReflectionConstructorDeclaration implements ResolvedConstructorDeclaration {
private Constructor<?> constructor;
private TypeSolver typeSolver;
public ReflectionConstructorDeclaration(Constructor<?> constructor, TypeSolver typeSolver) {
this.constructor = constructor;
this.typeSolver = typeSolver;
}
@Override
public ResolvedClassDeclaration declaringType() {
return new ReflectionClassDeclaration(constructor.getDeclaringClass(), typeSolver);
}
@Override
public int getNumberOfParams() {
return constructor.getParameterCount();
}
@Override
public ResolvedParameterDeclaration getParam(int i) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return constructor.getDeclaringClass().getSimpleName();
}
@Override
public AccessSpecifier accessSpecifier() {
return ReflectionFactory.modifiersToAccessLevel(constructor.getModifiers());
}
@Override
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
return Arrays.stream(constructor.getTypeParameters()).map((refTp) -> new ReflectionTypeParameter(refTp, false, typeSolver)).collect(Collectors.toList());
}
@Override
public int getNumberOfSpecifiedExceptions() {
return this.constructor.getExceptionTypes().length;
}
@Override
public ResolvedType getSpecifiedException(int index) {
if (index < 0 || index >= getNumberOfSpecifiedExceptions()) {
throw new IllegalArgumentException();
}
return ReflectionFactory.typeUsageFor(this.constructor.getExceptionTypes()[index], typeSolver);
}
}
|
if (i < 0 || i >= getNumberOfParams()) {
throw new IllegalArgumentException(String.format("No param with index %d. Number of params: %d", i, getNumberOfParams()));
}
boolean variadic = false;
if (constructor.isVarArgs()) {
variadic = i == (constructor.getParameterCount() - 1);
}
return new ReflectionParameterDeclaration(constructor.getParameterTypes()[i],
constructor.getGenericParameterTypes()[i], typeSolver, variadic,
constructor.getParameters()[i].getName());
| 434
| 143
| 577
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumConstantDeclaration.java
|
ReflectionEnumConstantDeclaration
|
getType
|
class ReflectionEnumConstantDeclaration implements ResolvedEnumConstantDeclaration {
private Field enumConstant;
private TypeSolver typeSolver;
public ReflectionEnumConstantDeclaration(Field enumConstant, TypeSolver typeSolver) {
if (!enumConstant.isEnumConstant()) {
throw new IllegalArgumentException("The given field does not represent an enum constant");
}
this.enumConstant = enumConstant;
this.typeSolver = typeSolver;
}
@Override
public String getName() {
return enumConstant.getName();
}
@Override
public ResolvedType getType() {<FILL_FUNCTION_BODY>}
}
|
Class<?> enumClass = enumConstant.getDeclaringClass();
ResolvedReferenceTypeDeclaration typeDeclaration = new ReflectionEnumDeclaration(enumClass, typeSolver);
return new ReferenceTypeImpl(typeDeclaration);
| 166
| 55
| 221
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionEnumDeclaration.java
|
ReflectionEnumDeclaration
|
getAncestors
|
class ReflectionEnumDeclaration extends AbstractTypeDeclaration
implements ResolvedEnumDeclaration, MethodResolutionCapability, MethodUsageResolutionCapability,
SymbolResolutionCapability {
///
/// Fields
///
private Class<?> clazz;
private TypeSolver typeSolver;
private ReflectionClassAdapter reflectionClassAdapter;
///
/// Constructors
///
public ReflectionEnumDeclaration(Class<?> clazz, TypeSolver typeSolver) {
if (clazz == null) {
throw new IllegalArgumentException("Class should not be null");
}
if (clazz.isInterface()) {
throw new IllegalArgumentException("Class should not be an interface");
}
if (clazz.isPrimitive()) {
throw new IllegalArgumentException("Class should not represent a primitive class");
}
if (clazz.isArray()) {
throw new IllegalArgumentException("Class should not be an array");
}
if (!clazz.isEnum()) {
throw new IllegalArgumentException("Class should be an enum");
}
this.clazz = clazz;
this.typeSolver = typeSolver;
this.reflectionClassAdapter = new ReflectionClassAdapter(clazz, typeSolver, this);
}
///
/// Public methods
///
@Override
public AccessSpecifier accessSpecifier() {
return ReflectionFactory.modifiersToAccessLevel(this.clazz.getModifiers());
}
@Override
public Optional<ResolvedReferenceTypeDeclaration> containerType() {
return reflectionClassAdapter.containerType();
}
@Override
public String getPackageName() {
if (clazz.getPackage() != null) {
return clazz.getPackage().getName();
}
return null;
}
@Override
public String getClassName() {
String canonicalName = clazz.getCanonicalName();
if (canonicalName != null && getPackageName() != null) {
return canonicalName.substring(getPackageName().length() + 1, canonicalName.length());
}
return null;
}
@Override
public String getQualifiedName() {
return clazz.getCanonicalName();
}
@Override
public List<ResolvedReferenceType> getAncestors(boolean acceptIncompleteList) {<FILL_FUNCTION_BODY>}
@Override
public ResolvedFieldDeclaration getField(String name) {
return reflectionClassAdapter.getField(name);
}
@Override
public boolean hasField(String name) {
return reflectionClassAdapter.hasField(name);
}
@Override
public List<ResolvedFieldDeclaration> getAllFields() {
return reflectionClassAdapter.getAllFields();
}
@Override
public Set<ResolvedMethodDeclaration> getDeclaredMethods() {
return reflectionClassAdapter.getDeclaredMethods();
}
@Override
public boolean canBeAssignedTo(ResolvedReferenceTypeDeclaration other) {
String otherName = other.getQualifiedName();
// Enums cannot be extended
if (otherName.equals(this.getQualifiedName())) {
return true;
}
if (JAVA_LANG_ENUM.equals(otherName)) {
return true;
}
// Enum implements Comparable and Serializable
if (otherName.equals(JAVA_LANG_COMPARABLE)) {
return true;
}
if (otherName.equals(JAVA_IO_SERIALIZABLE)) {
return true;
}
return other.isJavaLangObject();
}
@Override
public boolean isAssignableBy(ResolvedType type) {
return reflectionClassAdapter.isAssignableBy(type);
}
@Override
public boolean isAssignableBy(ResolvedReferenceTypeDeclaration other) {
return isAssignableBy(new ReferenceTypeImpl(other));
}
@Override
public boolean hasDirectlyAnnotation(String qualifiedName) {
return reflectionClassAdapter.hasDirectlyAnnotation(qualifiedName);
}
@Override
public String getName() {
return clazz.getSimpleName();
}
@Override
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
return reflectionClassAdapter.getTypeParameters();
}
@Override
public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> parameterTypes, boolean staticOnly) {
return ReflectionMethodResolutionLogic.solveMethod(name, parameterTypes, staticOnly,
typeSolver,this, clazz);
}
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<ResolvedType> parameterTypes,
Context invokationContext, List<ResolvedType> typeParameterValues) {
Optional<MethodUsage> res = ReflectionMethodResolutionLogic.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext,
typeParameterValues, this, clazz);
if (res.isPresent()) {
// We have to replace method type typeParametersValues here
InferenceContext inferenceContext = new InferenceContext(typeSolver);
MethodUsage methodUsage = res.get();
int i = 0;
List<ResolvedType> parameters = new LinkedList<>();
for (ResolvedType actualType : parameterTypes) {
ResolvedType formalType = methodUsage.getParamType(i);
// We need to replace the class type typeParametersValues (while we derive the method ones)
parameters.add(inferenceContext.addPair(formalType, actualType));
i++;
}
try {
ResolvedType returnType = inferenceContext.addSingle(methodUsage.returnType());
for (int j=0;j<parameters.size();j++) {
methodUsage = methodUsage.replaceParamType(j, inferenceContext.resolve(parameters.get(j)));
}
methodUsage = methodUsage.replaceReturnType(inferenceContext.resolve(returnType));
return Optional.of(methodUsage);
} catch (ConflictingGenericTypesException e) {
return Optional.empty();
}
} else {
return res;
}
}
@Override
public SymbolReference<? extends ResolvedValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
if (hasEnumConstant(name)) {
ResolvedEnumConstantDeclaration enumConstant = getEnumConstant(name);
return SymbolReference.solved(enumConstant);
}
return SymbolReference.unsolved();
}
@Override
public List<ResolvedEnumConstantDeclaration> getEnumConstants() {
return Arrays.stream(clazz.getFields())
.filter(Field::isEnumConstant)
.map(c -> new ReflectionEnumConstantDeclaration(c, typeSolver))
.collect(Collectors.toList());
}
@Override
public Set<ResolvedReferenceTypeDeclaration> internalTypes() {
return Arrays.stream(this.clazz.getDeclaredClasses())
.map(ic -> ReflectionFactory.typeDeclarationFor(ic, typeSolver))
.collect(Collectors.toSet());
}
@Override
public List<ResolvedConstructorDeclaration> getConstructors() {
return reflectionClassAdapter.getConstructors();
}
}
|
// we do not attempt to perform any symbol solving when analyzing ancestors in the reflection model, so we can
// simply ignore the boolean parameter here; an UnsolvedSymbolException cannot occur
return reflectionClassAdapter.getAncestors();
| 1,843
| 59
| 1,902
|
<methods>public non-sealed void <init>() ,public final Set<com.github.javaparser.resolution.MethodUsage> getAllMethods() ,public final boolean isFunctionalInterface() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFactory.java
|
ReflectionFactory
|
modifiersToAccessLevel
|
class ReflectionFactory {
private static String JAVA_LANG_OBJECT = Object.class.getCanonicalName();
public static ResolvedReferenceTypeDeclaration typeDeclarationFor(Class<?> clazz, TypeSolver typeSolver) {
if (clazz.isArray()) {
throw new IllegalArgumentException("No type declaration available for an Array");
}
if (clazz.isPrimitive()) {
throw new IllegalArgumentException();
}
if (clazz.isAnnotation()) {
return new ReflectionAnnotationDeclaration(clazz, typeSolver);
}
if (clazz.isInterface()) {
return new ReflectionInterfaceDeclaration(clazz, typeSolver);
}
if (clazz.isEnum()) {
return new ReflectionEnumDeclaration(clazz, typeSolver);
}
return new ReflectionClassDeclaration(clazz, typeSolver);
}
public static ResolvedType typeUsageFor(java.lang.reflect.Type type, TypeSolver typeSolver) {
if (type instanceof java.lang.reflect.TypeVariable) {
java.lang.reflect.TypeVariable<?> tv = (java.lang.reflect.TypeVariable<?>) type;
boolean declaredOnClass = tv.getGenericDeclaration() instanceof java.lang.reflect.Type;
ResolvedTypeParameterDeclaration typeParameter = new ReflectionTypeParameter(tv, declaredOnClass, typeSolver);
return new ResolvedTypeVariable(typeParameter);
}
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
ResolvedReferenceType rawType = typeUsageFor(pt.getRawType(), typeSolver).asReferenceType();
List<java.lang.reflect.Type> actualTypes = new ArrayList<>();
actualTypes.addAll(Arrays.asList(pt.getActualTypeArguments()));
// we consume the actual types
rawType = rawType.transformTypeParameters(tp -> typeUsageFor(actualTypes.remove(0), typeSolver)).asReferenceType();
return rawType;
}
if (type instanceof Class) {
Class<?> c = (Class<?>) type;
if (c.isPrimitive()) {
if (c.getName().equals(Void.TYPE.getName())) {
return ResolvedVoidType.INSTANCE;
}
return ResolvedPrimitiveType.byName(c.getName());
}
if (c.isArray()) {
return new ResolvedArrayType(typeUsageFor(c.getComponentType(), typeSolver));
}
return new ReferenceTypeImpl(typeDeclarationFor(c, typeSolver));
}
if (type instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) type;
return new ResolvedArrayType(typeUsageFor(genericArrayType.getGenericComponentType(), typeSolver));
}
if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
if (wildcardType.getLowerBounds().length > 0 && wildcardType.getUpperBounds().length > 0) {
if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) {
// ok, it does not matter
}
}
if (wildcardType.getLowerBounds().length > 0) {
if (wildcardType.getLowerBounds().length > 1) {
throw new UnsupportedOperationException();
}
return ResolvedWildcard.superBound(typeUsageFor(wildcardType.getLowerBounds()[0], typeSolver));
}
if (wildcardType.getUpperBounds().length > 0) {
if (wildcardType.getUpperBounds().length > 1) {
throw new UnsupportedOperationException();
}
if (wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0].getTypeName().equals(JAVA_LANG_OBJECT)) {
return ResolvedWildcard.UNBOUNDED;
}
return ResolvedWildcard.extendsBound(typeUsageFor(wildcardType.getUpperBounds()[0], typeSolver));
}
return ResolvedWildcard.UNBOUNDED;
}
throw new UnsupportedOperationException(type.getClass().getCanonicalName() + " " + type);
}
static AccessSpecifier modifiersToAccessLevel(final int modifiers) {<FILL_FUNCTION_BODY>}
}
|
if (Modifier.isPublic(modifiers)) {
return AccessSpecifier.PUBLIC;
}
if (Modifier.isProtected(modifiers)) {
return AccessSpecifier.PROTECTED;
}
if (Modifier.isPrivate(modifiers)) {
return AccessSpecifier.PRIVATE;
}
return AccessSpecifier.NONE;
| 1,144
| 100
| 1,244
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionFieldDeclaration.java
|
ReflectionFieldDeclaration
|
calcType
|
class ReflectionFieldDeclaration implements ResolvedFieldDeclaration {
private Field field;
private TypeSolver typeSolver;
private ResolvedType type;
public ReflectionFieldDeclaration(Field field, TypeSolver typeSolver) {
this.field = field;
this.typeSolver = typeSolver;
this.type = calcType();
}
private ReflectionFieldDeclaration(Field field, TypeSolver typeSolver, ResolvedType type) {
this.field = field;
this.typeSolver = typeSolver;
this.type = type;
}
@Override
public ResolvedType getType() {
return type;
}
private ResolvedType calcType() {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return field.getName();
}
@Override
public boolean isStatic() {
return Modifier.isStatic(field.getModifiers());
}
@Override
public boolean isVolatile() {
return Modifier.isVolatile(field.getModifiers());
}
@Override
public boolean isField() {
return true;
}
@Override
public ResolvedTypeDeclaration declaringType() {
return ReflectionFactory.typeDeclarationFor(field.getDeclaringClass(), typeSolver);
}
public ResolvedFieldDeclaration replaceType(ResolvedType fieldType) {
return new ReflectionFieldDeclaration(field, typeSolver, fieldType);
}
@Override
public boolean isParameter() {
return false;
}
@Override
public boolean isType() {
return false;
}
@Override
public AccessSpecifier accessSpecifier() {
return ReflectionFactory.modifiersToAccessLevel(field.getModifiers());
}
}
|
// TODO consider interfaces, enums, primitive types, arrays
return ReflectionFactory.typeUsageFor(field.getGenericType(), typeSolver);
| 470
| 38
| 508
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodDeclaration.java
|
ReflectionMethodDeclaration
|
declaringType
|
class ReflectionMethodDeclaration implements ResolvedMethodDeclaration, TypeVariableResolutionCapability {
private Method method;
private TypeSolver typeSolver;
public ReflectionMethodDeclaration(Method method, TypeSolver typeSolver) {
this.method = method;
if (method.isSynthetic() || method.isBridge()) {
throw new IllegalArgumentException();
}
this.typeSolver = typeSolver;
}
@Override
public String getName() {
return method.getName();
}
@Override
public boolean isField() {
return false;
}
@Override
public boolean isParameter() {
return false;
}
@Override
public String toString() {
return "ReflectionMethodDeclaration{" +
"method=" + method +
'}';
}
@Override
public boolean isType() {
return false;
}
@Override
public ResolvedReferenceTypeDeclaration declaringType() {<FILL_FUNCTION_BODY>}
@Override
public ResolvedType getReturnType() {
return ReflectionFactory.typeUsageFor(method.getGenericReturnType(), typeSolver);
}
@Override
public int getNumberOfParams() {
return method.getParameterTypes().length;
}
@Override
public ResolvedParameterDeclaration getParam(int i) {
boolean variadic = false;
if (method.isVarArgs()) {
variadic = i == (method.getParameterCount() - 1);
}
return new ReflectionParameterDeclaration(method.getParameterTypes()[i], method.getGenericParameterTypes()[i],
typeSolver, variadic, method.getParameters()[i].getName());
}
@Override
public List<ResolvedTypeParameterDeclaration> getTypeParameters() {
return Arrays.stream(method.getTypeParameters()).map((refTp) -> new ReflectionTypeParameter(refTp, false, typeSolver)).collect(Collectors.toList());
}
public MethodUsage resolveTypeVariables(Context context, List<ResolvedType> parameterTypes) {
return new MethodDeclarationCommonLogic(this, typeSolver).resolveTypeVariables(context, parameterTypes);
}
@Override
public boolean isAbstract() {
return Modifier.isAbstract(method.getModifiers());
}
@Override
public boolean isDefaultMethod() {
return method.isDefault();
}
@Override
public boolean isStatic() {
return Modifier.isStatic(method.getModifiers());
}
@Override
public AccessSpecifier accessSpecifier() {
return ReflectionFactory.modifiersToAccessLevel(this.method.getModifiers());
}
@Override
public int getNumberOfSpecifiedExceptions() {
return this.method.getExceptionTypes().length;
}
@Override
public ResolvedType getSpecifiedException(int index) {
if (index < 0 || index >= getNumberOfSpecifiedExceptions()) {
throw new IllegalArgumentException();
}
return ReflectionFactory.typeUsageFor(this.method.getExceptionTypes()[index], typeSolver);
}
@Override
public String toDescriptor() {
return TypeUtils.getMethodDescriptor(method);
}
}
|
if (method.getDeclaringClass().isInterface()) {
return new ReflectionInterfaceDeclaration(method.getDeclaringClass(), typeSolver);
}
if (method.getDeclaringClass().isEnum()) {
return new ReflectionEnumDeclaration(method.getDeclaringClass(), typeSolver);
}
return new ReflectionClassDeclaration(method.getDeclaringClass(), typeSolver);
| 840
| 99
| 939
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionMethodResolutionLogic.java
|
ReflectionMethodResolutionLogic
|
solveMethod
|
class ReflectionMethodResolutionLogic {
static SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> parameterTypes, boolean staticOnly,
TypeSolver typeSolver, ResolvedReferenceTypeDeclaration scopeType,
Class clazz){<FILL_FUNCTION_BODY>}
static Optional<MethodUsage> solveMethodAsUsage(String name, List<ResolvedType> argumentsTypes, TypeSolver typeSolver,
Context invokationContext, List<ResolvedType> typeParameterValues,
ResolvedReferenceTypeDeclaration scopeType, Class clazz) {
if (typeParameterValues.size() != scopeType.getTypeParameters().size()) {
// if it is zero we are going to ignore them
if (!scopeType.getTypeParameters().isEmpty()) {
// Parameters not specified, so default to Object
typeParameterValues = new ArrayList<>();
for (int i = 0; i < scopeType.getTypeParameters().size(); i++) {
typeParameterValues.add(new ReferenceTypeImpl(new ReflectionClassDeclaration(Object.class, typeSolver)));
}
}
}
List<MethodUsage> methods = new ArrayList<>();
for (Method method : clazz.getMethods()) {
if (method.getName().equals(name) && !method.isBridge() && !method.isSynthetic()) {
ResolvedMethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
MethodUsage methodUsage = replaceParams(typeParameterValues, scopeType, methodDeclaration);
methods.add(methodUsage);
}
}
List<ResolvedReferenceType> ancestors = scopeType.getAncestors();
for(ResolvedReferenceType ancestor : ancestors){
if(ancestor.getTypeDeclaration().isPresent()) {
ResolvedReferenceTypeDeclaration ancestorTypeDeclaration = ancestor.getTypeDeclaration().get();
SymbolReference<ResolvedMethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(ancestorTypeDeclaration, name, argumentsTypes);
if (ref.isSolved()){
ResolvedMethodDeclaration correspondingDeclaration = ref.getCorrespondingDeclaration();
MethodUsage methodUsage = replaceParams(typeParameterValues, ancestorTypeDeclaration, correspondingDeclaration);
methods.add(methodUsage);
}
}
}
if (ancestors.isEmpty()) {
Optional<ResolvedReferenceTypeDeclaration> optionalObjectClass = new ReferenceTypeImpl(new ReflectionClassDeclaration(Object.class, typeSolver)).getTypeDeclaration();
if (optionalObjectClass.isPresent()) {
SymbolReference<ResolvedMethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(optionalObjectClass.get(), name, argumentsTypes);
if (ref.isSolved()) {
MethodUsage usage = replaceParams(typeParameterValues, optionalObjectClass.get(), ref.getCorrespondingDeclaration());
methods.add(usage);
}
}
}
final List<ResolvedType> finalTypeParameterValues = typeParameterValues;
argumentsTypes = argumentsTypes.stream().map((pt) -> {
int i = 0;
for (ResolvedTypeParameterDeclaration tp : scopeType.getTypeParameters()) {
pt = pt.replaceTypeVariables(tp, finalTypeParameterValues.get(i));
i++;
}
return pt;
}).collect(Collectors.toList());
return MethodResolutionLogic.findMostApplicableUsage(methods, name, argumentsTypes, typeSolver);
}
private static MethodUsage replaceParams(List<ResolvedType> typeParameterValues, ResolvedReferenceTypeDeclaration typeParametrizable, ResolvedMethodDeclaration methodDeclaration) {
MethodUsage methodUsage = new MethodUsage(methodDeclaration);
int i = 0;
// Only replace if we have enough values provided
if (typeParameterValues.size() == typeParametrizable.getTypeParameters().size()){
for (ResolvedTypeParameterDeclaration tp : typeParametrizable.getTypeParameters()) {
methodUsage = methodUsage.replaceTypeParameter(tp, typeParameterValues.get(i));
i++;
}
}
for (ResolvedTypeParameterDeclaration methodTypeParameter : methodDeclaration.getTypeParameters()) {
methodUsage = methodUsage.replaceTypeParameter(methodTypeParameter, new ResolvedTypeVariable(methodTypeParameter));
}
return methodUsage;
}
}
|
List<ResolvedMethodDeclaration> methods = new ArrayList<>();
Predicate<Method> staticOnlyCheck = m -> !staticOnly || (staticOnly && Modifier.isStatic(m.getModifiers()));
for (Method method : clazz.getMethods()) {
if (method.isBridge() || method.isSynthetic() || !method.getName().equals(name)|| !staticOnlyCheck.test(method)) continue;
ResolvedMethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
methods.add(methodDeclaration);
}
for (ResolvedReferenceType ancestor : scopeType.getAncestors()) {
ancestor.getTypeDeclaration().ifPresent(ancestorTypeDeclaration -> {
SymbolReference<ResolvedMethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(ancestorTypeDeclaration, name, parameterTypes, staticOnly);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
});
}
if (scopeType.getAncestors().isEmpty()){
ReferenceTypeImpl objectClass = new ReferenceTypeImpl(new ReflectionClassDeclaration(Object.class, typeSolver));
objectClass.getTypeDeclaration().ifPresent(objectTypeDeclaration -> {
SymbolReference<ResolvedMethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(objectTypeDeclaration, name, parameterTypes, staticOnly);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
});
}
return MethodResolutionLogic.findMostApplicable(methods, name, parameterTypes, typeSolver);
| 1,086
| 412
| 1,498
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionParameterDeclaration.java
|
ReflectionParameterDeclaration
|
equals
|
class ReflectionParameterDeclaration implements ResolvedParameterDeclaration {
private Class<?> type;
private java.lang.reflect.Type genericType;
private TypeSolver typeSolver;
private boolean variadic;
private String name;
/**
*
* @param type
* @param genericType
* @param typeSolver
* @param variadic
* @param name can potentially be null
*/
public ReflectionParameterDeclaration(Class<?> type, java.lang.reflect.Type genericType, TypeSolver typeSolver,
boolean variadic, String name) {
this.type = type;
this.genericType = genericType;
this.typeSolver = typeSolver;
this.variadic = variadic;
this.name = name;
}
/**
*
* @return the name, which can be potentially null
*/
@Override
public String getName() {
return name;
}
@Override
public boolean hasName() {
return name != null;
}
@Override
public String toString() {
return "ReflectionParameterDeclaration{" +
"type=" + type +
", name=" + name +
'}';
}
@Override
public boolean isField() {
return false;
}
@Override
public boolean isParameter() {
return true;
}
@Override
public boolean isVariadic() {
return variadic;
}
@Override
public boolean isType() {
return false;
}
@Override
public ResolvedType getType() {
return ReflectionFactory.typeUsageFor(genericType, typeSolver);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(type, genericType, typeSolver, variadic, name);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReflectionParameterDeclaration that = (ReflectionParameterDeclaration) o;
return variadic == that.variadic &&
Objects.equals(type, that.type) &&
Objects.equals(genericType, that.genericType) &&
Objects.equals(typeSolver, that.typeSolver) &&
Objects.equals(name, that.name);
| 504
| 123
| 627
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionTypeParameter.java
|
ReflectionTypeParameter
|
equals
|
class ReflectionTypeParameter implements ResolvedTypeParameterDeclaration {
private TypeVariable typeVariable;
private TypeSolver typeSolver;
private ResolvedTypeParametrizable container;
public ReflectionTypeParameter(TypeVariable typeVariable, boolean declaredOnClass, TypeSolver typeSolver) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
if (genericDeclaration instanceof Class) {
container = ReflectionFactory.typeDeclarationFor((Class) genericDeclaration, typeSolver);
} else if (genericDeclaration instanceof Method) {
container = new ReflectionMethodDeclaration((Method) genericDeclaration, typeSolver);
} else if (genericDeclaration instanceof Constructor) {
container = new ReflectionConstructorDeclaration((Constructor) genericDeclaration, typeSolver);
}
this.typeVariable = typeVariable;
this.typeSolver = typeSolver;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = typeVariable.hashCode();
result = 31 * result + container.hashCode();
return result;
}
@Override
public String getName() {
return typeVariable.getName();
}
@Override
public String getContainerQualifiedName() {
if (container instanceof ResolvedReferenceTypeDeclaration) {
return ((ResolvedReferenceTypeDeclaration) container).getQualifiedName();
}
return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature();
}
@Override
public String getContainerId() {
if (container instanceof ResolvedReferenceTypeDeclaration) {
return ((ResolvedReferenceTypeDeclaration) container).getId();
}
return ((ResolvedMethodLikeDeclaration) container).getQualifiedSignature();
}
@Override
public ResolvedTypeParametrizable getContainer() {
return this.container;
}
@Override
public List<Bound> getBounds() {
return Arrays.stream(typeVariable.getBounds()).map((refB) -> Bound.extendsBound(ReflectionFactory.typeUsageFor(refB, typeSolver))).collect(Collectors.toList());
}
@Override
public String toString() {
return "ReflectionTypeParameter{" +
"typeVariable=" + typeVariable +
'}';
}
@Override
public Optional<ResolvedReferenceTypeDeclaration> containerType() {
if (container instanceof ResolvedReferenceTypeDeclaration) {
return Optional.of((ResolvedReferenceTypeDeclaration) container);
}
return Optional.empty();
}
@Override
public ResolvedReferenceType object() {
return new ReferenceTypeImpl(typeSolver.getSolvedJavaLangObject());
}
}
|
if (this == o) return true;
if (!(o instanceof ResolvedTypeParameterDeclaration)) return false;
ResolvedTypeParameterDeclaration that = (ResolvedTypeParameterDeclaration) o;
if (!getQualifiedName().equals(that.getQualifiedName())) {
return false;
}
if (declaredOnType() == that.declaredOnType()) {
return true;
}
// TODO check bounds
return declaredOnMethod() == that.declaredOnMethod();
| 692
| 128
| 820
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ClassComparator.java
|
ClassComparator
|
compare
|
class ClassComparator implements Comparator<Class<?>> {
@Override
public int compare(Class<?> o1, Class<?> o2) {<FILL_FUNCTION_BODY>}
}
|
int subCompare;
subCompare = o1.getCanonicalName().compareTo(o2.getCanonicalName());
if (subCompare != 0) return subCompare;
subCompare = Boolean.compare(o1.isAnnotation(), o2.isAnnotation());
if (subCompare != 0) return subCompare;
subCompare = Boolean.compare(o1.isArray(), o2.isArray());
if (subCompare != 0) return subCompare;
subCompare = Boolean.compare(o1.isEnum(), o2.isEnum());
if (subCompare != 0) return subCompare;
subCompare = Boolean.compare(o1.isInterface(), o2.isInterface());
if (subCompare != 0) return subCompare;
return 0;
| 56
| 193
| 249
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/MethodComparator.java
|
MethodComparator
|
compare
|
class MethodComparator implements Comparator<Method> {
@Override
public int compare(Method o1, Method o2) {<FILL_FUNCTION_BODY>}
}
|
int compareName = o1.getName().compareTo(o2.getName());
if (compareName != 0) return compareName;
int compareNParams = o1.getParameterCount() - o2.getParameterCount();
if (compareNParams != 0) return compareNParams;
for (int i = 0; i < o1.getParameterCount(); i++) {
int compareParam = new ParameterComparator().compare(o1.getParameters()[i], o2.getParameters()[i]);
if (compareParam != 0) return compareParam;
}
int compareResult = new ClassComparator().compare(o1.getReturnType(), o2.getReturnType());
if (compareResult != 0) return compareResult;
return 0;
| 48
| 194
| 242
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/reflectionmodel/comparators/ParameterComparator.java
|
ParameterComparator
|
compare
|
class ParameterComparator implements Comparator<Parameter> {
@Override
public int compare(Parameter o1, Parameter o2) {<FILL_FUNCTION_BODY>}
}
|
int compareName = o1.getName().compareTo(o2.getName());
if (compareName != 0) return compareName;
int compareType = new ClassComparator().compare(o1.getType(), o2.getType());
if (compareType != 0) return compareType;
return 0;
| 50
| 82
| 132
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/SymbolSolver.java
|
SymbolSolver
|
classToResolvedType
|
class SymbolSolver implements Solver {
private final TypeSolver typeSolver;
public SymbolSolver(TypeSolver typeSolver) {
if (typeSolver == null) {
throw new IllegalArgumentException("Missing Parameter - Cannot initialise a SymbolSolver, without a way to solve types.");
}
this.typeSolver = typeSolver;
}
@Override
public SymbolReference<? extends ResolvedValueDeclaration> solveSymbol(String name, Context context) {
return context.solveSymbol(name);
}
@Override
public SymbolReference<? extends ResolvedValueDeclaration> solveSymbol(String name, Node node) {
return solveSymbol(name, JavaParserFactory.getContext(node, typeSolver));
}
@Override
public Optional<Value> solveSymbolAsValue(String name, Context context) {
return context.solveSymbolAsValue(name);
}
@Override
public Optional<Value> solveSymbolAsValue(String name, Node node) {
Context context = JavaParserFactory.getContext(node, typeSolver);
return solveSymbolAsValue(name, context);
}
@Override
public SymbolReference<? extends ResolvedTypeDeclaration> solveType(String name, Context context) {
return context.solveType(name);
}
@Override
public SymbolReference<? extends ResolvedTypeDeclaration> solveType(String name, Node node) {
return solveType(name, JavaParserFactory.getContext(node, typeSolver));
}
@Override
public MethodUsage solveMethod(String methodName, List<ResolvedType> argumentsTypes, Context context) {
SymbolReference<ResolvedMethodDeclaration> decl = context.solveMethod(methodName, argumentsTypes, false);
if (!decl.isSolved()) {
throw new UnsolvedSymbolException(context.toString(), methodName);
}
return new MethodUsage(decl.getCorrespondingDeclaration());
}
@Override
public MethodUsage solveMethod(String methodName, List<ResolvedType> argumentsTypes, Node node) {
return solveMethod(methodName, argumentsTypes, JavaParserFactory.getContext(node, typeSolver));
}
@Override
public ResolvedTypeDeclaration solveType(Type type) {
if (type instanceof ClassOrInterfaceType) {
// FIXME should call typesolver here!
String name = ((ClassOrInterfaceType) type).getNameWithScope();
SymbolReference<ResolvedTypeDeclaration> ref = JavaParserFactory.getContext(type, typeSolver).solveType(name);
if (!ref.isSolved()) {
throw new UnsolvedSymbolException(JavaParserFactory.getContext(type, typeSolver).toString(), name);
}
return ref.getCorrespondingDeclaration();
}
throw new UnsupportedOperationException(type.getClass().getCanonicalName());
}
@Override
public ResolvedType solveTypeUsage(String name, Context context) {
Optional<ResolvedType> genericType = context.solveGenericType(name);
if (genericType.isPresent()) {
return genericType.get();
}
ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(name);
return new ReferenceTypeImpl(typeDeclaration);
}
/**
* Solve any possible visible symbols including: fields, internal types, type variables, the type itself or its
* containers.
* <p>
* It should contain its own private fields but not inherited private fields.
*/
@Override
public SymbolReference<? extends ResolvedValueDeclaration> solveSymbolInType(ResolvedTypeDeclaration typeDeclaration, String name) {
if (typeDeclaration instanceof SymbolResolutionCapability) {
return ((SymbolResolutionCapability) typeDeclaration).solveSymbol(name, typeSolver);
}
return SymbolReference.unsolved();
}
/**
* Try to solve a symbol just in the declaration, it does not delegate to the container.
*
* @deprecated Similarly to solveType this should eventually disappear as the symbol resolution logic should be more general
* and do not be specific to JavaParser classes like in this case.
*/
@Override
@Deprecated
public SymbolReference<ResolvedTypeDeclaration> solveTypeInType(ResolvedTypeDeclaration typeDeclaration, String name) {
if (typeDeclaration instanceof JavaParserClassDeclaration) {
return ((JavaParserClassDeclaration) typeDeclaration).solveType(name);
}
if (typeDeclaration instanceof JavaParserInterfaceDeclaration) {
return ((JavaParserInterfaceDeclaration) typeDeclaration).solveType(name);
}
return SymbolReference.unsolved();
}
/**
* Convert a {@link Class} into the corresponding {@link ResolvedType}.
*
* @param clazz The class to be converted.
*
* @return The class resolved.
*/
public ResolvedType classToResolvedType(Class<?> clazz) {<FILL_FUNCTION_BODY>}
}
|
if (clazz.isPrimitive()) {
return ResolvedPrimitiveType.byName(clazz.getName());
}
ResolvedReferenceTypeDeclaration declaration;
if (clazz.isAnnotation()) {
declaration = new ReflectionAnnotationDeclaration(clazz, typeSolver);
} else if (clazz.isEnum()) {
declaration = new ReflectionEnumDeclaration(clazz, typeSolver);
} else if (clazz.isInterface()) {
declaration = new ReflectionInterfaceDeclaration(clazz, typeSolver);
} else {
declaration = new ReflectionClassDeclaration(clazz, typeSolver);
}
return new ReferenceTypeImpl(declaration);
| 1,226
| 171
| 1,397
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/BooleanConditionalExprHandler.java
|
BooleanConditionalExprHandler
|
resolveType
|
class BooleanConditionalExprHandler implements ConditionalExprHandler {
ResolvedType thenExpr;
ResolvedType elseExpr;
public BooleanConditionalExprHandler(ResolvedType thenExpr, ResolvedType elseExpr) {
this.thenExpr = thenExpr;
this.elseExpr = elseExpr;
}
@Override
public ResolvedType resolveType() {<FILL_FUNCTION_BODY>}
}
|
if (thenExpr.isReferenceType() && elseExpr.isReferenceType()) {
return thenExpr.asReferenceType();
}
return thenExpr.isPrimitive() ? thenExpr : elseExpr;
| 109
| 53
| 162
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/ConditionalExprResolver.java
|
ConditionalExprResolver
|
getConditionExprHandler
|
class ConditionalExprResolver {
private static final ResolvedPrimitiveType TYPE_BOOLEAN = ResolvedPrimitiveType.BOOLEAN;
public static ConditionalExprHandler getConditionExprHandler(ResolvedType thenExpr, ResolvedType elseExpr) {<FILL_FUNCTION_BODY>}
}
|
// boolean conditional expressions
if (!thenExpr.isNull() && !elseExpr.isNull()
&& thenExpr.isAssignableBy(TYPE_BOOLEAN) && elseExpr.isAssignableBy(TYPE_BOOLEAN)) {
return new BooleanConditionalExprHandler(thenExpr, elseExpr);
// numeric conditional expressions
}
if (thenExpr.isNumericType() && elseExpr.isNumericType()) {
return new NumericConditionalExprHandler(thenExpr, elseExpr);
}
// reference conditional expressions
return new ReferenceConditionalExprHandler(thenExpr, elseExpr);
| 79
| 155
| 234
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/NumericConditionalExprHandler.java
|
NumericConditionalExprHandler
|
isResolvableTo
|
class NumericConditionalExprHandler implements ConditionalExprHandler {
private static Map<ResolvedType, List<ResolvedType>> NumericConverter = new HashMap();
static {
// first type is the type of the resolution
// the list indicates the types that can be resolved in the type specified as
// key
NumericConverter.put(ResolvedPrimitiveType.SHORT,
Arrays.asList(ResolvedPrimitiveType.SHORT, ResolvedPrimitiveType.BYTE));
}
private static ResolvedPrimitiveType[] resolvedPrimitiveTypeSubList = new ResolvedPrimitiveType[] {ResolvedPrimitiveType.BYTE, ResolvedPrimitiveType.SHORT, ResolvedPrimitiveType.CHAR};
ResolvedType thenExpr;
ResolvedType elseExpr;
public NumericConditionalExprHandler(ResolvedType thenExpr, ResolvedType elseExpr) {
this.thenExpr = thenExpr;
this.elseExpr = elseExpr;
}
@Override
public ResolvedType resolveType() {
String qnameTypeThenExpr = thenExpr.isPrimitive() ? thenExpr.asPrimitive().describe()
: thenExpr.asReferenceType().describe();
String qnameTypeElseExpr = elseExpr.isPrimitive() ? elseExpr.asPrimitive().describe()
: elseExpr.asReferenceType().describe();
if (qnameTypeThenExpr.equals(qnameTypeElseExpr)) {
return thenExpr;
}
/*
* If one of the second and third operands is of primitive type T, and the type of the other is the result of
* applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
*/
if (thenExpr.isPrimitive() && elseExpr.isReferenceType()
&& elseExpr.asReferenceType()
.isUnboxableTo((ResolvedPrimitiveType) ResolvedPrimitiveType.byName(qnameTypeThenExpr))) {
return thenExpr;
}
if (elseExpr.isPrimitive() && thenExpr.isReferenceType()
&& thenExpr.asReferenceType()
.isUnboxableTo((ResolvedPrimitiveType) ResolvedPrimitiveType.byName(qnameTypeElseExpr))) {
return elseExpr;
}
/*
* If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the
* conditional expression is short.
*/
if ((isResolvableTo(ResolvedPrimitiveType.SHORT, thenExpr) && relaxMatch(elseExpr, ResolvedPrimitiveType.BYTE))
|| (isResolvableTo(ResolvedPrimitiveType.SHORT, elseExpr) && relaxMatch(thenExpr, ResolvedPrimitiveType.BYTE))) {
return ResolvedPrimitiveType.SHORT;
}
// if ((in(thenExpr, ResolvedPrimitiveType.SHORT) && in(elseExpr, ResolvedPrimitiveType.BYTE))
// || (in(elseExpr, ResolvedPrimitiveType.SHORT) && in(thenExpr, ResolvedPrimitiveType.BYTE))) {
// return ResolvedPrimitiveType.SHORT;
// }
// If one of the operands is of type T where T is byte, short, or char, and the
// other operand is a constant expression (§15.28) of type int whose value is
// representable in type T, then the type of the conditional expression is T
// How can we know if the constant expression of type int is representable in
// type T ?
if (thenExpr.isPrimitive() && elseExpr.isPrimitive()) {
if (((ResolvedPrimitiveType)thenExpr).in(resolvedPrimitiveTypeSubList)
&& ((ResolvedPrimitiveType)elseExpr).equals(ResolvedPrimitiveType.INT)) {
return thenExpr;
}
if (((ResolvedPrimitiveType)elseExpr).in(resolvedPrimitiveTypeSubList)
&& ((ResolvedPrimitiveType)thenExpr).equals(ResolvedPrimitiveType.INT)) {
return elseExpr;
}
}
// If one of the operands is of type T, where T is Byte, Short, or Character,
// and the other operand is a constant expression of type int whose value is
// representable in the type U which is the result of applying unboxing
// conversion to T, then the type of the conditional expression is U.
// How can we know it?
if (thenExpr.isReference() && elseExpr.isPrimitive()
&& thenExpr.asReferenceType().isUnboxable()
&& thenExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList)
&& ((ResolvedPrimitiveType)elseExpr).equals(ResolvedPrimitiveType.INT)) {
return thenExpr.asReferenceType().toUnboxedType().get();
}
if (elseExpr.isReference() && thenExpr.isPrimitive()
&& elseExpr.asReferenceType().isUnboxable()
&& elseExpr.asReferenceType().toUnboxedType().get().in(resolvedPrimitiveTypeSubList)
&& ((ResolvedPrimitiveType)thenExpr).equals(ResolvedPrimitiveType.INT)) {
return elseExpr.asReferenceType().toUnboxedType().get();
}
// Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types,
// and the type of the conditional expression is the promoted type of the second
// and third operands.
ResolvedPrimitiveType PrimitiveThenExpr = thenExpr.isPrimitive() ? thenExpr.asPrimitive()
: thenExpr.asReferenceType().toUnboxedType().get();
ResolvedPrimitiveType PrimitiveElseExpr = elseExpr.isPrimitive() ? elseExpr.asPrimitive()
: elseExpr.asReferenceType().toUnboxedType().get();
return PrimitiveThenExpr.bnp(PrimitiveElseExpr);
}
/*
* Verify if the {code ResolvedType} is equals to one of the specified primitive types
*/
protected boolean exactMatch(ResolvedType type, ResolvedPrimitiveType... types) {
return type.isPrimitive() && type.asPrimitive().in(types);
}
protected boolean relaxMatch(ResolvedType type, ResolvedPrimitiveType... types) {
return exactMatch(type, types) || (type.isReferenceType() && Arrays.stream(types).anyMatch(t -> type.asReferenceType().getQualifiedName().equals(t.getBoxTypeQName())));
}
/*
* Verify if the {code ResolvedType} can be resolve to the specified primitive type
*/
protected boolean isResolvableTo(ResolvedPrimitiveType toType, ResolvedType resolvedType) {
// force to verify boxed type
return isResolvableTo(toType, resolvedType, true);
}
protected boolean isResolvableTo(ResolvedPrimitiveType toType, ResolvedType resolvedType, boolean verifyBoxedType) {<FILL_FUNCTION_BODY>}
}
|
return NumericConverter.entrySet().stream().filter(e -> e.getKey() == toType)
.flatMap(entry -> entry.getValue().stream())
.anyMatch(rt -> rt == resolvedType || (verifyBoxedType && resolvedType.isReferenceType()
&& resolvedType.asReferenceType().toUnboxedType().get() == toType));
| 1,793
| 96
| 1,889
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/promotion/ReferenceConditionalExprHandler.java
|
ReferenceConditionalExprHandler
|
resolveType
|
class ReferenceConditionalExprHandler implements ConditionalExprHandler {
ResolvedType thenExpr;
ResolvedType elseExpr;
public ReferenceConditionalExprHandler(ResolvedType thenExpr, ResolvedType elseExpr) {
this.thenExpr = thenExpr;
this.elseExpr = elseExpr;
}
@Override
public ResolvedType resolveType() {<FILL_FUNCTION_BODY>}
}
|
// If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
if (thenExpr.isNull()) {
return elseExpr;
}
if (elseExpr.isNull()) {
return thenExpr;
}
return TypeHelper.leastUpperBound(new HashSet<>(Arrays.asList(thenExpr, elseExpr)));
| 108
| 111
| 219
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Bound.java
|
Bound
|
isProperUpperBoundFor
|
class Bound {
///
/// Creation of bounds
///
static Bound falseBound() {
return FalseBound.getInstance();
}
///
/// Satisfiability
///
/**
* A bound is satisfied by an inference variable substitution if, after applying the substitution,
* the assertion is true.
*/
public abstract boolean isSatisfied(InferenceVariableSubstitution inferenceVariableSubstitution);
///
/// Classification of bounds
///
/**
* Given a bound of the form α = T or T = α, we say T is an instantiation of α.
*
* Return empty if it is not an instantiation. Otherwise it returns the variable of which this is an
* instantiation.
*/
public Optional<Instantiation> isAnInstantiation() {
return Optional.empty();
}
boolean isAnInstantiationFor(InferenceVariable v) {
return isAnInstantiation().isPresent() && isAnInstantiation().get().getInferenceVariable().equals(v);
}
/**
* Given a bound of the form α <: T, we say T is a proper upper bound of α.
*
* Return empty if it is not a proper upper bound. Otherwise it returns the variable of which this is an
* proper upper bound.
*/
public Optional<ProperUpperBound> isProperUpperBound() {
return Optional.empty();
}
/**
* Given a bound of the form T <: α, we say T is a proper lower bound of α.
*
* Return empty if it is not a proper lower bound. Otherwise it returns the variable of which this is an
* proper lower bound.
*/
public Optional<ProperLowerBound> isProperLowerBound() {
return Optional.empty();
}
Optional<ProperLowerBound> isProperLowerBoundFor(InferenceVariable inferenceVariable) {
Optional<ProperLowerBound> partial = isProperLowerBound();
if (partial.isPresent() && partial.get().getInferenceVariable().equals(inferenceVariable)) {
return partial;
}
return Optional.empty();
}
Optional<ProperUpperBound> isProperUpperBoundFor(InferenceVariable inferenceVariable) {<FILL_FUNCTION_BODY>}
/**
* Other bounds relate two inference variables, or an inference variable to a type that contains inference
* variables. Such bounds, of the form S = T or S <: T, are called dependencies.
*/
public boolean isADependency() {
return false;
}
boolean isThrowsBoundOn(InferenceVariable inferenceVariable) {
return false;
}
///
/// Other methods
///
public abstract Set<InferenceVariable> usedInferenceVariables();
}
|
Optional<ProperUpperBound> partial = isProperUpperBound();
if (partial.isPresent() && partial.get().getInferenceVariable().equals(inferenceVariable)) {
return partial;
}
return Optional.empty();
| 717
| 63
| 780
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ConstraintFormula.java
|
ReductionResult
|
equals
|
class ReductionResult {
private BoundSet boundSet;
private List<ConstraintFormula> constraintFormulas;
public BoundSet getBoundSet() {
return boundSet;
}
public List<ConstraintFormula> getConstraintFormulas() {
return constraintFormulas;
}
public static ReductionResult empty() {
return new ReductionResult();
}
public ReductionResult withConstraint(ConstraintFormula constraintFormula) {
ReductionResult newInstance = new ReductionResult();
newInstance.boundSet = this.boundSet;
newInstance.constraintFormulas = new LinkedList<>();
newInstance.constraintFormulas.addAll(this.constraintFormulas);
newInstance.constraintFormulas.add(constraintFormula);
return newInstance;
}
public ReductionResult withBound(Bound bound) {
ReductionResult newInstance = new ReductionResult();
newInstance.boundSet = this.boundSet.withBound(bound);
newInstance.constraintFormulas = this.constraintFormulas;
return newInstance;
}
private ReductionResult() {
this.boundSet = BoundSet.empty();
this.constraintFormulas = new LinkedList<>();
}
public static ReductionResult trueResult() {
return empty();
}
public static ReductionResult falseResult() {
return empty().withBound(Bound.falseBound());
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = boundSet.hashCode();
result = 31 * result + constraintFormulas.hashCode();
return result;
}
@Override
public String toString() {
return "ReductionResult{" +
"boundSet=" + boundSet +
", constraintFormulas=" + constraintFormulas +
'}';
}
public ConstraintFormula getConstraint(int index) {
if (constraintFormulas.size() <= index) {
throw new IllegalArgumentException("Constraint with index " + index + " is not available as there are " + constraintFormulas.size() + " constraints");
}
return constraintFormulas.get(index);
}
public static ReductionResult oneConstraint(ConstraintFormula constraintFormula) {
return empty().withConstraint(constraintFormula);
}
public static ReductionResult withConstraints(ConstraintFormula... constraints) {
return withConstraints(Arrays.asList(constraints));
}
public static ReductionResult oneBound(Bound bound) {
return empty().withBound(bound);
}
public static ReductionResult withConstraints(List<ConstraintFormula> constraints) {
ReductionResult reductionResult = new ReductionResult();
reductionResult.constraintFormulas.addAll(constraints);
return reductionResult;
}
public static ReductionResult bounds(BoundSet bounds) {
ReductionResult reductionResult = new ReductionResult();
reductionResult.boundSet = bounds;
return reductionResult;
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReductionResult that = (ReductionResult) o;
if (!boundSet.equals(that.boundSet)) return false;
return constraintFormulas.equals(that.constraintFormulas);
| 785
| 85
| 870
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ConstraintFormulaSet.java
|
ConstraintFormulaSet
|
reduce
|
class ConstraintFormulaSet {
private List<ConstraintFormula> constraintFormulas;
public ConstraintFormulaSet withConstraint(ConstraintFormula constraintFormula) {
ConstraintFormulaSet newInstance = new ConstraintFormulaSet();
newInstance.constraintFormulas.addAll(this.constraintFormulas);
newInstance.constraintFormulas.add(constraintFormula);
return newInstance;
}
private static final ConstraintFormulaSet EMPTY = new ConstraintFormulaSet();
public static ConstraintFormulaSet empty() {
return EMPTY;
}
private ConstraintFormulaSet() {
constraintFormulas = new LinkedList<>();
}
/**
* Takes a compatibility assertion about an expression or type, called a constraint formula, and reduces it to a
* set of bounds on inference variables. Often, a constraint formula reduces to other constraint formulas,
* which must be recursively reduced. A procedure is followed to identify these additional constraint formulas and,
* ultimately, to express via a bound set the conditions under which the choices for inferred types would render
* each constraint formula true.
*/
public BoundSet reduce(TypeSolver typeSolver) {<FILL_FUNCTION_BODY>}
public boolean isEmpty() {
return constraintFormulas.isEmpty();
}
}
|
List<ConstraintFormula> constraints = new LinkedList<>(constraintFormulas);
BoundSet boundSet = BoundSet.empty();
while (constraints.size() > 0) {
ConstraintFormula constraintFormula = constraints.remove(0);
ConstraintFormula.ReductionResult reductionResult = constraintFormula.reduce(boundSet);
constraints.addAll(reductionResult.getConstraintFormulas());
boundSet.incorporate(reductionResult.getBoundSet(), typeSolver);
}
return boundSet;
| 332
| 137
| 469
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InferenceVariable.java
|
InferenceVariable
|
equals
|
class InferenceVariable implements ResolvedType {
private static int unnamedInstantiated = 0;
private String name;
private ResolvedTypeParameterDeclaration typeParameterDeclaration;
public static List<InferenceVariable> instantiate(List<ResolvedTypeParameterDeclaration> typeParameterDeclarations) {
List<InferenceVariable> inferenceVariables = new LinkedList<>();
for (ResolvedTypeParameterDeclaration tp : typeParameterDeclarations) {
inferenceVariables.add(InferenceVariable.unnamed(tp));
}
return inferenceVariables;
}
public static InferenceVariable unnamed(ResolvedTypeParameterDeclaration typeParameterDeclaration) {
return new InferenceVariable("__unnamed__" + (unnamedInstantiated++), typeParameterDeclaration);
}
public InferenceVariable(String name, ResolvedTypeParameterDeclaration typeParameterDeclaration) {
this.name = name;
this.typeParameterDeclaration = typeParameterDeclaration;
}
@Override
public boolean isInferenceVariable() {
return true;
}
@Override
public String describe() {
return name;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (typeParameterDeclaration != null ? typeParameterDeclaration.hashCode() : 0);
return result;
}
@Override
public boolean isAssignableBy(ResolvedType other) {
if (other.equals(this)) {
return true;
}
throw new UnsupportedOperationException(
"We are unable to determine the assignability of an inference variable without knowing the bounds and"
+ " constraints");
}
public ResolvedTypeParameterDeclaration getTypeParameterDeclaration() {
if (typeParameterDeclaration == null) {
throw new IllegalStateException("The type parameter declaration was not specified");
}
return typeParameterDeclaration;
}
@Override
public String toString() {
return "InferenceVariable{" +
"name='" + name + '\'' +
", typeParameterDeclaration=" + typeParameterDeclaration +
'}';
}
@Override
public boolean mention(List<ResolvedTypeParameterDeclaration> typeParameters) {
return false;
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InferenceVariable that = (InferenceVariable) o;
if (!name.equals(that.name)) return false;
return typeParameterDeclaration != null ? typeParameterDeclaration.equals(that.typeParameterDeclaration)
: that.typeParameterDeclaration == null;
| 587
| 99
| 686
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InferenceVariableSubstitution.java
|
InferenceVariableSubstitution
|
withPair
|
class InferenceVariableSubstitution {
private final static InferenceVariableSubstitution EMPTY = new InferenceVariableSubstitution();
private List<InferenceVariable> inferenceVariables;
private List<ResolvedType> types;
public static InferenceVariableSubstitution empty() {
return EMPTY;
}
private InferenceVariableSubstitution() {
this.inferenceVariables = new LinkedList<>();
this.types = new LinkedList<>();
}
public InferenceVariableSubstitution withPair(InferenceVariable inferenceVariable, ResolvedType type) {<FILL_FUNCTION_BODY>}
}
|
InferenceVariableSubstitution newInstance = new InferenceVariableSubstitution();
newInstance.inferenceVariables.addAll(this.inferenceVariables);
newInstance.types.addAll(this.types);
newInstance.inferenceVariables.add(inferenceVariable);
newInstance.types.add(type);
return newInstance;
| 163
| 89
| 252
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Instantiation.java
|
Instantiation
|
hashCode
|
class Instantiation {
private InferenceVariable inferenceVariable;
private ResolvedType properType;
public Instantiation(InferenceVariable inferenceVariable, ResolvedType properType) {
this.inferenceVariable = inferenceVariable;
this.properType = properType;
}
public InferenceVariable getInferenceVariable() {
return inferenceVariable;
}
public ResolvedType getProperType() {
return properType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Instantiation that = (Instantiation) o;
if (!inferenceVariable.equals(that.inferenceVariable)) return false;
return properType.equals(that.properType);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "Instantiation{" +
"inferenceVariable=" + inferenceVariable +
", properType=" + properType +
'}';
}
}
|
int result = inferenceVariable.hashCode();
result = 31 * result + properType.hashCode();
return result;
| 296
| 34
| 330
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/InstantiationSet.java
|
InstantiationSet
|
withInstantiation
|
class InstantiationSet {
private List<Instantiation> instantiations;
public boolean allInferenceVariablesAreResolved(BoundSet boundSet) {
throw new UnsupportedOperationException();
}
public static InstantiationSet empty() {
return EMPTY;
}
private static final InstantiationSet EMPTY = new InstantiationSet();
private InstantiationSet() {
instantiations = new LinkedList<>();
}
public InstantiationSet withInstantiation(Instantiation instantiation) {<FILL_FUNCTION_BODY>}
public boolean isEmpty() {
return instantiations.isEmpty();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InstantiationSet that = (InstantiationSet) o;
return instantiations.equals(that.instantiations);
}
@Override
public int hashCode() {
return instantiations.hashCode();
}
@Override
public String toString() {
return "InstantiationSet{" +
"instantiations=" + instantiations +
'}';
}
public ResolvedType apply(ResolvedType type) {
for (Instantiation instantiation : instantiations) {
type = type.replaceTypeVariables(instantiation.getInferenceVariable().getTypeParameterDeclaration(), instantiation.getProperType());
}
return type;
}
}
|
InstantiationSet newInstance = new InstantiationSet();
newInstance.instantiations.addAll(this.instantiations);
newInstance.instantiations.add(instantiation);
return newInstance;
| 395
| 57
| 452
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/LeastUpperBoundLogic.java
|
TypeSubstitution
|
lctaBothWildcards
|
class TypeSubstitution {
private List<ResolvedTypeParameterDeclaration> typeParameterDeclarations;
private List<ResolvedType> types;
private final static TypeSubstitution EMPTY = new TypeSubstitution();
public static TypeSubstitution empty() {
return new TypeSubstitution();
}
private TypeSubstitution() {
this.typeParameterDeclarations = new LinkedList<>();
this.types = new LinkedList<>();
}
public boolean isEmpty() {
return this == EMPTY;
}
public void withPair(ResolvedTypeParameterDeclaration typeParameterDeclaration, ResolvedType type) {
this.typeParameterDeclarations.add(typeParameterDeclaration);
this.types.add(type);
}
public List<ResolvedTypeParameterDeclaration> typeParameterDeclarations() {
return typeParameterDeclarations;
}
public ResolvedType substitutedType(ResolvedTypeParameterDeclaration typeDecl) {
int index = typeParameterDeclarations.indexOf(typeDecl);
return index > -1 ? types.get(index) : typeDecl.object();
}
}
private TypeSubstitution substitution(List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs) {
TypeSubstitution substitution = TypeSubstitution.empty();
pairs.stream().forEach(pair -> substitution.withPair(pair.a, pair.b));
return substitution;
}
/*
* the least containing type argument, is: (assuming U and V are types)
* lcta(U, V) = U if U = V, otherwise ? extends lub(U, V)
* lcta(U, ? extends V) = ? extends lub(U, V)
* lcta(U, ? super V) = ? super glb(U, V)
* lcta(? extends U, ? extends V) = ? extends lub(U, V)
* lcta(? extends U, ? super V) = U if U = V, otherwise ?
* lcta(? super U, ? super V) = ? super glb(U, V)
* lcta(U) = ? if U's upper bound is Object, otherwise ? extends lub(U,Object)
* and where glb() is as defined in §5.1.10.
*/
private ResolvedType lcta(ResolvedType type1, ResolvedType type2) {
boolean isWildcard1 = type1.isWildcard();
boolean isWildcard2 = type2.isWildcard();
ResolvedType result;
if (type1.equals(type2)) {
// lcta(U, V) = U if U = V
result = type1;
} else if (isWildcard1 && isWildcard2) {
result = lctaBothWildcards(type1.asWildcard(), type2.asWildcard());
} else if (isWildcard1 ^ isWildcard2) {
ResolvedType rawType = isWildcard1 ? type2 : type1;
ResolvedWildcard wildcardType = (ResolvedWildcard) (isWildcard1 ? type1 : type2);
result = lctaOneWildcard(rawType, wildcardType);
} else {
// otherwise lcta(U, V) = ? extends lub(U, V)
result = lctaNoWildcard(type1, type2);
}
return result;
}
/*
* lcta(U, V) = U if U = V, otherwise ? extends lub(U, V)
*/
private ResolvedType lctaNoWildcard(ResolvedType type1, ResolvedType type2) {
ResolvedType lub = lub(toSet(type1, type2));
return bound(lub, BoundType.EXTENDS);
}
private ResolvedType lctaOneWildcard(ResolvedType rawType, ResolvedWildcard wildcardType) {
if (wildcardType.isUpperBounded()) {
ResolvedType glb = TypeHelper.glb(toSet(rawType, wildcardType.getBoundedType()));
return bound(glb, BoundType.SUPER);
}
ResolvedType lub = lub(toSet(rawType, wildcardType.getBoundedType()));
return bound(lub, BoundType.EXTENDS);
}
private ResolvedType lctaBothWildcards(ResolvedWildcard type1, ResolvedWildcard type2) {<FILL_FUNCTION_BODY>
|
// lcta(? super U, ? super V) = ? super glb(U, V)
if (type1.isUpperBounded() && type2.isUpperBounded()) {
ResolvedType glb = TypeHelper.glb(toSet(type1.getBoundedType(), type2.getBoundedType()));
return bound(glb, BoundType.SUPER);
}
// lcta(? extends U, ? extends V) = ? extends lub(U, V)
if (type1.isLowerBounded() && type2.isLowerBounded()) {
ResolvedType lub = lub(toSet(type1.getBoundedType(), type2.getBoundedType()));
return bound(lub, BoundType.EXTENDS);
}
// lcta(? extends U, ? super V) = U if U = V, otherwise ?
if (type1.getBoundedType().equals(type2.getBoundedType())) {
return type1.getBoundedType();
}
return ResolvedWildcard.UNBOUNDED;
| 1,185
| 278
| 1,463
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ProperLowerBound.java
|
ProperLowerBound
|
toString
|
class ProperLowerBound {
private InferenceVariable inferenceVariable;
private ResolvedType properType;
public ProperLowerBound(InferenceVariable inferenceVariable, ResolvedType properType) {
this.inferenceVariable = inferenceVariable;
this.properType = properType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProperLowerBound that = (ProperLowerBound) o;
if (!inferenceVariable.equals(that.inferenceVariable)) return false;
return properType.equals(that.properType);
}
@Override
public int hashCode() {
int result = inferenceVariable.hashCode();
result = 31 * result + properType.hashCode();
return result;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public InferenceVariable getInferenceVariable() {
return inferenceVariable;
}
public ResolvedType getProperType() {
return properType;
}
}
|
return "ProperLowerBound{" +
"inferenceVariable=" + inferenceVariable +
", properType=" + properType +
'}';
| 294
| 41
| 335
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/ProperUpperBound.java
|
ProperUpperBound
|
toString
|
class ProperUpperBound {
private InferenceVariable inferenceVariable;
private ResolvedType properType;
public ProperUpperBound(InferenceVariable inferenceVariable, ResolvedType properType) {
this.inferenceVariable = inferenceVariable;
this.properType = properType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProperUpperBound that = (ProperUpperBound) o;
if (!inferenceVariable.equals(that.inferenceVariable)) return false;
return properType.equals(that.properType);
}
@Override
public int hashCode() {
int result = inferenceVariable.hashCode();
result = 31 * result + properType.hashCode();
return result;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public InferenceVariable getInferenceVariable() {
return inferenceVariable;
}
public ResolvedType getProperType() {
return properType;
}
}
|
return "ProperUpperBound{" +
"inferenceVariable=" + inferenceVariable +
", properType=" + properType +
'}';
| 298
| 42
| 340
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/Substitution.java
|
Substitution
|
apply
|
class Substitution {
private List<ResolvedTypeParameterDeclaration> typeParameterDeclarations;
private List<ResolvedType> types;
private final static Substitution EMPTY = new Substitution();
public static Substitution empty() {
return EMPTY;
}
public Substitution withPair(ResolvedTypeParameterDeclaration typeParameterDeclaration, ResolvedType type) {
Substitution newInstance = new Substitution();
newInstance.typeParameterDeclarations.addAll(this.typeParameterDeclarations);
newInstance.types.addAll(this.types);
newInstance.typeParameterDeclarations.add(typeParameterDeclaration);
newInstance.types.add(type);
return newInstance;
}
private Substitution() {
this.typeParameterDeclarations = new LinkedList<>();
this.types = new LinkedList<>();
}
public ResolvedType apply(ResolvedType originalType) {<FILL_FUNCTION_BODY>}
}
|
ResolvedType result = originalType;
for (int i=0;i<typeParameterDeclarations.size();i++) {
result = result.replaceTypeVariables(typeParameterDeclarations.get(i), types.get(i));
}
return result;
| 256
| 72
| 328
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/TypeInferenceCache.java
|
TypeInferenceCache
|
addRecord
|
class TypeInferenceCache {
private static Map<TypeSolver, IdentityHashMap<LambdaExpr, Map<String, ResolvedType>>> typeForLambdaParameters = new HashMap<>();
private static Map<TypeSolver, IdentityHashMap<LambdaExpr, List<InferenceVariable>>> inferenceVariables = new HashMap<>();
public static void addRecord(TypeSolver typeSolver, LambdaExpr lambdaExpr, String paramName, ResolvedType type) {<FILL_FUNCTION_BODY>}
public static Optional<ResolvedType> retrieve(TypeSolver typeSolver, LambdaExpr lambdaExpr, String paramName) {
if (!typeForLambdaParameters.containsKey(typeSolver)) {
return Optional.empty();
}
if (!typeForLambdaParameters.get(typeSolver).containsKey(lambdaExpr)) {
return Optional.empty();
}
if (!typeForLambdaParameters.get(typeSolver).get(lambdaExpr).containsKey(paramName)) {
return Optional.empty();
}
return Optional.of(typeForLambdaParameters.get(typeSolver).get(lambdaExpr).get(paramName));
}
public static void recordInferenceVariables(TypeSolver typeSolver, LambdaExpr lambdaExpr, List<InferenceVariable> _inferenceVariables) {
if (!inferenceVariables.containsKey(typeSolver)) {
inferenceVariables.put(typeSolver, new IdentityHashMap<>());
}
inferenceVariables.get(typeSolver).put(lambdaExpr, _inferenceVariables);
}
public static Optional<List<InferenceVariable>> retrieveInferenceVariables(TypeSolver typeSolver, LambdaExpr lambdaExpr) {
if (!inferenceVariables.containsKey(typeSolver)) {
return Optional.empty();
}
if (!inferenceVariables.get(typeSolver).containsKey(lambdaExpr)) {
return Optional.empty();
}
return Optional.of(inferenceVariables.get(typeSolver).get(lambdaExpr));
}
}
|
if (!typeForLambdaParameters.containsKey(typeSolver)) {
typeForLambdaParameters.put(typeSolver, new IdentityHashMap<>());
}
if (!typeForLambdaParameters.get(typeSolver).containsKey(lambdaExpr)) {
typeForLambdaParameters.get(typeSolver).put(lambdaExpr, new HashMap<>());
}
typeForLambdaParameters.get(typeSolver).get(lambdaExpr).put(paramName, type);
| 508
| 116
| 624
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/CapturesBound.java
|
CapturesBound
|
equals
|
class CapturesBound extends Bound {
private List<InferenceVariable> inferenceVariables;
private List<ResolvedType> typesOrWildcards;
public CapturesBound(List<InferenceVariable> inferenceVariables, List<ResolvedType> typesOrWildcards) {
this.inferenceVariables = inferenceVariables;
this.typesOrWildcards = typesOrWildcards;
}
@Override
public boolean isSatisfied(InferenceVariableSubstitution inferenceVariableSubstitution) {
throw new UnsupportedOperationException();
}
@Override
public Set<InferenceVariable> usedInferenceVariables() {
throw new UnsupportedOperationException();
}
public List<InferenceVariable> getInferenceVariables() {
return inferenceVariables;
}
public List<ResolvedType> getTypesOrWildcards() {
return typesOrWildcards;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = inferenceVariables.hashCode();
result = 31 * result + typesOrWildcards.hashCode();
return result;
}
@Override
public String toString() {
return "CapturesBound{" +
"inferenceVariables=" + inferenceVariables +
", typesOrWildcards=" + typesOrWildcards +
'}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CapturesBound that = (CapturesBound) o;
if (!inferenceVariables.equals(that.inferenceVariables)) return false;
return typesOrWildcards.equals(that.typesOrWildcards);
| 382
| 95
| 477
|
<methods>public non-sealed void <init>() ,public boolean isADependency() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.Instantiation> isAnInstantiation() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperLowerBound> isProperLowerBound() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperUpperBound> isProperUpperBound() ,public abstract boolean isSatisfied(com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariableSubstitution) ,public abstract Set<com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariable> usedInferenceVariables() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SameAsBound.java
|
SameAsBound
|
toString
|
class SameAsBound extends Bound {
private ResolvedType s;
private ResolvedType t;
public SameAsBound(ResolvedType s, ResolvedType t) {
if (!s.isInferenceVariable() && !t.isInferenceVariable()) {
throw new IllegalArgumentException("One of S or T should be an inference variable");
}
this.s = s;
this.t = t;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SameAsBound that = (SameAsBound) o;
if (!s.equals(that.s)) return false;
return t.equals(that.t);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = s.hashCode();
result = 31 * result + t.hashCode();
return result;
}
@Override
public Set<InferenceVariable> usedInferenceVariables() {
Set<InferenceVariable> variables = new HashSet<>();
variables.addAll(TypeHelper.usedInferenceVariables(s));
variables.addAll(TypeHelper.usedInferenceVariables(t));
return variables;
}
public ResolvedType getS() {
return s;
}
public ResolvedType getT() {
return t;
}
@Override
public boolean isADependency() {
return !isAnInstantiation().isPresent();
}
@Override
public Optional<Instantiation> isAnInstantiation() {
if (s.isInferenceVariable() && isProperType(t)) {
return Optional.of(new Instantiation((InferenceVariable) s, t));
}
if (isProperType(s) && t.isInferenceVariable()) {
return Optional.of(new Instantiation((InferenceVariable) t, s));
}
return Optional.empty();
}
@Override
public boolean isSatisfied(InferenceVariableSubstitution inferenceVariableSubstitution) {
throw new UnsupportedOperationException();
}
}
|
return "SameAsBound{" +
"s=" + s +
", t=" + t +
'}';
| 579
| 35
| 614
|
<methods>public non-sealed void <init>() ,public boolean isADependency() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.Instantiation> isAnInstantiation() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperLowerBound> isProperLowerBound() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperUpperBound> isProperUpperBound() ,public abstract boolean isSatisfied(com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariableSubstitution) ,public abstract Set<com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariable> usedInferenceVariables() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/SubtypeOfBound.java
|
SubtypeOfBound
|
equals
|
class SubtypeOfBound extends Bound {
private ResolvedType s;
private ResolvedType t;
public SubtypeOfBound(ResolvedType s, ResolvedType t) {
if (!s.isInferenceVariable() && !t.isInferenceVariable()) {
throw new IllegalArgumentException("One of S or T should be an inference variable");
}
this.s = s;
this.t = t;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "SubtypeOfBound{" +
"s=" + s +
", t=" + t +
'}';
}
@Override
public int hashCode() {
int result = s.hashCode();
result = 31 * result + t.hashCode();
return result;
}
public ResolvedType getS() {
return s;
}
@Override
public Set<InferenceVariable> usedInferenceVariables() {
Set<InferenceVariable> variables = new HashSet<>();
variables.addAll(TypeHelper.usedInferenceVariables(s));
variables.addAll(TypeHelper.usedInferenceVariables(t));
return variables;
}
public ResolvedType getT() {
return t;
}
@Override
public Optional<ProperUpperBound> isProperUpperBound() {
if (s.isInferenceVariable() && isProperType(t)) {
return Optional.of(new ProperUpperBound((InferenceVariable) s, t));
}
return Optional.empty();
}
@Override
public Optional<ProperLowerBound> isProperLowerBound() {
if (isProperType(s) && t.isInferenceVariable()) {
return Optional.of(new ProperLowerBound((InferenceVariable) t, s));
}
return Optional.empty();
}
@Override
public boolean isADependency() {
return !isProperLowerBound().isPresent() && !isProperUpperBound().isPresent();
}
@Override
public boolean isSatisfied(InferenceVariableSubstitution inferenceVariableSubstitution) {
throw new UnsupportedOperationException();
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SubtypeOfBound that = (SubtypeOfBound) o;
if (!s.equals(that.s)) return false;
return t.equals(that.t);
| 590
| 79
| 669
|
<methods>public non-sealed void <init>() ,public boolean isADependency() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.Instantiation> isAnInstantiation() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperLowerBound> isProperLowerBound() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperUpperBound> isProperUpperBound() ,public abstract boolean isSatisfied(com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariableSubstitution) ,public abstract Set<com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariable> usedInferenceVariables() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/bounds/ThrowsBound.java
|
ThrowsBound
|
equals
|
class ThrowsBound extends Bound {
private InferenceVariable inferenceVariable;
public ThrowsBound(InferenceVariable inferenceVariable) {
this.inferenceVariable = inferenceVariable;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "ThrowsBound{" +
"inferenceVariable=" + inferenceVariable +
'}';
}
@Override
public int hashCode() {
return inferenceVariable.hashCode();
}
@Override
public Set<InferenceVariable> usedInferenceVariables() {
Set<InferenceVariable> variables = new HashSet<>();
variables.add(inferenceVariable);
return variables;
}
@Override
public boolean isSatisfied(InferenceVariableSubstitution inferenceVariableSubstitution) {
throw new UnsupportedOperationException();
}
public boolean isThrowsBoundOn(InferenceVariable inferenceVariable) {
return inferenceVariable.equals(this.inferenceVariable);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThrowsBound that = (ThrowsBound) o;
return inferenceVariable.equals(that.inferenceVariable);
| 271
| 65
| 336
|
<methods>public non-sealed void <init>() ,public boolean isADependency() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.Instantiation> isAnInstantiation() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperLowerBound> isProperLowerBound() ,public Optional<com.github.javaparser.symbolsolver.resolution.typeinference.ProperUpperBound> isProperUpperBound() ,public abstract boolean isSatisfied(com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariableSubstitution) ,public abstract Set<com.github.javaparser.symbolsolver.resolution.typeinference.InferenceVariable> usedInferenceVariables() <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/LambdaThrowsCompatibleWithType.java
|
LambdaThrowsCompatibleWithType
|
reduce
|
class LambdaThrowsCompatibleWithType extends ConstraintFormula {
private LambdaExpr lambdaExpression;
private ResolvedType T;
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LambdaThrowsCompatibleWithType that = (LambdaThrowsCompatibleWithType) o;
if (!lambdaExpression.equals(that.lambdaExpression)) return false;
return T.equals(that.T);
}
@Override
public int hashCode() {
int result = lambdaExpression.hashCode();
result = 31 * result + T.hashCode();
return result;
}
@Override
public String toString() {
return "LambdaThrowsCompatibleWithType{" +
"lambdaExpression=" + lambdaExpression +
", T=" + T +
'}';
}
}
|
// A constraint formula of the form ‹LambdaExpression →throws T› is reduced as follows:
//
// - If T is not a functional interface type (§9.8), the constraint reduces to false.
//
// - Otherwise, let the target function type for the lambda expression be determined as specified in §15.27.3. If no valid function type can be found, the constraint reduces to false.
//
// - Otherwise, if the lambda expression is implicitly typed, and one or more of the function type's parameter types is not a proper type, the constraint reduces to false.
//
// This condition never arises in practice, due to the substitution applied to the target type in §18.5.2.
//
// - Otherwise, if the function type's return type is neither void nor a proper type, the constraint reduces to false.
//
// This condition never arises in practice, due to the substitution applied to the target type in §18.5.2.
//
// - Otherwise, let E1, ..., En be the types in the function type's throws clause that are not proper types. If the lambda expression is implicitly typed, let its parameter types be the function type's parameter types. If the lambda body is a poly expression or a block containing a poly result expression, let the targeted return type be the function type's return type. Let X1, ..., Xm be the checked exception types that the lambda body can throw (§11.2). Then there are two cases:
//
// - If n = 0 (the function type's throws clause consists only of proper types), then if there exists some i (1 ≤ i ≤ m) such that Xi is not a subtype of any proper type in the throws clause, the constraint reduces to false; otherwise, the constraint reduces to true.
//
// - If n > 0, the constraint reduces to a set of subtyping constraints: for all i (1 ≤ i ≤ m), if Xi is not a subtype of any proper type in the throws clause, then the constraints include, for all j (1 ≤ j ≤ n), ‹Xi <: Ej›. In addition, for all j (1 ≤ j ≤ n), the constraint reduces to the bound throws Ej.
throw new UnsupportedOperationException();
| 274
| 571
| 845
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/MethodReferenceThrowsCompatibleWithType.java
|
MethodReferenceThrowsCompatibleWithType
|
reduce
|
class MethodReferenceThrowsCompatibleWithType extends ConstraintFormula {
private MethodReferenceExpr methodReference;
private ResolvedType T;
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MethodReferenceThrowsCompatibleWithType that = (MethodReferenceThrowsCompatibleWithType) o;
if (!methodReference.equals(that.methodReference)) return false;
return T.equals(that.T);
}
@Override
public int hashCode() {
int result = methodReference.hashCode();
result = 31 * result + T.hashCode();
return result;
}
@Override
public String toString() {
return "MethodReferenceThrowsCompatibleWithType{" +
"methodReference=" + methodReference +
", T=" + T +
'}';
}
}
|
// A constraint formula of the form ‹MethodReference →throws T› is reduced as follows:
//
// - If T is not a functional interface type, or if T is a functional interface type but does not have a function type (§9.9), the constraint reduces to false.
//
// - Otherwise, let the target function type for the method reference expression be the function type of T. If the method reference is inexact (§15.13.1) and one or more of the function type's parameter types is not a proper type, the constraint reduces to false.
//
// - Otherwise, if the method reference is inexact and the function type's result is neither void nor a proper type, the constraint reduces to false.
//
// - Otherwise, let E1, ..., En be the types in the function type's throws clause that are not proper types. Let X1, ..., Xm be the checked exceptions in the throws clause of the invocation type of the method reference's compile-time declaration (§15.13.2) (as derived from the function type's parameter types and return type). Then there are two cases:
//
// - If n = 0 (the function type's throws clause consists only of proper types), then if there exists some i (1 ≤ i ≤ m) such that Xi is not a subtype of any proper type in the throws clause, the constraint reduces to false; otherwise, the constraint reduces to true.
//
// - If n > 0, the constraint reduces to a set of subtyping constraints: for all i (1 ≤ i ≤ m), if Xi is not a subtype of any proper type in the throws clause, then the constraints include, for all j (1 ≤ j ≤ n), ‹Xi <: Ej›. In addition, for all j (1 ≤ j ≤ n), the constraint reduces to the bound throws Ej.
throw new UnsupportedOperationException();
| 273
| 479
| 752
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeCompatibleWithType.java
|
TypeCompatibleWithType
|
reduce
|
class TypeCompatibleWithType extends ConstraintFormula {
private ResolvedType s;
private ResolvedType t;
private TypeSolver typeSolver;
public TypeCompatibleWithType(TypeSolver typeSolver, ResolvedType s, ResolvedType t) {
this.typeSolver = typeSolver;
this.s = s;
this.t = t;
}
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeCompatibleWithType that = (TypeCompatibleWithType) o;
if (!s.equals(that.s)) return false;
return t.equals(that.t);
}
@Override
public int hashCode() {
int result = s.hashCode();
result = 31 * result + t.hashCode();
return result;
}
@Override
public String toString() {
return "TypeCompatibleWithType{" +
"s=" + s +
", t=" + t +
'}';
}
}
|
// A constraint formula of the form ‹S → T› is reduced as follows:
//
// 1. If S and T are proper types, the constraint reduces to true if S is compatible in a loose invocation context with T (§5.3), and false otherwise.
if (isProperType(s) && isProperType(t)) {
if (isCompatibleInALooseInvocationContext(s, t)) {
return ReductionResult.trueResult();
}
return ReductionResult.falseResult();
}
// 2. Otherwise, if S is a primitive type, let S' be the result of applying boxing conversion (§5.1.7) to S. Then the constraint reduces to ‹S' → T›.
if (s.isPrimitive()) {
ReflectionTypeSolver typeSolver = new ReflectionTypeSolver();
ResolvedType sFirst = new ReferenceTypeImpl(typeSolver.solveType(s.asPrimitive().getBoxTypeQName()));
return ReductionResult.oneConstraint(new TypeCompatibleWithType(typeSolver, sFirst, t));
}
// 3. Otherwise, if T is a primitive type, let T' be the result of applying boxing conversion (§5.1.7) to T. Then the constraint reduces to ‹S = T'›.
if (t.isPrimitive()) {
ReflectionTypeSolver typeSolver = new ReflectionTypeSolver();
ResolvedType tFirst = new ReferenceTypeImpl(typeSolver.solveType(t.asPrimitive().getBoxTypeQName()));
return ReductionResult.oneConstraint(new TypeSameAsType(s, tFirst));
}
// The fourth and fifth cases are implicit uses of unchecked conversion (§5.1.9). These, along with any use of
// unchecked conversion in the first case, may result in compile-time unchecked warnings, and may influence a
// method's invocation type (§15.12.2.6).
// 4. Otherwise, if T is a parameterized type of the form G<T1, ..., Tn>, and there exists no type of the
// form G<...> that is a supertype of S, but the raw type G is a supertype of S, then the constraint reduces
// to true.
if (t.isReferenceType() && t.asReferenceType().getTypeDeclaration().isPresent() && !t.asReferenceType().getTypeDeclaration().get().getTypeParameters().isEmpty()) {
// FIXME I really cannot understand what the specification means...
// there exists a type of the form G<...> that is a supertype of S?
boolean condition1 = t.isAssignableBy(s);
// the raw type G is a supertype of S
ResolvedType G = t.asReferenceType().toRawType();
boolean condition2 = G.isAssignableBy(s);
if (!condition1 && condition2) {
return ReductionResult.trueResult();
}
//throw new UnsupportedOperationException();
}
// 5. Otherwise, if T is an array type of the form G<T1, ..., Tn>[]k, and there exists no type of the form
// G<...>[]k that is a supertype of S, but the raw type G[]k is a supertype of S, then the constraint
// reduces to true. (The notation []k indicates an array type of k dimensions.)
if (t.isArray()) {
throw new UnsupportedOperationException();
}
// 6. Otherwise, the constraint reduces to ‹S <: T›
return ReductionResult.empty().withConstraint(new TypeSubtypeOfType(typeSolver, s, t));
| 327
| 945
| 1,272
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeContainedByType.java
|
TypeContainedByType
|
reduce
|
class TypeContainedByType extends ConstraintFormula {
private ResolvedType S;
private ResolvedType T;
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeContainedByType that = (TypeContainedByType) o;
if (!S.equals(that.S)) return false;
return T.equals(that.T);
}
@Override
public int hashCode() {
int result = S.hashCode();
result = 31 * result + T.hashCode();
return result;
}
@Override
public String toString() {
return "TypeContainedByType{" +
"S=" + S +
", T=" + T +
'}';
}
}
|
// A constraint formula of the form ‹S <= T›, where S and T are type arguments (§4.5.1), is reduced as follows:
//
// - If T is a type:
if (isProperType(T) && !T.isWildcard()) {
// - If S is a type, the constraint reduces to ‹S = T›.
//
// - If S is a wildcard, the constraint reduces to false.
throw new UnsupportedOperationException();
}
// - If T is a wildcard of the form ?, the constraint reduces to true.
if (T.isWildcard() && !T.asWildcard().isBounded()) {
return ReductionResult.trueResult();
}
// - If T is a wildcard of the form ? extends T':
if (T.isWildcard() && T.asWildcard().isExtends()) {
// - If S is a type, the constraint reduces to ‹S <: T'›.
//
// - If S is a wildcard of the form ?, the constraint reduces to ‹Object <: T'›.
//
// - If S is a wildcard of the form ? extends S', the constraint reduces to ‹S' <: T'›.
//
// - If S is a wildcard of the form ? super S', the constraint reduces to ‹Object = T'›.
throw new UnsupportedOperationException();
}
// - If T is a wildcard of the form ? super T':
if (T.isWildcard() && T.asWildcard().isSuper()) {
// - If S is a type, the constraint reduces to ‹T' <: S›.
//
// - If S is a wildcard of the form ? super S', the constraint reduces to ‹T' <: S'›.
//
// - Otherwise, the constraint reduces to false.
throw new UnsupportedOperationException();
}
throw new UnsupportedOperationException();
| 256
| 531
| 787
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSameAsType.java
|
TypeSameAsType
|
reduce
|
class TypeSameAsType extends ConstraintFormula {
private ResolvedType S;
private ResolvedType T;
public TypeSameAsType(ResolvedType s, ResolvedType t) {
S = s;
T = t;
}
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeSameAsType that = (TypeSameAsType) o;
if (!S.equals(that.S)) return false;
return T.equals(that.T);
}
@Override
public int hashCode() {
int result = S.hashCode();
result = 31 * result + T.hashCode();
return result;
}
@Override
public String toString() {
return "TypeSameAsType{" +
"S=" + S +
", T=" + T +
'}';
}
}
|
// A constraint formula of the form ‹S = T›, where S and T are types, is reduced as follows:
if (!S.isWildcard() && !T.isWildcard()) {
// - If S and T are proper types, the constraint reduces to true if S is the same as T (§4.3.4), and false
// otherwise.
if (isProperType(S) && isProperType(T)) {
if (S.equals(T)) {
return ReductionResult.trueResult();
}
return ReductionResult.falseResult();
}
// - Otherwise, if S or T is the null type, the constraint reduces to false.
if (S.isNull() || T.isNull()) {
return ReductionResult.falseResult();
}
// - Otherwise, if S is an inference variable, α, and T is not a primitive type, the constraint reduces to the
// bound α = T.
if (S.isInferenceVariable() && !T.isPrimitive()) {
return ReductionResult.oneBound(new SameAsBound(S, T));
}
// - Otherwise, if T is an inference variable, α, and S is not a primitive type, the constraint reduces to the
// bound S = α.
if (T.isInferenceVariable() && !S.isPrimitive()) {
return ReductionResult.oneBound(new SameAsBound(S, T));
}
// - Otherwise, if S and T are class or interface types with the same erasure, where S has
// type arguments B1, ..., Bn and T has type arguments A1, ..., An, the constraint reduces to the following
// new constraints: for all i (1 ≤ i ≤ n), ‹Bi = Ai›.
if (S.isReferenceType() && T.isReferenceType()
&& S.asReferenceType().toRawType().equals(T.asReferenceType().toRawType())) {
ReductionResult res = ReductionResult.empty();
List<ResolvedType> Bs = S.asReferenceType().typeParametersValues();
List<ResolvedType> As = T.asReferenceType().typeParametersValues();
for (int i = 0; i < Bs.size(); i++) {
res = res.withConstraint(new TypeSameAsType(Bs.get(i), As.get(i)));
}
return res;
}
// - Otherwise, if S and T are array types, S'[] and T'[], the constraint reduces to ‹S' = T'›.
if (S.isArray() && T.isArray()) {
return ReductionResult.oneConstraint(new TypeSameAsType(
S.asArrayType().getComponentType(),
T.asArrayType().getComponentType()));
}
// - Otherwise, the constraint reduces to false.
return ReductionResult.falseResult();
}
// Note that we do not address intersection types above, because it is impossible for reduction to encounter an
// intersection type that is not a proper type.
// A constraint formula of the form ‹S = T›, where S and T are type arguments (§4.5.1), is reduced as follows:
//
// - If S and T are types, the constraint is reduced as described above.
//
// - If S has the form ? and T has the form ?, the constraint reduces to true.
//
// - If S has the form ? and T has the form ? extends T', the constraint reduces to ‹Object = T'›.
//
// - If S has the form ? extends S' and T has the form ?, the constraint reduces to ‹S' = Object›.
//
// - If S has the form ? extends S' and T has the form ? extends T', the constraint reduces to ‹S' = T'›.
//
// - If S has the form ? super S' and T has the form ? super T', the constraint reduces to ‹S' = T'›.
//
// - Otherwise, the constraint reduces to false.
throw new UnsupportedOperationException();
| 288
| 1,045
| 1,333
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typeinference/constraintformulas/TypeSubtypeOfType.java
|
TypeSubtypeOfType
|
reduce
|
class TypeSubtypeOfType extends ConstraintFormula {
private ResolvedType S;
private ResolvedType T;
private TypeSolver typeSolver;
public TypeSubtypeOfType(TypeSolver typeSolver, ResolvedType S, ResolvedType T) {
this.typeSolver = typeSolver;
this.S = S;
this.T = T;
}
@Override
public ReductionResult reduce(BoundSet currentBoundSet) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeSubtypeOfType that = (TypeSubtypeOfType) o;
if (!S.equals(that.S)) return false;
return T.equals(that.T);
}
@Override
public int hashCode() {
int result = S.hashCode();
result = 31 * result + T.hashCode();
return result;
}
@Override
public String toString() {
return "TypeSubtypeOfType{" +
"S=" + S +
", T=" + T +
'}';
}
}
|
// A constraint formula of the form ‹S <: T› is reduced as follows:
//
// - If S and T are proper types, the constraint reduces to true if S is a subtype of T (§4.10), and false otherwise.
if (isProperType(S) && isProperType(T)) {
if (T.isAssignableBy(S)) {
return ReductionResult.trueResult();
}
return ReductionResult.falseResult();
}
// - Otherwise, if S is the null type, the constraint reduces to true.
if (S instanceof NullType) {
return ReductionResult.trueResult();
}
// - Otherwise, if T is the null type, the constraint reduces to false.
if (T instanceof NullType) {
return ReductionResult.falseResult();
}
// - Otherwise, if S is an inference variable, α, the constraint reduces to the bound α <: T.
if (S.isInferenceVariable()) {
return ReductionResult.oneBound(new SubtypeOfBound(S, T));
}
// - Otherwise, if T is an inference variable, α, the constraint reduces to the bound S <: α.
if (T.isInferenceVariable()) {
return ReductionResult.oneBound(new SubtypeOfBound(S, T));
}
// FEDERICO - Added start
//if (T.isTypeVariable()) {
// return ReductionResult.oneBound(new SubtypeOfBound(S, T));
//}
// FEDERICO - Added end
// - Otherwise, the constraint is reduced according to the form of T:
//
// - If T is a parameterized class or interface type, or an inner class type of a parameterized class or interface type (directly or indirectly), let A1, ..., An be the type arguments of T. Among the supertypes of S, a corresponding class or interface type is identified, with type arguments B1, ..., Bn. If no such type exists, the constraint reduces to false. Otherwise, the constraint reduces to the following new constraints: for all i (1 ≤ i ≤ n), ‹Bi <= Ai›.
//
// - If T is any other class or interface type, then the constraint reduces to true if T is among the supertypes of S, and false otherwise.
//
// - If T is an array type, T'[], then among the supertypes of S that are array types, a most specific type is identified, S'[] (this may be S itself). If no such array type exists, the constraint reduces to false. Otherwise:
//
// - If neither S' nor T' is a primitive type, the constraint reduces to ‹S' <: T'›.
//
// - Otherwise, the constraint reduces to true if S' and T' are the same primitive type, and false otherwise.
//
// - If T is a type variable, there are three cases:
if (T.isTypeVariable()) {
// - If S is an intersection type of which T is an element, the constraint reduces to true.
if (S instanceof ResolvedIntersectionType) {
throw new UnsupportedOperationException();
}
// - Otherwise, if T has a lower bound, B, the constraint reduces to ‹S <: B›.
if (T.asTypeVariable().asTypeParameter().hasLowerBound()) {
return ReductionResult.oneConstraint(new TypeSubtypeOfType(typeSolver, S, T.asTypeVariable().asTypeParameter().getLowerBound()));
}
// - Otherwise, the constraint reduces to false.
return ReductionResult.falseResult();
}
//
// - If T is an intersection type, I1 & ... & In, the constraint reduces to the following new constraints: for all i (1 ≤ i ≤ n), ‹S <: Ii›.
//
throw new UnsupportedOperationException("S = "+ S + ", T = " + T);
| 327
| 1,013
| 1,340
|
<methods>public non-sealed void <init>() ,public abstract com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula.ReductionResult reduce(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) <variables>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/AarTypeSolver.java
|
AarTypeSolver
|
setParent
|
class AarTypeSolver implements TypeSolver {
private JarTypeSolver delegate;
public AarTypeSolver(String aarFile) throws IOException {
this(new File(aarFile));
}
public AarTypeSolver(Path aarFile) throws IOException {
this(aarFile.toFile());
}
public AarTypeSolver(File aarFile) throws IOException {
JarFile jarFile = new JarFile(aarFile);
ZipEntry classesJarEntry = jarFile.getEntry("classes.jar");
if (classesJarEntry == null) {
throw new IllegalArgumentException(String.format("The given file (%s) is malformed: entry classes.jar was not found", aarFile.getAbsolutePath()));
}
delegate = new JarTypeSolver(jarFile.getInputStream(classesJarEntry));
}
@Override
public TypeSolver getParent() {
return delegate.getParent();
}
@Override
public void setParent(TypeSolver parent) {<FILL_FUNCTION_BODY>}
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {
return delegate.tryToSolveType(name);
}
}
|
if (parent == this)
throw new IllegalStateException("The parent of this TypeSolver cannot be itself.");
delegate.setParent(parent);
| 318
| 40
| 358
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/ClassLoaderTypeSolver.java
|
ClassLoaderTypeSolver
|
tryToSolveType
|
class ClassLoaderTypeSolver implements TypeSolver {
private TypeSolver parent;
private ClassLoader classLoader;
public ClassLoaderTypeSolver(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public TypeSolver getParent() {
return parent;
}
@Override
public void setParent(TypeSolver parent) {
Objects.requireNonNull(parent);
if (this.parent != null) {
throw new IllegalStateException("This TypeSolver already has a parent.");
}
if (parent == this) {
throw new IllegalStateException("The parent of this TypeSolver cannot be itself.");
}
this.parent = parent;
}
protected boolean filterName(String name) {
return true;
}
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {<FILL_FUNCTION_BODY>}
}
|
if (filterName(name)) {
try {
// Some implementations could return null when the class was loaded through the bootstrap classloader
// see https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--
if (classLoader == null) {
throw new RuntimeException(
"The ClassLoaderTypeSolver has been probably loaded through the bootstrap class loader. This usage is not supported by the JavaSymbolSolver");
}
Class<?> clazz = classLoader.loadClass(name);
return SymbolReference.solved(ReflectionFactory.typeDeclarationFor(clazz, getRoot()));
} catch (NoClassDefFoundError e) {
// We can safely ignore this one because it is triggered when there are package names which are almost the
// same as class name, with the exclusion of the case.
// For example:
// java.lang.NoClassDefFoundError: com/github/javaparser/printer/ConcreteSyntaxModel
// (wrong name: com/github/javaparser/printer/concretesyntaxmodel)
// note that this exception seems to be thrown only on certain platform (mac yes, linux no)
return SymbolReference.unsolved();
} catch (ClassNotFoundException e) {
// it could be an inner class
int lastDot = name.lastIndexOf('.');
if (lastDot == -1) {
return SymbolReference.unsolved();
}
String parentName = name.substring(0, lastDot);
String childName = name.substring(lastDot + 1);
SymbolReference<ResolvedReferenceTypeDeclaration> parent = tryToSolveType(parentName);
if (parent.isSolved()) {
Optional<ResolvedReferenceTypeDeclaration> innerClass = parent.getCorrespondingDeclaration()
.internalTypes()
.stream().filter(it -> it.getName().equals(childName)).findFirst();
return innerClass.map(SymbolReference::solved)
.orElseGet(() -> SymbolReference.unsolved());
}
return SymbolReference.unsolved();
}
} else {
return SymbolReference.unsolved();
}
| 246
| 545
| 791
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/resolution/typesolvers/MemoryTypeSolver.java
|
MemoryTypeSolver
|
toString
|
class MemoryTypeSolver implements TypeSolver {
private TypeSolver parent;
private Map<String, ResolvedReferenceTypeDeclaration> declarationMap = new HashMap<>();
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MemoryTypeSolver)) return false;
MemoryTypeSolver that = (MemoryTypeSolver) o;
if (parent != null ? !parent.equals(that.parent) : that.parent != null) return false;
return !(declarationMap != null ? !declarationMap.equals(that.declarationMap) : that.declarationMap != null);
}
@Override
public int hashCode() {
int result = parent != null ? parent.hashCode() : 0;
result = 31 * result + (declarationMap != null ? declarationMap.hashCode() : 0);
return result;
}
@Override
public TypeSolver getParent() {
return parent;
}
@Override
public void setParent(TypeSolver parent) {
Objects.requireNonNull(parent);
if (this.parent != null) {
throw new IllegalStateException("This TypeSolver already has a parent.");
}
if (parent == this) {
throw new IllegalStateException("The parent of this TypeSolver cannot be itself.");
}
this.parent = parent;
}
public void addDeclaration(String name, ResolvedReferenceTypeDeclaration typeDeclaration) {
this.declarationMap.put(name, typeDeclaration);
}
@Override
public SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name) {
if (declarationMap.containsKey(name)) {
return SymbolReference.solved(declarationMap.get(name));
}
return SymbolReference.unsolved();
}
}
|
return "MemoryTypeSolver{" +
"parent=" + parent +
", declarationMap=" + declarationMap +
'}';
| 503
| 38
| 541
|
<no_super_class>
|
javaparser_javaparser
|
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/utils/SymbolSolverCollectionStrategy.java
|
SymbolSolverCollectionStrategy
|
collect
|
class SymbolSolverCollectionStrategy implements CollectionStrategy {
private final ParserConfiguration parserConfiguration;
private final CombinedTypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(false));
public SymbolSolverCollectionStrategy() {
this(new ParserConfiguration());
}
public SymbolSolverCollectionStrategy(ParserConfiguration parserConfiguration) {
// Allow the symbol resolver to be set via the given parser configuration
this.parserConfiguration = parserConfiguration;
if (!parserConfiguration.getSymbolResolver().isPresent()) {
this.parserConfiguration.setSymbolResolver(new JavaSymbolSolver(typeSolver));
}
}
@Override
public ParserConfiguration getParserConfiguration() {
return parserConfiguration;
}
@Override
public ProjectRoot collect(Path path) {<FILL_FUNCTION_BODY>}
}
|
ProjectRoot projectRoot = new ProjectRoot(path, parserConfiguration);
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
private Path current_root;
private Path currentProjectDir;
private String previousSourceDirectory;
private final PathMatcher javaMatcher = getPathMatcher("glob:**.java");
private final PathMatcher jarMatcher = getPathMatcher("glob:**.jar");
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (javaMatcher.matches(file)) {
String parent = file.getParent().toString();
// This is not a very elegant or powerful solution but it works and it allows to unblock users :-(
// We are trying to verify the current_root directory for each package.
// Sometime (for exemple https://github.com/apache/logging-log4j1) we can have java packages directly under a base directory
// and source directory under the same base package.
// for exemple:
// logging-log4j1\examples\customLevel\XLevel.java <- examples is a package (the root source directory is logging-log4j1)
// logging-log4j1\src\main\java\org\apache\log4j\Appender.java <- org is a package (the root source directory is logging-log4j1\src\main\java)
if (!parent.equals(previousSourceDirectory)) {
Log.info("Trying to compute the source root from %s", () -> file.toString());
previousSourceDirectory = parent;
currentProjectDir = getRoot(file).orElse(null);
}
if (current_root == null || (currentProjectDir != null && !currentProjectDir.equals(current_root))) {
current_root = currentProjectDir;
if (current_root != null) Log.info("New current source root is %s", () -> current_root.toString());
}
} else if (jarMatcher.matches(file)) {
Log.info("Jar file is found %s", () -> file.toString());
typeSolver.add(new JarTypeSolver(file.toString()));
}
return CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (Files.isHidden(dir)) {
Log.info("Skipping sub-tree %s", () -> dir.toString());
return SKIP_SUBTREE;
}
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (current_root != null && Files.isSameFile(dir, current_root)) {
Log.info("Adding source root %s", () -> dir.toString());
projectRoot.addSourceRoot(dir);
typeSolver.add(new JavaParserTypeSolver(current_root.toFile(), parserConfiguration));
current_root = null;
}
return CONTINUE;
}
});
} catch (IOException e) {
Log.error(e, "Unable to walk %s", () -> path);
}
return projectRoot;
| 213
| 806
| 1,019
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/config/Config.java
|
Config
|
parseBuffer
|
class Config {
private static final String DEFAULT_SECTION = "default";
private static final String DEFAULT_COMMENT = "#";
private static final String DEFAULT_COMMENT_SEM = ";";
private ReentrantLock lock = new ReentrantLock();
// Section:key=value
private Map<String, Map<String, String>> data;
/**
* Config represents the configuration parser.
*/
public Config() {
data = new HashMap<>();
}
/**
* newConfig create an empty configuration representation from file.
*
* @param confName the path of the model file.
* @return the constructor of Config.
*/
public static Config newConfig(String confName) {
Config c = new Config();
c.parse(confName);
return c;
}
/**
* newConfigFromText create an empty configuration representation from text.
*
* @param text the model text.
* @return the constructor of Config.
*/
public static Config newConfigFromText(String text) {
Config c = new Config();
try {
c.parseBuffer(new BufferedReader(new StringReader(text)));
} catch (IOException e) {
throw new CasbinConfigException(e.getMessage(), e.getCause());
}
return c;
}
/**
* addConfig adds a new section->key:value to the configuration.
*/
private boolean addConfig(String section, String option, String value) {
if (section.equals("")) {
section = DEFAULT_SECTION;
}
if (!data.containsKey(section)) {
data.put(section, new HashMap<>());
}
boolean ok = data.get(section).containsKey(option);
data.get(section).put(option, value);
return !ok;
}
private void parse(String fname) {
lock.lock();
try (FileInputStream fis = new FileInputStream(fname)) {
BufferedReader buf = new BufferedReader(new InputStreamReader(fis));
parseBuffer(buf);
} catch (IOException e) {
throw new CasbinConfigException(e.getMessage(), e.getCause());
} finally {
lock.unlock();
}
}
private void parseBuffer(BufferedReader buf) throws IOException {<FILL_FUNCTION_BODY>}
public boolean getBool(String key) {
return Boolean.parseBoolean(get(key));
}
public int getInt(String key) {
return Integer.parseInt(get(key));
}
public float getFloat(String key) {
return Float.parseFloat(get(key));
}
public String getString(String key) {
return get(key);
}
public String[] getStrings(String key) {
String v = get(key);
if (v.equals("")) {
return null;
}
return v.split(",");
}
public void set(String key, String value) {
lock.lock();
if (key.length() == 0) {
lock.unlock();
throw new IllegalArgumentException("key is empty");
}
String section = "";
String option;
String[] keys = key.toLowerCase().split("::");
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
option = keys[0];
}
addConfig(section, option, value);
lock.unlock();
}
public String get(String key) {
String section;
String option;
String[] keys = key.toLowerCase().split("::");
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
section = DEFAULT_SECTION;
option = keys[0];
}
boolean ok = data.containsKey(section) && data.get(section).containsKey(option);
if (ok) {
return data.get(section).get(option);
} else {
return "";
}
}
}
|
String section = "";
int lineNum = 0;
String line;
while (true) {
lineNum++;
if ((line = buf.readLine()) != null) {
if ("".equals(line)) {
continue;
}
} else {
break;
}
line = line.trim();
if (line.startsWith(DEFAULT_COMMENT)) {
continue;
} else if (line.startsWith(DEFAULT_COMMENT_SEM)) {
continue;
} else if (line.startsWith("[") && line.endsWith("]")) {
section = line.substring(1, line.length() - 1);
} else {
int index1 = line.indexOf(DEFAULT_COMMENT);
int index2 = line.indexOf(DEFAULT_COMMENT_SEM);
int index = (index1 != -1 && index2 != -1) ? Math.min(index1, index2) : (index1 != -1) ? index1 : (index2 != -1) ? index2 : -1;
if (index != -1)
line = line.substring(0, index);
String[] optionVal = line.split("=", 2);
if (optionVal.length != 2) {
throw new IllegalArgumentException(String.format("parse the content error : line %d , %s = ? ", lineNum, optionVal[0]));
}
String option = optionVal[0].trim();
String value = optionVal[1].trim();
if (value.endsWith("\\")) {
value = value.substring(0, value.length() - 1);
while ((line = buf.readLine()) != null && line.endsWith("\\")) {
lineNum++;
line = line.trim();
value = value.concat(line.substring(0, line.length() - 1));
}
if (line != null) {
lineNum++;
if (line.endsWith("\\")) {
line = line.substring(0, line.length() - 1);
}
line = line.trim();
value = value.concat(line);
}
}
addConfig(section, option, value);
}
}
| 1,055
| 575
| 1,630
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/effect/DefaultEffector.java
|
DefaultEffector
|
mergeEffects
|
class DefaultEffector implements Effector {
/**
* DefaultEffector is the constructor for DefaultEffector.
*/
public DefaultEffector() {
}
/**
* mergeEffects merges all matching results collected by the enforcer into a single decision.
*/
@Override
public boolean mergeEffects(String expr, Effect[] effects, float[] results) {<FILL_FUNCTION_BODY>}
@Override
public StreamEffector newStreamEffector(String expr) {
return new DefaultStreamEffector(expr);
}
}
|
boolean result;
if (expr.equals("some(where (p_eft == allow))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
break;
}
}
} else if (expr.equals("!some(where (p_eft == deny))")) {
result = true;
for (Effect eft : effects) {
if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("some(where (p_eft == allow)) && !some(where (p_eft == deny))")) {
result = false;
for (Effect eft : effects) {
if (eft == Effect.Allow) {
result = true;
} else if (eft == Effect.Deny) {
result = false;
break;
}
}
} else if (expr.equals("priority(p_eft) || deny") || expr.equals("subjectPriority(p_eft) || deny")) {
result = false;
for (Effect eft : effects) {
if (eft != Effect.Indeterminate) {
if (eft == Effect.Allow) {
result = true;
} else {
result = false;
}
break;
}
}
} else {
throw new UnsupportedOperationException("unsupported effect");
}
return result;
| 151
| 386
| 537
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/effect/DefaultStreamEffector.java
|
DefaultStreamEffector
|
push
|
class DefaultStreamEffector implements StreamEffector {
private final String expr;
private boolean done = false;
private boolean effect = false;
private int explainIndex = -1;
public DefaultStreamEffector(String expr) {
this.expr = expr;
}
@Override
public StreamEffectorResult current() {
return new DefaultStreamEffectorResult(effect, done, explainIndex);
}
@Override
public boolean push(Effect eft, int currentIndex, int policySize) {<FILL_FUNCTION_BODY>}
}
|
switch (this.expr) {
case "some(where (p_eft == allow))":
if (eft == Effect.Allow) {
this.effect = true;
explainIndex = currentIndex;
this.done = true;
}
break;
case "!some(where (p_eft == deny))":
this.effect = true;
if (eft == Effect.Deny) {
this.effect = false;
explainIndex = currentIndex;
this.done = true;
}
break;
case "some(where (p_eft == allow)) && !some(where (p_eft == deny))":
if (eft == Effect.Allow) {
this.effect = true;
explainIndex = explainIndex == -1 ? currentIndex : explainIndex;
} else if (eft == Effect.Deny) {
this.effect = false;
explainIndex = currentIndex;
this.done = true;
}
break;
case "priority(p_eft) || deny":
case "subjectPriority(p_eft) || deny":
if (eft != Effect.Indeterminate) {
this.effect = eft == Effect.Allow;
explainIndex = currentIndex;
this.done = true;
}
break;
default:
throw new UnsupportedOperationException("unsupported effect");
}
return this.done;
| 149
| 361
| 510
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/log/DefaultLogger.java
|
DefaultLogger
|
logPolicy
|
class DefaultLogger implements Logger {
private boolean enabled;
@Override
public void enableLog(boolean enable) {
this.enabled = enable;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void logModel(String[][] model) {
if (!enabled) {
return;
}
StringBuilder str = new StringBuilder("Model: ");
for (String[] v : model) {
str.append(String.format("%s\n", String.join(", ", v)));
}
System.out.println(str.toString());
}
@Override
public void logEnforce(String matcher, Object[] request, boolean result, String[][] explains) {
if (!enabled) {
return;
}
StringBuilder reqStr = new StringBuilder("Request: ");
for (int i = 0; i < request.length; i++) {
reqStr.append(i != request.length - 1 ? String.format("%s, ", request[i]) : request[i]);
}
reqStr.append(String.format(" ---> %b\n", result));
reqStr.append("Hit Policy: ");
for (int i = 0; i < explains.length; i++) {
reqStr.append(i != explains.length - 1 ? String.format("%s, ", String.join(", ", explains[i])) : String.join(", ", explains[i]));
}
System.out.println(reqStr.toString());
}
@Override
public void logPolicy(Map<String, String[][]> policy) {<FILL_FUNCTION_BODY>}
/**
* tool for logPolicy
* [][] -> String
*/
private String arrayToString(String[][] array) {
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < array.length; i++) {
result.append("[")
.append(String.join(", ", array[i]))
.append("]");
if (i < array.length - 1) {
result.append(", ");
}
}
result.append("]");
return result.toString();
}
@Override
public void logRole(String[] roles) {
if (!enabled) {
return;
}
System.out.println("Roles: " + String.join("\n", roles));
}
@Override
public void logError(Throwable err, String... msg) {
if (!enabled) {
return;
}
System.out.println(String.join(" ", msg) + " " + err.getMessage());
}
}
|
if (!enabled) {
return;
}
StringBuilder str = new StringBuilder("Policy: ");
for (Map.Entry<String, String[][]> entry : policy.entrySet()) {
str.append(String.format("%s : %s\n", entry.getKey(), arrayToString(entry.getValue())));
}
System.out.println(str.toString());
| 689
| 99
| 788
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/main/EnforceResult.java
|
EnforceResult
|
toString
|
class EnforceResult {
private boolean allow;
private List<String> explain;
public boolean isAllow() {
return allow;
}
public void setAllow(boolean allow) {
this.allow = allow;
}
public List<String> getExplain() {
return explain;
}
public void setExplain(List<String> explain) {
this.explain = explain;
}
public EnforceResult() {
}
public EnforceResult(boolean allow, List<String> explain) {
this.allow = allow;
this.explain = explain;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "EnforceResult{" +
"allow=" + allow +
", explain=" + explain +
'}';
| 187
| 35
| 222
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/main/Frontend.java
|
Frontend
|
casbinJsGetPermissionForUser
|
class Frontend {
public static String casbinJsGetPermissionForUser(Enforcer e, String user) {<FILL_FUNCTION_BODY>}
}
|
Model model = e.getModel();
Map<String, Object> m = new HashMap<>();
m.put("m", model.saveModelToText().trim());
List<List<String>> policies = new ArrayList<>();
for (String ptype : model.model.get("p").keySet()) {
List<List<String>> policy = model.getPolicy("p", ptype);
for (List<String> p : policy) {
List<String> tmp = new ArrayList<>(p);
tmp.add(0, ptype);
policies.add(tmp);
}
}
m.put("p", policies);
return new Gson().toJson(m);
| 42
| 173
| 215
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/model/Assertion.java
|
Assertion
|
buildIncrementalRoleLinks
|
class Assertion {
public String key;
public String value;
public String[] tokens;
public String[] paramsTokens;
public List<List<String>> policy;
public Map<String, Integer> policyIndex;
public RoleManager rm;
public ConditionalRoleManager condRM;
public int priorityIndex;
private Logger logger;
public Assertion() {
policy = new ArrayList<>();
policyIndex = new HashMap<>();
}
public Assertion(Logger logger) {
policy = new ArrayList<>();
policyIndex = new HashMap<>();
setLogger(logger);
}
protected void buildRoleLinks(RoleManager rm) {
this.rm = rm;
int count = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '_') {
count++;
}
}
for (List<String> rule : policy) {
if (count < 2) {
throw new IllegalArgumentException("the number of \"_\" in role definition should be at least 2");
}
if (rule.size() < count) {
throw new IllegalArgumentException("grouping policy elements do not meet role definition");
}
if (rule.size() > count){
rule = rule.subList(0, count);
}
this.rm.addLink(rule.get(0), rule.get(1), rule.subList(2, rule.size()).toArray(new String[0]));
}
Util.logPrint("Role links for: " + key);
rm.printRoles();
}
public void buildIncrementalRoleLinks(RoleManager rm, Model.PolicyOperations op, List<List<String>> rules) {<FILL_FUNCTION_BODY>}
public void buildIncrementalConditionalRoleLinks(ConditionalRoleManager condRM, Model.PolicyOperations op, List<List<String>> rules){
this.condRM = condRM;
int count = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '_') {
count++;
}
}
if (count < 2) {
throw new IllegalArgumentException("the number of \"_\" in role definition should be at least 2");
}
for (List<String> rule : rules) {
if (count < 2) {
throw new IllegalArgumentException("the number of \"_\" in role definition should be at least 2");
}
if (rule.size() < count) {
throw new IllegalArgumentException("grouping policy elements do not meet role definition");
}
if (rule.size() > count) {
rule = rule.subList(0, count);
}
List<String> domainRule = rule.subList(2, tokens.length);
switch (op) {
case POLICY_ADD:
addConditionalRoleLink(rule, domainRule);
break;
case POLICY_REMOVE:
condRM.deleteLink(rule.get(0), rule.get(1), rule.subList(2, rule.size()).toArray(new String[0]));
break;
default:
throw new IllegalArgumentException("invalid operation:" + op.toString());
}
}
}
public void buildConditionalRoleLinks(ConditionalRoleManager condRM){
this.condRM = condRM;
int count = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '_') {
count++;
}
}
for (List<String> rule : policy) {
if (count < 2) {
throw new IllegalArgumentException("the number of \"_\" in role definition should be at least 2");
}
if (rule.size() < count) {
throw new IllegalArgumentException("grouping policy elements do not meet role definition");
}
if (rule.size() > count){
rule = rule.subList(0, count);
}
List<String> domainRule = rule.subList(2, tokens.length);
addConditionalRoleLink(rule, domainRule);
}
Util.logPrint("Role links for: " + key);
condRM.printRoles();
}
// addConditionalRoleLinks adds Link to rbac.ConditionalRoleManager and sets the parameters for LinkConditionFunc
public void addConditionalRoleLink(List<String> rule, List<String> domainRule){
int domainRule_num = (domainRule!=null? domainRule.size() : 0);
if (domainRule_num == 0){
condRM.addLink(rule.get(0), rule.get(1));
condRM.setLinkConditionFuncParams(rule.get(0), rule.get(1), rule.subList(tokens.length, rule.size()).toArray(new String[0]));
}else {
String domain = domainRule.get(0);
condRM.addLink(rule.get(0), rule.get(1));
condRM.setDomainLinkConditionFuncParams(rule.get(0), rule.get(1), domain, rule.subList(tokens.length, rule.size()).toArray(new String[0]));
}
}
public void initPriorityIndex() {
priorityIndex = -1;
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
}
|
this.rm = rm;
int count = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '_') {
count++;
}
}
for (List<String> rule : rules) {
if (count < 2) {
throw new IllegalArgumentException("the number of \"_\" in role definition should be at least 2");
}
if (rule.size() < count) {
throw new IllegalArgumentException("grouping policy elements do not meet role definition");
}
if (rule.size() > count) {
rule = rule.subList(0, count);
}
switch (op) {
case POLICY_ADD:
rm.addLink(rule.get(0), rule.get(1), rule.subList(2, rule.size()).toArray(new String[0]));
break;
case POLICY_REMOVE:
rm.deleteLink(rule.get(0), rule.get(1), rule.subList(2, rule.size()).toArray(new String[0]));
break;
default:
throw new IllegalArgumentException("invalid operation:" + op.toString());
}
}
| 1,411
| 311
| 1,722
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/model/FunctionMap.java
|
FunctionMap
|
setAviatorEval
|
class FunctionMap {
/**
* AviatorFunction represents a function that is used in the matchers, used to get attributes in ABAC.
*/
public Map<String, AviatorFunction> fm;
public boolean isModify = false;
/**
* addFunction adds an expression function.
*
* @param name the name of the new function.
* @param function the function.
*/
public void addFunction(String name, AviatorFunction function) {
fm.put(name, function);
isModify=true;
}
/**
* setAviatorEval adds AviatorEvaluatorInstance to the custom function.
*
* @param name the name of the custom function.
* @param aviatorEval the AviatorEvaluatorInstance object.
*/
public void setAviatorEval(String name, AviatorEvaluatorInstance aviatorEval) {<FILL_FUNCTION_BODY>}
/**
* setAviatorEval adds AviatorEvaluatorInstance to all the custom function.
*
* @param aviatorEval the AviatorEvaluatorInstance object.
*/
public void setAviatorEval(AviatorEvaluatorInstance aviatorEval) {
for (AviatorFunction function : fm.values()) {
if (function instanceof CustomFunction) {
((CustomFunction) function).setAviatorEval(aviatorEval);
}
}
}
/**
* loadFunctionMap loads an initial function map.
*
* @return the constructor of FunctionMap.
*/
public static FunctionMap loadFunctionMap() {
FunctionMap fm = new FunctionMap();
fm.fm = new HashMap<>();
fm.addFunction("keyMatch", new KeyMatchFunc());
fm.addFunction("keyMatch2", new KeyMatch2Func());
fm.addFunction("keyMatch3", new KeyMatch3Func());
fm.addFunction("keyMatch4", new KeyMatch4Func());
fm.addFunction("keyMatch5", new KeyMatch5Func());
fm.addFunction("keyGet", new KeyGetFunc());
fm.addFunction("keyGet2", new KeyGet2Func());
fm.addFunction("regexMatch", new RegexMatchFunc());
fm.addFunction("ipMatch", new IPMatchFunc());
fm.addFunction("eval", new EvalFunc());
fm.addFunction("globMatch", new GlobMatchFunc());
return fm;
}
}
|
if (fm.containsKey(name) && fm.get(name) instanceof CustomFunction) {
((CustomFunction) fm.get(name)).setAviatorEval(aviatorEval);
}
| 650
| 55
| 705
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/persist/Helper.java
|
Helper
|
loadPolicyLine
|
class Helper {
public interface loadPolicyLineHandler<T, U> {
void accept(T t, U u);
}
public static void loadPolicyLine(String line, Model model) {<FILL_FUNCTION_BODY>}
}
|
if ("".equals(line)) {
return;
}
if (line.charAt(0) == '#') {
return;
}
String[] tokens = splitCommaDelimited(line);
String key = tokens[0];
String sec = key.substring(0, 1);
Assertion ast = model.model.get(sec).get(key);
List<String> policy = Arrays.asList(Arrays.copyOfRange(tokens, 1, tokens.length));
ast.policy.add(policy);
ast.policyIndex.put(policy.toString(), ast.policy.size() - 1);
| 64
| 166
| 230
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/persist/file_adapter/AdapterMock.java
|
AdapterMock
|
loadPolicy
|
class AdapterMock implements Adapter {
private String filePath;
private String errorValue;
public AdapterMock(String filePath) {
this.filePath = filePath;
}
public void setMockErr(String errorToSet) {
this.errorValue = errorToSet;
}
public Exception getMockErr() {
if (errorValue != null && !errorValue.isEmpty()) {
return new Exception(errorValue);
}
return null;
}
@Override
public void loadPolicy(Model model) {<FILL_FUNCTION_BODY>}
@Override
public void savePolicy(Model model) {
}
@Override
public void addPolicy(String sec, String ptype, List<String> rule) {
}
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
}
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
}
private void loadPolicyFile(Model model, Helper.loadPolicyLineHandler<String, Model> handler) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
handler.accept(line, model);
}
}
}
}
|
try {
loadPolicyFile(model, Helper::loadPolicyLine);
} catch (IOException e) {
e.printStackTrace();
}
| 366
| 42
| 408
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/persist/file_adapter/FileAdapter.java
|
FileAdapter
|
getModelPolicy
|
class FileAdapter implements Adapter {
private String filePath;
private boolean readOnly = false;
private ByteArrayInputStream byteArrayInputStream;
/**
* FileAdapter is the constructor for FileAdapter.
*
* @param filePath the path of the policy file.
*/
public FileAdapter(String filePath) {
this.filePath = filePath;
}
/**
* FileAdapter is the constructor for FileAdapter.
*
* @param inputStream the policy file.inputStream
*/
public FileAdapter(InputStream inputStream) {
readOnly = true;
try {
byteArrayInputStream = new ByteArrayInputStream(IOUtils.toByteArray(inputStream));
} catch (IOException e) {
e.printStackTrace();
throw new CasbinAdapterException("File adapter init error");
}
}
/**
* loadPolicy loads all policy rules from the storage.
*/
@Override
public void loadPolicy(Model model) {
if (filePath != null && !"".equals(filePath)) {
try (FileInputStream fis = new FileInputStream(filePath)) {
loadPolicyData(model, Helper::loadPolicyLine, fis);
} catch (IOException e) {
throw new CasbinAdapterException("Load policy file error", e.getCause());
}
}
if (byteArrayInputStream != null) {
loadPolicyData(model, Helper::loadPolicyLine, byteArrayInputStream);
}
}
/**
* savePolicy saves all policy rules to the storage.
*/
@Override
public void savePolicy(Model model) {
if (byteArrayInputStream != null && readOnly) {
throw new CasbinAdapterException("Policy file can not write, because use inputStream is readOnly");
}
if (filePath == null || "".equals(filePath) || !new File(filePath).exists()) {
throw new CasbinPolicyFileNotFoundException("invalid file path: " + filePath);
}
List<String> policy = new ArrayList<>();
policy.addAll(getModelPolicy(model, "p"));
policy.addAll(getModelPolicy(model, "g"));
savePolicyFile(String.join("\n", policy));
}
private List<String> getModelPolicy(Model model, String ptype) {<FILL_FUNCTION_BODY>}
private void loadPolicyData(Model model, Helper.loadPolicyLineHandler<String, Model> handler, InputStream inputStream) {
try {
List<String> lines = IOUtils.readLines(inputStream, Charset.forName("UTF-8"));
lines.forEach(x -> handler.accept(x, model));
} catch (IOException e) {
e.printStackTrace();
throw new CasbinAdapterException("Policy load error");
}
}
private void savePolicyFile(String text) {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
IOUtils.write(text, fos, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
throw new CasbinAdapterException("Policy save error");
}
}
/**
* addPolicy adds a policy rule to the storage.
*/
@Override
public void addPolicy(String sec, String ptype, List<String> rule) {
String ruleText = System.lineSeparator() + ptype + ", " + String.join(", ", rule);
if (byteArrayInputStream != null && readOnly) {
throw new CasbinAdapterException("Policy file can not write, because use inputStream is readOnly");
}
try (FileOutputStream fos = new FileOutputStream(filePath, true)) {
IOUtils.write(ruleText, fos, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
throw new CasbinAdapterException("Policy add error");
}
}
/**
* removePolicy removes a policy rule from the storage.
*/
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
String ruleText = ptype + ", " + String.join(", ", rule);
if (byteArrayInputStream != null && readOnly) {
throw new CasbinAdapterException("Policy file can not write, because use inputStream is readOnly");
}
try {
List<String> lines = IOUtils.readLines(new FileInputStream(filePath), Charset.forName("UTF-8"));
lines.remove(ruleText);
savePolicyFile(String.join("\n", lines));
} catch (IOException e) {
e.printStackTrace();
throw new CasbinAdapterException("Policy remove error");
}
}
/**
* removeFilteredPolicy removes policy rules that match the filter from the storage.
*/
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new UnsupportedOperationException("not implemented");
}
}
|
List<String> policy = new ArrayList<>();
Optional.ofNullable(model.model.get(ptype)).ifPresent(entry -> entry.forEach((k, v) -> {
List<String> p = v.policy.parallelStream().map(x -> k + ", " + Util.arrayToString(x)).collect(Collectors.toList());
policy.addAll(p);
}));
return policy;
| 1,254
| 106
| 1,360
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/persist/file_adapter/FilteredAdapter.java
|
FilteredAdapter
|
loadFilteredPolicy
|
class FilteredAdapter implements org.casbin.jcasbin.persist.FilteredAdapter {
private Adapter adapter;
private boolean isFiltered = true;
private String filepath;
public FilteredAdapter(String filepath) {
adapter = new FileAdapter(filepath);
this.filepath = filepath;
}
/**
* loadFilteredPolicy loads only policy rules that match the filter.
* @param model the model.
* @param filter the filter used to specify which type of policy should be loaded.
* @throws CasbinAdapterException if the file path or the type of the filter is incorrect.
*/
@Override
public void loadFilteredPolicy(Model model, Object filter) throws CasbinAdapterException {<FILL_FUNCTION_BODY>}
/**
* loadFilteredPolicyFile loads only policy rules that match the filter from file.
*/
private void loadFilteredPolicyFile(Model model, Filter filter, Helper.loadPolicyLineHandler<String, Model> handler) throws CasbinAdapterException {
try (FileInputStream fis = new FileInputStream(filepath)) {
List<String> lines = IOUtils.readLines(fis, Charset.forName("UTF-8"));
for (String line : lines) {
line = line.trim();
if (filterLine(line, filter)) {
continue;
}
handler.accept(line, model);
}
} catch (IOException e) {
throw new CasbinAdapterException("Load policy file error", e.getCause());
}
}
/**
* match the line.
*/
private boolean filterLine(String line, Filter filter) {
if (filter == null) {
return false;
}
String[] p = line.split(",");
if (p.length == 0) {
return true;
}
String[] filterSlice = null;
switch (p[0].trim()) {
case "p":
filterSlice = filter.p;
break;
case "g":
filterSlice = filter.g;
break;
}
if (filterSlice == null) {
filterSlice = new String[]{};
}
return filterWords(p, filterSlice);
}
/**
* match the words in the specific line.
*/
private boolean filterWords(String[] line, String[] filter) {
if (line.length < filter.length + 1) {
return true;
}
boolean skipLine = false;
int i = 0;
for (String s : filter) {
i++;
if (s.length() > 0 && !s.trim().equals(line[i].trim())) {
skipLine = true;
break;
}
}
return skipLine;
}
/**
* @return true if have any filter roles.
*/
@Override
public boolean isFiltered(){
return isFiltered;
}
/**
* loadPolicy loads all policy rules from the storage.
*/
@Override
public void loadPolicy(Model model) {
adapter.loadPolicy(model);
isFiltered = false;
}
/**
* savePolicy saves all policy rules to the storage.
*/
@Override
public void savePolicy(Model model) {
adapter.savePolicy(model);
}
/**
* addPolicy adds a policy rule to the storage.
*/
@Override
public void addPolicy(String sec, String ptype, List<String> rule) {
adapter.addPolicy(sec, ptype, rule);
}
/**
* removePolicy removes a policy rule from the storage.
*/
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
adapter.removePolicy(sec, ptype, rule);
}
/**
* removeFilteredPolicy removes policy rules that match the filter from the storage.
*/
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
adapter.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues);
}
/**
* the filter class.
* Enforcer only accept this filter currently.
*/
public static class Filter {
public String[] p;
public String[] g;
}
}
|
if ("".equals(filepath)) {
throw new CasbinAdapterException("Invalid file path, file path cannot be empty.");
}
if (filter == null) {
adapter.loadPolicy(model);
isFiltered = false;
return;
}
if (!(filter instanceof Filter)) {
throw new CasbinAdapterException("Invalid filter type.");
}
try {
loadFilteredPolicyFile(model, (Filter) filter, Helper::loadPolicyLine);
isFiltered = true;
} catch (Exception e) {
e.printStackTrace();
}
| 1,100
| 149
| 1,249
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/rbac/ConditionalRoleManager.java
|
ConditionalRoleManager
|
hasLinkHelper
|
class ConditionalRoleManager extends DefaultRoleManager{
public ConditionalRoleManager(int maxHierarchyLevel) {
super(maxHierarchyLevel);
}
public ConditionalRoleManager(int maxHierarchyLevel, BiPredicate<String, String> matchingFunc, BiPredicate<String, String> domainMatchingFunc) {
super(maxHierarchyLevel, matchingFunc, domainMatchingFunc);
}
public synchronized boolean hasLink(String name1, String name2, String... domains) {
if (name1.equals(name2) || (this.matchingFunc != null && this.matchingFunc.test(name1, name2))) {
return true;
}
boolean userCreated = !this.allRoles.containsKey(name1);
boolean roleCreated = !this.allRoles.containsKey(name2);
Role user = getRole(name1);
Role role = getRole(name2);
Map<String, Role> roles = new HashMap<>();
roles.put(user.getName(), user);
try {
return hasLinkHelper(role.getName(), roles, this.maxHierarchyLevel, domains);
} finally {
if (userCreated) {
removeRole(user.getName());
}
if (roleCreated) {
removeRole(role.getName());
}
}
}
public boolean hasLinkHelper(String targetName, Map<String, Role> roles, int level, String... domains) {<FILL_FUNCTION_BODY>}
public boolean getNextRoles(Role currentRole, Role nextRole, String[] domains, Map<String, Role> nextRoles) {
boolean passLinkConditionFunc = true;
Exception err = null;
// If LinkConditionFunc exists, it needs to pass the verification to get nextRole
if (domains.length == 0) {
Function<String[], Boolean> linkConditionFunc = getLinkConditionFunc(currentRole.getName(), nextRole.getName());
if (linkConditionFunc != null) {
List<String> params = getLinkConditionFuncParams(currentRole.getName(), nextRole.getName(), domains);
try {
passLinkConditionFunc = linkConditionFunc.apply(params.toArray(new String[0]));
} catch (Exception e) {
err = e;
}
}
} else {
Function<String[], Boolean> linkConditionFunc = getDomainLinkConditionFunc(currentRole.getName(), nextRole.getName(), domains[0]);
if (linkConditionFunc != null) {
List<String> params = getLinkConditionFuncParams(currentRole.getName(), nextRole.getName(), domains);
try {
passLinkConditionFunc = linkConditionFunc.apply(params.toArray(new String[0]));
} catch (Exception e) {
err = e;
}
}
}
if (err != null) {
System.err.println("hasLinkHelper LinkCondition Error");
err.printStackTrace();
return false;
}
if (passLinkConditionFunc) {
nextRoles.put(nextRole.getName(), nextRole);
}
return true;
}
/**
* getLinkConditionFunc get LinkConditionFunc based on userName, roleName
*/
public Function<String[], Boolean> getLinkConditionFunc(String userName, String roleName){
return getDomainLinkConditionFunc(userName, roleName, "");
}
/**
* getDomainLinkConditionFunc get LinkConditionFunc based on userName, roleName, domain
*/
public Function<String[], Boolean> getDomainLinkConditionFunc(String userName, String roleName, String domain){
Role user = getRole(userName);
Role role = getRole(roleName);
if (user == null) {
return null;
}
if (role == null) {
return null;
}
return user.getLinkConditionFunc(role, domain);
}
/**
* getLinkConditionFuncParams gets parameters of LinkConditionFunc based on userName, roleName, domain
*/
public List<String> getLinkConditionFuncParams(String userName, String roleName, String[] domain){
boolean userCreated = !this.allRoles.containsKey(userName);
boolean roleCreated = !this.allRoles.containsKey(roleName);
Role user = getRole(userName);
Role role = getRole(roleName);
if (userCreated)
removeRole(user.getName());
if (roleCreated)
removeRole(role.getName());
String domainName = "";
if (domain.length != 0) {
domainName = domain[0];
}
String[] params = user.getLinkConditionFuncParams(role, domainName);
if (params != null){
return Arrays.asList(params);
} else {
return null;
}
}
/**
* addLinkConditionFunc is based on userName, roleName, add LinkConditionFunc
*/
public void addLinkConditionFunc(String userName, String roleName, Function<String[], Boolean> fn){
addDomainLinkConditionFunc(userName, roleName, "", fn);
}
/**
* addDomainLinkConditionFunc is based on userName, roleName, domain, add LinkConditionFunc
*/
public void addDomainLinkConditionFunc(String userName, String roleName, String domain, Function<String[], Boolean> fn){
Role user = getRole(userName);
Role role = getRole(roleName);
user.addLinkConditionFunc(role, domain, fn);
}
/**
* SetLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain
*/
public void setLinkConditionFuncParams(String userName, String roleName, String... params) {
setDomainLinkConditionFuncParams(userName, roleName, "", params);
}
/**
* SetDomainLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain
*/
public void setDomainLinkConditionFuncParams(String userName, String roleName, String domain, String... params) {
Role user = getRole(userName);
Role role = getRole(roleName);
user.setLinkConditionFuncParams(role, domain, params);
}
}
|
if (level < 0 || roles.isEmpty()) {
return false;
}
Map<String, Role> nextRoles = new HashMap<>();
for (Role role : roles.values()) {
if (targetName.equals(role.getName()) || (matchingFunc != null && match(role.getName(), targetName))) {
return true;
}
role.rangeRoles(new Consumer<Role>() {
@Override
public void accept(Role nextRole) {
getNextRoles(role, nextRole, domains, nextRoles);
}
});
}
return hasLinkHelper(targetName, nextRoles, level - 1, domains);
| 1,584
| 173
| 1,757
|
<methods>public void <init>(int) ,public void <init>(int, BiPredicate<java.lang.String,java.lang.String>, BiPredicate<java.lang.String,java.lang.String>) ,public void addDomainMatchingFunc(java.lang.String, BiPredicate<java.lang.String,java.lang.String>) ,public transient void addLink(java.lang.String, java.lang.String, java.lang.String[]) ,public void addMatchingFunc(java.lang.String, BiPredicate<java.lang.String,java.lang.String>) ,public void clear() ,public transient void deleteLink(java.lang.String, java.lang.String, java.lang.String[]) ,public transient List<java.lang.String> getRoles(java.lang.String, java.lang.String[]) ,public transient List<java.lang.String> getUsers(java.lang.String, java.lang.String[]) ,public synchronized transient boolean hasLink(java.lang.String, java.lang.String, java.lang.String[]) ,public void printRoles() ,public java.lang.String toString() <variables>private static final java.lang.String DEFAULT_DOMAIN,Map<java.lang.String,org.casbin.jcasbin.rbac.Role> allRoles,BiPredicate<java.lang.String,java.lang.String> matchingFunc,private SyncedLRUCache<java.lang.String,java.lang.Boolean> matchingFuncCache,final non-sealed int maxHierarchyLevel
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/rbac/DomainManager.java
|
DomainManager
|
match
|
class DomainManager implements RoleManager {
private static final String DEFAULT_DOMAIN = "casbin::default";
private Map<String, DefaultRoleManager> rmMap;
private int maxHierarchyLevel;
private BiPredicate<String, String> matchingFunc;
private BiPredicate<String, String> domainMatchingFunc;
private SyncedLRUCache<String, Boolean> domainMatchingFuncCache;
public DomainManager(int maxHierarchyLevel) {
this(maxHierarchyLevel, null, null);
}
public DomainManager(int maxHierarchyLevel, final BiPredicate<String, String> matchingFunc,
final BiPredicate<String, String> domainMatchingFunc) {
clear();
this.maxHierarchyLevel = maxHierarchyLevel;
this.matchingFunc = matchingFunc;
this.domainMatchingFunc = domainMatchingFunc;
}
public void addMatchingFunc(String name, BiPredicate<String, String> matchingFunc) {
this.matchingFunc = matchingFunc;
this.rmMap.values().forEach(rm -> rm.addMatchingFunc(name, matchingFunc));
}
public void addDomainMatchingFunc(String name, BiPredicate<String, String> domainMatchingFunc) {
this.domainMatchingFunc = domainMatchingFunc;
rebuild();
}
/**
* rebuild clears the map of RoleManagers
*/
private void rebuild() {
Map<String, DefaultRoleManager> rmMap = new HashMap<>(this.rmMap);
clear();
rmMap.forEach((domain, rm) -> {
rm.allRoles.values().forEach(user -> {
user.roles.keySet().forEach(roleName -> addLink(user.getName(), roleName, domain));
});
});
}
private String domainName(String... domain) {
return domain.length == 0 ? DEFAULT_DOMAIN : domain[0];
}
private DefaultRoleManager getRoleManager(String domain, boolean store) {
DefaultRoleManager rm = this.rmMap.get(domain);
if (rm == null) {
rm = new DefaultRoleManager(this.maxHierarchyLevel, this.matchingFunc, null);
if (store) {
this.rmMap.put(domain, rm);
}
if (this.domainMatchingFunc != null) {
for (Map.Entry<String, DefaultRoleManager> entry : this.rmMap.entrySet()) {
String domain2 = entry.getKey();
DefaultRoleManager rm2 = entry.getValue();
if (!domain.equals(domain2) && match(domain, domain2)) {
rm.copyFrom(rm2);
}
}
}
}
return rm;
}
private boolean match(String str, String pattern) {<FILL_FUNCTION_BODY>}
@Override
public void clear() {
this.rmMap = new HashMap<>();
this.domainMatchingFuncCache = new SyncedLRUCache<>(100);
}
@Override
public void addLink(String name1, String name2, String... domain) {
DefaultRoleManager roleManager = getRoleManager(domainName(domain), true);
roleManager.addLink(name1, name2, domain);
if (this.domainMatchingFunc != null) {
this.rmMap.forEach((domain2, rm) -> {
if (!domainName(domain).equals(domain2) && match(domain2, domainName(domain))) {
rm.addLink(name1, name2, domain);
}
});
}
}
@Override
public void deleteLink(String name1, String name2, String... domain) {
DefaultRoleManager roleManager = getRoleManager(domainName(domain), true);
roleManager.deleteLink(name1, name2, domain);
if (this.domainMatchingFunc != null) {
this.rmMap.forEach((domain2, rm) -> {
if (!domainName(domain).equals(domain2) && match(domain2, domainName(domain))) {
rm.deleteLink(name1, name2, domain);
}
});
}
}
@Override
public boolean hasLink(String name1, String name2, String... domain) {
DefaultRoleManager roleManager = getRoleManager(domainName(domain), false);
return roleManager.hasLink(name1, name2, domain);
}
@Override
public List<String> getRoles(String name, String... domain) {
DefaultRoleManager roleManager = getRoleManager(domainName(domain), false);
return roleManager.getRoles(name, domain);
}
@Override
public List<String> getUsers(String name, String... domain) {
DefaultRoleManager roleManager = getRoleManager(domainName(domain), false);
return roleManager.getUsers(name, domain);
}
@Override
public String toString() {
List<String> roles = new ArrayList<>();
this.rmMap.forEach((domain, rm) -> {
List<String> domainRoles = new ArrayList<>();
rm.allRoles.values().forEach(role -> {
if (!"".equals(role.toString())) {
domainRoles.add(role.toString());
}
});
roles.add(domain + ": " + String.join(", ", domainRoles));
});
return String.join("\n", roles);
}
@Override
public void printRoles() {
Util.logPrint(toString());
}
}
|
String cacheKey = String.join("$$", str, pattern);
Boolean matched = this.domainMatchingFuncCache.get(cacheKey);
if (matched == null) {
if (this.domainMatchingFunc != null) {
matched = this.domainMatchingFunc.test(str, pattern);
} else {
matched = str.equals(pattern);
}
this.domainMatchingFuncCache.put(cacheKey, matched);
}
return matched;
| 1,418
| 122
| 1,540
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/rbac/GroupRoleManager.java
|
GroupRoleManager
|
hasLink
|
class GroupRoleManager extends DefaultRoleManager {
/**
* GroupRoleManager is the constructor for creating an instance of the
* GroupRoleManager implementation.
*
* @param maxHierarchyLevel the maximized allowed RBAC hierarchy level.
*/
public GroupRoleManager(int maxHierarchyLevel) {
super(maxHierarchyLevel);
}
/**
* hasLink determines whether role: name1 inherits role: name2.
* domain is a prefix to the roles.
*/
@Override
public boolean hasLink(String name1, String name2, String... domain) {<FILL_FUNCTION_BODY>}
}
|
if(super.hasLink(name1, name2, domain)) {
return true;
}
// check name1's groups
if (domain.length == 1) {
try {
List<String> groups = Optional.ofNullable(super.getRoles(name1)).orElse(new ArrayList<>());
for(String group : groups) {
if(hasLink(group, name2, domain)) {
return true;
}
}
} catch (IllegalArgumentException ignore) {
return false;
}
}
return false;
| 165
| 146
| 311
|
<methods>public void <init>(int) ,public void <init>(int, BiPredicate<java.lang.String,java.lang.String>, BiPredicate<java.lang.String,java.lang.String>) ,public void addDomainMatchingFunc(java.lang.String, BiPredicate<java.lang.String,java.lang.String>) ,public transient void addLink(java.lang.String, java.lang.String, java.lang.String[]) ,public void addMatchingFunc(java.lang.String, BiPredicate<java.lang.String,java.lang.String>) ,public void clear() ,public transient void deleteLink(java.lang.String, java.lang.String, java.lang.String[]) ,public transient List<java.lang.String> getRoles(java.lang.String, java.lang.String[]) ,public transient List<java.lang.String> getUsers(java.lang.String, java.lang.String[]) ,public synchronized transient boolean hasLink(java.lang.String, java.lang.String, java.lang.String[]) ,public void printRoles() ,public java.lang.String toString() <variables>private static final java.lang.String DEFAULT_DOMAIN,Map<java.lang.String,org.casbin.jcasbin.rbac.Role> allRoles,BiPredicate<java.lang.String,java.lang.String> matchingFunc,private SyncedLRUCache<java.lang.String,java.lang.Boolean> matchingFuncCache,final non-sealed int maxHierarchyLevel
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/rbac/LinkConditionFuncKey.java
|
LinkConditionFuncKey
|
equals
|
class LinkConditionFuncKey {
private String roleName;
private String domainName;
public LinkConditionFuncKey(String roleName, String domainName) {
this.roleName = roleName;
this.domainName = domainName;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(roleName, domainName);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LinkConditionFuncKey that = (LinkConditionFuncKey) o;
return Objects.equals(roleName, that.roleName) &&
Objects.equals(domainName, that.domainName);
| 213
| 83
| 296
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/rbac/Role.java
|
Role
|
removeMatches
|
class Role {
private final String name;
final Map<String, Role> roles;
private final Map<String, Role> users;
private final Map<String, Role> matched;
private final Map<String, Role> matchedBy;
private final Map<LinkConditionFuncKey, Function<String[], Boolean>> linkConditionFuncMap;
private final Map<LinkConditionFuncKey, String[]> linkConditionFuncParamsMap;
protected Role(String name) {
this.name = name;
this.roles = new HashMap<>();
this.users = new HashMap<>();
this.matched = new HashMap<>();
this.matchedBy = new HashMap<>();
this.linkConditionFuncMap = new HashMap<>();
this.linkConditionFuncParamsMap = new HashMap<>();
}
String getName() {
return name;
}
void addRole(Role role) {
this.roles.put(role.name, role);
role.addUser(this);
}
void removeRole(Role role) {
this.roles.remove(role.name);
role.removeUser(this);
}
private void addUser(Role user) {
this.users.put(user.name, user);
}
private void removeUser(Role user) {
this.users.remove(user.name);
}
void addMatch(Role role) {
this.matched.put(role.name, role);
role.matchedBy.put(this.name, this);
}
void removeMatch(Role role) {
this.matched.remove(role.name);
role.matchedBy.remove(this.name);
}
void removeMatches() {<FILL_FUNCTION_BODY>}
public void rangeRoles(Consumer<? super Role> fn) {
roles.forEach((key, value) -> {
Role role = (Role) value;
fn.accept(role);
role.matched.forEach((matchedKey, matchedValue) -> {
Role matchedRole = (Role) matchedValue;
fn.accept(matchedRole);
});
});
matchedBy.forEach((key, value) -> {
Role role = (Role) value;
role.roles.forEach((roleKey, roleValue) -> {
Role subRole = (Role) roleValue;
fn.accept(subRole);
});
});
}
@Override
public String toString() {
List<String> roles = getRoles();
if (roles.size() == 0) {
return "";
}
StringBuilder names = new StringBuilder();
names.append(this.name).append(" < ");
if (roles.size() != 1) {
names.append("(");
}
for (int i = 0; i < roles.size(); i++) {
String role = roles.get(i);
if (i == 0) {
names.append(role);
} else {
names.append(", ").append(role);
}
}
if (roles.size() != 1) {
names.append(")");
}
return names.toString();
}
List<String> getRoles() {
return new ArrayList<>(getAllRoles().keySet());
}
List<String> getUsers() {
return new ArrayList<>(getAllUsers().keySet());
}
Map<String, Role> getAllRoles() {
Map<String, Role> allRoles = new HashMap<>(this.roles);
this.roles.values().forEach(role -> allRoles.putAll(role.matched));
this.matchedBy.values().forEach(role -> allRoles.putAll(role.roles));
return allRoles;
}
Map<String, Role> getAllUsers() {
Map<String, Role> allUsers = new HashMap<>(this.users);
this.users.values().forEach(role -> allUsers.putAll(role.matched));
this.matchedBy.values().forEach(role -> allUsers.putAll(role.users));
return allUsers;
}
void addLinkConditionFunc(Role role, String domain, Function<String[], Boolean> fn){
linkConditionFuncMap.put(new LinkConditionFuncKey(role.name, domain), fn);
}
Function<String[], Boolean> getLinkConditionFunc(Role role, String domain){
Function<String[], Boolean> function = linkConditionFuncMap.get(new LinkConditionFuncKey(role.name, domain));
if (function == null) {
return null;
}
return linkConditionFuncMap.get(new LinkConditionFuncKey(role.name, domain));
}
void setLinkConditionFuncParams(Role role, String domain, String... params){
linkConditionFuncParamsMap.put(new LinkConditionFuncKey(role.name, domain), params);
}
String[] getLinkConditionFuncParams(Role role, String domain){
return linkConditionFuncParamsMap.get(new LinkConditionFuncKey(role.name, domain));
}
}
|
Iterator<Map.Entry<String, Role>> iterator = this.matchedBy.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Role> entry = iterator.next();
Role role = entry.getValue();
role.matched.remove(this.name);
iterator.remove();
}
| 1,328
| 92
| 1,420
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java
|
GenerateConditionalGFunctionClass
|
timeMatch
|
class GenerateConditionalGFunctionClass {
// key:name such as g,g2 value:user-role mapping
private static Map<String, Map<String, AviatorBoolean>> memorizedMap = new ConcurrentHashMap<>();
/**
* GenerateConditionalGFunction is the factory method of the g(_, _[, _]) function with conditions.
*
* @param name the name of the g(_, _) function, can be "g", "g2", ..
* @param condRm the conditional role manager used by the function.
* @return the function.
*/
public static AviatorFunction generateConditionalGFunction(String name, ConditionalRoleManager condRm) {
memorizedMap.put(name, new ConcurrentHashMap<>());
return new AbstractVariadicFunction() {
@Override
public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... args) {
Map<String, AviatorBoolean> memorized = memorizedMap.get(name);
int len = args.length;
if (len < 2) {
return AviatorBoolean.valueOf(false);
}
String name1 = FunctionUtils.getStringValue(args[0], env);
String name2 = FunctionUtils.getStringValue(args[1], env);
String key = "";
for (AviatorObject arg : args) {
String name = FunctionUtils.getStringValue(arg, env);
key += ";" + name;
}
AviatorBoolean value = memorized.get(key);
if (value != null) {
return value;
}
boolean hasLink;
if (condRm == null) {
hasLink = name1.equals(name2);
} else if (len == 2) {
hasLink = condRm.hasLink(name1, name2);
} else if (len == 3) {
String domain = FunctionUtils.getStringValue(args[2], env);
hasLink = condRm.hasLink(name1, name2, domain);
} else {
hasLink = false;
}
value = AviatorBoolean.valueOf(hasLink);
memorized.put(key, value);
return value;
}
@Override
public String getName() {
return name;
}
};
}
}
/**
* eval calculates the stringified boolean expression and return its result.
*
* @param eval the stringified boolean expression.
* @param env the key-value pair of the parameters in the expression.
* @param aviatorEval the AviatorEvaluatorInstance object which contains built-in functions and custom functions.
* @return the result of the eval.
*/
public static boolean eval(String eval, Map<String, Object> env, AviatorEvaluatorInstance aviatorEval) {
boolean res;
if (aviatorEval != null) {
try {
res = (boolean) aviatorEval.execute(eval, env);
} catch (Exception e) {
Util.logPrintfWarn("Execute 'eval' function error, nested exception is: {}", e.getMessage());
res = false;
}
} else {
res = (boolean) AviatorEvaluator.execute(eval, env);
}
return res;
}
// builtin LinkConditionFunc
/**
* timeMatchFunc is the wrapper for TimeMatch.
*/
public static boolean timeMatchFunc(String... args) {
try {
validateVariadicStringArgs(2, args);
return timeMatch(args[0], args[1]);
} catch (IllegalArgumentException e) {
System.err.println("TimeMatch: " + e.getMessage());
return false;
}
}
/**
* TimeMatch determines whether the current time is between startTime and endTime.
* You can use "_" to indicate that the parameter is ignored
*/
public static boolean timeMatch(String startTime, String endTime) {<FILL_FUNCTION_BODY>
|
LocalDateTime now = LocalDateTime.now();
if (!startTime.equals("_")) {
LocalDateTime start;
// special process for "0000" year,LocalDateTime range is 1-999999999
if (startTime.startsWith("0000")){
start = LocalDateTime.MIN;
}else {
start = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
if (!now.isAfter(start)) {
return false;
}
}
if (!endTime.equals("_")) {
LocalDateTime end;
// special process for "0000" year,LocalDateTime range is 1-999999999
if (endTime.startsWith("0000")){
end = LocalDateTime.MIN;
}else {
end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
if (!now.isBefore(end)) {
return false;
}
}
return true;
| 1,029
| 297
| 1,326
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/Glob.java
|
Glob
|
toRegexPattern
|
class Glob {
private static final String REGEX_META_CHARS = ".^$+{[]|()";
private static final String GLOB_META_CHARS = "\\*?[{";
/**
* Creates a regex pattern from the given glob expression.
*
* @param globPattern the given glob expression
* @return the regex pattern
*/
public static String toRegexPattern(String globPattern) {<FILL_FUNCTION_BODY>}
private static boolean isRegexMeta(char c) {
return REGEX_META_CHARS.indexOf(c) != -1;
}
private static boolean isGlobMeta(char c) {
return GLOB_META_CHARS.indexOf(c) != -1;
}
private static char next(String glob, int i) {
return i < glob.length() ? glob.charAt(i) : 0;
}
}
|
boolean inGroup = false;
StringBuilder regex = new StringBuilder("^");
int i = 0;
while (i < globPattern.length()) {
char c = globPattern.charAt(i++);
switch (c) {
case '\\':
// escape special characters
if (i == globPattern.length()) {
throw new PatternSyntaxException("No character to escape",
globPattern, i - 1);
}
char next = globPattern.charAt(i++);
if (isGlobMeta(next) || isRegexMeta(next)) {
regex.append('\\');
}
regex.append(next);
break;
case '/':
regex.append(c);
break;
case '[':
// don't match name separator in class
regex.append("[[^/]&&[");
if (next(globPattern, i) == '^') {
// escape the regex negation char if it appears
regex.append("\\^");
i++;
} else {
// negation
if (next(globPattern, i) == '!') {
regex.append('^');
i++;
}
// hyphen allowed at start
if (next(globPattern, i) == '-') {
regex.append('-');
i++;
}
}
boolean hasRangeStart = false;
char last = 0;
while (i < globPattern.length()) {
c = globPattern.charAt(i++);
if (c == ']') {
break;
}
if (c == '/') {
throw new PatternSyntaxException("Explicit 'name separator' in class",
globPattern, i - 1);
}
// TBD: how to specify ']' in a class?
if (c == '\\' || c == '[' || c == '&' && next(globPattern, i) == '&') {
// escape '\', '[' or "&&" for regex class
regex.append('\\');
}
regex.append(c);
if (c == '-') {
if (!hasRangeStart) {
throw new PatternSyntaxException("Invalid range",
globPattern, i - 1);
}
if ((c = next(globPattern, i++)) == 0 || c == ']') {
break;
}
if (c < last) {
throw new PatternSyntaxException("Invalid range",
globPattern, i - 3);
}
regex.append(c);
hasRangeStart = false;
} else {
hasRangeStart = true;
last = c;
}
}
if (c != ']') {
throw new PatternSyntaxException("Missing ']", globPattern, i - 1);
}
regex.append("]]");
break;
case '{':
if (inGroup) {
throw new PatternSyntaxException("Cannot nest groups",
globPattern, i - 1);
}
regex.append("(?:(?:");
inGroup = true;
break;
case '}':
if (inGroup) {
regex.append("))");
inGroup = false;
} else {
regex.append('}');
}
break;
case ',':
if (inGroup) {
regex.append(")|(?:");
} else {
regex.append(',');
}
break;
case '*':
if (next(globPattern, i) == '*') {
// crosses directory boundaries
regex.append(".*");
i++;
} else {
// within directory boundary
regex.append("[^/]*");
}
break;
case '?':
regex.append("[^/]");
break;
default:
if (isRegexMeta(c)) {
regex.append('\\');
}
regex.append(c);
}
}
if (inGroup) {
throw new PatternSyntaxException("Missing '}", globPattern, i - 1);
}
return regex.append('$').toString();
| 243
| 1,059
| 1,302
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/CustomFunction.java
|
CustomFunction
|
replaceTargets
|
class CustomFunction extends AbstractFunction {
private AviatorEvaluatorInstance aviatorEval;
public String replaceTargets(String exp, Map<String, Object> env) {<FILL_FUNCTION_BODY>}
public AviatorEvaluatorInstance getAviatorEval() {
return aviatorEval;
}
public void setAviatorEval(AviatorEvaluatorInstance aviatorEval) {
this.aviatorEval = aviatorEval;
}
}
|
//Replace the first dot, because it can't be recognized by the 'reg' below.
if (exp.startsWith( "r") || exp.startsWith( "p")) {
exp = exp.replaceFirst("\\.","_");
}
//match example: "&&r.","||r.","=r."
String reg = "([| =)(&<>,+\\-*/!])((r|p)[0-9]*)\\.";
exp = exp.replaceAll(reg,"$1$2_");
return exp;
| 135
| 139
| 274
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/EvalFunc.java
|
EvalFunc
|
call
|
class EvalFunc extends CustomFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "eval";
}
}
|
String eval = FunctionUtils.getStringValue(arg1, env);
eval = replaceTargets(eval, env);
return AviatorBoolean.valueOf(BuiltInFunctions.eval(eval, env, getAviatorEval()));
| 75
| 63
| 138
|
<methods>public non-sealed void <init>() ,public AviatorEvaluatorInstance getAviatorEval() ,public java.lang.String replaceTargets(java.lang.String, Map<java.lang.String,java.lang.Object>) ,public void setAviatorEval(AviatorEvaluatorInstance) <variables>private AviatorEvaluatorInstance aviatorEval
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/GlobMatchFunc.java
|
GlobMatchFunc
|
call
|
class GlobMatchFunc extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "globMatch";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.globMatch(key1, key2));
| 83
| 64
| 147
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/IPMatchFunc.java
|
IPMatchFunc
|
call
|
class IPMatchFunc extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "ipMatch";
}
}
|
String ip1 = FunctionUtils.getStringValue(arg1, env);
String ip2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.ipMatch(ip1, ip2));
| 82
| 64
| 146
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyGet2Func.java
|
KeyGet2Func
|
call
|
class KeyGet2Func extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyGet2";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
String pathVar = FunctionUtils.getStringValue(arg3, env);
return new AviatorString(BuiltInFunctions.keyGet2Func(key1, key2, pathVar));
| 91
| 84
| 175
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyGetFunc.java
|
KeyGetFunc
|
call
|
class KeyGetFunc extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyGet";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return new AviatorString(BuiltInFunctions.keyGetFunc(key1, key2));
| 82
| 63
| 145
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyMatch2Func.java
|
KeyMatch2Func
|
call
|
class KeyMatch2Func extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyMatch2";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.keyMatch2(key1, key2));
| 84
| 65
| 149
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyMatch3Func.java
|
KeyMatch3Func
|
call
|
class KeyMatch3Func extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyMatch3";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.keyMatch3(key1, key2));
| 84
| 65
| 149
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyMatch4Func.java
|
KeyMatch4Func
|
call
|
class KeyMatch4Func extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyMatch4";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.keyMatch4(key1, key2));
| 84
| 65
| 149
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyMatch5Func.java
|
KeyMatch5Func
|
call
|
class KeyMatch5Func extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyMatch5";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.keyMatch5(key1, key2));
| 85
| 65
| 150
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/KeyMatchFunc.java
|
KeyMatchFunc
|
call
|
class KeyMatchFunc extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "keyMatch";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.keyMatch(key1, key2));
| 82
| 64
| 146
|
<no_super_class>
|
casbin_jcasbin
|
jcasbin/src/main/java/org/casbin/jcasbin/util/function/RegexMatchFunc.java
|
RegexMatchFunc
|
call
|
class RegexMatchFunc extends AbstractFunction {
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "regexMatch";
}
}
|
String key1 = FunctionUtils.getStringValue(arg1, env);
String key2 = FunctionUtils.getStringValue(arg2, env);
return AviatorBoolean.valueOf(BuiltInFunctions.regexMatch(key1, key2));
| 79
| 64
| 143
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/executor/MqThreadExecutor.java
|
MqThreadExecutor
|
mqQueue4PayOrderMchNotifyExecutor
|
class MqThreadExecutor {
public static final String EXECUTOR_PAYORDER_MCH_NOTIFY = "mqQueue4PayOrderMchNotifyExecutor";
/*
* 功能描述:
* 支付结果通知到商户的异步执行器 (由于量大, 单独新建一个线程池处理, 之前的不做变动 )
* 20, 300, 10, 60 该配置: 同一时间最大并发量300,(已经验证通过, 商户都可以收到请求消息)
* 缓存队列尽量减少,否则将堵塞在队列中无法执行。 corePoolSize 根据机器的配置进行添加。此处设置的为20
*/
@Bean
public Executor mqQueue4PayOrderMchNotifyExecutor() {<FILL_FUNCTION_BODY>}
}
|
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20); // 线程池维护线程的最少数量
executor.setMaxPoolSize(300); // 线程池维护线程的最大数量
executor.setQueueCapacity(10); // 缓存队列
executor.setThreadNamePrefix("payOrderMchNotifyExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(60); // 允许的空闲时间
executor.initialize();
return executor;
| 231
| 223
| 454
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/activemq/ActiveMQConfig.java
|
ActiveMQConfig
|
init
|
class ActiveMQConfig {
Map<String, Destination> map = new ConcurrentHashMap<>();
public Destination getDestination(AbstractMQ mqModel){
if(map.get(mqModel.getMQName()) == null){
this.init(mqModel.getMQName(), mqModel.getMQType());
}
return map.get(mqModel.getMQName());
}
private synchronized void init(String mqName, MQSendTypeEnum mqSendTypeEnum){<FILL_FUNCTION_BODY>}
public static final String TOPIC_LISTENER_CONTAINER = "jmsTopicListenerContainer";
/** 新增jmsListenerContainer, 用于接收topic类型的消息 **/
@Bean
public JmsListenerContainerFactory<?> jmsTopicListenerContainer(ConnectionFactory factory){
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
bean.setPubSubDomain(true);
bean.setConnectionFactory(factory);
return bean;
}
}
|
if(mqSendTypeEnum == MQSendTypeEnum.QUEUE){
map.put(mqName, new ActiveMQQueue(mqName) );
}else{
map.put(mqName, new ActiveMQTopic(mqName) );
}
| 272
| 74
| 346
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/activemq/ActiveMQSender.java
|
ActiveMQSender
|
send
|
class ActiveMQSender implements IMQSender {
@Autowired
private ActiveMQConfig activeMQConfig;
@Autowired
private JmsTemplate jmsTemplate;
@Override
public void send(AbstractMQ mqModel) {
jmsTemplate.convertAndSend(activeMQConfig.getDestination(mqModel), mqModel.toMessage());
}
@Override
public void send(AbstractMQ mqModel, int delay) {<FILL_FUNCTION_BODY>}
}
|
jmsTemplate.send(activeMQConfig.getDestination(mqModel), session -> {
TextMessage tm = session.createTextMessage(mqModel.toMessage());
tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay * 1000);
tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1*1000);
tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
return tm;
});
| 138
| 153
| 291
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/aliyunrocketmq/AliYunRocketMQFactory.java
|
AliYunRocketMQFactory
|
broadcastConsumerClient
|
class AliYunRocketMQFactory {
public static final String defaultTag = "Default";
@Value("${aliyun-rocketmq.namesrvAddr:}")
public String namesrvAddr;
@Value("${aliyun-rocketmq.accessKey}")
private String accessKey;
@Value("${aliyun-rocketmq.secretKey}")
private String secretKey;
@Value("${aliyun-rocketmq.groupId}")
private String groupId;
@Bean(name = "producerClient")
public Producer producerClient() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.GROUP_ID, groupId);
properties.put(PropertyKeyConst.AccessKey, accessKey);
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 判断是否为空(生产环境走k8s集群环境变量自动注入,不获取本地配置文件的值)
if (StringUtils.isNotEmpty(namesrvAddr)) {
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
}
return ONSFactory.createProducer(properties);
}
@Bean(name = "consumerClient")
public Consumer consumerClient() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.GROUP_ID, groupId);
properties.put(PropertyKeyConst.AccessKey, accessKey);
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 判断是否为空(生产环境走k8s集群环境变量自动注入,不获取本地配置文件的值)
if (StringUtils.isNotEmpty(namesrvAddr)) {
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
}
return ONSFactory.createConsumer(properties);
}
@Bean(name = "broadcastConsumerClient")
public Consumer broadcastConsumerClient() {<FILL_FUNCTION_BODY>}
}
|
Properties properties = new Properties();
properties.put(PropertyKeyConst.GROUP_ID, groupId);
properties.put(PropertyKeyConst.AccessKey, accessKey);
properties.put(PropertyKeyConst.SecretKey, secretKey);
// 广播订阅方式设置
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
// 判断是否为空(生产环境走k8s集群环境变量自动注入,不获取本地配置文件的值)
if (StringUtils.isNotEmpty(namesrvAddr)) {
properties.put(PropertyKeyConst.NAMESRV_ADDR, namesrvAddr);
}
return ONSFactory.createConsumer(properties);
| 515
| 182
| 697
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/aliyunrocketmq/AliYunRocketMQSender.java
|
AliYunRocketMQSender
|
send
|
class AliYunRocketMQSender implements IMQSender {
/** 最大延迟24小时 */
private static final int MAX_DELAY_TIME = 60 * 60 * 24;
/** 最小延迟1秒 */
private static final int MIN_DELAY_TIME = 1;
@Autowired
private AliYunRocketMQFactory aliYunRocketMQFactory;
private Producer producerClient;
@Override
public void send(AbstractMQ mqModel) {
Message message = new Message(mqModel.getMQName(), AliYunRocketMQFactory.defaultTag, mqModel.toMessage().getBytes());
sendMessage(message);
}
@Override
public void send(AbstractMQ mqModel, int delaySeconds) {<FILL_FUNCTION_BODY>}
private void sendMessage(Message message) {
if (producerClient == null) {
producerClient = aliYunRocketMQFactory.producerClient();
}
producerClient.start();
SendResult sendResult = producerClient.send(message);
log.info("消息队列推送返回结果:{}", JSONObject.toJSONString(sendResult));
}
/**
* 检查延迟时间的有效性并返回校正后的延迟时间
**/
private int delayTimeCorrector(int delay) {
if (delay < MIN_DELAY_TIME) {
return MIN_DELAY_TIME;
}
if (delay > MAX_DELAY_TIME) {
return MAX_DELAY_TIME;
}
return delay;
}
}
|
Message message = new Message(mqModel.getMQName(), AliYunRocketMQFactory.defaultTag, mqModel.toMessage().getBytes());
if (delaySeconds > 0) {
long delayTime = System.currentTimeMillis() + delayTimeCorrector(delaySeconds) * 1000;
// 设置消息需要被投递的时间。
message.setStartDeliverTime(delayTime);
}
sendMessage(message);
| 422
| 119
| 541
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/rabbitmq/RabbitMQBeanProcessor.java
|
RabbitMQBeanProcessor
|
delayedExchange
|
class RabbitMQBeanProcessor implements BeanDefinitionRegistryPostProcessor {
/** bean注册器 **/
protected BeanDefinitionRegistry beanDefinitionRegistry;
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
this.beanDefinitionRegistry = beanDefinitionRegistry;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
/** 自定义交换机: 用于延迟消息 **/
@Bean(name = RabbitMQConfig.DELAYED_EXCHANGE_NAME)
CustomExchange delayedExchange() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> args = new HashMap<>();
args.put("x-delayed-type", "direct");
return new CustomExchange(RabbitMQConfig.DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, args);
| 181
| 73
| 254
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/rabbitmq/RabbitMQConfig.java
|
RabbitMQConfig
|
init
|
class RabbitMQConfig {
/** 全局定义延迟交换机名称 **/
public static final String DELAYED_EXCHANGE_NAME = "delayedExchange";
/** 扇形交换机前缀(activeMQ中的topic模式), 需根据queue动态拼接 **/
public static final String FANOUT_EXCHANGE_NAME_PREFIX = "fanout_exchange_";
/** 注入延迟交换机Bean **/
@Autowired
@Qualifier(DELAYED_EXCHANGE_NAME)
private CustomExchange delayedExchange;
/** 注入rabbitMQBeanProcessor **/
@Autowired
private RabbitMQBeanProcessor rabbitMQBeanProcessor;
/** 在全部bean注册完成后再执行 **/
@PostConstruct
public void init(){<FILL_FUNCTION_BODY>}
}
|
// 获取到所有的MQ定义
Set<Class<?>> set = ClassUtil.scanPackageBySuper(ClassUtil.getPackage(AbstractMQ.class), AbstractMQ.class);
for (Class<?> aClass : set) {
// 实例化
AbstractMQ amq = (AbstractMQ) ReflectUtil.newInstance(aClass);
// 注册Queue === new Queue(name), queue名称/bean名称 = mqName
rabbitMQBeanProcessor.beanDefinitionRegistry.registerBeanDefinition(amq.getMQName(),
BeanDefinitionBuilder.rootBeanDefinition(Queue.class).addConstructorArgValue(amq.getMQName()).getBeanDefinition());
// 广播模式
if(amq.getMQType() == MQSendTypeEnum.BROADCAST){
// 动态注册交换机, 交换机名称/bean名称 = FANOUT_EXCHANGE_NAME_PREFIX + amq.getMQName()
rabbitMQBeanProcessor.beanDefinitionRegistry.registerBeanDefinition(FANOUT_EXCHANGE_NAME_PREFIX +amq.getMQName(),
BeanDefinitionBuilder.genericBeanDefinition(FanoutExchange.class, () ->{
// 普通FanoutExchange 交换机
return new FanoutExchange(FANOUT_EXCHANGE_NAME_PREFIX +amq.getMQName(),true,false);
// 支持 延迟的 FanoutExchange 交换机, 配置无效果。
// Map<String, Object> args = new HashMap<>();
// args.put("x-delayed-type", ExchangeTypes.FANOUT);
// return new CustomExchange(RabbitMQConfig.DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, args);
}
).getBeanDefinition()
);
}else{
// 延迟交换机与Queue进行绑定, 绑定Bean名称 = mqName_DelayedBind
rabbitMQBeanProcessor.beanDefinitionRegistry.registerBeanDefinition(amq.getMQName() + "_DelayedBind",
BeanDefinitionBuilder.genericBeanDefinition(Binding.class, () ->
BindingBuilder.bind(SpringBeansUtil.getBean(amq.getMQName(), Queue.class)).to(delayedExchange).with(amq.getMQName()).noargs()
).getBeanDefinition()
);
}
}
| 234
| 636
| 870
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/rabbitmq/RabbitMQSender.java
|
RabbitMQSender
|
send
|
class RabbitMQSender implements IMQSender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public void send(AbstractMQ mqModel) {<FILL_FUNCTION_BODY>}
@Override
public void send(AbstractMQ mqModel, int delay) {
if(mqModel.getMQType() == MQSendTypeEnum.QUEUE){
rabbitTemplate.convertAndSend(RabbitMQConfig.DELAYED_EXCHANGE_NAME, mqModel.getMQName(), mqModel.toMessage(), messagePostProcessor ->{
messagePostProcessor.getMessageProperties().setDelay(Math.toIntExact(delay * 1000));
return messagePostProcessor;
});
}else{
// fanout模式 的 routeKEY 没意义。 没有延迟属性
this.rabbitTemplate.convertAndSend(RabbitMQConfig.FANOUT_EXCHANGE_NAME_PREFIX + mqModel.getMQName(), null, mqModel.toMessage());
}
}
}
|
if(mqModel.getMQType() == MQSendTypeEnum.QUEUE){
rabbitTemplate.convertAndSend(mqModel.getMQName(), mqModel.toMessage());
}else{
// fanout模式 的 routeKEY 没意义。
this.rabbitTemplate.convertAndSend(RabbitMQConfig.FANOUT_EXCHANGE_NAME_PREFIX + mqModel.getMQName(), null, mqModel.toMessage());
}
| 282
| 127
| 409
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-mq/src/main/java/com/jeequan/jeepay/components/mq/vender/rocketmq/RocketMQSender.java
|
RocketMQSender
|
getNearDelayLevel
|
class RocketMQSender implements IMQSender {
private static final List<Integer> DELAY_TIME_LEVEL = new ArrayList<>();
static{
// 预设值的延迟时间间隔为:1s、 5s、 10s、 30s、 1m、 2m、 3m、 4m、 5m、 6m、 7m、 8m、 9m、 10m、 20m、 30m、 1h、 2h
DELAY_TIME_LEVEL.add(1);
DELAY_TIME_LEVEL.add(5);
DELAY_TIME_LEVEL.add(10);
DELAY_TIME_LEVEL.add(30);
DELAY_TIME_LEVEL.add(60 * 1);
DELAY_TIME_LEVEL.add(60 * 2);
DELAY_TIME_LEVEL.add(60 * 3);
DELAY_TIME_LEVEL.add(60 * 4);
DELAY_TIME_LEVEL.add(60 * 5);
DELAY_TIME_LEVEL.add(60 * 6);
DELAY_TIME_LEVEL.add(60 * 7);
DELAY_TIME_LEVEL.add(60 * 8);
DELAY_TIME_LEVEL.add(60 * 9);
DELAY_TIME_LEVEL.add(60 * 10);
DELAY_TIME_LEVEL.add(60 * 20);
DELAY_TIME_LEVEL.add(60 * 30);
DELAY_TIME_LEVEL.add(60 * 60 * 1);
DELAY_TIME_LEVEL.add(60 * 60 * 2);
}
@Autowired private RocketMQTemplate rocketMQTemplate;
@Override
public void send(AbstractMQ mqModel) {
rocketMQTemplate.convertAndSend(mqModel.getMQName(), mqModel.toMessage());
}
@Override
public void send(AbstractMQ mqModel, int delay) {
// RocketMQ不支持自定义延迟时间, 需要根据传入的参数进行最近的匹配。
rocketMQTemplate.syncSend(mqModel.getMQName(), MessageBuilder.withPayload(mqModel.toMessage()).build(),300000, getNearDelayLevel(delay));
}
/** 获取最接近的节点值 **/
private int getNearDelayLevel(int delay){<FILL_FUNCTION_BODY>}
}
|
// 如果包含则直接返回
if(DELAY_TIME_LEVEL.contains(delay)){
return DELAY_TIME_LEVEL.indexOf(delay) + 1;
}
//两个时间的绝对值 - 位置
TreeMap<Integer, Integer> resultMap = new TreeMap<>();
DELAY_TIME_LEVEL.stream().forEach(time -> resultMap.put(Math.abs(delay - time), DELAY_TIME_LEVEL.indexOf(time) + 1));
return resultMap.firstEntry().getValue();
| 671
| 136
| 807
|
<no_super_class>
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-oss/src/main/java/com/jeequan/jeepay/components/oss/ctrl/OssFileController.java
|
OssFileController
|
singleFileUpload
|
class OssFileController extends AbstractCtrl {
@Autowired private IOssService ossService;
/** 上传文件 (单文件上传) */
@PostMapping("/{bizType}")
public ApiRes singleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable("bizType") String bizType) {<FILL_FUNCTION_BODY>}
}
|
if( file == null ) {
return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "选择文件不存在");
}
try {
OssFileConfig ossFileConfig = OssFileConfig.getOssFileConfigByBizType(bizType);
//1. 判断bizType 是否可用
if(ossFileConfig == null){
throw new BizException("类型有误");
}
// 2. 判断文件是否支持
String fileSuffix = FileKit.getFileSuffix(file.getOriginalFilename(), false);
if( !ossFileConfig.isAllowFileSuffix(fileSuffix) ){
throw new BizException("上传文件格式不支持!");
}
// 3. 判断文件大小是否超限
if( !ossFileConfig.isMaxSizeLimit(file.getSize()) ){
throw new BizException("上传大小请限制在["+ossFileConfig.getMaxSize() / 1024 / 1024 +"M]以内!");
}
// 新文件地址 (xxx/xxx.jpg 格式)
String saveDirAndFileName = bizType + "/" + UUID.fastUUID() + "." + fileSuffix;
String url = ossService.upload2PreviewUrl(ossFileConfig.getOssSavePlaceEnum(), file, saveDirAndFileName);
return ApiRes.ok(url);
} catch (BizException biz) {
throw biz;
} catch (Exception e) {
logger.error("upload error, fileName = {}", file.getOriginalFilename(), e);
throw new BizException(ApiCodeEnum.SYSTEM_ERROR);
}
| 104
| 440
| 544
|
<methods>public non-sealed void <init>() ,public java.lang.Long getAmountL(java.lang.String) ,public java.lang.String getClientIp() ,public java.lang.Long getRequiredAmountL(java.lang.String) ,public java.lang.String getUserAgent() ,public transient void handleParamAmount(java.lang.String[]) ,public Map<java.lang.String,java.lang.Object> request2payResponseMap(HttpServletRequest, java.lang.String[]) <variables>private static final int DEFAULT_PAGE_INDEX,private static final int DEFAULT_PAGE_SIZE,private static final java.lang.String PAGE_INDEX_PARAM_NAME,private static final java.lang.String PAGE_SIZE_PARAM_NAME,private static final java.lang.String SORT_FIELD_PARAM_NAME,private static final java.lang.String SORT_ORDER_FLAG_PARAM_NAME,protected static final Logger logger,protected HttpServletRequest request,protected com.jeequan.jeepay.core.beans.RequestKitBean requestKitBean,protected HttpServletResponse response
|
jeequan_jeepay
|
jeepay/jeepay-components/jeepay-components-oss/src/main/java/com/jeequan/jeepay/components/oss/model/OssFileConfig.java
|
OssFileConfig
|
isMaxSizeLimit
|
class OssFileConfig {
/** 用户头像 **/
interface BIZ_TYPE {
String AVATAR = "avatar"; /** 用户头像 **/
String IF_BG = "ifBG"; /** 接口类型卡片背景图片 **/
String CERT = "cert"; /** 接口参数 **/
}
/** 图片类型后缀格式 **/
public static final Set IMG_SUFFIX = new HashSet(Arrays.asList("jpg", "png", "jpeg", "gif"));
/** 全部后缀格式的文件标识符 **/
public static final String ALL_SUFFIX_FLAG = "*";
/** 不校验文件大小标识符 **/
public static final Long ALL_MAX_SIZE = -1L;
/** 允许上传的最大文件大小的默认值 **/
public static final Long DEFAULT_MAX_SIZE = 5 * 1024 * 1024L;
private static final Map<String, OssFileConfig> ALL_BIZ_TYPE_MAP = new HashMap<>();
static{
ALL_BIZ_TYPE_MAP.put(BIZ_TYPE.AVATAR, new OssFileConfig(OssSavePlaceEnum.PUBLIC, IMG_SUFFIX, DEFAULT_MAX_SIZE) );
ALL_BIZ_TYPE_MAP.put(BIZ_TYPE.IF_BG, new OssFileConfig(OssSavePlaceEnum.PUBLIC, IMG_SUFFIX, DEFAULT_MAX_SIZE) );
ALL_BIZ_TYPE_MAP.put(BIZ_TYPE.CERT, new OssFileConfig(OssSavePlaceEnum.PRIVATE, new HashSet<>(Arrays.asList(ALL_SUFFIX_FLAG)), DEFAULT_MAX_SIZE) );
}
/** 存储位置 **/
private OssSavePlaceEnum ossSavePlaceEnum;
/** 允许的文件后缀, 默认全部类型 **/
private Set<String> allowFileSuffix = new HashSet<>(Arrays.asList(ALL_SUFFIX_FLAG));
/** 允许的文件大小, 单位: Byte **/
private Long maxSize = DEFAULT_MAX_SIZE;
/** 是否在允许的文件类型后缀内 **/
public boolean isAllowFileSuffix(String fixSuffix){
if(this.allowFileSuffix.contains(ALL_SUFFIX_FLAG)){ //允许全部
return true;
}
return this.allowFileSuffix.contains(StringUtils.defaultIfEmpty(fixSuffix, "").toLowerCase());
}
/** 是否在允许的大小范围内 **/
public boolean isMaxSizeLimit(Long fileSize){<FILL_FUNCTION_BODY>}
public static OssFileConfig getOssFileConfigByBizType(String bizType){
return ALL_BIZ_TYPE_MAP.get(bizType);
}
}
|
if(ALL_MAX_SIZE.equals(this.maxSize)){ //允许全部大小
return true;
}
return this.maxSize >= ( fileSize == null ? 0L : fileSize);
| 746
| 55
| 801
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.