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
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/password/IntuitiveHardcodePasswordDetector.java
IntuitiveHardcodePasswordDetector
getInjectionPoint
class IntuitiveHardcodePasswordDetector extends BasicInjectionDetector { private static final String HARD_CODE_PASSWORD_TYPE = "HARD_CODE_PASSWORD"; /** * Passwords in various language * http://www.indifferentlanguages.com/words/password * * The keyword is also used to detect variable name that are likely to be password (reused in AbstractHardcodedPassword). */ @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION_PKGPROTECT", justification = "It is intended to be shared with AbstractHardcodedPassword. Accidental modification of this list is unlikely.") protected static final List<String> PASSWORD_WORDS = new ArrayList<String>(); static { PASSWORD_WORDS.add("password"); PASSWORD_WORDS.add("motdepasse"); PASSWORD_WORDS.add("heslo"); PASSWORD_WORDS.add("adgangskode"); PASSWORD_WORDS.add("wachtwoord"); PASSWORD_WORDS.add("salasana"); PASSWORD_WORDS.add("passwort"); PASSWORD_WORDS.add("passord"); PASSWORD_WORDS.add("senha"); PASSWORD_WORDS.add("geslo"); PASSWORD_WORDS.add("clave"); PASSWORD_WORDS.add("losenord"); PASSWORD_WORDS.add("clave"); PASSWORD_WORDS.add("parola"); //Others PASSWORD_WORDS.add("secretkey"); PASSWORD_WORDS.add("pwd"); } public IntuitiveHardcodePasswordDetector(BugReporter bugReporter) { super(bugReporter); } @Override protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint stringValue = fact.getStackValue(offset); if (TaintUtil.isConstantValue(stringValue)) { //Is a constant value return Priorities.NORMAL_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; } } @Override protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg, InstructionHandle handle) {<FILL_FUNCTION_BODY>} }
assert invoke != null && cpg != null; String method = invoke.getMethodName(cpg); String sig = invoke.getSignature(cpg); if(sig.startsWith("(Ljava/lang/String;)")) { if(method.startsWith("set")) { // Targeting : x.setPassword("abc123") String methodLowerCase = method.toLowerCase(); for (String password : PASSWORD_WORDS) { if (methodLowerCase.contains(password)) { return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE); } } } else if(PASSWORD_WORDS.contains(method.toLowerCase())) { // Targeting : DSL().user("").password(String x) return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE); } } return InjectionPoint.NONE;
624
237
861
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/password/JschPasswordDetector.java
JschPasswordDetector
getPriorityFromTaintFrame
class JschPasswordDetector extends BasicInjectionDetector { private static final String HARD_CODE_PASSWORD_TYPE = "HARD_CODE_PASSWORD"; public JschPasswordDetector(BugReporter bugReporter) { super(bugReporter); } @Override protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException {<FILL_FUNCTION_BODY>} @Override protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg, InstructionHandle handle) { assert invoke != null && cpg != null; String className = invoke.getClassName(cpg); String method = invoke.getMethodName(cpg); String sig = invoke.getSignature(cpg); if(className.equals("com.jcraft.jsch.JSch") && method.equals("addIdentity")) { if(sig.equals("(Ljava/lang/String;Ljava/lang/String;)V") || sig.equals("(Ljava/lang/String;[B)V") || sig.equals("(Ljava/lang/String;Ljava/lang/String;[B)V") || sig.equals("(Ljava/lang/String;[B[B[B)V")){ return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE); } } return InjectionPoint.NONE; } }
Taint stringValue = fact.getStackValue(offset); if (TaintUtil.isConstantValue(stringValue)) { //Is a constant value return Priorities.NORMAL_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; }
374
78
452
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/saml/SamlIgnoreCommentsDetector.java
SamlIgnoreCommentsDetector
sawOpcode
class SamlIgnoreCommentsDetector extends OpcodeStackDetector { private static final String SAML_IGNORE_COMMENTS = "SAML_IGNORE_COMMENTS"; private static final InvokeMatcherBuilder SET_IGNORE_COMMENTS = invokeInstruction() .atClass( "org.opensaml.xml.parse.BasicParserPool", "org.opensaml.xml.parse.StaticBasicParserPool" ) .atMethod("setIgnoreComments"); private BugReporter bugReporter; public SamlIgnoreCommentsDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen == Const.INVOKEVIRTUAL && SET_IGNORE_COMMENTS.matches(this)) { final OpcodeStack.Item item = stack.getStackItem(0); /* item has signature of Integer, check "instanceof" added to prevent cast from throwing exceptions */ if (StackUtils.isConstantInteger(item) && (Integer) item.getConstant() == 0) { bugReporter.reportBug(new BugInstance(this, SAML_IGNORE_COMMENTS, Priorities.HIGH_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } }
201
169
370
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/scala/PlayUnvalidatedRedirectDetector.java
PlayUnvalidatedRedirectDetector
sawOpcode
class PlayUnvalidatedRedirectDetector extends OpcodeStackDetector { private static final String PLAY_UNVALIDATED_REDIRECT_TYPE = "PLAY_UNVALIDATED_REDIRECT"; private static List<String> REDIRECT_METHODS = Arrays.asList("Redirect","SeeOther","MovedPermanently","TemporaryRedirect"); private BugReporter bugReporter; public PlayUnvalidatedRedirectDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
try { if(seen == Const.INVOKEVIRTUAL && REDIRECT_METHODS.contains(getNameConstantOperand())) { if("scala/runtime/AbstractFunction0".equals(getClassDescriptor().getXClass().getSuperclassDescriptor().getClassName())) { bugReporter.reportBug(new BugInstance(this, PLAY_UNVALIDATED_REDIRECT_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this).addString(getNameConstantOperand())); // } } } catch (CheckedAnalysisException e) { }
170
165
335
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/scala/ScalaSensitiveDataExposureDetector.java
ScalaSensitiveDataExposureDetector
getPriority
class ScalaSensitiveDataExposureDetector extends BasicInjectionDetector { private static final String SCALA_SENSITIVE_DATA_EXPOSURE_TYPE = "SCALA_SENSITIVE_DATA_EXPOSURE"; public ScalaSensitiveDataExposureDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("sensitive-data-exposure-scala.txt", SCALA_SENSITIVE_DATA_EXPOSURE_TYPE); } @Override protected int getPriority(Taint taint) {<FILL_FUNCTION_BODY>} }
// If this call doesn't contain any sensitive data - There is no reason to report it. if (!taint.hasTag(Taint.Tag.SENSITIVE_DATA)) { return Priorities.IGNORE_PRIORITY; } return super.getPriority(taint);
166
79
245
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/scala/SslDisablerDetector.java
SslDisablerDetector
sawOpcode
class SslDisablerDetector extends OpcodeStackDetector { private static final String WEAK_TRUST_MANAGER_TYPE = "WEAK_TRUST_MANAGER"; private static final String WEAK_HOSTNAME_VERIFIER_TYPE = "WEAK_HOSTNAME_VERIFIER"; private BugReporter bugReporter; public SslDisablerDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
// printOpCode(seen); // SslDisablerDetector: [0000] getstatic // SslDisablerDetector: [0003] invokevirtual SecurityBypasser$.destroyAllSSLSecurityForTheEntireVMForever ()V if(seen == INVOKEVIRTUAL && getClassConstantOperand().endsWith("SecurityBypasser$") && getNameConstantOperand().equals("destroyAllSSLSecurityForTheEntireVMForever")) { bugReporter.reportBug(new BugInstance(this, WEAK_TRUST_MANAGER_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } if(seen == GETSTATIC) { XField field = this.getXFieldOperand(); if(field == null) return; //It is expected that developers either build the project or copy-paste the code in a random package.. //Scala code: //1. HttpsURLConnection.setDefaultHostnameVerifier(SecurityBypasser.AllHosts); if(field.getClassName().endsWith("SecurityBypasser$AllHosts$") && field.getName().equals("MODULE$")) { bugReporter.reportBug(new BugInstance(this, WEAK_HOSTNAME_VERIFIER_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } //Scala code: //2. val trustAllCerts = Array[TrustManager](SecurityBypasser.AllTM) else if(field.getClassName().endsWith("SecurityBypasser$AllTM$") && field.getName().equals("MODULE$")) { bugReporter.reportBug(new BugInstance(this, WEAK_TRUST_MANAGER_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } }
157
519
676
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/scala/XssMvcApiDetector.java
XssMvcApiDetector
getPriorityFromTaintFrame
class XssMvcApiDetector extends BasicInjectionDetector { private static final String SCALA_XSS_MVC_API_TYPE = "SCALA_XSS_MVC_API"; // This variable is compared with a .toLowerCase() variable. Please keep this const lowercase. private static final String VULNERABLE_CONTENT_TYPE = "text/html"; public XssMvcApiDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("xss-scala-mvc-api.txt", SCALA_XSS_MVC_API_TYPE); } @Override protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException {<FILL_FUNCTION_BODY>} @Override protected int getPriority(Taint taint) { if (!taint.isSafe() && taint.hasTag(Taint.Tag.XSS_SAFE)) { if (FindSecBugsGlobalConfig.getInstance().isReportPotentialXssWrongContext()) { return Priorities.LOW_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; } } else if (!taint.isSafe() && (taint.hasOneTag(Taint.Tag.QUOTE_ENCODED, Taint.Tag.APOSTROPHE_ENCODED)) && taint.hasTag(Taint.Tag.LT_ENCODED)) { return Priorities.LOW_PRIORITY; } else { return super.getPriority(taint); } } }
Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); if ( !parameterTaint.isSafe() || VULNERABLE_CONTENT_TYPE.equalsIgnoreCase(parameterTaint.getConstantValue())) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY;
426
163
589
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/scala/XssTwirlDetector.java
XssTwirlDetector
getPriority
class XssTwirlDetector extends BasicInjectionDetector { private static final String SCALA_XSS_TWIRL_TYPE = "SCALA_XSS_TWIRL"; public XssTwirlDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("xss-scala-twirl.txt", SCALA_XSS_TWIRL_TYPE); } @Override protected int getPriority(Taint taint) {<FILL_FUNCTION_BODY>} }
if (!taint.isSafe() && taint.hasTag(Taint.Tag.XSS_SAFE)) { if(FindSecBugsGlobalConfig.getInstance().isReportPotentialXssWrongContext()) { return Priorities.LOW_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; } } else if (!taint.isSafe() && (taint.hasOneTag(Taint.Tag.QUOTE_ENCODED, Taint.Tag.APOSTROPHE_ENCODED)) && taint.hasTag(Taint.Tag.LT_ENCODED)) { return Priorities.LOW_PRIORITY; } else { return super.getPriority(taint); }
146
201
347
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/serial/DeserializationGadgetDetector.java
DeserializationGadgetDetector
visitClassContext
class DeserializationGadgetDetector implements Detector { private static final String DESERIALIZATION_GADGET_TYPE = "DESERIALIZATION_GADGET"; private static final List<String> DANGEROUS_APIS = Arrays.asList( "java/lang/reflect/Method", // "java/lang/reflect/Constructor", // "org/springframework/beans/BeanUtils", // "org/apache/commons/beanutils/BeanUtils", // "org/apache/commons/beanutils/PropertyUtils", // "org/springframework/util/ReflectionUtils"); List<String> classesToIgnoreInReadObjectMethod = Arrays.asList("java/io/ObjectInputStream","java/lang/Object"); private final BugReporter bugReporter; private static final List<String> READ_DESERIALIZATION_METHODS = Arrays.asList("readObject", // "readUnshared", "readArray", "readResolve"); public DeserializationGadgetDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) {<FILL_FUNCTION_BODY>} /** * Check if the readObject is doing multiple external call beyond the basic readByte, readBoolean, etc.. * @param m * @param classContext * @return * @throws CFGBuilderException * @throws DataflowAnalysisException */ private boolean hasCustomReadObject(Method m, ClassContext classContext,List<String> classesToIgnore) throws CFGBuilderException, DataflowAnalysisException { ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); int count = 0; for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //ByteCode.printOpCode(inst,cpg); if(inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; if (!READ_DESERIALIZATION_METHODS.contains(invoke.getMethodName(cpg)) && !classesToIgnore.contains(invoke.getClassName(cpg))) { count +=1; } } } return count > 3; } @Override public void report() { } }
JavaClass javaClass = classContext.getJavaClass(); boolean isSerializable = InterfaceUtils.isSubtype(javaClass, "java.io.Serializable"); boolean isInvocationHandler = InterfaceUtils.isSubtype(javaClass, "java.lang.reflect.InvocationHandler"); boolean useDangerousApis = false; boolean customReadObjectMethod = false; boolean customInvokeMethod = false; boolean hasMethodField = false; if (!isSerializable) { return; //Nothing to see, move on. } for (Constant c : javaClass.getConstantPool().getConstantPool()) { if (c instanceof ConstantUtf8) { ConstantUtf8 utf8 = (ConstantUtf8) c; String constantValue = String.valueOf(utf8.getBytes()); //System.out.println(constantValue); if (DANGEROUS_APIS.contains(constantValue)) { useDangerousApis = true; break; } } } for (Method m : javaClass.getMethods()) { if (!customReadObjectMethod && READ_DESERIALIZATION_METHODS.contains(m.getName())) { try { customReadObjectMethod = hasCustomReadObject(m, classContext, classesToIgnoreInReadObjectMethod); } catch (CFGBuilderException | DataflowAnalysisException e) { AnalysisContext.logError("Cannot check custom read object", e); } } else if (!customInvokeMethod && "invoke".equals(m.getName())) { try { customInvokeMethod = hasCustomReadObject(m, classContext, classesToIgnoreInReadObjectMethod); } catch (CFGBuilderException | DataflowAnalysisException e) { AnalysisContext.logError("Cannot check custom read object", e); } } } for (Field f : javaClass.getFields()) { if ((f.getName().toLowerCase().contains("method") && f.getType().equals(new ObjectType("java.lang.String"))) || f.getType().equals(new ObjectType("java.reflect.Method"))) { hasMethodField = true; } } if ((isSerializable && customReadObjectMethod) || (isInvocationHandler && customInvokeMethod)) { int priority = useDangerousApis ? Priorities.NORMAL_PRIORITY : Priorities.LOW_PRIORITY; bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_GADGET_TYPE, priority) // .addClass(javaClass)); } else if (isSerializable && hasMethodField && useDangerousApis) { bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_GADGET_TYPE, Priorities.LOW_PRIORITY) // .addClass(javaClass)); }
632
716
1,348
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/serial/ObjectDeserializationDetector.java
ObjectDeserializationDetector
analyzeMethod
class ObjectDeserializationDetector implements Detector { private static final String OBJECT_DESERIALIZATION_TYPE = "OBJECT_DESERIALIZATION"; private BugReporter bugReporter; private static List<String> OBJECT_INPUTSTREAM_READ_METHODS = Arrays.asList("readObject", // "readUnshared", "readArray"); public ObjectDeserializationDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { try { if((OBJECT_INPUTSTREAM_READ_METHODS.contains(m.getName()) && InterfaceUtils.isSubtype(javaClass, "java.io.Serializable")) || (InterfaceUtils.isSubtype(javaClass, "java.lang.reflect.InvocationHandler"))) { continue; } analyzeMethod(m,classContext); } catch (CFGBuilderException e) { } catch (DataflowAnalysisException e) { } } } private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {<FILL_FUNCTION_BODY>} @Override public void report() { } }
MethodGen methodGen = classContext.getMethodGen(m); ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); if (methodGen == null || methodGen.getInstructionList() == null) { return; //No instruction .. nothing to do } for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); // if (inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; String className = invoke.getClassName(cpg); if ("java.io.ObjectInputStream".equals(className) || className.contains("InputStream") || InterfaceUtils.isSubtype(className, "java.io.ObjectInputStream") || InterfaceUtils.isSubtype(className, "java.io.ObjectInput")) { if(className.equals("org.bouncycastle.asn1.ASN1InputStream")) { //This class has a readObject method continue; } String methodName = invoke.getMethodName(cpg); if (OBJECT_INPUTSTREAM_READ_METHODS.contains(methodName)) { JavaClass clz = classContext.getJavaClass(); bugReporter.reportBug(new BugInstance(this, OBJECT_DESERIALIZATION_TYPE, HIGH_PRIORITY) // .addClass(clz).addMethod(clz, m).addSourceLine(classContext,m,location)); } } } }
381
422
803
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/serial/UnsafeJacksonDeserializationDetector.java
UnsafeJacksonDeserializationDetector
analyzeField
class UnsafeJacksonDeserializationDetector implements Detector { private static final String DESERIALIZATION_TYPE = "JACKSON_UNSAFE_DESERIALIZATION"; private BugReporter bugReporter; public UnsafeJacksonDeserializationDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } private static final List<String> ANNOTATION_TYPES = Arrays.asList( "Lcom/fasterxml/jackson/annotation/JsonTypeInfo;"); private static final List<String> VULNERABLE_USE_NAMES = Arrays.asList( "CLASS", "MINIMAL_CLASS"); private static final List<String> OBJECT_MAPPER_CLASSES = Arrays.asList( "com.fasterxml.jackson.databind.ObjectMapper", "org.codehaus.jackson.map.ObjectMapper"); @Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); if (OBJECT_MAPPER_CLASSES.contains(javaClass.getClassName())) { return; } for (Field field : javaClass.getFields()) { analyzeField(field, javaClass); } for (Method m : javaClass.getMethods()) { try { analyzeMethod(m, classContext); } catch (CFGBuilderException | DataflowAnalysisException e) { } } } private void analyzeField(Field field, JavaClass javaClass) {<FILL_FUNCTION_BODY>} private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException { MethodGen methodGen = classContext.getMethodGen(m); ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); if (methodGen == null || methodGen.getInstructionList() == null) { return; //No instruction .. nothing to do } for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); if (inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; String methodName = invoke.getMethodName(cpg); if ("enableDefaultTyping".equals(methodName)) { JavaClass clz = classContext.getJavaClass(); bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY) .addClass(clz) .addMethod(clz, m) .addCalledMethod(cpg, invoke) .addSourceLine(classContext, m, location) ); } } } } @Override public void report() { } }
for (AnnotationEntry annotation : field.getAnnotationEntries()) { if (ANNOTATION_TYPES.contains(annotation.getAnnotationType()) || annotation.getAnnotationType().contains("JsonTypeInfo")) { for (ElementValuePair elementValuePair : annotation.getElementValuePairs()) { if ("use".equals((elementValuePair.getNameString())) && VULNERABLE_USE_NAMES.contains(elementValuePair.getValue().stringifyValue())) { bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY) .addClass(javaClass) .addString(javaClass.getClassName() + " on field " + field.getName() + " of type " + field.getType() + " annotated with " + annotation.toShortString()) .addField(FieldAnnotation.fromBCELField(javaClass, field)) .addString("") ); } } } }
762
250
1,012
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/spring/CorsRegistryCORSDetector.java
CorsRegistryCORSDetector
getStringArray
class CorsRegistryCORSDetector extends OpcodeStackDetector { private BugReporter bugReporter; public CorsRegistryCORSDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) { //printOpCode(seen); if (seen == Const.INVOKEVIRTUAL && getNameConstantOperand().equals("allowedOrigins")) { if ("org/springframework/web/servlet/config/annotation/CorsRegistration".equals(getClassConstantOperand())) { OpcodeStack.Item item = stack.getStackItem(0); //First item on the stack is the last if(item.isArray()) { String[] strings=getStringArray(item); String pattern="*"; for (String s: strings) { if (s.equals(pattern)) { bugReporter.reportBug(new BugInstance(this, "PERMISSIVE_CORS", HIGH_PRIORITY) .addClassAndMethod(this).addSourceLine(this)); break; } } } } } } public String[] getStringArray(OpcodeStack.Item item){<FILL_FUNCTION_BODY>} public String getStringFromIdx(int idx) { Constant constant= getConstantPool().getConstant(idx); int s = ((ConstantString) constant).getStringIndex(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream=new DataOutputStream(baos); try { Constant string = getConstantPool().getConstant(s); if (string!=null) { string.dump(outputStream); } else { return null; } } catch (IOException e) { e.printStackTrace(); } return baos.toString().substring(3); } }
Integer argumentsNum = (Integer) item.getConstant(); String[] strings = new String[argumentsNum]; for (int i=0; i<argumentsNum; i++) { int idx=-5-5*i; int stringIdx=getNextCodeByte(idx); // System.out.println(stringIdx); String s=getStringFromIdx(stringIdx); // System.out.println(Arrays.toString(s.toCharArray())); strings[i]=s; } return strings;
487
137
624
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/spring/SignatureParserWithGeneric.java
SignatureParserWithGeneric
getArgumentsClasses
class SignatureParserWithGeneric { private final List<String> argumentsTypes; private final String returnType; public SignatureParserWithGeneric(String signature) { GenericSignatureParser delegate = new GenericSignatureParser(signature); List<String> arguments = new ArrayList<>(); delegate.parameterSignatureIterator().forEachRemaining(arguments::add); this.argumentsTypes = Collections.unmodifiableList(arguments); this.returnType = delegate.getReturnTypeSignature(); } public List<JavaClass[]> getArgumentsClasses() {<FILL_FUNCTION_BODY>} public JavaClass[] getReturnClasses() { return typeToJavaClass(returnType); } private JavaClass[] typeToJavaClass(String signature) { if ("V".equals(signature)) { // Special case for void return new JavaClass[0]; } Type type = GenericUtilities.getType(signature); List<JavaClass> types = typeToJavaClass(type); return types.toArray(new JavaClass[types.size()]); } private List<JavaClass> typeToJavaClass(Type type) { List<JavaClass> types = new ArrayList<>(); if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; return typeToJavaClass(arrayType.getBasicType()); } else if (type instanceof GenericObjectType) { GenericObjectType genericObjectType = (GenericObjectType) type; try { types.add(Repository.lookupClass(genericObjectType.getClassName())); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } if (genericObjectType.getParameters() != null) { for (Type parameterType : genericObjectType.getParameters()) { types.addAll(typeToJavaClass(parameterType)); } } } else if (type instanceof ObjectType) { ObjectType objectType = (ObjectType) type; try { types.add(Repository.lookupClass(objectType.getClassName())); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } return types; } }
List<JavaClass[]> types = new ArrayList<>(); for(String argumentType : argumentsTypes) { if(argumentType.equals("")) continue; types.add(typeToJavaClass(argumentType)); } return types;
576
64
640
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/spring/SpringEntityLeakDetector.java
SpringEntityLeakDetector
visitClassContext
class SpringEntityLeakDetector implements Detector { private static final String ENTITY_LEAK_TYPE = "ENTITY_LEAK"; private static final String ENTITY_MASS_ASSIGNMENT_TYPE = "ENTITY_MASS_ASSIGNMENT"; private static final List<String> REQUEST_MAPPING_ANNOTATION_TYPES = Arrays.asList( "Lorg/springframework/web/bind/annotation/RequestMapping;", "Lorg/springframework/web/bind/annotation/GetMapping;", "Lorg/springframework/web/bind/annotation/PostMapping;", "Lorg/springframework/web/bind/annotation/PutMapping;", "Lorg/springframework/web/bind/annotation/DeleteMapping;", "Lorg/springframework/web/bind/annotation/PatchMapping;"); private static final List<String> ENTITY_ANNOTATION_TYPES = Arrays.asList( "Ljavax/persistence/Entity;", "Ljavax/jdo/spi/PersistenceCapable;", "Lorg/springframework/data/mongodb/core/mapping/Document;"); private BugReporter reporter; public SpringEntityLeakDetector(BugReporter bugReporter) { this.reporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) {<FILL_FUNCTION_BODY>} private boolean hasRequestMapping(Method m) { AnnotationEntry[] annotations = m.getAnnotationEntries(); m.getReturnType(); for (AnnotationEntry ae: annotations) { if (REQUEST_MAPPING_ANNOTATION_TYPES.contains(ae.getAnnotationType())) { return true; } } return false; } private List<String> getAnnotationList(JavaClass javaClass) { ArrayList<String> annotations = new ArrayList<>(); for (AnnotationEntry annotationEntry: javaClass.getAnnotationEntries()) { annotations.add(annotationEntry.getAnnotationType()); } try { for (JavaClass subclass: javaClass.getSuperClasses()) { annotations.addAll(getAnnotationList(subclass)); } } catch (Exception e) { } return annotations; } private void analyzeMethod(Method m, ClassContext classContext) { JavaClass clazz = classContext.getJavaClass(); String signature = m.getGenericSignature() == null ? m.getSignature() : m.getGenericSignature(); SignatureParserWithGeneric sig = new SignatureParserWithGeneric(signature); //Look for potential mass assignment for(JavaClass[] argument : sig.getArgumentsClasses()) { testClassesForEntityAnnotation(argument, ENTITY_MASS_ASSIGNMENT_TYPE, clazz, m); } //Look for potential leak testClassesForEntityAnnotation(sig.getReturnClasses(), ENTITY_LEAK_TYPE, clazz,m); } @Override public void report() { } private void testClassesForEntityAnnotation(JavaClass[] javaClasses,String bugType, JavaClass reportedClass, Method reportedMethod) { for(JavaClass j : javaClasses) { for (String annotation : getAnnotationList(j)) { if (ENTITY_ANNOTATION_TYPES.contains(annotation)) { BugInstance bug = new BugInstance(this, bugType, Priorities.NORMAL_PRIORITY); bug.addClassAndMethod(reportedClass, reportedMethod); reporter.reportBug(bug); break; } } } } }
JavaClass clazz = classContext.getJavaClass(); Method[] methods = clazz.getMethods(); for (Method m: methods) { if (hasRequestMapping(m)) { //We only need to analyse method with the annotation @RequestMapping analyzeMethod(m, classContext); } }
908
82
990
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/spring/SpringUnvalidatedRedirectDetector.java
SpringUnvalidatedRedirectDetector
analyzeMethod
class SpringUnvalidatedRedirectDetector implements Detector { private static final String SPRING_UNVALIDATED_REDIRECT_TYPE = "SPRING_UNVALIDATED_REDIRECT"; private static final List<String> REQUEST_MAPPING_ANNOTATION_TYPES = Arrays.asList( "Lorg/springframework/web/bind/annotation/RequestMapping;", // "Lorg/springframework/web/bind/annotation/GetMapping;", // "Lorg/springframework/web/bind/annotation/PostMapping;", // "Lorg/springframework/web/bind/annotation/PutMapping;", // "Lorg/springframework/web/bind/annotation/DeleteMapping;", // "Lorg/springframework/web/bind/annotation/PatchMapping;"); private BugReporter reporter; public SpringUnvalidatedRedirectDetector(BugReporter bugReporter) { this.reporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { JavaClass clazz = classContext.getJavaClass(); if (hasRequestMapping(clazz)) { Method[] methods = clazz.getMethods(); for (Method m: methods) { try { analyzeMethod(m, classContext); } catch (CFGBuilderException e){ } } } } private boolean hasRequestMapping(JavaClass clazz) { Method[] methods = clazz.getMethods(); for (Method m: methods) { AnnotationEntry[] annotations = m.getAnnotationEntries(); for (AnnotationEntry ae: annotations) { if (REQUEST_MAPPING_ANNOTATION_TYPES.contains(ae.getAnnotationType())) { return true; } } } return false; } private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException{<FILL_FUNCTION_BODY>} @Override public void report() { } }
JavaClass clazz = classContext.getJavaClass(); ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location loc = i.next(); Instruction inst = loc.getHandle().getInstruction(); if (inst instanceof INVOKEVIRTUAL) { INVOKEVIRTUAL invoke = (INVOKEVIRTUAL)inst; if( "java.lang.StringBuilder".equals(invoke.getClassName(cpg)) && "append".equals(invoke.getMethodName(cpg))) { Instruction prev = loc.getHandle().getPrev().getInstruction(); if (prev instanceof LDC) { LDC ldc = (LDC)prev; Object value = ldc.getValue(cpg); if (value instanceof String) { String v = (String)value; if ("redirect:".equals(v)) { BugInstance bug = new BugInstance(this, SPRING_UNVALIDATED_REDIRECT_TYPE, Priorities.NORMAL_PRIORITY); bug.addClass(clazz).addMethod(clazz,m).addSourceLine(classContext,m,loc); reporter.reportBug(bug); } } } } } }
511
362
873
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintClassConfig.java
TaintClassConfig
load
class TaintClassConfig implements TaintTypeConfig { public static final Taint.State DEFAULT_TAINT_STATE = Taint.State.NULL; private static final String IMMUTABLE = "#IMMUTABLE"; private Taint.State taintState = DEFAULT_TAINT_STATE; private boolean immutable; private String typeSignature; private static final Pattern typePattern; private static final Pattern taintConfigPattern; static { String javaIdentifierRegex = "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"; String classWithPackageRegex = javaIdentifierRegex+"(\\/"+javaIdentifierRegex+")*"; String typeRegex = "(\\[)*((L" + classWithPackageRegex + ";)|B|C|D|F|I|J|S|Z)"; typePattern = Pattern.compile(typeRegex); String taintConfigRegex = "([A-Z_]+|#IMMUTABLE|[A-Z_]+#IMMUTABLE)"; taintConfigPattern = Pattern.compile(taintConfigRegex); } public static boolean accepts(String typeSignature, String taintConfig) { return typePattern.matcher(typeSignature).matches() && taintConfigPattern.matcher(taintConfig).matches(); } /** * Loads class summary from String<br/> * <br/> * The summary should have the following syntax:<br /> * <code>defaultTaintState #IMMUTABLE</code>, where <ol> * <li><code>defaultTaintState</code> means the Taint state for type casting and return types. Usually <code>SAFE</code> is used to specify classes that cannot contain injection escape characters</li> * <li><code>#IMMUTABLE</code> flags is used for classes that cannot be subject to taint state mutation during taint analysis</li> * <li>at least one of two above are required</li> * </ol> * * Example: <br/> * <code>Ljava/lang/Boolean;:SAFE#IMMUTABLE</code><br /> * <ul> * <li>Here the summary is: <code>SAFE#IMMUTABLE</code></li> * <li>When a object is casted to Boolean or Boolean is a method result type, the taint state will be always SAFE</li> * <li>When applying taint mutation to method arguments, Boolean arguments cannot change taint state</li> * <li>Practically, Booleans cannot transfer characters that could cause injections and thus are SAFE as return types and casts</li> * </ul> * * Example: <br/> * <code>Ljava/lang/String;:#IMMUTABLE</code><br /> * <ul> * <li>String is immutable class and therefore String method arguments cannot change taint state</li> * <li>Practically, String can carry injection sensitive characters but is always immutable</li> * </ul> * * Example: <br/> * <code>Ljava/util/concurrent/atomic/AtomicBoolean;:SAFE</code><br /> * <ul> * <li>AtomicBoolean value can be changed but cannot carry injection sensitive value</li> * </ul> * * @param taintConfig <code>state#IMMUTABLE</code>, where state is one of Taint.STATE or empty * @return initialized object with taint class summary * @throws java.io.IOException for bad format of parameter * @throws NullPointerException if argument is null */ @Override public TaintClassConfig load(String taintConfig) throws IOException {<FILL_FUNCTION_BODY>} public Taint.State getTaintState() { return taintState; } public boolean isImmutable() { return immutable; } public Taint.State getTaintState(Taint.State defaultState) { if (taintState.equals(DEFAULT_TAINT_STATE)) { return defaultState; } return taintState; } /** * Set full class and method signature for the analyzed method * * @param typeSignature method signature */ public void setTypeSignature(String typeSignature) { this.typeSignature = typeSignature; } /** * Returns the analyzed method full signature * * @return signature of the method */ public String getTypeSignature() { return typeSignature; } }
if (taintConfig == null) { throw new NullPointerException("Taint config is null"); } taintConfig = taintConfig.trim(); if (taintConfig.isEmpty()) { throw new IOException("No taint class config specified"); } if (taintConfig.endsWith(IMMUTABLE)) { immutable = true; taintConfig = taintConfig.substring(0, taintConfig.length() - IMMUTABLE.length()); } if (!taintConfig.isEmpty()) { taintState = Taint.State.valueOf(taintConfig); } return this;
1,184
165
1,349
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintConfigLoader.java
TaintConfigLoader
putFromLine
class TaintConfigLoader { /** * Loads the summaries and do what is specified * * @param input input stream with configured summaries * @param receiver specifies the action for each summary when loaded * @throws IOException if cannot read the stream or the format is bad */ public void load(InputStream input, TaintConfigReceiver receiver) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); for (;;) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.isEmpty()) { continue; } putFromLine(line, receiver); } } private void putFromLine(String line, TaintConfigReceiver receiver) throws IOException {<FILL_FUNCTION_BODY>} /** * Specifies what to do for each loaded summary */ public interface TaintConfigReceiver { void receiveTaintConfig(String typeSignature, String config) throws IOException; } }
if (line.startsWith("-")) { // for comments or removing summary temporarily return; } String[] tuple = line.split("\\:"); if (tuple.length != 2) { throw new IOException("Line format is not 'type signature:config info': " + line); } receiver.receiveTaintConfig(tuple[0].trim(), tuple[1]);
274
103
377
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintFieldConfig.java
TaintFieldConfig
load
class TaintFieldConfig implements TaintTypeConfig { public static final Taint.State DEFAULT_TAINT_STATE = Taint.State.NULL; private Taint.State taintState = DEFAULT_TAINT_STATE; private String typeSignature; private static final Pattern typePattern; private static final Pattern taintConfigPattern; static { String javaIdentifierRegex = "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"; String classWithPackageRegex = javaIdentifierRegex+"(\\/"+javaIdentifierRegex+")*"; String typeRegex = classWithPackageRegex + "\\." + javaIdentifierRegex; typePattern = Pattern.compile(typeRegex); String taintConfigRegex = "([A-Z_]+)"; taintConfigPattern = Pattern.compile(taintConfigRegex); } public static boolean accepts(String typeSignature, String taintConfig) { return typePattern.matcher(typeSignature).matches() && taintConfigPattern.matcher(taintConfig).matches(); } /** * Loads class field summary from String<br/> * <br/> * The summary should have the following syntax:<br /> * <code>defaultTaintState #IMMUTABLE</code>, where <ol> * <li><code>defaultTaintState</code> means the Taint state for type casting and return types. Usually <code>SAFE</code> is used to specify classes that cannot contain injection escape characters</li> * <li><code>#IMMUTABLE</code> flags is used for classes that cannot be subject to taint state mutation during taint analysis</li> * <li>at least one of two above are required</li> * </ol> * * Example: <br/> * <code>Ljava/lang/Boolean;:SAFE#IMMUTABLE</code><br /> * <ul> * <li>Here the summary is: <code>SAFE#IMMUTABLE</code></li> * <li>When a object is casted to Boolean or Boolean is a method result type, the taint state will be always SAFE</li> * <li>When applying taint mutation to method arguments, Boolean arguments cannot change taint state</li> * <li>Practically, Booleans cannot transfer characters that could cause injections and thus are SAFE as return types and casts</li> * </ul> * * Example: <br/> * <code>Ljava/lang/String;:#IMMUTABLE</code><br /> * <ul> * <li>String is immutable class and therefore String method arguments cannot change taint state</li> * <li>Practically, String can carry injection sensitive characters but is always immutable</li> * </ul> * * Example: <br/> * <code>Ljava/util/concurrent/atomic/AtomicBoolean;:SAFE</code><br /> * <ul> * <li>AtomicBoolean value can be changed but cannot carry injection sensitive value</li> * </ul> * * @param taintConfig <code>state#IMMUTABLE</code>, where state is one of Taint.STATE or empty * @return initialized object with taint class summary * @throws IOException for bad format of parameter * @throws NullPointerException if argument is null */ @Override public TaintFieldConfig load(String taintConfig) throws IOException {<FILL_FUNCTION_BODY>} public Taint.State getTaintState() { return taintState; } public Taint.State getTaintState(Taint.State defaultState) { if (taintState.equals(DEFAULT_TAINT_STATE)) { return defaultState; } return taintState; } /** * Set full class and method signature for the analyzed method * * @param typeSignature method signature */ public void setTypeSignature(String typeSignature) { this.typeSignature = typeSignature; } /** * Returns the analyzed method full signature * * @return signature of the method */ public String getTypeSignature() { return typeSignature; } }
if (taintConfig == null) { throw new NullPointerException("Taint config is null"); } taintConfig = taintConfig.trim(); if (taintConfig.isEmpty()) { throw new IOException("No taint class config specified"); } if (!taintConfig.isEmpty()) { taintState = Taint.State.valueOf(taintConfig); } return this;
1,101
109
1,210
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintFrame.java
TaintFrame
toString
class TaintFrame extends Frame<Taint> { public TaintFrame(int numLocals) { super(numLocals); } public String toString(MethodGen method) {<FILL_FUNCTION_BODY>} @Override public String toString() { return toString(new String[getNumLocals()]); } /** * The toString method are intended for debugging. * To see the visual state of TaintFrame in IntelliJ, Right-Click on the variable and select "View Text". * * @param variableNames List of variables names that will be map to local sloths. * @return View of the stack followed by the local variables */ public String toString(String[] variableNames) { StringBuilder str = new StringBuilder(); try { str.append("+============================\n"); if(!FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) { str.append("| /!\\ Warning : The taint debugging is not fully activated.\n"); } str.append("| [[ Stack ]]\n"); int stackDepth = getStackDepth(); for (int i = 0; i < stackDepth; i++) { Taint taintValue = getStackValue(i); str.append(String.format("| %s. %s {%s}%n", i, taintValue.getState().toString(), taintValue.toString())); } if (stackDepth == 0) { str.append("| Empty\n"); } str.append("|============================\n"); str.append("| [[ Local variables ]]\n"); int nb = getNumLocals(); for (int i = 0; i < nb; i++) { Taint taintValue = getValue(i); str.append("| ").append(variableNames[i]).append(" = ") .append(taintValue == null ? "<not set>" : taintValue.toString()) .append("\n"); } str.append("+============================\n"); } catch (DataflowAnalysisException e) { str.append("Oups "+e.getMessage()); } return str.toString(); } }
String[] variables = new String[method.getLocalVariables().length]; LocalVariableGen[] variablesGen = method.getLocalVariables(); for(int i=0; i<variablesGen.length ;i++) { variables[i] = variablesGen[i].getName(); } return toString(variables);
572
84
656
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodConfigWithArgumentsAndLocation.java
TaintMethodConfigWithArgumentsAndLocation
accepts
class TaintMethodConfigWithArgumentsAndLocation extends TaintMethodConfig { private static final Pattern methodWithStringConstantOrEnumPattern; private String location; static { String javaIdentifierRegex = "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"; String classNameRegex = javaIdentifierRegex+"(\\/"+javaIdentifierRegex+")*"; String methodRegex = "(("+javaIdentifierRegex+"(\\$extension)?)|(<init>))"; // javax/servlet/http/HttpServletRequest.getAttribute("applicationConstant"):SAFE@org/apache/jsp/edit_jsp // javax/servlet/http/HttpServletRequest.getAttribute(UNKNOWN):SAFE@org/apache/jsp/constants_jsp String stringConstantRegex = "\"[^\"]*\""; String enumNameRegex = "[A-Z_]+"; String methodArguments = "(" + stringConstantRegex + ",?|" + enumNameRegex + ",?)*"; String methodWithStringConstantOrEnumRegex = classNameRegex + "\\." + methodRegex + "\\(" + methodArguments + "\\)"; methodWithStringConstantOrEnumPattern = Pattern.compile(methodWithStringConstantOrEnumRegex); } /** * Constructs an empty configured summary */ public TaintMethodConfigWithArgumentsAndLocation() { super(true); } public static boolean accepts(String typeSignature, String config) {<FILL_FUNCTION_BODY>} /** * Loads method config from String, the method config contains a current class as the context<br /> * <br /> * The method accepts syntax similar to {@link TaintMethodConfig#load(String)} with small difference.<br /> * The summary must ends with '@' character followed by class name<br /> * @param taintConfig method summary with syntax described above * @return initialized object with taint method summary * @throws IOException for bad format of parameter * @throws NullPointerException if argument is null */ @Override public TaintMethodConfigWithArgumentsAndLocation load(String taintConfig) throws IOException { if (taintConfig == null) { throw new NullPointerException("String is null"); } taintConfig = taintConfig.trim(); if (taintConfig.isEmpty()) { throw new IOException("No taint method config specified"); } int locationPos = taintConfig.lastIndexOf('@'); if (locationPos < 0) { throw new IOException("Bad format: @ expected"); } location = taintConfig.substring(locationPos + 1).trim(); taintConfig = taintConfig.substring(0, locationPos); super.load(taintConfig); return this; } public String getLocation() { return location; } }
int pos = config.lastIndexOf('@'); if (pos < 0) { return false; } config = config.substring(0, pos); return methodWithStringConstantOrEnumPattern.matcher(typeSignature).matches() && TaintMethodConfig.configPattern.matcher(config).matches();
728
86
814
<methods>public void <init>(boolean) ,public void <init>(com.h3xstream.findsecbugs.taintanalysis.TaintMethodConfig) ,public static boolean accepts(java.lang.String, java.lang.String) ,public void addMutableStackIndex(int) ,public static com.h3xstream.findsecbugs.taintanalysis.TaintMethodConfig getDefaultConstructorConfig(int) ,public Collection<java.lang.Integer> getMutableStackIndices() ,public com.h3xstream.findsecbugs.taintanalysis.Taint getOutputTaint() ,public Map<java.lang.Integer,com.h3xstream.findsecbugs.taintanalysis.Taint> getParametersOutputTaints() ,public java.lang.String getTypeSignature() ,public boolean hasMutableStackIndices() ,public boolean isConfigured() ,public boolean isInformative() ,public boolean isParametersOutputTaintsProcessed() ,public com.h3xstream.findsecbugs.taintanalysis.TaintMethodConfig load(java.lang.String) throws java.io.IOException,public void setOuputTaint(com.h3xstream.findsecbugs.taintanalysis.Taint) ,public void setParameterOutputTaint(int, com.h3xstream.findsecbugs.taintanalysis.Taint) ,public void setParametersOutputTaintsProcessed(boolean) ,public void setTypeSignature(java.lang.String) ,public java.lang.String toString() <variables>public static final non-sealed com.h3xstream.findsecbugs.taintanalysis.TaintMethodConfig SAFE_CONFIG,protected static final non-sealed java.util.regex.Pattern configPattern,protected static final non-sealed java.util.regex.Pattern fullMethodPattern,private final non-sealed boolean isConfigured,private final non-sealed Set<java.lang.Integer> mutableStackIndices,private com.h3xstream.findsecbugs.taintanalysis.Taint outputTaint,private Map<java.lang.Integer,com.h3xstream.findsecbugs.taintanalysis.Taint> parametersOutputTaints,private boolean parametersOutputTaintsProcessed,private java.lang.String typeSignature
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/data/TaintLocation.java
TaintLocation
equals
class TaintLocation { private final MethodDescriptor methodDescriptor; private final int position; /** * Constructs a location from the specified method and position inside * * @param methodDescriptor method of the location * @param position position in the method * @throws NullPointerException if method is null * @throws IllegalArgumentException if position is negative */ public TaintLocation(MethodDescriptor methodDescriptor, int position) { if (methodDescriptor == null) { throw new NullPointerException("method not specified"); } if (position < 0) { throw new IllegalArgumentException("postition is negative"); } this.methodDescriptor = methodDescriptor; this.position = position; } /** * Returns the method of this location * * @return descriptor of the method */ public MethodDescriptor getMethodDescriptor() { return methodDescriptor; } /** * Returns the position in the method of this location * * @return index of the position */ public int getPosition() { return position; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return methodDescriptor.hashCode() + 11 * position; } @Override public String toString() { return methodDescriptor.toString() + " " + position; } }
if (obj == null) { return false; } if (!(obj instanceof TaintLocation)) { return false; } final TaintLocation other = (TaintLocation) obj; return methodDescriptor.equals(other.methodDescriptor) && position == other.position;
365
75
440
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/data/UnknownSource.java
UnknownSource
hashCode
class UnknownSource { private UnknownSourceType sourceType; private int parameterIndex = -1; private String signatureMethod = ""; private String signatureField = ""; private final Taint.State state; public UnknownSource(UnknownSourceType sourceType, Taint.State state) { this.sourceType = sourceType; this.state = state; } /** Auto-generate getter and setter with the template Builder **/ public Taint.State getState() { return state; } public UnknownSourceType getSourceType() { return sourceType; } public UnknownSource setSourceType(UnknownSourceType sourceType) { this.sourceType = sourceType; return this; } public int getParameterIndex() { return parameterIndex; } public UnknownSource setParameterIndex(int parameterIndex) { this.parameterIndex = parameterIndex; return this; } public String getSignatureMethod() { return signatureMethod; } public UnknownSource setSignatureMethod(String signatureMethod) { this.signatureMethod = signatureMethod; return this; } public String getSignatureField() { return signatureField; } public UnknownSource setSignatureField(String signatureField) { this.signatureField = signatureField; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UnknownSource that = (UnknownSource) o; if (parameterIndex != that.parameterIndex) return false; if (sourceType != that.sourceType) return false; if (!signatureMethod.equals(that.signatureMethod)) return false; return signatureField.equals(that.signatureField); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { if(parameterIndex != -1) { return "Parameter (index=" + parameterIndex + ")"; } else if(!signatureMethod.equals("")) { return "Method "+signatureMethod; } else { //Field return "Field "+signatureField; } } }
int result = sourceType.hashCode(); result = 31 * result + parameterIndex; result = 31 * result + signatureMethod.hashCode(); result = 31 * result + signatureField.hashCode(); return result;
587
61
648
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/extra/JstlExpressionWhiteLister.java
JstlExpressionWhiteLister
patternsFromStream
class JstlExpressionWhiteLister extends BasicInjectionDetector implements TaintFrameAdditionalVisitor { private static final String SYSTEM_PROPERTY = "findsecbugs.jstlsafe.customregexfile"; private static final Pattern TAG_FOR_HTML_CONTENT_PATTERN = Pattern.compile("\\$\\{e:forHtmlContent\\([a-zA-Z0-9\\._]+\\)\\}"); private static final Pattern TAG_TO_SAFE_JSON_PATTERN = Pattern.compile("^\\$\\{\\s*[a-zA-Z]+:toSafeJSON\\([a-zA-Z0-9\\-#,\\\'\\\"\\&\\[\\]@\\\\ \\._\\(\\):]+\\)\\s*\\}$"); private static final Pattern TAG_SAFE_QUOTE_PATTERN = Pattern.compile("^\\$\\{\\s*[a-zA-Z]+:safeQuote\\([a-zA-Z0-9\\-#,\\\'\\\"\\&\\[\\]@\\\\ \\._\\(\\):]+\\)\\s*\\}$"); private static final String CONTEXT_PATH_PATTERN = "${pageContext.request.contextPath}"; private static final InvokeMatcherBuilder PROPRIETARY_EVALUATE = invokeInstruction() .atClass("org/apache/jasper/runtime/PageContextImpl") .atMethod("proprietaryEvaluate") .withArgs("(Ljava/lang/String;Ljava/lang/Class;Ljavax/servlet/jsp/PageContext;Lorg/apache/jasper/runtime/ProtectedFunctionMapper;)Ljava/lang/Object;"); private final List<Pattern> safePatterns; public JstlExpressionWhiteLister(BugReporter bugReporter) { super(bugReporter); this.safePatterns = getCustomPatterns(); registerVisitor(this); } @Override public void visitInvoke(InvokeInstruction invoke, MethodGen methodGen, TaintFrame frameType, List<Taint> parameters, ConstantPoolGen cpg) throws DataflowAnalysisException { if(PROPRIETARY_EVALUATE.matches(invoke,cpg)) { Taint defaultVal = parameters.get(3); //The expression is the fourth parameter starting from the right. (Top of the stack last arguments) if(defaultVal.getConstantValue() != null) { String expression = defaultVal.getConstantValue(); if(TAG_FOR_HTML_CONTENT_PATTERN.matcher(expression).find() || TAG_TO_SAFE_JSON_PATTERN.matcher(expression).find() || TAG_SAFE_QUOTE_PATTERN.matcher(expression).find() || CONTEXT_PATH_PATTERN.equals(expression)) { Taint value = frameType.getTopValue(); value.addTag(Taint.Tag.XSS_SAFE); } else { for (final Pattern safePattern : safePatterns) { if (safePattern.matcher(expression).find()) { Taint value = frameType.getTopValue(); value.addTag(Taint.Tag.XSS_SAFE); } } } } } } @Override public void visitLoad(LoadInstruction load, MethodGen methodGen, TaintFrame frameType, int numProduced, ConstantPoolGen cpg) { } @Override public void visitField(FieldInstruction put, MethodGen methodGen, TaintFrame frameType, Taint taintFrame, int numProduced, ConstantPoolGen cpg) throws Exception { } @Override public void visitReturn(MethodGen methodGen, Taint returnValue, ConstantPoolGen cpg) throws Exception { } private static List<Pattern> getCustomPatterns() { final List<Pattern> safePatterns = new ArrayList<>(); String propertyValue = FindSecBugsGlobalConfig.getInstance().loadFromSystem(SYSTEM_PROPERTY, ""); if(!propertyValue.trim().equals("")) { for (final String patternFile : propertyValue.split(File.pathSeparator)) { safePatterns.addAll(customPatternsFromFile(patternFile)); } } return safePatterns; } private static List<Pattern> customPatternsFromFile(final String path) { File file = new File(path); try (InputStream stream = file.exists() ? new FileInputStream(file) : JstlExpressionWhiteLister.class.getClassLoader().getResourceAsStream(path)) { if (stream == null) { String message = String.format("Could not add custom patterns. " + "Neither file %s nor resource matching %s found.", file.getAbsolutePath(), path); throw new IllegalArgumentException(message); } return patternsFromStream(stream); } catch (IOException ex) { throw new RuntimeException("Cannot load custom safe regex patterns from " + path, ex); } } private static List<Pattern> patternsFromStream(final InputStream stream) throws IOException {<FILL_FUNCTION_BODY>} }
final List<Pattern> patterns = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (!"".equals(line.trim())) { patterns.add(Pattern.compile(line)); } } } return patterns;
1,318
104
1,422
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/extra/PotentialValueTracker.java
PotentialValueTracker
visitInvoke
class PotentialValueTracker extends BasicInjectionDetector implements TaintFrameAdditionalVisitor { private static final InvokeMatcherBuilder PROPERTIES_GET_WITH_DEFAULT = invokeInstruction() .atClass("java/util/Properties") .atMethod("getProperty") .withArgs("(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); private static final InvokeMatcherBuilder OPTIONAL_OR = invokeInstruction() .atClass("com/google/common/base/Optional") .atMethod("or") .withArgs("(Ljava/lang/Object;)Ljava/lang/Object;"); private static final InvokeMatcherBuilder HASHMAP_GET_WITH_DEFAULT = invokeInstruction() .atClass("java/util/HashMap") .atMethod("getOrDefault") .withArgs("(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); public PotentialValueTracker(BugReporter bugReporter) { super(bugReporter); registerVisitor(this); } @Override public void visitInvoke(InvokeInstruction invoke, MethodGen methodGen, TaintFrame frameType, List<Taint> parameters, ConstantPoolGen cpg) throws DataflowAnalysisException{<FILL_FUNCTION_BODY>} @Override public void visitLoad(LoadInstruction load, MethodGen methodGen, TaintFrame frameType, int numProduced, ConstantPoolGen cpg) { } @Override public void visitField(FieldInstruction put, MethodGen methodGen, TaintFrame frameType, Taint taintFrame, int numProduced, ConstantPoolGen cpg) throws Exception { } @Override public void visitReturn(MethodGen methodGen, Taint returnValue, ConstantPoolGen cpg) throws Exception { } }
if(PROPERTIES_GET_WITH_DEFAULT.matches(invoke,cpg) || OPTIONAL_OR.matches(invoke,cpg) || HASHMAP_GET_WITH_DEFAULT.matches(invoke,cpg)) { Taint defaultVal = parameters.get(0); //Top of the stack last arguments if(defaultVal.getConstantValue() != null) { Taint value = frameType.getTopValue(); value.setPotentialValue(defaultVal.getConstantValue()); } } //ByteCode.printOpCode(invoke,cpg);
469
150
619
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/template/FreemarkerDetector.java
FreemarkerDetector
sawOpcode
class FreemarkerDetector extends OpcodeStackDetector { private static final String FREEMARKER_TYPE = "TEMPLATE_INJECTION_FREEMARKER"; private BugReporter bugReporter; public FreemarkerDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
//printOpCode(seen); // FreemarkerDetector: [0113] invokevirtual freemarker/template/Template.process (Ljava/lang/Object;Ljava/io/Writer;)V if (seen == Const.INVOKEVIRTUAL && getClassConstantOperand().equals("freemarker/template/Template") && getNameConstantOperand().equals("process")) { bugReporter.reportBug(new BugInstance(this, FREEMARKER_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); }
127
167
294
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/template/PebbleDetector.java
PebbleDetector
sawOpcode
class PebbleDetector extends OpcodeStackDetector { private static final String PEBBLE_TYPE = "TEMPLATE_INJECTION_PEBBLE"; private BugReporter bugReporter; public PebbleDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen == Const.INVOKEVIRTUAL && getClassConstantOperand().equals("com/mitchellbosecke/pebble/template/PebbleTemplate") && getNameConstantOperand().equals("evaluate")) { bugReporter.reportBug(new BugInstance(this, PEBBLE_TYPE, Priorities.NORMAL_PRIORITY) .addClass(this).addMethod(this).addSourceLine(this)); }
118
120
238
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/template/VelocityDetector.java
VelocityDetector
sawOpcode
class VelocityDetector extends OpcodeStackDetector { private static final String VELOCITY_TYPE = "TEMPLATE_INJECTION_VELOCITY"; private BugReporter bugReporter; public VelocityDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
// printOpCode(seen); if (seen == Const.INVOKESTATIC && getClassConstantOperand().equals("org/apache/velocity/app/Velocity") && getNameConstantOperand().equals("evaluate")) { OpcodeStack.Item item = stack.getStackItem(0); if(!StackUtils.isConstantString(item)) { bugReporter.reportBug(new BugInstance(this, VELOCITY_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } }
118
156
274
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/wicket/WicketXssComponentDetector.java
WicketXssComponentDetector
analyzeMethod
class WicketXssComponentDetector implements Detector { private static final boolean DEBUG = false; private static final String WIC_XSS = "WICKET_XSS1"; /** * For simplicity we don't look at the class name. The method args signature is precise enough. */ private static final InvokeMatcherBuilder COMPONENT_ESCAPE_MODEL_STRINGS = invokeInstruction() .atMethod("setEscapeModelStrings").withArgs("(Z)Lorg/apache/wicket/Component;"); private final BugReporter bugReporter; public WicketXssComponentDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); for (Method m : javaClass.getMethods()) { try { analyzeMethod(m, classContext); } catch (CFGBuilderException e) { } catch (DataflowAnalysisException e) { } } } private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {<FILL_FUNCTION_BODY>} @Override public void report() { } }
//Conditions that needs to fill to identify the vulnerability boolean escapeModelStringsSetToFalse = false; boolean escapeModelStringsValueUnknown = false; Location locationWeakness = null; ConstantPoolGen cpg = classContext.getConstantPoolGen(); CFG cfg = classContext.getCFG(m); for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //ByteCode.printOpCode(location.getHandle(),classContext.getConstantPoolGen()); if (inst instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) inst; if (COMPONENT_ESCAPE_MODEL_STRINGS.matches(invoke, cpg)) { Integer booleanValue = ByteCode.getConstantInt(location.getHandle().getPrev()); if (booleanValue != null && booleanValue == 0) { escapeModelStringsSetToFalse = true; locationWeakness = location; } else if (booleanValue == null) { escapeModelStringsValueUnknown = true; locationWeakness = location; } } } } //Both condition have been found in the same method if (escapeModelStringsSetToFalse) { JavaClass clz = classContext.getJavaClass(); bugReporter.reportBug(new BugInstance(this, WIC_XSS, Priorities.NORMAL_PRIORITY) // .addClass(clz) .addMethod(clz, m) .addSourceLine(classContext, m, locationWeakness)); } else if (escapeModelStringsValueUnknown) { JavaClass clz = classContext.getJavaClass(); bugReporter.reportBug(new BugInstance(this, WIC_XSS, Priorities.LOW_PRIORITY) // .addClass(clz) .addMethod(clz, m) .addSourceLine(classContext, m, locationWeakness)); }
334
531
865
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/EnabledExtensionsInApacheXmlRpcDetector.java
EnabledExtensionsInApacheXmlRpcDetector
sawOpcode
class EnabledExtensionsInApacheXmlRpcDetector extends OpcodeStackDetector { private static final String RPC_ENABLED_EXTENSIONS = "RPC_ENABLED_EXTENSIONS"; private static final InvokeMatcherBuilder ENABLE_EXTENSIONS = invokeInstruction() .atClass( "org.apache.xmlrpc.client.XmlRpcClientConfigImpl", "org.apache.xmlrpc.server.XmlRpcServerConfigImpl" ) .atMethod("setEnabledForExtensions"); private BugReporter bugReporter; public EnabledExtensionsInApacheXmlRpcDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen == Const.INVOKEVIRTUAL && ENABLE_EXTENSIONS.matches(this)) { final OpcodeStack.Item item = stack.getStackItem(0); /* item has signature of Integer, check "instanceof" added to prevent cast from throwing exceptions */ if ((item.getConstant() == null) || ((item.getConstant() instanceof Integer) && (((Integer) item.getConstant()).intValue() == 1))) { bugReporter.reportBug(new BugInstance(this, RPC_ENABLED_EXTENSIONS, Priorities.HIGH_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); } }
217
182
399
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/SchemaFactoryDetector.java
SchemaFactoryDetector
sawOpcode
class SchemaFactoryDetector extends OpcodeStackDetector { private static final String XXE_SCHEMA_FACTORY_TYPE = "XXE_SCHEMA_FACTORY"; private static final String SCHEMA_FACTORY_CLASS_NAME = "javax/xml/validation/SchemaFactory"; private static final String SET_FEATURE_METHOD = "setFeature"; private static final String SET_PROPERTY_METHOD = "setProperty"; private static final String NEW_SCHEMA_METHOD_NAME = "newSchema"; private static final Number BOOLEAN_TRUE_VALUE = 1; private static final String EXTERNAL_REFERENCES_DISABLED = ""; private final BugReporter bugReporter; public SchemaFactoryDetector(final BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(final int opcode) {<FILL_FUNCTION_BODY>} private boolean isNotNewSchemaMethod(final int opcode) { boolean notValidateInvocation = true; if (Const.INVOKEVIRTUAL == opcode) { final String slashedClassName = getClassConstantOperand(); final String methodName = getNameConstantOperand(); if (SCHEMA_FACTORY_CLASS_NAME.equals(slashedClassName) && NEW_SCHEMA_METHOD_NAME.equals(methodName)) { notValidateInvocation = false; } } return notValidateInvocation; } private boolean isSecureProcessingEnabled(final Location location, final ConstantPoolGen cpg) { boolean enabled = false; final Instruction instruction = location.getHandle().getInstruction(); if (instruction instanceof INVOKEVIRTUAL) { final InvokeInstruction invokeInstruction = (InvokeInstruction) instruction; final String instructionMethodName = invokeInstruction.getMethodName(cpg); final InstructionHandle handle = location.getHandle(); if (SET_FEATURE_METHOD.equals(instructionMethodName)) { final Object ldcValue = getLdcValue(handle, cpg); if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(ldcValue)) { final ICONST constant = ByteCode.getPrevInstruction(handle, ICONST.class); enabled = constant != null && BOOLEAN_TRUE_VALUE.equals(constant.getValue()); } } } return enabled; } private boolean isAccessPropertyDisabled(final Location location, final ConstantPoolGen cpg, final String accessPropertyName) { boolean enabled = false; final Instruction instruction = location.getHandle().getInstruction(); if (instruction instanceof INVOKEVIRTUAL) { final InvokeInstruction invokeInstruction = (InvokeInstruction) instruction; final String instructionMethodName = invokeInstruction.getMethodName(cpg); final InstructionHandle handle = location.getHandle(); if (SET_PROPERTY_METHOD.equals(instructionMethodName)) { final Object propertyName = getLdcValue(handle.getPrev(), cpg); final Object propertyValue = getLdcValue(handle, cpg); if (accessPropertyName.equals(propertyName)) { enabled = EXTERNAL_REFERENCES_DISABLED.equals(propertyValue); } } } return enabled; } private Object getLdcValue(final InstructionHandle instructionHandle, final ConstantPoolGen cpg) { final LDC ldc = ByteCode.getPrevInstruction(instructionHandle, LDC.class); return ldc == null ? null : ldc.getValue(cpg); } }
if (isNotNewSchemaMethod(opcode)) { return; } final ClassContext classContext = getClassContext(); final CFG cfg; try { cfg = classContext.getCFG(getMethod()); } catch (final CFGBuilderException e) { AnalysisContext.logError("Cannot get CFG", e); return; } final ConstantPoolGen cpg = classContext.getConstantPoolGen(); boolean secureProcessingEnabled = false; boolean accessExternalDtdDisabled = false; boolean accessExternalSchemaDisabled = false; for (final Location location : cfg.locations()) { if (isSecureProcessingEnabled(location, cpg)) { secureProcessingEnabled = true; } else if (isAccessPropertyDisabled(location, cpg, XMLConstants.ACCESS_EXTERNAL_DTD)) { accessExternalDtdDisabled = true; } else if (isAccessPropertyDisabled(location, cpg, XMLConstants.ACCESS_EXTERNAL_SCHEMA)) { accessExternalSchemaDisabled = true; } } // Enabling Secure Processing or disabling both Access External DTD and Access External Schema are solutions if (secureProcessingEnabled || (accessExternalDtdDisabled && accessExternalSchemaDisabled)) { return; } bugReporter.reportBug(new BugInstance(this, XXE_SCHEMA_FACTORY_TYPE, Priorities.HIGH_PRIORITY) .addClass(this).addMethod(this).addSourceLine(this));
946
401
1,347
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/TransformerFactoryDetector.java
TransformerFactoryDetector
sawOpcode
class TransformerFactoryDetector extends OpcodeStackDetector { private static final String XXE_DTD_TRANSFORM_FACTORY_TYPE = "XXE_DTD_TRANSFORM_FACTORY"; private static final String XXE_XSLT_TRANSFORM_FACTORY_TYPE = "XXE_XSLT_TRANSFORM_FACTORY"; private static final String PROPERTY_SUPPORT_DTD = "http://javax.xml.XMLConstants/property/accessExternalDTD"; private static final String PROPERTY_SUPPORT_STYLESHEET = "http://javax.xml.XMLConstants/property/accessExternalStylesheet"; private static final String PROPERTY_SECURE_PROCESSING = "http://javax.xml.XMLConstants/feature/secure-processing"; private final BugReporter bugReporter; public TransformerFactoryDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen != Const.INVOKEVIRTUAL && seen != Const.INVOKEINTERFACE && seen != Const.INVOKESTATIC) { return; } String fullClassName = getClassConstantOperand(); String method = getNameConstantOperand(); //The method call is doing XML parsing (see class javadoc) if (seen == Const.INVOKESTATIC && (fullClassName.equals("javax/xml/transform/TransformerFactory") || fullClassName.equals("javax/xml/transform/sax/SAXTransformerFactory")) && method.equals("newInstance")) { ClassContext classCtx = getClassContext(); ConstantPoolGen cpg = classCtx.getConstantPoolGen(); CFG cfg; try { cfg = classCtx.getCFG(getMethod()); } catch (CFGBuilderException e) { AnalysisContext.logError("Cannot get CFG", e); return; } //The combination of the 2 following is consider safe boolean hasFeatureDTD = false; boolean hasFeatureStylesheet = false; boolean hasSecureProcessing = false; for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //DTD and Stylesheet disallow //factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); //factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); if(inst instanceof INVOKEVIRTUAL || inst instanceof INVOKEINTERFACE) { InvokeInstruction invoke = (InvokeInstruction) inst; if ("setAttribute".equals(invoke.getMethodName(cpg))) { LDC propertyConst = ByteCode.getPrevInstruction(location.getHandle().getPrev(), LDC.class); LDC loadConst = ByteCode.getPrevInstruction(location.getHandle(), LDC.class); if (propertyConst != null && loadConst != null) { if (PROPERTY_SUPPORT_DTD.equals(propertyConst.getValue(cpg))) { // All values other than "all", "http" and "jar" will disable external DTD processing. // Since other vulnerable values could be added, we do not want to use a blacklist mechanism. hasFeatureDTD = ( "".equals(loadConst.getValue(cpg)) ); } else if (PROPERTY_SUPPORT_STYLESHEET.equals(propertyConst.getValue(cpg))){ // All values other than "all", "http" and "jar" will disable external DTD processing. // Since other vulnerable values could be added, we do not want to use a blacklist mechanism. hasFeatureStylesheet = ( "".equals(loadConst.getValue(cpg)) ); } } } else if ("setFeature".equals(invoke.getMethodName(cpg))) { LDC propertyConst = ByteCode.getPrevInstruction(location.getHandle().getPrev(), LDC.class); ICONST loadConst = ByteCode.getPrevInstruction(location.getHandle(), ICONST.class); if (propertyConst != null && loadConst != null && PROPERTY_SECURE_PROCESSING.equals(propertyConst.getValue(cpg))){ // If SecureProcessing is set to true (loadConst == 1), the call is not vulnerable hasSecureProcessing = loadConst.getValue().equals(1); } } } } // Secure Processing includes all the suggested settings if (hasSecureProcessing) { return; } String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('/') + 1); //Raise a bug if (!hasFeatureDTD) { bugReporter.reportBug(new BugInstance(this, XXE_DTD_TRANSFORM_FACTORY_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this) .addString(simpleClassName + "." + method + "(...)")); } if (!hasFeatureStylesheet) { bugReporter.reportBug(new BugInstance(this, XXE_XSLT_TRANSFORM_FACTORY_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this) .addString(simpleClassName + "." + method + "(...)")); } }
282
1,171
1,453
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/ValidatorDetector.java
ValidatorDetector
sawOpcode
class ValidatorDetector extends OpcodeStackDetector { private static final String XXE_VALIDATOR_TYPE = "XXE_VALIDATOR"; private static final String VALIDATOR_CLASS_NAME = "javax/xml/validation/Validator"; private static final String SET_FEATURE_METHOD = "setFeature"; private static final String SET_PROPERTY_METHOD = "setProperty"; private static final String VALIDATE_METHOD_NAME = "validate"; private static final Number BOOLEAN_TRUE_VALUE = 1; private static final String EXTERNAL_REFERENCES_DISABLED = ""; private final BugReporter bugReporter; public ValidatorDetector(final BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(final int opcode) {<FILL_FUNCTION_BODY>} private boolean isNotValidateMethod(final int opcode) { boolean notValidateInvocation = true; if (Const.INVOKEVIRTUAL == opcode) { final String slashedClassName = getClassConstantOperand(); final String methodName = getNameConstantOperand(); if (VALIDATOR_CLASS_NAME.equals(slashedClassName) && VALIDATE_METHOD_NAME.equals(methodName)) { notValidateInvocation = false; } } return notValidateInvocation; } private boolean isSecureProcessingEnabled(final Location location, final ConstantPoolGen cpg) { boolean enabled = false; final Instruction instruction = location.getHandle().getInstruction(); if (instruction instanceof INVOKEVIRTUAL) { final InvokeInstruction invokeInstruction = (InvokeInstruction) instruction; final String instructionMethodName = invokeInstruction.getMethodName(cpg); final InstructionHandle handle = location.getHandle(); if (SET_FEATURE_METHOD.equals(instructionMethodName)) { final Object ldcValue = getLdcValue(handle, cpg); if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(ldcValue)) { final ICONST constant = ByteCode.getPrevInstruction(handle, ICONST.class); enabled = constant != null && BOOLEAN_TRUE_VALUE.equals(constant.getValue()); } } } return enabled; } private boolean isAccessPropertyDisabled(final Location location, final ConstantPoolGen cpg, final String accessPropertyName) { boolean enabled = false; final Instruction instruction = location.getHandle().getInstruction(); if (instruction instanceof INVOKEVIRTUAL) { final InvokeInstruction invokeInstruction = (InvokeInstruction) instruction; final String instructionMethodName = invokeInstruction.getMethodName(cpg); final InstructionHandle handle = location.getHandle(); if (SET_PROPERTY_METHOD.equals(instructionMethodName)) { final Object propertyName = getLdcValue(handle.getPrev(), cpg); final Object propertyValue = getLdcValue(handle, cpg); if (accessPropertyName.equals(propertyName)) { enabled = EXTERNAL_REFERENCES_DISABLED.equals(propertyValue); } } } return enabled; } private Object getLdcValue(final InstructionHandle instructionHandle, final ConstantPoolGen cpg) { final LDC ldc = ByteCode.getPrevInstruction(instructionHandle, LDC.class); return ldc == null ? null : ldc.getValue(cpg); } }
if (isNotValidateMethod(opcode)) { return; } final ClassContext classContext = getClassContext(); final CFG cfg; try { cfg = classContext.getCFG(getMethod()); } catch (final CFGBuilderException e) { AnalysisContext.logError("Cannot get CFG", e); return; } final ConstantPoolGen cpg = classContext.getConstantPoolGen(); boolean secureProcessingEnabled = false; boolean accessExternalDtdDisabled = false; boolean accessExternalSchemaDisabled = false; for (final Location location : cfg.locations()) { if (isSecureProcessingEnabled(location, cpg)) { secureProcessingEnabled = true; } else if (isAccessPropertyDisabled(location, cpg, XMLConstants.ACCESS_EXTERNAL_DTD)) { accessExternalDtdDisabled = true; } else if (isAccessPropertyDisabled(location, cpg, XMLConstants.ACCESS_EXTERNAL_SCHEMA)) { accessExternalSchemaDisabled = true; } } // Enabling Secure Processing or disabling both Access External DTD and Access External Schema are solutions if (secureProcessingEnabled || (accessExternalDtdDisabled && accessExternalSchemaDisabled)) { return; } bugReporter.reportBug(new BugInstance(this, XXE_VALIDATOR_TYPE, Priorities.HIGH_PRIORITY) .addClass(this).addMethod(this).addSourceLine(this));
919
396
1,315
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/XmlDecoderDetector.java
XmlDecoderDetector
sawOpcode
class XmlDecoderDetector extends OpcodeStackDetector { private static final String XML_DECODER = "XML_DECODER"; private static final InvokeMatcherBuilder XML_DECODER_CONSTRUCTOR = invokeInstruction().atClass("java/beans/XMLDecoder").atMethod("<init>"); private BugReporter bugReporter; public XmlDecoderDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen == Const.INVOKESPECIAL && XML_DECODER_CONSTRUCTOR.matches(this)) { bugReporter.reportBug(new BugInstance(this, XML_DECODER, Priorities.HIGH_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); }
158
94
252
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xml/XmlStreamReaderDetector.java
XmlStreamReaderDetector
sawOpcode
class XmlStreamReaderDetector extends OpcodeStackDetector { private static final String XXE_XMLSTREAMREADER_TYPE = "XXE_XMLSTREAMREADER";; private static final String PROPERTY_SUPPORT_DTD = "javax.xml.stream.supportDTD"; private static final String PROPERTY_IS_SUPPORTING_EXTERNAL_ENTITIES = "javax.xml.stream.isSupportingExternalEntities"; private final BugReporter bugReporter; public XmlStreamReaderDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int seen) {<FILL_FUNCTION_BODY>} }
if (seen != Const.INVOKEVIRTUAL) { return; } String fullClassName = getClassConstantOperand(); String method = getNameConstantOperand(); //The method call is doing XML parsing (see class javadoc) if (fullClassName.equals("javax/xml/stream/XMLInputFactory") && (method.equals("createXMLStreamReader") || method.equals("createXMLEventReader") || method.equals("createFilteredReader"))) { ClassContext classCtx = getClassContext(); ConstantPoolGen cpg = classCtx.getConstantPoolGen(); CFG cfg; try { cfg = classCtx.getCFG(getMethod()); } catch (CFGBuilderException e) { AnalysisContext.logError("Cannot get CFG", e); return; } for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) { Location location = i.next(); Instruction inst = location.getHandle().getInstruction(); //DTD disallow //XMLInputFactory.setProperty if (inst instanceof org.apache.bcel.generic.INVOKEVIRTUAL) { InvokeInstruction invoke = (InvokeInstruction) inst; if ("setProperty".equals(invoke.getMethodName(cpg))) { org.apache.bcel.generic.LDC loadConst = ByteCode.getPrevInstruction(location.getHandle(), LDC.class); if (loadConst != null) { if (PROPERTY_SUPPORT_DTD.equals(loadConst.getValue(cpg)) || PROPERTY_IS_SUPPORTING_EXTERNAL_ENTITIES.equals(loadConst.getValue(cpg))){ InstructionHandle prev1 = location.getHandle().getPrev(); InstructionHandle prev2 = prev1.getPrev(); //Case where the boolean is wrapped like : Boolean.valueOf(true) : 2 instructions if (invokeInstruction().atClass("java.lang.Boolean").atMethod("valueOf").matches(prev1.getInstruction(),cpg)) { if (prev2.getInstruction() instanceof ICONST) { Integer valueWrapped = ByteCode.getConstantInt(prev2); if (valueWrapped != null && valueWrapped.equals(0)) { //Value is false return; //Safe feature is disable } } } //Case where the boolean is declared as : Boolean.FALSE else if (prev1.getInstruction() instanceof org.apache.bcel.generic.GETSTATIC) { org.apache.bcel.generic.GETSTATIC getstatic = (org.apache.bcel.generic.GETSTATIC) prev1.getInstruction(); if (getstatic.getClassType(cpg).getClassName().equals("java.lang.Boolean") && getstatic.getFieldName(cpg).equals("FALSE")) { return; } } } } } } } //Raise a bug bugReporter.reportBug(new BugInstance(this, XXE_XMLSTREAMREADER_TYPE, Priorities.NORMAL_PRIORITY) // .addClass(this).addMethod(this).addSourceLine(this)); }
195
830
1,025
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xpath/XPathInjectionDetector.java
XPathInjectionDetector
getPriority
class XPathInjectionDetector extends BasicInjectionDetector { public XPathInjectionDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("xpath-javax.txt", "XPATH_INJECTION"); loadConfiguredSinks("xpath-apache.txt", "XPATH_INJECTION"); // TODO add net.sf.saxon.xpath.XPathEvaluator // TODO add org.apache.commons.jxpath // TODO add org.jdom.xpath.XPath // TODO add org.jaxen.XPath // TODO add edu.UCL.utils.XPathAPI // TODO add org.xmldb.api.modules } @Override protected int getPriority(Taint taint) {<FILL_FUNCTION_BODY>} }
if (!taint.isSafe() && taint.hasTag(Taint.Tag.XPATH_INJECTION_SAFE)) { return Priorities.IGNORE_PRIORITY; } else { return super.getPriority(taint); }
223
71
294
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xss/XSSRequestWrapperDetector.java
XSSRequestWrapperDetector
visitClassContext
class XSSRequestWrapperDetector implements Detector { private static final String XSS_REQUEST_WRAPPER_TYPE = "XSS_REQUEST_WRAPPER"; private BugReporter bugReporter; public XSSRequestWrapperDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) {<FILL_FUNCTION_BODY>} @Override public void report() { } }
JavaClass javaClass = classContext.getJavaClass(); //The class extends HttpServletRequestWrapper boolean isRequestWrapper = InterfaceUtils.isSubtype(javaClass, "javax.servlet.http.HttpServletRequestWrapper"); //Not the target of this detector if (!isRequestWrapper) return; Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { if (m.getName().equals("stripXSS")) { bugReporter.reportBug(new BugInstance(this, XSS_REQUEST_WRAPPER_TYPE, Priorities.NORMAL_PRIORITY) // .addClassAndMethod(javaClass, m)); return; } }
136
184
320
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xss/XssJspDetector.java
XssJspDetector
getPriority
class XssJspDetector extends BasicInjectionDetector { private static final String XSS_JSP_PRINT_TYPE = "XSS_JSP_PRINT"; @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION_PKGPROTECT", justification = "It is intended to be shared with XssServletDetector. Accidental modification of this list is unlikely.") protected static final String[] JSP_PARENT_CLASSES = { "org.apache.jasper.runtime.HttpJspBase", "weblogic.servlet.jsp.JspBase" }; public XssJspDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("xss-jsp.txt", XSS_JSP_PRINT_TYPE); } @Override protected int getPriority(Taint taint) {<FILL_FUNCTION_BODY>} @Override public boolean shouldAnalyzeClass(ClassContext classContext) { String className = classContext.getClassDescriptor().getDottedClassName(); return InterfaceUtils.isSubtype(className, JSP_PARENT_CLASSES); } }
if (!taint.isSafe() && taint.hasTag(Taint.Tag.XSS_SAFE)) { if(FindSecBugsGlobalConfig.getInstance().isReportPotentialXssWrongContext()) { return Priorities.LOW_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; } } else if (!taint.isSafe() && (taint.hasOneTag(Taint.Tag.QUOTE_ENCODED, Taint.Tag.APOSTROPHE_ENCODED)) && taint.hasTag(Taint.Tag.LT_ENCODED)) { return Priorities.LOW_PRIORITY; } else { return super.getPriority(taint); }
313
201
514
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/xss/XssServletDetector.java
XssServletDetector
getPriority
class XssServletDetector extends BasicInjectionDetector { private static final String XSS_SERVLET_TYPE = "XSS_SERVLET"; private static final String[] REQUIRED_CLASSES = { "Ljavax/servlet/http/ServletResponse;", "Ljavax/servlet/http/ServletResponseWrapper;", "Ljavax/servlet/http/HttpServletResponse;", "Ljavax/servlet/http/HttpServletResponseWrapper;", "Lorg/apache/jetspeed/portlet/PortletResponse;", "Lorg/apache/jetspeed/portlet/PortletResponseWrapper;", "Ljavax/portlet/RenderResponse;", "Ljavax/portlet/MimeResponse;", "Ljavax/portlet/filter/RenderResponseWrapper;", "Ljavax/portlet/PortletResponse;", "Ljavax/portlet/ActionResponseWrapper;", "Ljavax/portlet/EventResponseWrapper;", "Ljavax/portlet/PortletResponseWrapper;", "Ljavax/portlet/RenderResponseWrapper;", "Ljavax/portlet/ResourceResponseWrapper;", }; public XssServletDetector(BugReporter bugReporter) { super(bugReporter); loadConfiguredSinks("xss-servlet.txt", XSS_SERVLET_TYPE); } @Override protected int getPriority(Taint taint) {<FILL_FUNCTION_BODY>} @Override public boolean shouldAnalyzeClass(ClassContext classContext) { ConstantPoolGen constantPoolGen = classContext.getConstantPoolGen(); for (String requiredClass : REQUIRED_CLASSES) { if (constantPoolGen.lookupUtf8(requiredClass) != -1) { String className = classContext.getClassDescriptor().getDottedClassName(); return !InterfaceUtils.isSubtype(className, XssJspDetector.JSP_PARENT_CLASSES); } } return false; } }
if (!taint.isSafe() && taint.hasTag(Taint.Tag.XSS_SAFE)) { if(FindSecBugsGlobalConfig.getInstance().isReportPotentialXssWrongContext()) { return Priorities.LOW_PRIORITY; } else { return Priorities.IGNORE_PRIORITY; } } else if (!taint.isSafe() && (taint.hasOneTag(Taint.Tag.QUOTE_ENCODED, Taint.Tag.APOSTROPHE_ENCODED)) && taint.hasTag(Taint.Tag.LT_ENCODED)) { return Priorities.LOW_PRIORITY; } else { return super.getPriority(taint); }
536
199
735
<methods>public void registerVisitor(com.h3xstream.findsecbugs.taintanalysis.TaintFrameAdditionalVisitor) <variables>static com.h3xstream.findsecbugs.injection.ClassMethodSignature OBJECT,private static final com.h3xstream.findsecbugs.injection.SinksLoader SINKS_LOADER,private final Map<com.h3xstream.findsecbugs.injection.ClassMethodSignature,com.h3xstream.findsecbugs.injection.InjectionPoint> injectionMap
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-samples-deps/src/main/java/javax/ws/rs/core/Response.java
ResponseBuilder
fromStatusCode
class ResponseBuilder { protected ResponseBuilder() {} protected static ResponseBuilder newInstance() { return null; } public abstract Response build(); @Override public abstract ResponseBuilder clone(); public abstract ResponseBuilder status(int status); public ResponseBuilder status(Status status) { return null; }; public abstract ResponseBuilder entity(Object entity); public abstract ResponseBuilder type(MediaType type); public abstract ResponseBuilder type(String type); public abstract ResponseBuilder variant(Variant variant); public abstract ResponseBuilder variants(List<Variant> variants); public abstract ResponseBuilder language(String language); public abstract ResponseBuilder language(Locale language); public abstract ResponseBuilder location(URI location); public abstract ResponseBuilder contentLocation(URI location); public abstract ResponseBuilder tag(EntityTag tag); public abstract ResponseBuilder tag(String tag); public abstract ResponseBuilder lastModified(Date lastModified); public abstract ResponseBuilder cacheControl(CacheControl cacheControl); public abstract ResponseBuilder expires(Date expires); public abstract ResponseBuilder header(String name, Object value); public abstract ResponseBuilder cookie(NewCookie... cookies); } public enum Status { OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), MOVED_PERMANENTLY(301, "Moved Permanently"), SEE_OTHER(303, "See Other"), NOT_MODIFIED(304, "Not Modified"), TEMPORARY_REDIRECT(307, "Temporary Redirect"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), NOT_ACCEPTABLE(406, "Not Acceptable"), CONFLICT(409, "Conflict"), GONE(410, "Gone"), PRECONDITION_FAILED(412, "Precondition Failed"), UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), INTERNAL_SERVER_ERROR(500, "Internal Server Error"), SERVICE_UNAVAILABLE(503, "Service Unavailable"); private final int code; private final String reason; private Family family; public enum Family {INFORMATIONAL, SUCCESSFUL, REDIRECTION, CLIENT_ERROR, SERVER_ERROR, OTHER} ; Status(final int statusCode, final String reasonPhrase) { this.code = statusCode; this.reason = reasonPhrase; switch (code / 100) { case 1: this.family = Family.INFORMATIONAL; break; case 2: this.family = Family.SUCCESSFUL; break; case 3: this.family = Family.REDIRECTION; break; case 4: this.family = Family.CLIENT_ERROR; break; case 5: this.family = Family.SERVER_ERROR; break; default: this.family = Family.OTHER; break; } } public Family getFamily() { return family; } public int getStatusCode() { return code; } @Override public String toString() { return reason; } public static Status fromStatusCode(final int statusCode) {<FILL_FUNCTION_BODY>
for (Status s : Status.values()) { if (s.code == statusCode) { return s; } } return null;
970
43
1,013
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-samples-deps/src/main/java/org/apache/commons/collections4/comparators/TransformingComparator.java
TransformingComparator
hashCode
class TransformingComparator<I, O> implements Comparator<I>, Serializable { private static final long serialVersionUID = 3456940356043606220L; private final Comparator<O> decorated; private final Transformer<? super I, ? extends O> transformer; public TransformingComparator(Transformer<? super I, ? extends O> transformer) { this(transformer, null); } public TransformingComparator(Transformer<? super I, ? extends O> transformer, Comparator<O> decorated) { this.decorated = decorated; this.transformer = transformer; } public int compare(I obj1, I obj2) { O value1 = this.transformer.transform(obj1); O value2 = this.transformer.transform(obj2); return this.decorated.compare(value1, value2); } public int hashCode() {<FILL_FUNCTION_BODY>} public boolean equals(Object object) { if(this == object) { return true; } else if(null == object) { return false; } else if(!object.getClass().equals(this.getClass())) { return false; } else { TransformingComparator comp = (TransformingComparator)object; return null == this.decorated?null == comp.decorated:(this.decorated.equals(comp.decorated) && null == this.transformer?null == comp.transformer:this.transformer.equals(comp.transformer)); } } }
byte total = 17; int total1 = total * 37 + (this.decorated == null?0:this.decorated.hashCode()); total1 = total1 * 37 + (this.transformer == null?0:this.transformer.hashCode()); return total1;
412
77
489
<no_super_class>
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-samples-deps/src/main/java/org/apache/commons/io/input/ClassLoaderObjectInputStream.java
ClassLoaderObjectInputStream
resolveProxyClass
class ClassLoaderObjectInputStream extends ObjectInputStream { /** * The class loader to use. */ private final ClassLoader classLoader; /** * Constructs a new ClassLoaderObjectInputStream. * * @param classLoader the ClassLoader from which classes should be loaded * @param inputStream the InputStream to work on * @throws IOException in case of an I/O error * @throws StreamCorruptedException if the stream is corrupted */ public ClassLoaderObjectInputStream( final ClassLoader classLoader, final InputStream inputStream) throws IOException, StreamCorruptedException { super(inputStream); this.classLoader = classLoader; } /** * Resolve a class specified by the descriptor using the * specified ClassLoader or the super ClassLoader. * * @param objectStreamClass descriptor of the class * @return the Class object described by the ObjectStreamClass * @throws IOException in case of an I/O error * @throws ClassNotFoundException if the Class cannot be found */ @Override protected Class<?> resolveClass(final ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException { try { return Class.forName(objectStreamClass.getName(), false, classLoader); } catch (final ClassNotFoundException cnfe) { // delegate to super class loader which can resolve primitives return super.resolveClass(objectStreamClass); } } /** * Create a proxy class that implements the specified interfaces using * the specified ClassLoader or the super ClassLoader. * * @param interfaces the interfaces to implement * @return a proxy class implementing the interfaces * @throws IOException in case of an I/O error * @throws ClassNotFoundException if the Class cannot be found * @see java.io.ObjectInputStream#resolveProxyClass(java.lang.String[]) * @since 2.1 */ @Override protected Class<?> resolveProxyClass(final String[] interfaces) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
final Class<?>[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); } try { return Proxy.getProxyClass(classLoader, interfaceClasses); } catch (final IllegalArgumentException e) { return super.resolveProxyClass(interfaces); }
520
113
633
<methods>public void <init>(java.io.InputStream) throws java.io.IOException,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public void defaultReadObject() throws java.io.IOException, java.lang.ClassNotFoundException,public final java.io.ObjectInputFilter getObjectInputFilter() ,public int read() throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public boolean readBoolean() throws java.io.IOException,public byte readByte() throws java.io.IOException,public char readChar() throws java.io.IOException,public double readDouble() throws java.io.IOException,public java.io.ObjectInputStream.GetField readFields() throws java.io.IOException, java.lang.ClassNotFoundException,public float readFloat() throws java.io.IOException,public void readFully(byte[]) throws java.io.IOException,public void readFully(byte[], int, int) throws java.io.IOException,public int readInt() throws java.io.IOException,public java.lang.String readLine() throws java.io.IOException,public long readLong() throws java.io.IOException,public final java.lang.Object readObject() throws java.io.IOException, java.lang.ClassNotFoundException,public short readShort() throws java.io.IOException,public java.lang.String readUTF() throws java.io.IOException,public java.lang.Object readUnshared() throws java.io.IOException, java.lang.ClassNotFoundException,public int readUnsignedByte() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public void registerValidation(java.io.ObjectInputValidation, int) throws java.io.NotActiveException, java.io.InvalidObjectException,public final void setObjectInputFilter(java.io.ObjectInputFilter) ,public int skipBytes(int) throws java.io.IOException<variables>static final boolean $assertionsDisabled,private static final int NULL_HANDLE,private static final jdk.internal.misc.Unsafe UNSAFE,private final java.io.ObjectInputStream.BlockDataInputStream bin,private boolean closed,private java.io.SerialCallbackContext curContext,private boolean defaultDataEnd,private long depth,private final boolean enableOverride,private boolean enableResolve,private final java.io.ObjectInputStream.HandleTable handles,private int passHandle,private static final Map<java.lang.String,Class<?>> primClasses,private java.io.ObjectInputFilter serialFilter,private boolean streamFilterSet,private long totalObjectRefs,private static final java.lang.Object unsharedMarker,private final java.io.ObjectInputStream.ValidationList vlist
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/internal/DocxLinkResolver.java
DocxLinkResolver
resolveLink
class DocxLinkResolver implements LinkResolver { final private String docRelativeURL; final private String docRootURL; final private String[] relativeParts; final private boolean prefixWwwLinks; public DocxLinkResolver(LinkResolverBasicContext context) { // can use context for custom settings String docRelativeURL = DocxRenderer.DOC_RELATIVE_URL.get(context.getOptions()); String docRootURL = DocxRenderer.DOC_ROOT_URL.get(context.getOptions()); this.docRelativeURL = docRelativeURL; this.docRootURL = docRootURL; docRelativeURL = Utils.removePrefix(docRelativeURL, '/'); relativeParts = docRelativeURL.split("/"); prefixWwwLinks = DocxRenderer.PREFIX_WWW_LINKS.get(context.getOptions()); } @NotNull @Override public ResolvedLink resolveLink(@NotNull Node node, @NotNull LinkResolverBasicContext context, @NotNull ResolvedLink link) {<FILL_FUNCTION_BODY>} public static class Factory implements LinkResolverFactory { @Nullable @Override public Set<Class<?>> getAfterDependents() { return null; } @Nullable @Override public Set<Class<?>> getBeforeDependents() { return null; } @Override public boolean affectsGlobalScope() { return false; } @NotNull @Override public LinkResolver apply(@NotNull LinkResolverBasicContext context) { return new DocxLinkResolver(context); } } }
if (node instanceof Image || node instanceof Link || node instanceof Reference || node instanceof JekyllTag) { String url = link.getUrl(); if (docRelativeURL.isEmpty() && docRootURL.isEmpty()) { // resolve url, return one of LinkStatus other than LinkStatus.UNKNOWN return link.withStatus(LinkStatus.VALID) .withUrl(url); } if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://") || url.startsWith("sftp://")) { // resolve url, return one of LinkStatus other than LinkStatus.UNKNOWN return link.withStatus(LinkStatus.VALID) .withUrl(url); } else if (url.startsWith("file:/")) { // assume it is good return link.withStatus(LinkStatus.VALID) .withUrl(url); } else if (url.startsWith(DocxRenderer.EMOJI_RESOURCE_PREFIX)) { // assume it is good return link.withStatus(LinkStatus.VALID) .withUrl(url); } else if (url.startsWith("/")) { if (docRootURL != null && !docRootURL.isEmpty()) { // this one is root url, prefix with root url, without the trailing / url = docRootURL + url; if (!url.startsWith("file:")) url = "file://" + url; return link.withStatus(LinkStatus.VALID) .withUrl(url); } } else if (prefixWwwLinks && url.startsWith("www.")) { // should be prefixed with http://, we will just add it return link.withStatus(LinkStatus.INVALID) .withUrl("http://" + url); } else if (!url.startsWith("data:") && !url.matches("^(?:[a-z]+:|#|\\?)")) { // relative, we will process it as a relative path to the docRelativeURL String pageRef = url; String suffix = ""; int pos = url.indexOf('#'); if (pos == 0) { return link.withStatus(LinkStatus.VALID); } else { if (pos > 0) { // remove anchor suffix = url.substring(pos); pageRef = url.substring(0, pos); } else if (url.contains("?")) { // remove query pos = url.indexOf("?"); suffix = url.substring(pos); pageRef = url.substring(0, pos); } String[] pathParts = pageRef.split("/"); int docParts = relativeParts.length; int iMax = pathParts.length; StringBuilder resolved = new StringBuilder(); String sep = ""; for (int i = 0; i < iMax; i++) { String part = pathParts[i]; if (part.equals(".")) { // skp } else if (part.equals("..")) { // remove one doc part if (docParts == 0) return link; docParts--; } else { resolved.append(sep); resolved.append(part); sep = "/"; } } // prefix with remaining docParts sep = docRelativeURL.startsWith("/") ? "/" : ""; StringBuilder resolvedPath = new StringBuilder(); iMax = docParts; for (int i = 0; i < iMax; i++) { resolvedPath.append(sep); resolvedPath.append(relativeParts[i]); sep = "/"; } resolvedPath.append('/').append(resolved).append(suffix); String resolvedUri = resolvedPath.toString(); if (!resolvedUri.startsWith("file:")) resolvedUri = "file://" + resolvedUri; return link.withStatus(LinkStatus.VALID) .withUrl(resolvedUri); } } } return link;
415
1,031
1,446
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/AttributeFormat.java
AttributeFormat
getValidFontItalic
class AttributeFormat { final public @Nullable String fontFamily; final public @Nullable String fontSize; final public @Nullable Boolean fontBold; final public @Nullable Boolean fontItalic; final public @Nullable String textColor; final public @Nullable String fillColor; public AttributeFormat(@Nullable String fontFamily, @Nullable String fontSize, @Nullable String fontWeight, @Nullable String fontStyle, @Nullable String textColor, @Nullable String fillColor) { this.fontFamily = getValidFontFamily(trimEmptyToNull(fontFamily)); this.fontSize = getValidFontSize(trimEmptyToNull(fontSize)); this.fontBold = getValidFontBold(trimEmptyToNull(fontWeight)); this.fontItalic = getValidFontItalic(trimEmptyToNull(fontStyle)); this.textColor = getValidNamedOrHexColor(trimEmptyToNull(textColor)); this.fillColor = getValidNamedOrHexColor(trimEmptyToNull(fillColor)); } @Nullable private static String trimEmptyToNull(@Nullable String textColor) { if (textColor == null) return null; String trimmed = textColor.trim(); if (!trimmed.isEmpty()) return trimmed; return null; } public boolean isEmpty() { return fontFamily == null && fontSize == null && fontBold == null && fontItalic == null && textColor == null && fillColor == null; } @Nullable String getValidHexColor(@Nullable String s) { if (s == null) return null; return ColorNameMapper.getValidHexColor(s); } @Nullable String getValidNamedOrHexColor(@Nullable String s) { if (s == null) return null; return ColorNameMapper.getValidNamedOrHexColor(s); } @Nullable private String getValidFontFamily(@Nullable String fontFamily) { return fontFamily == null || fontFamily.isEmpty() ? null : fontFamily; } @Nullable private String getValidFontSize(@Nullable String fontSize) { return fontSize == null || fontSize.isEmpty() ? null : fontSize; } @Nullable private Boolean getValidFontBold(@Nullable String s) { if (s == null) return null; switch (s) { case "bolder": case "bold": return true; case "lighter": case "normal": return false; default: // convert to numeric then round up/down to 700/400 int weight = SequenceUtils.parseIntOrDefault(s, -1); if (weight != -1) return weight >= 550; } return null; } @Nullable private Boolean getValidFontItalic(@Nullable String s) {<FILL_FUNCTION_BODY>} @NotNull public <T> CTShd getShd(@NotNull DocxContext<T> docx) { CTShd shd = docx.getFactory().createCTShd(); shd.setColor("auto"); shd.setFill(fillColor); shd.setVal(STShd.CLEAR); return shd; } public <T> void setFormatRPr(@NotNull RPrAbstract rPr, @NotNull DocxContext<T> docx) { if (textColor != null) { Color color = docx.getFactory().createColor(); rPr.setColor(color); color.setVal(ColorNameMapper.getValidHexColorOrDefault(textColor, "000000").toUpperCase()); rPr.setColor(color); } if (fillColor != null) { CTShd shd = rPr.getShd(); if (shd == null) { shd = docx.getFactory().createCTShd(); rPr.setShd(shd); } shd.setColor("auto"); shd.setFill(fillColor); shd.setVal(STShd.CLEAR); } if (fontBold != null) { rPr.setBCs(fontBold ? docx.getFactory().createBooleanDefaultTrue() : null); rPr.setB(fontBold ? docx.getFactory().createBooleanDefaultTrue() : null); } if (fontItalic != null) { rPr.setICs(fontItalic ? docx.getFactory().createBooleanDefaultTrue() : null); rPr.setI(fontItalic ? docx.getFactory().createBooleanDefaultTrue() : null); } if (fontSize != null) { long sz = 0; if (fontSize.endsWith("pt")) { float ptSz = Float.parseFloat(fontSize.substring(0, fontSize.length() - 2).trim()); sz = Math.round(ptSz * 2.0); } else { // treat as float ptSz = Float.parseFloat(fontSize); sz = Math.round(ptSz * 2.0); } if (sz != 0) { HpsMeasure hpsMeasure = docx.getFactory().createHpsMeasure(); hpsMeasure.setVal(BigInteger.valueOf(sz)); rPr.setSzCs(hpsMeasure); rPr.setSz(hpsMeasure); } else { rPr.setSzCs(null); rPr.setSz(null); } } } }
if (s == null) return null; switch (s) { case "oblique": case "italic": return true; case "normal": return false; default: // convert to numeric then round up/down to 700/400 if (s.startsWith("oblique ")) { int angle = SequenceUtils.parseIntOrDefault(s.substring("oblique ".length()).trim(), -1); if (angle != -1) return angle >= 14; } } return null;
1,453
154
1,607
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/AttributeRunFormatProvider.java
AttributeRunFormatProvider
getRPr
class AttributeRunFormatProvider<T> extends RunFormatProviderBase<T> { final public AttributeFormat myAttributeFormat; public AttributeRunFormatProvider(DocxContext<T> docx, String fontFamily, String fontSize, String fontWeight, String fontStyle, String textColor, String fillColor) { super(docx, null, false, null); myAttributeFormat = new AttributeFormat(fontFamily, fontSize, fontWeight, fontStyle, textColor, fillColor); } public AttributeRunFormatProvider(DocxContext<T> docx, AttributeFormat attributeFormat) { super(docx, null, false, null); myAttributeFormat = attributeFormat; } @Override public void getRPr(RPr rPr) {<FILL_FUNCTION_BODY>} }
RunFormatProvider<T> parent = myParent; if (parent != null) { RPr rpr1 = myDocx.getFactory().createRPr(); parent.getRPr(rpr1); inheritParentStyle(rPr, rpr1); } ParaRPr paraRPr = myDocx.getP().getPPr().getRPr(); myAttributeFormat.setFormatRPr(rPr, myDocx); myDocx.getHelper().keepDiff(rPr, paraRPr);
203
137
340
<methods>public void <init>(DocxContext<T>, java.lang.String, boolean, java.lang.String) ,public void close() ,public T getProviderFrame() ,public void getRPr(org.docx4j.wml.RPr) ,public RunFormatProvider<T> getRunParent() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected final non-sealed java.lang.String myHighlightShadingColor,protected final non-sealed boolean myNoCharacterStyles,protected final non-sealed RunFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/BlockFormatProviderBase.java
BlockFormatProviderBase
getParaRPr
class BlockFormatProviderBase<T> implements BlockFormatProvider<T> { protected final DocxContext<T> myDocx; protected final T myFrame; protected final BlockFormatProvider<T> myParent; protected final String myBaseStyleId; protected int myPCount; public BlockFormatProviderBase(DocxContext<T> docx, String baseStyleId) { myDocx = docx; myFrame = docx.getContextFrame(); myParent = docx.getBlockFormatProvider(); myBaseStyleId = baseStyleId; myPCount = 0; } @Override public void adjustPPrForFormatting(PPr pP) { myPCount++; } @Override public T getProviderFrame() { return myFrame; } @Override public void open() { } @Override public void close() { } protected Style getBaseStyle() { return myDocx.getStyle(getBaseStyleId()); } @Override public Style getStyle() { return myDocx.getStyle(getStyleId()); } protected String getBaseStyleId() { return myBaseStyleId; } @Override public String getStyleId() { return myBaseStyleId; } /** * Get the style parent for the next P of this block * * @return parent to use for style inheritance */ protected BlockFormatProvider<T> getStyleParent() { return myParent; } @Override public BlockFormatProvider<T> getBlockParent() { return myParent; } protected void inheritIndent(PPr pPrBase, PPr parentPrBase) { if (parentPrBase != null) { myDocx.getHelper().inheritInd(pPrBase, parentPrBase); } } protected void inheritParentFormat(PPr pPr, PPr parentPPr) { inheritIndent(pPr, parentPPr); inheritBdr(pPr, parentPPr); } protected void adjustPPr(PPr pPrBase) { } /** * Inherit left border * <p> * must be called after ind has been determined * * @param pPr ppr to set * @param parentPPr parent ppr */ protected void inheritBdr(PPr pPr, PPr parentPPr) { // combine indent with parent myDocx.getHelper().inheritPBdr(pPr, parentPPr); } @Override public void getPPr(PPr pPr) { // Create object for pStyle if one does not already exist if (myBaseStyleId != null) { PPrBase.PStyle basePStyle = myDocx.getFactory().createPPrBasePStyle(); pPr.setPStyle(basePStyle); basePStyle.setVal(myBaseStyleId); } // Create object for rPr ParaRPr pararpr = pPr.getRPr(); if (pararpr == null) { pararpr = myDocx.getFactory().createParaRPr(); pPr.setRPr(pararpr); } // handle inheritance BlockFormatProvider<T> parent = getStyleParent(); if (parent != null) { PPr ppr = myDocx.getFactory().createPPr(); parent.getPPr(ppr); ppr = myDocx.getHelper().getExplicitPPr(ppr); //PPr ppr = myDocx.getFactory().createPPr(); //Style parentStyle = myDocx.getStyle(parent.getStyleId()); //if (parentStyle != null) { // myDocx.getHelper().setPPrBase(ppr, parentStyle.getPPr(), false); //} //parent.getPPr(ppr); inheritParentFormat(pPr, ppr); } // allow adjustments adjustPPr(pPr); } @Override public void getParaRPr(RPr rPr) {<FILL_FUNCTION_BODY>} }
BlockFormatProvider<T> parent = getStyleParent(); if (parent != null) { parent.getParaRPr(rPr); } Style style = getStyle(); if (style != null && style.getRPr() != null) { StyleUtil.apply(myDocx.getHelper().getExplicitRPr(style.getRPr()), rPr); }
1,092
103
1,195
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/ColorNameMapper.java
ColorNameMapper
colorToString
class ColorNameMapper { final private static Map<String, Color> colors = new HashMap<>(); static { colors.put("black", new Color(0x000000)); colors.put("blue", new Color(0x0000FF)); colors.put("cyan", new Color(0x00FFFF)); colors.put("green", new Color(0x008000)); colors.put("magenta", new Color(0xFF00FF)); colors.put("red", new Color(0xFF0000)); colors.put("yellow", new Color(0xFFFF00)); colors.put("white", new Color(0xFFFFFF)); colors.put("darkBlue", new Color(0x00008B)); colors.put("darkCyan", new Color(0x008B8B)); colors.put("darkGreen", new Color(0x006400)); colors.put("darkMagenta", new Color(0x8B008B)); colors.put("darkRed", new Color(0x8B0000)); colors.put("darkYellow", new Color(0xFFD700)); colors.put("darkGray", new Color(0xA9A9A9)); colors.put("lightGray", new Color(0xD3D3D3)); } ; final private static String hexPattern = "^[0-9a-fA-F]{6}$"; /** * from: https://stackoverflow.com/questions/6334311/whats-the-best-way-to-round-a-color-object-to-the-nearest-color-constant * * @param c1 color 1 * @param c2 color 2 * @return distance between two colors */ public static double colorDistance(@NotNull Color c1, @NotNull Color c2) { int red1 = c1.getRed(); int red2 = c2.getRed(); int rmean = (red1 + red2) >> 1; int r = red1 - red2; int g = c1.getGreen() - c2.getGreen(); int b = c1.getBlue() - c2.getBlue(); return Math.sqrt((((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8)); } public static String colorToString(@NotNull Color color) {<FILL_FUNCTION_BODY>} @NotNull public static Color colorFromString(@NotNull String color) { return new Color( Integer.valueOf(color.substring(0, 2), 16), Integer.valueOf(color.substring(2, 4), 16), Integer.valueOf(color.substring(4, 6), 16)); } public static boolean isHexColor(@NotNull String color) { return color.matches(hexPattern); } public static boolean isNamedColor(@NotNull String color) { return colors.containsKey(color); } @Nullable public static String getValidNamedOrHexColor(@NotNull String s) { if (ColorNameMapper.isNamedColor(s) || ColorNameMapper.isHexColor(s)) { return s; } return null; } @NotNull public static String getValidHexColorOrDefault(@NotNull String s, @NotNull String defaultValue) { String hexColor = getValidHexColor(s); return hexColor != null ? hexColor : defaultValue; } @Nullable public static String getValidHexColor(@NotNull String s) { if (ColorNameMapper.isNamedColor(s)) { return colorToString(colors.get(s)); } else if (ColorNameMapper.isHexColor(s)) { return s; } return null; } @NotNull public static String findClosestNamedColor(@NotNull Color color) { String colorName = "black"; double minDistance = Double.MAX_VALUE; for (Map.Entry<String, Color> entry : colors.entrySet()) { double distance = colorDistance(color, entry.getValue()); if (distance < minDistance) { minDistance = distance; colorName = entry.getKey(); } } return colorName; } @NotNull public static String findClosestNamedColor(@NotNull String color) { return findClosestNamedColor(colorFromString(color)); } }
int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); return String.format("%02x%02x%02x", r, g, b);
1,179
59
1,238
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/FootnoteBlockFormatProvider.java
FootnoteBlockFormatProvider
inheritParentFormat
class FootnoteBlockFormatProvider<T> extends BlockFormatProviderBase<T> { public FootnoteBlockFormatProvider(DocxContext<T> docx) { super(docx, docx.getRenderingOptions().FOOTNOTE_STYLE); } @Override protected void inheritParentFormat(PPr pPr, PPr parentPPr) {<FILL_FUNCTION_BODY>} @Override protected BlockFormatProvider<T> getStyleParent() { return null; } }
// do not inherit otherwise the formatting for the footnote reference is // applied to footnote block children
130
28
158
<methods>public void <init>(DocxContext<T>, java.lang.String) ,public void adjustPPrForFormatting(org.docx4j.wml.PPr) ,public void close() ,public BlockFormatProvider<T> getBlockParent() ,public void getPPr(org.docx4j.wml.PPr) ,public void getParaRPr(org.docx4j.wml.RPr) ,public T getProviderFrame() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected int myPCount,protected final non-sealed BlockFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/ListItemBlockFormatProvider.java
ListItemBlockFormatProvider
getPPr
class ListItemBlockFormatProvider<T> extends BlockFormatProviderBase<T> { final private DocxContext<T> myDocx; final private String mySpacingStyleId; final private long myIdNum; final private int myListLevel; final private Class[] mySkipContextFrameClasses; public ListItemBlockFormatProvider(DocxContext<T> docx, String listStyle, String listSpacingStyle, long idNum, int listLevel, Class... skipContextFrameClasses) { super(docx, listStyle); mySpacingStyleId = listSpacingStyle; myDocx = docx; myIdNum = idNum; myListLevel = listLevel; mySkipContextFrameClasses = skipContextFrameClasses; } @Override public void getPPr(PPr pPr) {<FILL_FUNCTION_BODY>} @Override protected void adjustPPr(PPr pPrBase) { if (mySpacingStyleId != null && !mySpacingStyleId.equals(myBaseStyleId)) { // get the spacing from spacing style Style style = myDocx.getStyle(mySpacingStyleId); if (style != null && style.getPPr() != null) { PPr pPr = myDocx.getHelper().getExplicitPPr(style.getPPr()); PPr pPrExplicitBase = myDocx.getHelper().getExplicitPPr(pPrBase); PPrBase pPrDiff = myDocx.getHelper().keepDiff(pPr, pPrExplicitBase); StyleUtil.apply(pPrDiff, pPrBase); } } } private boolean containsClass(Class[] list, Object item) { for (Class nodeType : list) { if (nodeType.isInstance(item)) return true; } return false; } @Override protected BlockFormatProvider<T> getStyleParent() { BlockFormatProvider<T> parent = myParent; while (parent != null && containsClass(mySkipContextFrameClasses, parent.getProviderFrame())) { parent = parent.getBlockParent(); } return parent; } @Override protected void inheritBdr(PPr pPr, PPr parentPPr) { super.inheritBdr(pPr, parentPPr); } }
if (myPCount == 0) { // Create object for numPr PPrBase.NumPr numPr = myDocx.getFactory().createPPrBaseNumPr(); pPr.setNumPr(numPr); // Create object for numId PPrBase.NumPr.NumId numId = myDocx.getFactory().createPPrBaseNumPrNumId(); numPr.setNumId(numId); numId.setVal(BigInteger.valueOf(myIdNum)); //listNumId)); // Create object for ilvl PPrBase.NumPr.Ilvl ilvl = myDocx.getFactory().createPPrBaseNumPrIlvl(); numPr.setIlvl(ilvl); ilvl.setVal(BigInteger.valueOf(myListLevel)); } else { // need to inherit indent from our base style NumberingDefinitionsPart ndp = myDocx.getDocxDocument().getNumberingDefinitionsPart(); PPrBase.Ind ind = ndp.getInd(String.valueOf(myIdNum), String.valueOf(myListLevel)); if (ind != null) { DocxHelper helper = myDocx.getHelper(); helper.ensureInd(pPr); pPr.getInd().setLeft(helper.safeIndLeft(ind)); pPr.getInd().setHanging(BigInteger.ZERO); } } super.getPPr(pPr);
596
377
973
<methods>public void <init>(DocxContext<T>, java.lang.String) ,public void adjustPPrForFormatting(org.docx4j.wml.PPr) ,public void close() ,public BlockFormatProvider<T> getBlockParent() ,public void getPPr(org.docx4j.wml.PPr) ,public void getParaRPr(org.docx4j.wml.RPr) ,public T getProviderFrame() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected int myPCount,protected final non-sealed BlockFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/QuotedFormatProvider.java
QuotedFormatProvider
adjustPPrForFormatting
class QuotedFormatProvider<T> extends BlockFormatProviderBase<T> { final private BigInteger myBefore; final private BigInteger myAfter; public QuotedFormatProvider(DocxContext<T> docx, int level, String styleId) { super(docx, styleId); BigInteger left; BigInteger before; BigInteger after; Style style = docx.getStyle(styleId); if (style != null) { // Should always be true left = docx.getHelper().safeIndLeft(style.getPPr(), 240); before = docx.getHelper().safeSpacingBefore(style.getPPr()); after = docx.getHelper().safeSpacingAfter(style.getPPr()); } else { left = BigInteger.valueOf(240); before = BigInteger.ZERO; after = BigInteger.ZERO; } BigInteger quoteLevel = BigInteger.valueOf(level); BigInteger leftInd = left.multiply(quoteLevel); myBefore = before; myAfter = after; } @Override public void open() { super.close(); myDocx.addBlankLine(myBefore, myDocx.getRenderingOptions().DEFAULT_STYLE); } @Override public void close() { myDocx.addBlankLine(myAfter, myDocx.getRenderingOptions().DEFAULT_STYLE); super.close(); } @Override public void adjustPPrForFormatting(PPr pPr) {<FILL_FUNCTION_BODY>} }
// // here we need to adjust for inherited left margin // BigInteger newLeftInd = myDocx.getHelper().safeIndLeft(pPr); // PPr styledPPr = myDocx.getHelper().getExplicitPPr(pPr); // if (styledPPr != null && styledPPr.getPBdr() != null && newLeftInd != null && newLeftInd.compareTo(myLeftInd) > 0) { // // it grew, word has the border hanging and we want to shift it by our left border spacing // CTBorder leftBorder = styledPPr.getPBdr().getLeft(); // if (leftBorder != null && leftBorder.getSpace() != null && leftBorder.getSpace().compareTo(BigInteger.ZERO) > 0) { // //pPr.getInd().setLeft(newLeftInd.add(leftBorder.getSpace().multiply(BigInteger.valueOf(20)))); // // // //T currentNode = myDocx.getContextFrame(); // //if (currentNode instanceof Paragraph) { // // int tmp = 0; // //} // } // }
420
296
716
<methods>public void <init>(DocxContext<T>, java.lang.String) ,public void adjustPPrForFormatting(org.docx4j.wml.PPr) ,public void close() ,public BlockFormatProvider<T> getBlockParent() ,public void getPPr(org.docx4j.wml.PPr) ,public void getParaRPr(org.docx4j.wml.RPr) ,public T getProviderFrame() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected int myPCount,protected final non-sealed BlockFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/RunFormatProviderBase.java
RunFormatProviderBase
getRPr
class RunFormatProviderBase<T> implements RunFormatProvider<T> { protected final DocxContext<T> myDocx; protected final T myFrame; protected final RunFormatProvider<T> myParent; protected final String myBaseStyleId; protected final boolean myNoCharacterStyles; protected final String myHighlightShadingColor; public RunFormatProviderBase(DocxContext<T> docx, String baseStyleId, boolean noCharacterStyles, String highlightShadingColor) { myDocx = docx; myFrame = docx.getContextFrame(); myParent = docx.getRunFormatProvider(); myBaseStyleId = baseStyleId; myNoCharacterStyles = noCharacterStyles; myHighlightShadingColor = highlightShadingColor == null ? "" : highlightShadingColor; } @Override public T getProviderFrame() { return myFrame; } @Override public void open() { } @Override public void close() { } @Override public Style getStyle() { return myDocx.getStyle(myBaseStyleId); } @Override public String getStyleId() { return myBaseStyleId; } @Override public RunFormatProvider<T> getRunParent() { return myParent; } /** * Get the style parent for the next P of this block * * @return parent to use for style inheritance */ protected RunFormatProvider<T> getStyleParent() { return myParent; } protected void inheritParentStyle(RPr rPr, RPr parentRPr) { RPr parentStyledRPr = myDocx.getHelper().getExplicitRPr(parentRPr); StyleUtil.apply(rPr, parentStyledRPr); StyleUtil.apply(parentStyledRPr, rPr); Style style = getStyle(); if (style != null) { RPr styleRPr = myDocx.getHelper().getExplicitRPr(style.getRPr()); StyleUtil.apply(rPr, styleRPr); StyleUtil.apply(styleRPr, rPr); } } @Override public void getRPr(RPr rPr) {<FILL_FUNCTION_BODY>} }
// Create object for rStyle if (!myNoCharacterStyles && myHighlightShadingColor.isEmpty() && myBaseStyleId != null) { RStyle rstyle = myDocx.getFactory().createRStyle(); rPr.setRStyle(rstyle); rstyle.setVal(myBaseStyleId); } // handle inheritance RunFormatProvider<T> parent = myParent; if (parent != null) { RPr rpr1 = myDocx.getFactory().createRPr(); parent.getRPr(rpr1); inheritParentStyle(rPr, rpr1); } if (myNoCharacterStyles || !myHighlightShadingColor.isEmpty()) { Style thisStyle = myBaseStyleId == null ? null : myDocx.getStyle(myBaseStyleId); if (thisStyle != null) { ParaRPr paraRPr = myDocx.getP().getPPr().getRPr(); if (!myHighlightShadingColor.isEmpty()) { String color = myHighlightShadingColor; CTShd shd = rPr.getShd(); if (shd != null) { String shdFill = shd.getFill(); if (shdFill != null && !shdFill.isEmpty() && !shdFill.equals("auto") && color.equals("shade")) { if (ColorNameMapper.isNamedColor(shdFill) || ColorNameMapper.isHexColor(shdFill)) { color = shdFill; } } rPr.setShd(null); } if (ColorNameMapper.isNamedColor(color)) { Highlight highlight = myDocx.getFactory().createHighlight(); highlight.setVal(color); rPr.setHighlight(highlight); } else if (ColorNameMapper.isHexColor(color)) { Highlight highlight = myDocx.getFactory().createHighlight(); highlight.setVal(ColorNameMapper.findClosestNamedColor(color)); rPr.setHighlight(highlight); } else { // not valid color } } //myDocx.getHelper().keepDiff(rPr, pr); myDocx.getHelper().keepDiff(rPr, paraRPr); } }
596
589
1,185
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/SubscriptRunFormatProvider.java
SubscriptRunFormatProvider
getRPr
class SubscriptRunFormatProvider<T> extends RunFormatProviderBase<T> { public SubscriptRunFormatProvider(DocxContext<T> docx, boolean noCharacterStyles) { super(docx, docx.getRenderingOptions().SUBSCRIPT_STYLE, noCharacterStyles, null); } @Override public void getRPr(RPr rPr) {<FILL_FUNCTION_BODY>} }
super.getRPr(rPr); // //// Create object for sz //HpsMeasure hpsmeasure = docx.getFactory().createHpsMeasure(); //rPr.setSz(hpsmeasure); //hpsmeasure.setVal(BigInteger.valueOf(19)); // //// Create object for position //CTSignedHpsMeasure signedhpsmeasure = docx.getFactory().createCTSignedHpsMeasure(); //rPr.setPosition(signedhpsmeasure); //signedhpsmeasure.setVal(BigInteger.valueOf(-4));
109
154
263
<methods>public void <init>(DocxContext<T>, java.lang.String, boolean, java.lang.String) ,public void close() ,public T getProviderFrame() ,public void getRPr(org.docx4j.wml.RPr) ,public RunFormatProvider<T> getRunParent() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected final non-sealed java.lang.String myHighlightShadingColor,protected final non-sealed boolean myNoCharacterStyles,protected final non-sealed RunFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/SuperscriptRunFormatProvider.java
SuperscriptRunFormatProvider
getRPr
class SuperscriptRunFormatProvider<T> extends RunFormatProviderBase<T> { public SuperscriptRunFormatProvider(DocxContext<T> docx, boolean noCharacterStyles) { super(docx, docx.getRenderingOptions().SUPERSCRIPT_STYLE, noCharacterStyles, null); } @Override public void getRPr(RPr rPr) {<FILL_FUNCTION_BODY>} }
super.getRPr(rPr); // //// Create object for sz //HpsMeasure hpsmeasure = docx.getFactory().createHpsMeasure(); //rPr.setSz(hpsmeasure); //hpsmeasure.setVal(BigInteger.valueOf(19)); // //// Create object for position //CTSignedHpsMeasure signedhpsmeasure = docx.getFactory().createCTSignedHpsMeasure(); //rPr.setPosition(signedhpsmeasure); //signedhpsmeasure.setVal(BigInteger.valueOf(8));
113
154
267
<methods>public void <init>(DocxContext<T>, java.lang.String, boolean, java.lang.String) ,public void close() ,public T getProviderFrame() ,public void getRPr(org.docx4j.wml.RPr) ,public RunFormatProvider<T> getRunParent() ,public org.docx4j.wml.Style getStyle() ,public java.lang.String getStyleId() ,public void open() <variables>protected final non-sealed java.lang.String myBaseStyleId,protected final non-sealed DocxContext<T> myDocx,protected final non-sealed T myFrame,protected final non-sealed java.lang.String myHighlightShadingColor,protected final non-sealed boolean myNoCharacterStyles,protected final non-sealed RunFormatProvider<T> myParent
vsch_flexmark-java
flexmark-java/flexmark-docx-converter/src/main/java/com/vladsch/flexmark/docx/converter/util/XmlFormatter.java
XmlFormatter
format
class XmlFormatter { public static String format(String xml) {<FILL_FUNCTION_BODY>} public static String formatDocumentBody(String xml) { try { InputSource src = new InputSource(new StringReader(xml)); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(false); Document document = builderFactory.newDocumentBuilder().parse(src); NodeList bodies = document.getElementsByTagName("w:body"); NodeList sections = document.getElementsByTagName("w:sectPr"); NodeList footnotes = document.getElementsByTagName("w:footnote"); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", false); int iMax = sections.getLength(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < iMax; i++) { Node item = sections.item(i); item.getParentNode().removeChild(item); } iMax = bodies.getLength(); for (int i = 0; i < iMax; i++) { Node item = bodies.item(i); sb.append(writer.writeToString(item)); } iMax = footnotes.getLength(); for (int i = 0; i < iMax; i++) { Node item = footnotes.item(i); sb.append(writer.writeToString(item)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } } }
try { InputSource src = new InputSource(new StringReader(xml)); Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement(); Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml")); //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted. return writer.writeToString(document); } catch (Exception e) { throw new RuntimeException(e); }
488
270
758
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/AbbreviationExtension.java
AbbreviationExtension
extend
class AbbreviationExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, Parser.ReferenceHoldingExtension, Formatter.FormatterExtension { /** * A {@link DataKey} that is used to set the behavior of the abbreviations repository when duplicates are defined. {@link KeepType} */ final public static DataKey<KeepType> ABBREVIATIONS_KEEP = new DataKey<>("ABBREVIATIONS_KEEP", KeepType.FIRST); /** * A {@link DataKey} that is used to get the document's Node repository holding all the abbreviations defined in the current document. */ final public static DataKey<AbbreviationRepository> ABBREVIATIONS = new DataKey<>("ABBREVIATIONS", new AbbreviationRepository(null), AbbreviationRepository::new); /** * A {@link DataKey} that is used to set the use links option when true, default is false and abbr tag will be used in the rendered HTML. */ final public static DataKey<Boolean> USE_LINKS = new DataKey<>("USE_LINKS", false); // format options final public static DataKey<ElementPlacement> ABBREVIATIONS_PLACEMENT = new DataKey<>("ABBREVIATIONS_PLACEMENT", ElementPlacement.AS_IS); final public static DataKey<ElementPlacementSort> ABBREVIATIONS_SORT = new DataKey<>("ABBREVIATIONS_SORT", ElementPlacementSort.AS_IS); final public static DataKey<Boolean> MAKE_MERGED_ABBREVIATIONS_UNIQUE = new DataKey<>("MERGE_MAKE_ABBREVIATIONS_UNIQUE", false); public static AbbreviationExtension create() { return new AbbreviationExtension(); } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new AbbreviationNodeFormatter.Factory()); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public boolean transferReferences(MutableDataHolder document, DataHolder included) { // abbreviations cannot be transferred except before parsing the document //if (document.contains(ABBREVIATIONS) && included.contains(ABBREVIATIONS)) { // if (Parser.transferReferences(ABBREVIATIONS.getFrom(document), ABBREVIATIONS.getFrom(included), ABBREVIATIONS_KEEP.getFrom(document) == KeepType.FIRST)) { // // reset abbreviations optimization // document.set(RECOMPUTE_ABBREVIATIONS_MAP, true); // } //} return false; } @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new AbbreviationBlockParser.Factory()); //parserBuilder.paragraphPreProcessorFactory(AbbreviationParagraphPreProcessor.Factory()); parserBuilder.postProcessorFactory(new AbbreviationNodePostProcessor.Factory()); } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) {<FILL_FUNCTION_BODY>} }
if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new AbbreviationNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { }
848
59
907
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/AbbreviationVisitorExt.java
AbbreviationVisitorExt
VISIT_HANDLERS
class AbbreviationVisitorExt { public static <V extends AbbreviationVisitor> VisitHandler<?>[] VISIT_HANDLERS(V visitor) {<FILL_FUNCTION_BODY>} }
return new VisitHandler<?>[] { new VisitHandler<>(AbbreviationBlock.class, visitor::visit), new VisitHandler<>(Abbreviation.class, visitor::visit), };
55
54
109
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/internal/AbbreviationBlockParser.java
BlockFactory
tryStart
class BlockFactory extends AbstractBlockParserFactory { BlockFactory(DataHolder options) { super(options); } @Override public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {<FILL_FUNCTION_BODY>} }
if (state.getIndent() >= 4) { return BlockStart.none(); } BasedSequence line = state.getLine(); int nextNonSpace = state.getNextNonSpaceIndex(); BasedSequence trySequence = line.subSequence(nextNonSpace, line.length()); Matcher matcher = ABBREVIATION_BLOCK.matcher(trySequence); if (matcher.find()) { // abbreviation definition int openingStart = nextNonSpace + matcher.start(); int openingEnd = nextNonSpace + matcher.end(); BasedSequence openingMarker = trySequence.subSequence(openingStart, openingStart + 2); BasedSequence text = trySequence.subSequence(openingStart + 2, openingEnd - 2).trim(); BasedSequence closingMarker = trySequence.subSequence(openingEnd - 2, openingEnd); AbbreviationBlockParser abbreviationBlock = new AbbreviationBlockParser(); abbreviationBlock.block.setOpeningMarker(openingMarker); abbreviationBlock.block.setText(text); abbreviationBlock.block.setClosingMarker(closingMarker); abbreviationBlock.block.setAbbreviation(trySequence.subSequence(matcher.end()).trim()); abbreviationBlock.block.setCharsFromContent(); return BlockStart.of(abbreviationBlock) .atIndex(line.length()); } else { return BlockStart.none(); }
70
360
430
<methods>public non-sealed void <init>() ,public void addLine(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.util.sequence.BasedSequence) ,public boolean breakOutOnDoubleBlankLine() ,public boolean canContain(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.parser.block.BlockParser, com.vladsch.flexmark.util.ast.Block) ,public boolean canInterruptBy(com.vladsch.flexmark.parser.block.BlockParserFactory) ,public final void finalizeClosedBlock() ,public com.vladsch.flexmark.util.ast.BlockContent getBlockContent() ,public com.vladsch.flexmark.util.data.MutableDataHolder getDataHolder() ,public boolean isClosed() ,public boolean isContainer() ,public boolean isInterruptible() ,public boolean isParagraphParser() ,public boolean isPropagatingLastBlankLine(com.vladsch.flexmark.parser.block.BlockParser) ,public boolean isRawText() ,public void parseInlines(com.vladsch.flexmark.parser.InlineParser) ,public void removeBlankLines() <variables>private boolean isClosed,private com.vladsch.flexmark.util.data.MutableDataSet mutableData
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/internal/AbbreviationNodeFormatter.java
AbbreviationNodeFormatter
modifyTransformedReference
class AbbreviationNodeFormatter extends NodeRepositoryFormatter<AbbreviationRepository, AbbreviationBlock, Abbreviation> { final public static DataKey<Map<String, String>> ABBREVIATION_TRANSLATION_MAP = new DataKey<>("ABBREVIATION_TRANSLATION_MAP", new HashMap<>()); // final public static DataKey<Map<String, String>> ABBREVIATION_UNIQUIFICATION_MAP = new DataKey<>("ABBREVIATION_UNIQUIFICATION_MAP", new HashMap<>()); // uniquified references final private AbbreviationFormatOptions options; final private boolean transformUnderscores; final private boolean makeMergedAbbreviationsUnique; public AbbreviationNodeFormatter(DataHolder options) { super(options, ABBREVIATION_TRANSLATION_MAP, ABBREVIATION_UNIQUIFICATION_MAP); this.options = new AbbreviationFormatOptions(options); String transformedId = String.format(Formatter.TRANSLATION_ID_FORMAT.get(options), 1); transformUnderscores = transformedId.startsWith("_") && transformedId.endsWith("_"); makeMergedAbbreviationsUnique = AbbreviationExtension.MAKE_MERGED_ABBREVIATIONS_UNIQUE.get(options); } @Override protected boolean makeReferencesUnique() { return makeMergedAbbreviationsUnique; } @Override public AbbreviationRepository getRepository(DataHolder options) { return AbbreviationExtension.ABBREVIATIONS.get(options); } @Override public ElementPlacement getReferencePlacement() { return options.abbreviationsPlacement; } @Override public ElementPlacementSort getReferenceSort() { return options.abbreviationsSort; } @Override public String modifyTransformedReference(String transformedText, NodeFormatterContext context) {<FILL_FUNCTION_BODY>} @Override public void renderReferenceBlock(AbbreviationBlock node, NodeFormatterContext context, MarkdownWriter markdown) { markdown.append(node.getOpeningMarker()); markdown.append(transformReferenceId(node.getText().toString(), context)); markdown.append(node.getClosingMarker()).append(' '); markdown.appendTranslating(node.getAbbreviation()).line(); } @Nullable @Override public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() { return new HashSet<>(Arrays.asList( new NodeFormattingHandler<>(Abbreviation.class, AbbreviationNodeFormatter.this::render), new NodeFormattingHandler<>(AbbreviationBlock.class, AbbreviationNodeFormatter.this::render) )); } @Nullable @Override public Set<Class<?>> getNodeClasses() { if (options.abbreviationsPlacement.isNoChange() || !options.abbreviationsSort.isUnused()) return null; // noinspection ArraysAsListWithZeroOrOneArgument return new HashSet<>(Arrays.asList( Abbreviation.class )); } private void render(AbbreviationBlock node, NodeFormatterContext context, MarkdownWriter markdown) { renderReference(node, context, markdown); } private void render(Abbreviation node, NodeFormatterContext context, MarkdownWriter markdown) { if (context.isTransformingText()) { String referenceId = transformReferenceId(node.getChars().toString(), context); markdown.append(referenceId); } else { markdown.append(node.getChars()); } } public static class Factory implements NodeFormatterFactory { @NotNull @Override public NodeFormatter create(@NotNull DataHolder options) { return new AbbreviationNodeFormatter(options); } } }
if (transformUnderscores && context.isTransformingText()) { if (transformedText.startsWith("-") && transformedText.endsWith("-")) { transformedText = "_" + transformedText.substring(1, transformedText.length() - 1) + "_"; } else if (transformedText.startsWith("_") && transformedText.endsWith("_")) { transformedText = "-" + transformedText.substring(1, transformedText.length() - 1) + "-"; } } return transformedText;
1,004
141
1,145
<methods>public void <init>(com.vladsch.flexmark.util.data.DataHolder, DataKey<Map<java.lang.String,java.lang.String>>, DataKey<Map<java.lang.String,java.lang.String>>) ,public @Nullable Set<FormattingPhase> getFormattingPhases() ,public Comparator<com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock> getReferenceComparator() ,public abstract com.vladsch.flexmark.util.format.options.ElementPlacement getReferencePlacement() ,public abstract com.vladsch.flexmark.util.format.options.ElementPlacementSort getReferenceSort() ,public abstract com.vladsch.flexmark.ext.abbreviation.internal.AbbreviationRepository getRepository(com.vladsch.flexmark.util.data.DataHolder) ,public java.lang.String modifyTransformedReference(java.lang.String, com.vladsch.flexmark.formatter.NodeFormatterContext) ,public void renderDocument(@NotNull NodeFormatterContext, @NotNull MarkdownWriter, @NotNull Document, @NotNull FormattingPhase) <variables>public static final HashSet<com.vladsch.flexmark.formatter.FormattingPhase> FORMATTING_PHASES,protected final non-sealed com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock lastReference,protected final non-sealed Comparator<com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock> myComparator,private final non-sealed DataKey<Map<java.lang.String,java.lang.String>> myReferenceMapKey,private final non-sealed DataKey<Map<java.lang.String,java.lang.String>> myReferenceUniqificationMapKey,protected boolean recheckUndefinedReferences,protected final non-sealed List<com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock> referenceList,protected final non-sealed com.vladsch.flexmark.ext.abbreviation.internal.AbbreviationRepository referenceRepository,private Map<java.lang.String,java.lang.String> referenceTranslationMap,protected Map<java.lang.String,java.lang.String> referenceUniqificationMap,protected boolean repositoryNodesDone,protected final non-sealed HashSet<com.vladsch.flexmark.util.ast.Node> unusedReferences
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/internal/AbbreviationNodePostProcessor.java
AbbreviationNodePostProcessor
process
class AbbreviationNodePostProcessor extends NodePostProcessor { private Pattern abbreviations = null; private HashMap<String, BasedSequence> abbreviationMap = null; private AbbreviationNodePostProcessor(Document document) { computeAbbreviations(document); } private void computeAbbreviations(Document document) { AbbreviationRepository abbrRepository = AbbreviationExtension.ABBREVIATIONS.get(document); if (!abbrRepository.isEmpty()) { abbreviationMap = new HashMap<>(); StringBuilder sb = new StringBuilder(); // sort reverse alphabetical order so longer ones match first. for sdk7 ArrayList<String> abbreviations = new ArrayList<>(abbrRepository.keySet()); abbreviations.sort(Comparator.reverseOrder()); for (String abbr : abbreviations) { // Issue #198, test for empty abbr if (!abbr.isEmpty()) { AbbreviationBlock abbreviationBlock = abbrRepository.get(abbr); if (abbreviationBlock != null) { BasedSequence abbreviation = abbreviationBlock.getAbbreviation(); if (!abbreviation.isEmpty()) { abbreviationMap.put(abbr, abbreviation); if (sb.length() > 0) sb.append("|"); if (Character.isLetterOrDigit(abbr.charAt(0))) sb.append("\\b"); sb.append("\\Q").append(abbr).append("\\E"); if (Character.isLetterOrDigit(abbr.charAt(abbr.length() - 1))) sb.append("\\b"); } } } } if (sb.length() > 0) this.abbreviations = Pattern.compile(sb.toString()); } } @Override public void process(@NotNull NodeTracker state, @NotNull Node node) {<FILL_FUNCTION_BODY>} public static class Factory extends NodePostProcessorFactory { @Nullable @Override public Set<Class<?>> getAfterDependents() { HashSet<Class<?>> set = new HashSet<>(); set.add(AutolinkNodePostProcessor.Factory.class); return set; } public Factory() { super(false); addNodeWithExclusions(Text.class, DoNotDecorate.class, DoNotLinkDecorate.class); } @NotNull @Override public NodePostProcessor apply(@NotNull Document document) { return new AbbreviationNodePostProcessor(document); } } }
if (abbreviations == null) return; BasedSequence original = node.getChars(); ReplacedTextMapper textMapper = new ReplacedTextMapper(original); BasedSequence literal = Escaping.unescape(original, textMapper); Matcher m = abbreviations.matcher(literal); int lastEscaped = 0; boolean wrapInTextBase = !(node.getParent() instanceof TextBase); TextBase textBase = wrapInTextBase ? null : (TextBase) node.getParent(); while (m.find()) { //String found = m.group(); BasedSequence abbreviation = abbreviationMap.get(m.group(0)); if (abbreviation != null) { int startOffset = textMapper.originalOffset(m.start(0)); int endOffset = textMapper.originalOffset(m.end(0)); if (wrapInTextBase) { wrapInTextBase = false; textBase = new TextBase(original); node.insertBefore(textBase); state.nodeAdded(textBase); } if (startOffset != lastEscaped) { BasedSequence escapedChars = original.subSequence(lastEscaped, startOffset); Node node1 = new Text(escapedChars); textBase.appendChild(node1); state.nodeAdded(node1); } BasedSequence origToDecorateText = original.subSequence(startOffset, endOffset); Abbreviation decorationNode = new Abbreviation(origToDecorateText, abbreviation); textBase.appendChild(decorationNode); state.nodeAdded(decorationNode); lastEscaped = endOffset; } } if (lastEscaped > 0) { if (lastEscaped != original.length()) { BasedSequence escapedChars = original.subSequence(lastEscaped, original.length()); Node node1 = new Text(escapedChars); textBase.appendChild(node1); state.nodeAdded(node1); } node.unlink(); state.nodeRemoved(node); }
652
534
1,186
<methods>public non-sealed void <init>() ,public final @NotNull Document processDocument(@NotNull Document) <variables>
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/internal/AbbreviationNodeRenderer.java
AbbreviationNodeRenderer
render
class AbbreviationNodeRenderer implements NodeRenderer { final private AbbreviationOptions options; public AbbreviationNodeRenderer(DataHolder options) { this.options = new AbbreviationOptions(options); } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() { return new HashSet<>(Arrays.asList( new NodeRenderingHandler<>(Abbreviation.class, this::render), new NodeRenderingHandler<>(AbbreviationBlock.class, this::render) )); } private void render(AbbreviationBlock node, NodeRendererContext context, HtmlWriter html) { } private void render(Abbreviation node, NodeRendererContext context, HtmlWriter html) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new AbbreviationNodeRenderer(options); } } }
String text = node.getChars().unescape(); BasedSequence abbreviation = node.getAbbreviation(); String tag; if (options.useLinks) { html.attr("href", "#"); tag = "a"; } else { tag = "abbr"; } html.attr("title", abbreviation); html.srcPos(node.getChars()).withAttr().tag(tag); html.text(text); html.closeTag(tag);
254
130
384
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-abbreviation/src/main/java/com/vladsch/flexmark/ext/abbreviation/internal/AbbreviationRepository.java
AbbreviationRepository
getReferencedElements
class AbbreviationRepository extends NodeRepository<AbbreviationBlock> { public AbbreviationRepository(DataHolder options) { super(AbbreviationExtension.ABBREVIATIONS_KEEP.get(options)); } @NotNull @Override public DataKey<AbbreviationRepository> getDataKey() { return AbbreviationExtension.ABBREVIATIONS; } @NotNull @Override public DataKey<KeepType> getKeepDataKey() { return AbbreviationExtension.ABBREVIATIONS_KEEP; } @NotNull @Override public Set<AbbreviationBlock> getReferencedElements(Node parent) {<FILL_FUNCTION_BODY>} }
HashSet<AbbreviationBlock> references = new HashSet<>(); visitNodes(parent, value -> { if (value instanceof Abbreviation) { AbbreviationBlock reference = ((Abbreviation) value).getReferenceNode(AbbreviationRepository.this); if (reference != null) { references.add(reference); } } }, Abbreviation.class); return references;
189
106
295
<methods>public void <init>(@Nullable KeepType) ,public void clear() ,public boolean containsKey(@NotNull Object) ,public boolean containsValue(java.lang.Object) ,public @NotNull Set<Map.Entry<String,AbbreviationBlock>> entrySet() ,public boolean equals(java.lang.Object) ,public @Nullable AbbreviationBlock get(@NotNull Object) ,public abstract @NotNull DataKey<? extends NodeRepository<AbbreviationBlock>> getDataKey() ,public @Nullable AbbreviationBlock getFromRaw(@NotNull CharSequence) ,public abstract @NotNull DataKey<KeepType> getKeepDataKey() ,public abstract @NotNull Set<AbbreviationBlock> getReferencedElements(com.vladsch.flexmark.util.ast.Node) ,public @NotNull Collection<AbbreviationBlock> getValues() ,public int hashCode() ,public boolean isEmpty() ,public @NotNull Set<String> keySet() ,public @NotNull String normalizeKey(@NotNull CharSequence) ,public @Nullable AbbreviationBlock put(@NotNull String, @NotNull AbbreviationBlock) ,public void putAll(@NotNull Map<? extends String,? extends AbbreviationBlock>) ,public @Nullable AbbreviationBlock putRawKey(@NotNull CharSequence, @NotNull AbbreviationBlock) ,public @Nullable AbbreviationBlock remove(@NotNull Object) ,public int size() ,public static boolean transferReferences(@NotNull NodeRepository<T>, @NotNull NodeRepository<T>, boolean, @Nullable Map<String,String>) ,public @NotNull List<AbbreviationBlock> values() <variables>protected final non-sealed com.vladsch.flexmark.util.ast.KeepType keepType,protected final ArrayList<com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock> nodeList,protected final Map<java.lang.String,com.vladsch.flexmark.ext.abbreviation.AbbreviationBlock> nodeMap
vsch_flexmark-java
flexmark-java/flexmark-ext-admonition/src/main/java/com/vladsch/flexmark/ext/admonition/AdmonitionBlock.java
AdmonitionBlock
setTitleChars
class AdmonitionBlock extends Block implements ParagraphContainer { private BasedSequence openingMarker = BasedSequence.NULL; private BasedSequence info = BasedSequence.NULL; protected BasedSequence titleOpeningMarker = BasedSequence.NULL; protected BasedSequence title = BasedSequence.NULL; protected BasedSequence titleClosingMarker = BasedSequence.NULL; @NotNull @Override public BasedSequence[] getSegments() { return new BasedSequence[] { openingMarker, info, titleOpeningMarker, title, titleClosingMarker, }; } @NotNull @Override public BasedSequence[] getSegmentsForChars() { return new BasedSequence[] { openingMarker, info, titleOpeningMarker, title, titleClosingMarker, }; } @Override public void getAstExtra(@NotNull StringBuilder out) { segmentSpanChars(out, openingMarker, "open"); segmentSpanChars(out, info, "info"); delimitedSegmentSpanChars(out, titleOpeningMarker, title, titleClosingMarker, "title"); } public AdmonitionBlock() { } public AdmonitionBlock(BasedSequence chars) { super(chars); } public AdmonitionBlock(BasedSequence chars, BasedSequence openingMarker, BasedSequence info, List<BasedSequence> segments) { super(chars, segments); this.openingMarker = openingMarker; this.info = info; } public BasedSequence getOpeningMarker() { return openingMarker; } public void setOpeningMarker(BasedSequence openingMarker) { this.openingMarker = openingMarker; } public void setInfo(BasedSequence info) { this.info = info; } public BasedSequence getInfo() { return info; } public BasedSequence getTitle() { return title; } public BasedSequence getTitleOpeningMarker() { return titleOpeningMarker; } public void setTitleOpeningMarker(BasedSequence titleOpeningMarker) { this.titleOpeningMarker = titleOpeningMarker; } public void setTitle(BasedSequence title) { this.title = title; } public BasedSequence getTitleClosingMarker() { return titleClosingMarker; } public void setTitleClosingMarker(BasedSequence titleClosingMarker) { this.titleClosingMarker = titleClosingMarker; } public BasedSequence getTitleChars() { return spanningChars(titleOpeningMarker, title, titleClosingMarker); } public void setTitleChars(BasedSequence titleChars) {<FILL_FUNCTION_BODY>} @Override public boolean isParagraphEndWrappingDisabled(Paragraph node) { return false; } @Override public boolean isParagraphStartWrappingDisabled(Paragraph node) { if (node == getFirstChild()) { // need to see if there is a blank line between it and our start int ourEOL = getChars().getBaseSequence().endOfLine(getChars().getStartOffset()); int childStartEOL = node.getStartOfLine(); return ourEOL + 1 == childStartEOL; } return false; } }
if (titleChars != null && titleChars != BasedSequence.NULL) { int titleCharsLength = titleChars.length(); titleOpeningMarker = titleChars.subSequence(0, 1); title = titleChars.subSequence(1, titleCharsLength - 1); titleClosingMarker = titleChars.subSequence(titleCharsLength - 1, titleCharsLength); } else { titleOpeningMarker = BasedSequence.NULL; title = BasedSequence.NULL; titleClosingMarker = BasedSequence.NULL; }
853
147
1,000
<methods>public void <init>() ,public void <init>(@NotNull BasedSequence) ,public void <init>(@NotNull BasedSequence, @NotNull List<BasedSequence>) ,public void <init>(@NotNull List<BasedSequence>) ,public void <init>(com.vladsch.flexmark.util.ast.BlockContent) ,public @Nullable Block getParent() <variables>
vsch_flexmark-java
flexmark-java/flexmark-ext-admonition/src/main/java/com/vladsch/flexmark/ext/admonition/internal/AdmonitionBlockParser.java
BlockFactory
tryStart
class BlockFactory extends AbstractBlockParserFactory { final private AdmonitionOptions options; BlockFactory(DataHolder options) { super(options); this.options = new AdmonitionOptions(options); } @Override public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {<FILL_FUNCTION_BODY>} }
if (state.getIndent() >= 4) { return BlockStart.none(); } int nextNonSpace = state.getNextNonSpaceIndex(); BlockParser matched = matchedBlockParser.getBlockParser(); boolean inParagraph = matched.isParagraphParser(); boolean inParagraphListItem = inParagraph && matched.getBlock().getParent() instanceof ListItem && matched.getBlock() == matched.getBlock().getParent().getFirstChild(); if (isMarker(state, nextNonSpace, inParagraph, inParagraphListItem, options)) { BasedSequence line = state.getLine(); BasedSequence trySequence = line.subSequence(nextNonSpace, line.length()); Parsing parsing = state.getParsing(); Pattern startPattern = Pattern.compile(String.format(ADMONITION_START_FORMAT, parsing.ATTRIBUTENAME, parsing.LINK_TITLE_STRING)); Matcher matcher = startPattern.matcher(trySequence); if (matcher.find()) { // admonition block BasedSequence openingMarker = line.subSequence(nextNonSpace + matcher.start(1), nextNonSpace + matcher.end(1)); BasedSequence info = line.subSequence(nextNonSpace + matcher.start(2), nextNonSpace + matcher.end(2)); BasedSequence titleChars = matcher.group(3) == null ? BasedSequence.NULL : line.subSequence(nextNonSpace + matcher.start(3), nextNonSpace + matcher.end(3)); int contentOffset = options.contentIndent; AdmonitionBlockParser admonitionBlockParser = new AdmonitionBlockParser(options, contentOffset); admonitionBlockParser.block.setOpeningMarker(openingMarker); admonitionBlockParser.block.setInfo(info); admonitionBlockParser.block.setTitleChars(titleChars); return BlockStart.of(admonitionBlockParser) .atIndex(line.length()); } else { return BlockStart.none(); } } else { return BlockStart.none(); }
95
533
628
<methods>public non-sealed void <init>() ,public void addLine(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.util.sequence.BasedSequence) ,public boolean breakOutOnDoubleBlankLine() ,public boolean canContain(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.parser.block.BlockParser, com.vladsch.flexmark.util.ast.Block) ,public boolean canInterruptBy(com.vladsch.flexmark.parser.block.BlockParserFactory) ,public final void finalizeClosedBlock() ,public com.vladsch.flexmark.util.ast.BlockContent getBlockContent() ,public com.vladsch.flexmark.util.data.MutableDataHolder getDataHolder() ,public boolean isClosed() ,public boolean isContainer() ,public boolean isInterruptible() ,public boolean isParagraphParser() ,public boolean isPropagatingLastBlankLine(com.vladsch.flexmark.parser.block.BlockParser) ,public boolean isRawText() ,public void parseInlines(com.vladsch.flexmark.parser.InlineParser) ,public void removeBlankLines() <variables>private boolean isClosed,private com.vladsch.flexmark.util.data.MutableDataSet mutableData
vsch_flexmark-java
flexmark-java/flexmark-ext-admonition/src/main/java/com/vladsch/flexmark/ext/admonition/internal/AdmonitionNodeFormatter.java
AdmonitionNodeFormatter
render
class AdmonitionNodeFormatter implements NodeFormatter { final private AdmonitionOptions options; public AdmonitionNodeFormatter(DataHolder options) { this.options = new AdmonitionOptions(options); } @Nullable @Override public Set<Class<?>> getNodeClasses() { return null; } @Nullable @Override public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() { return new HashSet<>(Collections.singletonList( new NodeFormattingHandler<>(AdmonitionBlock.class, AdmonitionNodeFormatter.this::render) )); } private void render(AdmonitionBlock node, NodeFormatterContext context, MarkdownWriter markdown) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeFormatterFactory { @NotNull @Override public NodeFormatter create(@NotNull DataHolder options) { return new AdmonitionNodeFormatter(options); } } }
markdown.blankLine(); markdown.append(node.getOpeningMarker()).append(' '); markdown.appendNonTranslating(node.getInfo()); if (node.getTitle().isNotNull()) { markdown.append(' ').append('"').appendTranslating(node.getTitle()).append('"'); } markdown.line(); markdown.pushPrefix().addPrefix(RepeatedSequence.repeatOf(" ", options.contentIndent).toString()); context.renderChildren(node); markdown.blankLine(); markdown.popPrefix();
258
148
406
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-admonition/src/main/java/com/vladsch/flexmark/ext/admonition/internal/AdmonitionNodeRenderer.java
AdmonitionNodeRenderer
renderDocument
class AdmonitionNodeRenderer implements PhasedNodeRenderer { public static AttributablePart ADMONITION_SVG_OBJECT_PART = new AttributablePart("ADMONITION_SVG_OBJECT_PART"); public static AttributablePart ADMONITION_HEADING_PART = new AttributablePart("ADMONITION_HEADING_PART"); public static AttributablePart ADMONITION_ICON_PART = new AttributablePart("ADMONITION_ICON_PART"); public static AttributablePart ADMONITION_TITLE_PART = new AttributablePart("ADMONITION_TITLE_PART"); public static AttributablePart ADMONITION_BODY_PART = new AttributablePart("ADMONITION_BODY_PART"); final private AdmonitionOptions options; public AdmonitionNodeRenderer(DataHolder options) { this.options = new AdmonitionOptions(options); } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() { Set<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(AdmonitionBlock.class, this::render)); return set; } @Override public Set<RenderingPhase> getRenderingPhases() { LinkedHashSet<RenderingPhase> phaseSet = new LinkedHashSet<>(); phaseSet.add(BODY_TOP); return phaseSet; } @Override public void renderDocument(@NotNull NodeRendererContext context, @NotNull HtmlWriter html, @NotNull Document document, @NotNull RenderingPhase phase) {<FILL_FUNCTION_BODY>} private void render(AdmonitionBlock node, NodeRendererContext context, HtmlWriter html) { String info = node.getInfo().toString().toLowerCase(); String type = this.options.qualifierTypeMap.get(info); if (type == null) { type = options.unresolvedQualifier; } String title; if (node.getTitle().isNull()) { title = this.options.qualifierTitleMap.get(info); if (title == null) { title = info.substring(0, 1).toUpperCase() + info.substring(1); } } else { title = node.getTitle().toString(); } String openClose; if (node.getOpeningMarker().equals("???")) openClose = " adm-collapsed"; else if (node.getOpeningMarker().equals("???+")) openClose = "adm-open"; else openClose = null; if (title.isEmpty()) { html.srcPos(node.getChars()).withAttr() .attr(Attribute.CLASS_ATTR, "adm-block") .attr(Attribute.CLASS_ATTR, "adm-" + type) .tag("div", false).line(); html.attr(Attribute.CLASS_ATTR, "adm-body").withAttr(ADMONITION_BODY_PART).tag("div").indent().line(); context.renderChildren(node); html.unIndent().closeTag("div").line(); html.closeTag("div").line(); } else { html.srcPos(node.getChars()) .attr(Attribute.CLASS_ATTR, "adm-block").attr(Attribute.CLASS_ATTR, "adm-" + type); if (openClose != null) { html.attr(Attribute.CLASS_ATTR, openClose).attr(Attribute.CLASS_ATTR, "adm-" + type); } html.withAttr().tag("div", false).line(); html.attr(Attribute.CLASS_ATTR, "adm-heading").withAttr(ADMONITION_HEADING_PART).tag("div").line(); html.attr(Attribute.CLASS_ATTR, "adm-icon").withAttr(ADMONITION_ICON_PART).tag("svg").raw("<use xlink:href=\"#adm-").raw(type).raw("\" />").closeTag("svg"); html.withAttr(ADMONITION_TITLE_PART).tag("span").text(title).closeTag("span").line(); html.closeTag("div").line(); html.attr(Attribute.CLASS_ATTR, "adm-body").withAttr(ADMONITION_BODY_PART).withCondIndent().tagLine("div", () -> context.renderChildren(node)); html.closeTag("div").line(); } } public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new AdmonitionNodeRenderer(options); } } }
if (phase == BODY_TOP) { // dump out the SVG used by the rest of the nodes HashSet<String> resolvedQualifiers = new HashSet<>(); Set<String> referencedQualifiers = new AdmonitionCollectingVisitor().collectAndGetQualifiers(document); for (String qualifier : referencedQualifiers) { String resolvedQualifier = this.options.qualifierTypeMap.get(qualifier); if (resolvedQualifier == null) resolvedQualifier = options.unresolvedQualifier; resolvedQualifiers.add(resolvedQualifier); } if (!resolvedQualifiers.isEmpty()) { html.line().attr("xmlns", "http://www.w3.org/2000/svg").attr(Attribute.CLASS_ATTR, "adm-hidden").withAttr(ADMONITION_SVG_OBJECT_PART) .tag("svg").indent().line(); for (String info : resolvedQualifiers) { String svgContent = options.typeSvgMap.get(info); if (svgContent != null && !svgContent.isEmpty()) { html.raw("<symbol id=\"adm-").raw(info).raw("\">").indent().line() .raw(svgContent).line() .unIndent().raw("</symbol>").line(); } } html.unIndent().closeTag("svg").line(); } }
1,180
366
1,546
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-anchorlink/src/main/java/com/vladsch/flexmark/ext/anchorlink/AnchorLinkExtension.java
AnchorLinkExtension
extend
class AnchorLinkExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension { final public static DataKey<Boolean> ANCHORLINKS_WRAP_TEXT = new DataKey<>("ANCHORLINKS_WRAP_TEXT", true); final public static DataKey<String> ANCHORLINKS_TEXT_PREFIX = new DataKey<>("ANCHORLINKS_TEXT_PREFIX", ""); final public static DataKey<String> ANCHORLINKS_TEXT_SUFFIX = new DataKey<>("ANCHORLINKS_TEXT_SUFFIX", ""); final public static DataKey<String> ANCHORLINKS_ANCHOR_CLASS = new DataKey<>("ANCHORLINKS_ANCHOR_CLASS", ""); final public static DataKey<Boolean> ANCHORLINKS_SET_NAME = new DataKey<>("ANCHORLINKS_SET_NAME", false); final public static DataKey<Boolean> ANCHORLINKS_SET_ID = new DataKey<>("ANCHORLINKS_SET_ID", true); final public static DataKey<Boolean> ANCHORLINKS_NO_BLOCK_QUOTE = new DataKey<>("ANCHORLINKS_NO_BLOCK_QUOTE", false); private AnchorLinkExtension() { } public static AnchorLinkExtension create() { return new AnchorLinkExtension(); } @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.postProcessorFactory(new AnchorLinkNodePostProcessor.Factory(parserBuilder)); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) {<FILL_FUNCTION_BODY>} }
if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new AnchorLinkNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { }
473
59
532
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-anchorlink/src/main/java/com/vladsch/flexmark/ext/anchorlink/internal/AnchorLinkNodePostProcessor.java
AnchorLinkNodePostProcessor
process
class AnchorLinkNodePostProcessor extends NodePostProcessor { final private AnchorLinkOptions options; public AnchorLinkNodePostProcessor(DataHolder options) { this.options = new AnchorLinkOptions(options); } @Override public void process(@NotNull NodeTracker state, @NotNull Node node) {<FILL_FUNCTION_BODY>} public static class Factory extends NodePostProcessorFactory { public Factory(DataHolder options) { super(false); if (ANCHORLINKS_NO_BLOCK_QUOTE.get(options)) { addNodeWithExclusions(Heading.class, BlockQuote.class); } else { addNodes(Heading.class); } } @NotNull @Override public NodePostProcessor apply(@NotNull Document document) { return new AnchorLinkNodePostProcessor(document); } } }
if (node instanceof Heading) { Heading heading = (Heading) node; if (heading.getText().isNotNull()) { Node anchor = new AnchorLink(); if (!options.wrapText) { if (heading.getFirstChild() == null) { anchor.setChars(heading.getText().subSequence(0, 0)); heading.appendChild(anchor); } else { anchor.setChars(heading.getFirstChild().getChars().subSequence(0, 0)); heading.getFirstChild().insertBefore(anchor); } } else { anchor.takeChildren(heading); heading.appendChild(anchor); } anchor.setCharsFromContent(); state.nodeAdded(anchor); } }
228
200
428
<methods>public non-sealed void <init>() ,public final @NotNull Document processDocument(@NotNull Document) <variables>
vsch_flexmark-java
flexmark-java/flexmark-ext-anchorlink/src/main/java/com/vladsch/flexmark/ext/anchorlink/internal/AnchorLinkNodeRenderer.java
AnchorLinkNodeRenderer
getNodeRenderingHandlers
class AnchorLinkNodeRenderer implements NodeRenderer { final private AnchorLinkOptions options; public AnchorLinkNodeRenderer(DataHolder options) { this.options = new AnchorLinkOptions(options); } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() {<FILL_FUNCTION_BODY>} private void render(AnchorLink node, NodeRendererContext context, HtmlWriter html) { if (context.isDoNotRenderLinks()) { if (options.wrapText) { context.renderChildren(node); } } else { String id = context.getNodeId(node.getParent()); if (id != null) { html.attr("href", "#" + id); if (options.setId) html.attr("id", id); if (options.setName) html.attr("name", id); if (!options.anchorClass.isEmpty()) html.attr("class", options.anchorClass); if (!options.wrapText) { html.withAttr().tag("a"); if (!options.textPrefix.isEmpty()) html.raw(options.textPrefix); if (!options.textSuffix.isEmpty()) html.raw(options.textSuffix); html.tag("/a"); } else { html.withAttr().tag("a", false, false, () -> { if (!options.textPrefix.isEmpty()) html.raw(options.textPrefix); context.renderChildren(node); if (!options.textSuffix.isEmpty()) html.raw(options.textSuffix); }); } } else { if (options.wrapText) { context.renderChildren(node); } } } } public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new AnchorLinkNodeRenderer(options); } } }
HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(AnchorLink.class, this::render)); return set;
495
50
545
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-aside/src/main/java/com/vladsch/flexmark/ext/aside/AsideExtension.java
AsideExtension
extend
class AsideExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, Formatter.FormatterExtension { final public static DataKey<Boolean> EXTEND_TO_BLANK_LINE = new DataKey<>("EXTEND_TO_BLANK_LINE", Parser.BLOCK_QUOTE_EXTEND_TO_BLANK_LINE); final public static DataKey<Boolean> IGNORE_BLANK_LINE = new DataKey<>("IGNORE_BLANK_LINE", Parser.BLOCK_QUOTE_IGNORE_BLANK_LINE); final public static DataKey<Boolean> ALLOW_LEADING_SPACE = new DataKey<>("ALLOW_LEADING_SPACE", Parser.BLOCK_QUOTE_ALLOW_LEADING_SPACE); final public static DataKey<Boolean> INTERRUPTS_PARAGRAPH = new DataKey<>("INTERRUPTS_PARAGRAPH", Parser.BLOCK_QUOTE_INTERRUPTS_PARAGRAPH); final public static DataKey<Boolean> INTERRUPTS_ITEM_PARAGRAPH = new DataKey<>("INTERRUPTS_ITEM_PARAGRAPH", Parser.BLOCK_QUOTE_INTERRUPTS_ITEM_PARAGRAPH); final public static DataKey<Boolean> WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH = new DataKey<>("WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH", Parser.BLOCK_QUOTE_WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH); private AsideExtension() { } public static AsideExtension create() { return new AsideExtension(); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new AsideNodeFormatter.Factory()); } @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new AsideBlockParser.Factory()); } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) {<FILL_FUNCTION_BODY>} }
if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new AsideNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { }
625
58
683
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-aside/src/main/java/com/vladsch/flexmark/ext/aside/internal/AsideBlockParser.java
AsideBlockParser
isMarker
class AsideBlockParser extends AbstractBlockParser { final public static char MARKER_CHAR = '|'; final private AsideBlock block = new AsideBlock(); final private boolean allowLeadingSpace; final private boolean continueToBlankLine; final private boolean ignoreBlankLine; final private boolean interruptsParagraph; final private boolean interruptsItemParagraph; final private boolean withLeadSpacesInterruptsItemParagraph; private int lastWasBlankLine = 0; public AsideBlockParser(DataHolder options, BasedSequence marker) { block.setOpeningMarker(marker); continueToBlankLine = AsideExtension.EXTEND_TO_BLANK_LINE.get(options); allowLeadingSpace = AsideExtension.ALLOW_LEADING_SPACE.get(options); ignoreBlankLine = AsideExtension.IGNORE_BLANK_LINE.get(options); interruptsParagraph = AsideExtension.INTERRUPTS_PARAGRAPH.get(options); interruptsItemParagraph = AsideExtension.INTERRUPTS_ITEM_PARAGRAPH.get(options); withLeadSpacesInterruptsItemParagraph = AsideExtension.WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH.get(options); } @Override public boolean isContainer() { return true; } @Override public boolean isPropagatingLastBlankLine(BlockParser lastMatchedBlockParser) { return false; } @Override public boolean canContain(ParserState state, BlockParser blockParser, Block block) { return true; } @Override public AsideBlock getBlock() { return block; } @Override public void closeBlock(ParserState state) { block.setCharsFromContent(); if (!Parser.BLANK_LINES_IN_AST.get(state.getProperties())) { removeBlankLines(); } } @Override public BlockContinue tryContinue(ParserState state) { int nextNonSpace = state.getNextNonSpaceIndex(); boolean isMarker; if (!state.isBlank() && ((isMarker = isMarker(state, nextNonSpace, false, false, allowLeadingSpace, interruptsParagraph, interruptsItemParagraph, withLeadSpacesInterruptsItemParagraph)) || (continueToBlankLine && lastWasBlankLine == 0))) { int newColumn = state.getColumn() + state.getIndent(); lastWasBlankLine = 0; if (isMarker) { newColumn++; // optional following space or tab if (Parsing.isSpaceOrTab(state.getLine(), nextNonSpace + 1)) { newColumn++; } } return BlockContinue.atColumn(newColumn); } else { if (ignoreBlankLine && state.isBlank()) { lastWasBlankLine++; int newColumn = state.getColumn() + state.getIndent(); return BlockContinue.atColumn(newColumn); } return BlockContinue.none(); } } static boolean isMarker( final ParserState state, final int index, final boolean inParagraph, final boolean inParagraphListItem, final boolean allowLeadingSpace, final boolean interruptsParagraph, final boolean interruptsItemParagraph, final boolean withLeadSpacesInterruptsItemParagraph ) {<FILL_FUNCTION_BODY>} static boolean endsWithMarker(BasedSequence line) { int tailBlanks = line.countTrailing(CharPredicate.WHITESPACE_NBSP); return tailBlanks + 1 < line.length() && line.charAt(line.length() - tailBlanks - 1) == MARKER_CHAR; } public static class Factory implements CustomBlockParserFactory { @Nullable @SuppressWarnings("UnnecessaryLocalVariable") @Override public Set<Class<?>> getAfterDependents() { HashSet<Class<?>> set = new HashSet<>(); //set.add(BlockQuoteParser.Factory.class); return set; } @Nullable @Override public Set<Class<?>> getBeforeDependents() { return new HashSet<>(Arrays.asList( //BlockQuoteParser.Factory.class, HeadingParser.Factory.class, FencedCodeBlockParser.Factory.class, HtmlBlockParser.Factory.class, ThematicBreakParser.Factory.class, ListBlockParser.Factory.class, IndentedCodeBlockParser.Factory.class )); } @Override public @Nullable SpecialLeadInHandler getLeadInHandler(@NotNull DataHolder options) { return AsideLeadInHandler.HANDLER; } @Override public boolean affectsGlobalScope() { return false; } @NotNull @Override public BlockParserFactory apply(@NotNull DataHolder options) { return new BlockFactory(options); } } static class AsideLeadInHandler { final static SpecialLeadInHandler HANDLER = SpecialLeadInStartsWithCharsHandler.create('|'); } private static class BlockFactory extends AbstractBlockParserFactory { final private boolean allowLeadingSpace; final private boolean interruptsParagraph; final private boolean interruptsItemParagraph; final private boolean withLeadSpacesInterruptsItemParagraph; BlockFactory(DataHolder options) { super(options); allowLeadingSpace = AsideExtension.ALLOW_LEADING_SPACE.get(options); interruptsParagraph = AsideExtension.INTERRUPTS_PARAGRAPH.get(options); interruptsItemParagraph = AsideExtension.INTERRUPTS_ITEM_PARAGRAPH.get(options); withLeadSpacesInterruptsItemParagraph = AsideExtension.WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH.get(options); } public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) { int nextNonSpace = state.getNextNonSpaceIndex(); BlockParser matched = matchedBlockParser.getBlockParser(); boolean inParagraph = matched.isParagraphParser(); boolean inParagraphListItem = inParagraph && matched.getBlock().getParent() instanceof ListItem && matched.getBlock() == matched.getBlock().getParent().getFirstChild(); if (!endsWithMarker(state.getLine()) && isMarker(state, nextNonSpace, inParagraph, inParagraphListItem, allowLeadingSpace, interruptsParagraph, interruptsItemParagraph, withLeadSpacesInterruptsItemParagraph)) { int newColumn = state.getColumn() + state.getIndent() + 1; // optional following space or tab if (Parsing.isSpaceOrTab(state.getLine(), nextNonSpace + 1)) { newColumn++; } return BlockStart.of(new AsideBlockParser(state.getProperties(), state.getLine().subSequence(nextNonSpace, nextNonSpace + 1))).atColumn(newColumn); } else { return BlockStart.none(); } } } }
CharSequence line = state.getLine(); if ((!inParagraph || interruptsParagraph) && index < line.length() && line.charAt(index) == MARKER_CHAR) { if ((allowLeadingSpace || state.getIndent() == 0) && (!inParagraphListItem || interruptsItemParagraph)) { if (inParagraphListItem && !withLeadSpacesInterruptsItemParagraph) { return state.getIndent() == 0; } else { return state.getIndent() < state.getParsing().CODE_BLOCK_INDENT; } } } return false;
1,860
165
2,025
<methods>public non-sealed void <init>() ,public void addLine(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.util.sequence.BasedSequence) ,public boolean breakOutOnDoubleBlankLine() ,public boolean canContain(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.parser.block.BlockParser, com.vladsch.flexmark.util.ast.Block) ,public boolean canInterruptBy(com.vladsch.flexmark.parser.block.BlockParserFactory) ,public final void finalizeClosedBlock() ,public com.vladsch.flexmark.util.ast.BlockContent getBlockContent() ,public com.vladsch.flexmark.util.data.MutableDataHolder getDataHolder() ,public boolean isClosed() ,public boolean isContainer() ,public boolean isInterruptible() ,public boolean isParagraphParser() ,public boolean isPropagatingLastBlankLine(com.vladsch.flexmark.parser.block.BlockParser) ,public boolean isRawText() ,public void parseInlines(com.vladsch.flexmark.parser.InlineParser) ,public void removeBlankLines() <variables>private boolean isClosed,private com.vladsch.flexmark.util.data.MutableDataSet mutableData
vsch_flexmark-java
flexmark-java/flexmark-ext-aside/src/main/java/com/vladsch/flexmark/ext/aside/internal/AsideNodeFormatter.java
AsideNodeFormatter
getNodeFormattingHandlers
class AsideNodeFormatter implements NodeFormatter { public AsideNodeFormatter(DataHolder options) { } @Nullable @Override public Set<Class<?>> getNodeClasses() { return null; } @Override public char getBlockQuoteLikePrefixChar() { return '|'; } // only registered if assignTextAttributes is enabled @Nullable @Override public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() {<FILL_FUNCTION_BODY>} private void render(AsideBlock node, NodeFormatterContext context, MarkdownWriter markdown) { FormatterUtils.renderBlockQuoteLike(node, context, markdown); } public static class Factory implements NodeFormatterFactory { @NotNull @Override public NodeFormatter create(@NotNull DataHolder options) { return new AsideNodeFormatter(options); } } }
HashSet<NodeFormattingHandler<?>> set = new HashSet<>(); set.add(new NodeFormattingHandler<>(AsideBlock.class, AsideNodeFormatter.this::render)); return set;
243
56
299
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-aside/src/main/java/com/vladsch/flexmark/ext/aside/internal/AsideNodeRenderer.java
AsideNodeRenderer
getNodeRenderingHandlers
class AsideNodeRenderer implements NodeRenderer { public AsideNodeRenderer(DataHolder options) { } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() {<FILL_FUNCTION_BODY>} private void render(AsideBlock node, NodeRendererContext context, HtmlWriter html) { html.withAttr().withCondIndent().tagLine("aside", () -> context.renderChildren(node)); } public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new AsideNodeRenderer(options); } } }
HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(AsideBlock.class, this::render)); return set;
170
50
220
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/AttributeNode.java
AttributeNode
getAstExtra
class AttributeNode extends Node implements DoNotDecorate { protected BasedSequence name = BasedSequence.NULL; protected BasedSequence attributeSeparator = BasedSequence.NULL; protected BasedSequence openingMarker = BasedSequence.NULL; protected BasedSequence value = BasedSequence.NULL; protected BasedSequence closingMarker = BasedSequence.NULL; @NotNull @Override public BasedSequence[] getSegments() { //return EMPTY_SEGMENTS; return new BasedSequence[] { name, attributeSeparator, openingMarker, value, closingMarker }; } @Override public void getAstExtra(@NotNull StringBuilder out) {<FILL_FUNCTION_BODY>} public AttributeNode() { } public AttributeNode(BasedSequence chars) { super(chars); } public AttributeNode(@Nullable BasedSequence name, @Nullable BasedSequence attributeSeparator, @Nullable BasedSequence openingMarker, @Nullable BasedSequence value, @Nullable BasedSequence closingMarker) { super(spanningChars(name, attributeSeparator, openingMarker, value, closingMarker)); this.name = name != null ? name : BasedSequence.NULL; this.attributeSeparator = attributeSeparator != null ? attributeSeparator : BasedSequence.NULL; this.openingMarker = openingMarker != null ? openingMarker : BasedSequence.NULL; this.value = value != null ? value : BasedSequence.NULL; this.closingMarker = closingMarker != null ? closingMarker : BasedSequence.NULL; } public static boolean isImplicitName(CharSequence text) { return text.length() > 0 && (text.charAt(0) == '.' || text.charAt(0) == '#'); } public boolean isImplicitName() { return (value.isNotNull() && attributeSeparator.isNull() && name.isNotNull()); } public boolean isClass() { return (isImplicitName() && name.equals(".")) || (!isImplicitName() && name.equals(Attribute.CLASS_ATTR)); } public boolean isId() { return (isImplicitName() && name.equals("#")) || (!isImplicitName() && name.equals(Attribute.ID_ATTR)); } public BasedSequence getName() { return name; } public void setName(BasedSequence name) { this.name = name; } public BasedSequence getAttributeSeparator() { return attributeSeparator; } public void setAttributeSeparator(BasedSequence attributeSeparator) { this.attributeSeparator = attributeSeparator; } public BasedSequence getValue() { return value; } public void setValue(BasedSequence value) { this.value = value; } public BasedSequence getOpeningMarker() { return openingMarker; } public void setOpeningMarker(BasedSequence openingMarker) { this.openingMarker = openingMarker; } public BasedSequence getClosingMarker() { return closingMarker; } public void setClosingMarker(BasedSequence closingMarker) { this.closingMarker = closingMarker; } }
segmentSpanChars(out, name, "name"); segmentSpanChars(out, attributeSeparator, "sep"); delimitedSegmentSpanChars(out, openingMarker, value, closingMarker, "value"); if (isImplicitName()) out.append(" isImplicit"); if (isClass()) out.append(" isClass"); if (isId()) out.append(" isId");
796
101
897
<methods>public void <init>() ,public void <init>(@NotNull BasedSequence) ,public void appendChain(@NotNull Node) ,public void appendChild(com.vladsch.flexmark.util.ast.Node) ,public static void astChars(@NotNull StringBuilder, @NotNull CharSequence, @NotNull String) ,public void astExtraChars(@NotNull StringBuilder) ,public void astString(@NotNull StringBuilder, boolean) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int, int) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int) ,public transient int countAncestorsOfType(@NotNull Class<?> []) ,public transient int countDirectAncestorsOfType(@Nullable Class<?>, @NotNull Class<?> []) ,public static void delimitedSegmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public static void delimitedSegmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public int endOfLine(int) ,public void extractChainTo(@NotNull Node) ,public void extractToFirstInChain(@NotNull Node) ,public transient @Nullable Node getAncestorOfType(@NotNull Class<?> []) ,public void getAstExtra(@NotNull StringBuilder) ,public com.vladsch.flexmark.util.sequence.BasedSequence getBaseSequence() ,public @NotNull Node getBlankLineSibling() ,public @NotNull BasedSequence getChars() ,public @NotNull BasedSequence getCharsFromSegments() ,public com.vladsch.flexmark.util.sequence.BasedSequence getChildChars() ,public @NotNull ReversiblePeekingIterator<Node> getChildIterator() ,public transient @Nullable Node getChildOfType(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterable<Node> getChildren() ,public @NotNull ReversiblePeekingIterable<Node> getDescendants() ,public @NotNull Document getDocument() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptyPrefix() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptySuffix() ,public int getEndLineNumber() ,public int getEndOfLine() ,public int getEndOffset() ,public com.vladsch.flexmark.util.sequence.BasedSequence getExactChildChars() ,public @Nullable Node getFirstChild() ,public transient @Nullable Node getFirstChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getFirstChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getFirstInChain() ,public @Nullable Node getGrandParent() ,public @Nullable Node getLastBlankLineChild() ,public @Nullable Node getLastChild() ,public transient @Nullable Node getLastChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getLastChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getLastInChain() ,public static @NotNull BasedSequence getLeadSegment(@NotNull BasedSequence []) ,public Pair<java.lang.Integer,java.lang.Integer> getLineColumnAtEnd() ,public int getLineNumber() ,public @Nullable Node getNext() ,public transient @Nullable Node getNextAny(@NotNull Class<?> []) ,public transient @Nullable Node getNextAnyNot(@NotNull Class<?> []) ,public @NotNull String getNodeName() ,public static transient int getNodeOfTypeIndex(@NotNull Node, @NotNull Class<?> []) ,public transient int getNodeOfTypeIndex(@NotNull Class<?> []) ,public @Nullable Node getOldestAncestorOfTypeAfter(@NotNull Class<?>, @NotNull Class<?>) ,public @Nullable Node getParent() ,public @Nullable Node getPrevious() ,public transient @Nullable Node getPreviousAny(@NotNull Class<?> []) ,public transient @Nullable Node getPreviousAnyNot(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterator<Node> getReversedChildIterator() ,public @NotNull ReversiblePeekingIterable<Node> getReversedChildren() ,public @NotNull ReversiblePeekingIterable<Node> getReversedDescendants() ,public abstract @NotNull BasedSequence [] getSegments() ,public @NotNull BasedSequence [] getSegmentsForChars() ,public com.vladsch.flexmark.util.sequence.Range getSourceRange() ,public int getStartLineNumber() ,public int getStartOfLine() ,public int getStartOffset() ,public int getTextLength() ,public static @NotNull BasedSequence getTrailSegment(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public boolean hasChildren() ,public boolean hasOrMoreChildren(int) ,public void insertAfter(@NotNull Node) ,public void insertBefore(com.vladsch.flexmark.util.ast.Node) ,public void insertChainAfter(@NotNull Node) ,public void insertChainBefore(@NotNull Node) ,public transient boolean isOrDescendantOfType(@NotNull Class<?> []) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtIndex(int) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtStart() ,public void moveTrailingBlankLines() ,public void prependChild(@NotNull Node) ,public void removeChildren() ,public static void segmentSpan(@NotNull StringBuilder, int, int, @Nullable String) ,public static void segmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @Nullable String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String, @NotNull String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public static void segmentSpanCharsToVisible(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public void setChars(@NotNull BasedSequence) ,public void setCharsFromContent() ,public void setCharsFromContentOnly() ,public void setCharsFromSegments() ,public static transient @NotNull BasedSequence spanningChars(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public int startOfLine(int) ,public void takeChildren(@NotNull Node) ,public @NotNull String toAstString(boolean) ,public static @NotNull String toSegmentSpan(@NotNull BasedSequence, @Nullable String) ,public java.lang.String toString() ,public void unlink() <variables>public static final AstNode<com.vladsch.flexmark.util.ast.Node> AST_ADAPTER,public static final com.vladsch.flexmark.util.sequence.BasedSequence[] EMPTY_SEGMENTS,public static final java.lang.String SPLICE,private @NotNull BasedSequence chars,@Nullable Node firstChild,private @Nullable Node lastChild,@Nullable Node next,private @Nullable Node parent,private @Nullable Node prev
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/AttributesExtension.java
AttributesExtension
parserOptions
class AttributesExtension implements Parser.ParserExtension , RendererExtension , HtmlRenderer.HtmlRendererExtension , Formatter.FormatterExtension //, Parser.ReferenceHoldingExtension { final public static DataKey<NodeAttributeRepository> NODE_ATTRIBUTES = new DataKey<>("NODE_ATTRIBUTES", new NodeAttributeRepository(null), NodeAttributeRepository::new); final public static DataKey<KeepType> ATTRIBUTES_KEEP = new DataKey<>("ATTRIBUTES_KEEP", KeepType.FIRST); // standard option to allow control over how to handle duplicates final public static DataKey<Boolean> ASSIGN_TEXT_ATTRIBUTES = new DataKey<>("ASSIGN_TEXT_ATTRIBUTES", true); // assign attributes to text if previous is not a space final public static DataKey<Boolean> FENCED_CODE_INFO_ATTRIBUTES = new DataKey<>("FENCED_CODE_INFO_ATTRIBUTES", false); // assign attributes found at end of fenced code info strings final public static DataKey<FencedCodeAddType> FENCED_CODE_ADD_ATTRIBUTES = new DataKey<>("FENCED_CODE_ADD_ATTRIBUTES", FencedCodeAddType.ADD_TO_PRE_CODE); // assign attributes to pre/code tag final public static DataKey<Boolean> WRAP_NON_ATTRIBUTE_TEXT = new DataKey<>("WRAP_NON_ATTRIBUTE_TEXT", true); final public static DataKey<Boolean> USE_EMPTY_IMPLICIT_AS_SPAN_DELIMITER = new DataKey<>("USE_EMPTY_IMPLICIT_AS_SPAN_DELIMITER", false); final public static DataKey<Boolean> FORMAT_ATTRIBUTES_COMBINE_CONSECUTIVE = new DataKey<>("FORMAT_ATTRIBUTES_COMBINE_CONSECUTIVE", false); final public static DataKey<Boolean> FORMAT_ATTRIBUTES_SORT = new DataKey<>("FORMAT_ATTRIBUTES_SORT", false); final public static DataKey<DiscretionaryText> FORMAT_ATTRIBUTES_SPACES = new DataKey<>("FORMAT_ATTRIBUTES_SPACES", DiscretionaryText.AS_IS); // add spaces after { and before } final public static DataKey<DiscretionaryText> FORMAT_ATTRIBUTE_EQUAL_SPACE = new DataKey<>("FORMAT_ATTRIBUTE_EQUAL_SPACE", DiscretionaryText.AS_IS); final public static DataKey<AttributeValueQuotes> FORMAT_ATTRIBUTE_VALUE_QUOTES = new DataKey<>("FORMAT_ATTRIBUTE_VALUE_QUOTES", AttributeValueQuotes.AS_IS); final public static DataKey<AttributeImplicitName> FORMAT_ATTRIBUTE_ID = new DataKey<>("FORMAT_ATTRIBUTE_ID", AttributeImplicitName.AS_IS); final public static DataKey<AttributeImplicitName> FORMAT_ATTRIBUTE_CLASS = new DataKey<>("FORMAT_ATTRIBUTE_CLASS", AttributeImplicitName.AS_IS); private AttributesExtension() { } public static AttributesExtension create() { return new AttributesExtension(); } @Override public void parserOptions(MutableDataHolder options) {<FILL_FUNCTION_BODY>} @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.postProcessorFactory(new AttributesNodePostProcessor.Factory()); parserBuilder.customInlineParserExtensionFactory(new AttributesInlineParserExtension.Factory()); } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new AttributesNodeFormatter.Factory()); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) { if (ASSIGN_TEXT_ATTRIBUTES.get(htmlRendererBuilder)) { htmlRendererBuilder.nodeRendererFactory(new AttributesNodeRenderer.Factory()); } htmlRendererBuilder.attributeProviderFactory(new AttributesAttributeProvider.Factory()); } @Override public void extend(@NotNull RendererBuilder rendererBuilder, @NotNull String rendererType) { //rendererBuilder.nodeRendererFactory(new AttributesNodeRenderer.Factory()); rendererBuilder.attributeProviderFactory(new AttributesAttributeProvider.Factory()); } }
if (options.contains(FENCED_CODE_INFO_ATTRIBUTES) && FENCED_CODE_INFO_ATTRIBUTES.get(options) && !options.contains(FENCED_CODE_ADD_ATTRIBUTES)) { // change default to pre only, to add to code use attributes after info options.set(FENCED_CODE_ADD_ATTRIBUTES, FencedCodeAddType.ADD_TO_PRE); }
1,133
113
1,246
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/AttributesVisitorExt.java
AttributesVisitorExt
VISIT_HANDLERS
class AttributesVisitorExt { public static <V extends AttributesVisitor> VisitHandler<?>[] VISIT_HANDLERS(V visitor) {<FILL_FUNCTION_BODY>} }
return new VisitHandler<?>[] { new VisitHandler<>(AttributesNode.class, visitor::visit), new VisitHandler<>(AttributeNode.class, visitor::visit), };
53
51
104
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/AttributesAttributeProvider.java
AttributesAttributeProvider
setAttributes
class AttributesAttributeProvider implements AttributeProvider { final private NodeAttributeRepository nodeAttributeRepository; final private AttributesOptions attributeOptions; public AttributesAttributeProvider(LinkResolverContext context) { DataHolder options = context.getOptions(); attributeOptions = new AttributesOptions(options); nodeAttributeRepository = AttributesExtension.NODE_ATTRIBUTES.get(options); } @Override public void setAttributes(@NotNull Node node, @NotNull AttributablePart part, @NotNull MutableAttributes attributes) {<FILL_FUNCTION_BODY>} public static class Factory extends IndependentAttributeProviderFactory { //@Override //public Set<Class<?>> getAfterDependents() { // return null; //} // //@Override //public Set<Class<?>> getBeforeDependents() { // return null; //} // //@Override //public boolean affectsGlobalScope() { // return false; //} @NotNull @Override public AttributeProvider apply(@NotNull LinkResolverContext context) { return new AttributesAttributeProvider(context); } } }
// regression bug, issue #372, add option, default to both as before if (part == CoreNodeRenderer.CODE_CONTENT ? attributeOptions.fencedCodeAddAttributes.addToCode : attributeOptions.fencedCodeAddAttributes.addToPre) { ArrayList<AttributesNode> nodeAttributesList = nodeAttributeRepository.get(node); if (nodeAttributesList != null) { // add these as attributes for (AttributesNode nodeAttributes : nodeAttributesList) { for (Node attribute : nodeAttributes.getChildren()) { if (!(attribute instanceof AttributeNode)) continue; final AttributeNode attributeNode = (AttributeNode) attribute; if (!attributeNode.isImplicitName()) { final BasedSequence attributeNodeName = attributeNode.getName(); if (attributeNodeName.isNotNull() && !attributeNodeName.isBlank()) { if (!attributeNodeName.equals(CLASS_ATTR)) { attributes.remove(attributeNodeName); } attributes.addValue(attributeNodeName, attributeNode.getValue()); } else { // empty then ignore } } else { // implicit if (attributeNode.isClass()) { attributes.addValue(CLASS_ATTR, attributeNode.getValue()); } else if (attributeNode.isId()) { if (node instanceof AnchorRefTarget) { // was already provided via setAnchorRefId } else { attributes.remove(Attribute.ID_ATTR); attributes.addValue(Attribute.ID_ATTR, attributeNode.getValue()); } } else { // unknown throw new IllegalStateException("Implicit attribute yet not class or id"); } } } } } }
290
422
712
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/AttributesFormatOptions.java
AttributesFormatOptions
setIn
class AttributesFormatOptions implements MutableDataSetter { final public boolean attributesCombineConsecutive; final public boolean attributesSort; final public DiscretionaryText attributesSpaces; final public DiscretionaryText attributeEqualSpace; final public AttributeValueQuotes attributeValueQuotes; final public AttributeImplicitName attributeIdFormat; final public AttributeImplicitName attributeClassFormat; public AttributesFormatOptions(DataHolder options) { attributesCombineConsecutive = AttributesExtension.FORMAT_ATTRIBUTES_COMBINE_CONSECUTIVE.get(options); attributesSort = AttributesExtension.FORMAT_ATTRIBUTES_SORT.get(options); attributesSpaces = AttributesExtension.FORMAT_ATTRIBUTES_SPACES.get(options); attributeEqualSpace = AttributesExtension.FORMAT_ATTRIBUTE_EQUAL_SPACE.get(options); attributeValueQuotes = AttributesExtension.FORMAT_ATTRIBUTE_VALUE_QUOTES.get(options); attributeIdFormat = AttributesExtension.FORMAT_ATTRIBUTE_ID.get(options); attributeClassFormat = AttributesExtension.FORMAT_ATTRIBUTE_CLASS.get(options); } @NotNull @Override public MutableDataHolder setIn(@NotNull MutableDataHolder dataHolder) {<FILL_FUNCTION_BODY>} }
dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTES_COMBINE_CONSECUTIVE, attributesCombineConsecutive); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTES_SORT, attributesSort); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTES_SPACES, attributesSpaces); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTE_EQUAL_SPACE, attributeEqualSpace); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTE_VALUE_QUOTES, attributeValueQuotes); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTE_ID, attributeIdFormat); dataHolder.set(AttributesExtension.FORMAT_ATTRIBUTE_CLASS, attributeClassFormat); return dataHolder;
338
189
527
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/AttributesInlineParserExtension.java
AttributesInlineParserExtension
parse
class AttributesInlineParserExtension implements InlineParserExtension { final private AttributeParsing parsing; public AttributesInlineParserExtension(LightInlineParser inlineParser) { this.parsing = new AttributeParsing(inlineParser.getParsing()); } @Override public void finalizeDocument(@NotNull InlineParser inlineParser) { } @Override public void finalizeBlock(@NotNull InlineParser inlineParser) { } @Override public boolean parse(@NotNull LightInlineParser inlineParser) {<FILL_FUNCTION_BODY>} public static class Factory implements InlineParserExtensionFactory { @Nullable @Override public Set<Class<?>> getAfterDependents() { return null; } @NotNull @Override public CharSequence getCharacters() { return "{"; } @Nullable @Override public Set<Class<?>> getBeforeDependents() { return null; } @NotNull @Override public InlineParserExtension apply(@NotNull LightInlineParser inlineParser) { return new AttributesInlineParserExtension(inlineParser); } @Override public boolean affectsGlobalScope() { return false; } } }
if (inlineParser.peek(1) != '{') { int index = inlineParser.getIndex(); BasedSequence input = inlineParser.getInput(); Matcher matcher = inlineParser.matcher(parsing.ATTRIBUTES_TAG); if (matcher != null) { BasedSequence attributesOpen = input.subSequence(matcher.start(), matcher.end()); // see what we have // open, see if open/close BasedSequence attributesText = input.subSequence(matcher.start(1), matcher.end(1)); AttributesNode attributes = attributesText.equals("#") || attributesText.equals(".") ? new AttributesDelimiter(attributesOpen.subSequence(0, 1), attributesText, attributesOpen.endSequence(1)) : new AttributesNode(attributesOpen.subSequence(0, 1), attributesText, attributesOpen.endSequence(1)); attributes.setCharsFromContent(); inlineParser.flushTextNode(); inlineParser.getBlock().appendChild(attributes); BasedSequence attributeText = attributesText.trim(); if (!attributeText.isEmpty()) { // have some attribute text // parse attributes Matcher attributeMatcher = parsing.ATTRIBUTE.matcher(attributeText); while (attributeMatcher.find()) { BasedSequence attributeName = attributeText.subSequence(attributeMatcher.start(1), attributeMatcher.end(1)); BasedSequence attributeSeparator = attributeMatcher.groupCount() == 1 || attributeMatcher.start(2) == -1 ? BasedSequence.NULL : attributeText.subSequence(attributeMatcher.end(1), attributeMatcher.start(2)).trim(); BasedSequence attributeValue = attributeMatcher.groupCount() == 1 || attributeMatcher.start(2) == -1 ? BasedSequence.NULL : attributeText.subSequence(attributeMatcher.start(2), attributeMatcher.end(2)); boolean isQuoted = attributeValue.length() >= 2 && (attributeValue.charAt(0) == '"' && attributeValue.endCharAt(1) == '"' || attributeValue.charAt(0) == '\'' && attributeValue.endCharAt(1) == '\''); BasedSequence attributeOpen = !isQuoted ? BasedSequence.NULL : attributeValue.subSequence(0, 1); BasedSequence attributeClose = !isQuoted ? BasedSequence.NULL : attributeValue.endSequence(1, 0); if (isQuoted) { attributeValue = attributeValue.midSequence(1, -1); } AttributeNode attribute; if (attributeSeparator.isNull() && attributeValue.isNull() && AttributeNode.isImplicitName(attributeName)) { attribute = new AttributeNode(attributeName.subSequence(0, 1), attributeSeparator, attributeOpen, attributeName.subSequence(1), attributeClose); } else { attribute = new AttributeNode(attributeName, attributeSeparator, attributeOpen, attributeValue, attributeClose); } attributes.appendChild(attribute); } return true; } // did not process, reset to where we started inlineParser.setIndex(index); } } return false;
327
786
1,113
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/AttributesNodeRenderer.java
AttributesNodeRenderer
getNodeRenderingHandlers
class AttributesNodeRenderer implements NodeRenderer { final private AttributesOptions myOptions; public AttributesNodeRenderer(DataHolder options) { myOptions = new AttributesOptions(options); } // only registered if assignTextAttributes is enabled @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() {<FILL_FUNCTION_BODY>} public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new AttributesNodeRenderer(options); } } }
HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(AttributesNode.class, (node, context, html) -> { })); set.add(new NodeRenderingHandler<>(TextBase.class, (node, context, html) -> { if (myOptions.assignTextAttributes) { Attributes nodeAttributes = context.extendRenderingNodeAttributes(AttributablePart.NODE, null); if (!nodeAttributes.isEmpty()) { // has attributes then we wrap it in a span html.setAttributes(nodeAttributes).withAttr().tag("span"); context.delegateRender(); html.closeTag("span"); return; } } context.delegateRender(); })); return set;
150
204
354
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/AttributesOptions.java
AttributesOptions
setIn
class AttributesOptions implements MutableDataSetter { final public boolean assignTextAttributes; final public boolean wrapNonAttributeText; final public boolean useEmptyImplicitAsSpanDelimiter; final public boolean fencedCodeInfoAttributes; final public FencedCodeAddType fencedCodeAddAttributes; public AttributesOptions(DataHolder options) { assignTextAttributes = AttributesExtension.ASSIGN_TEXT_ATTRIBUTES.get(options); wrapNonAttributeText = AttributesExtension.WRAP_NON_ATTRIBUTE_TEXT.get(options); useEmptyImplicitAsSpanDelimiter = AttributesExtension.USE_EMPTY_IMPLICIT_AS_SPAN_DELIMITER.get(options); fencedCodeInfoAttributes = AttributesExtension.FENCED_CODE_INFO_ATTRIBUTES.get(options); fencedCodeAddAttributes = AttributesExtension.FENCED_CODE_ADD_ATTRIBUTES.get(options); } @NotNull @Override public MutableDataHolder setIn(@NotNull MutableDataHolder dataHolder) {<FILL_FUNCTION_BODY>} }
dataHolder.set(AttributesExtension.ASSIGN_TEXT_ATTRIBUTES, assignTextAttributes); dataHolder.set(AttributesExtension.WRAP_NON_ATTRIBUTE_TEXT, wrapNonAttributeText); dataHolder.set(AttributesExtension.USE_EMPTY_IMPLICIT_AS_SPAN_DELIMITER, useEmptyImplicitAsSpanDelimiter); dataHolder.set(AttributesExtension.FENCED_CODE_INFO_ATTRIBUTES, fencedCodeInfoAttributes); dataHolder.set(AttributesExtension.FENCED_CODE_ADD_ATTRIBUTES, fencedCodeAddAttributes); return dataHolder;
280
159
439
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-attributes/src/main/java/com/vladsch/flexmark/ext/attributes/internal/NodeAttributeRepository.java
NodeAttributeRepository
put
class NodeAttributeRepository implements Map<Node, ArrayList<AttributesNode>> { protected final HashMap<Node, ArrayList<AttributesNode>> nodeAttributesHashMap = new HashMap<>(); public NodeAttributeRepository(DataHolder options) { } public DataKey<NodeAttributeRepository> getDataKey() { return AttributesExtension.NODE_ATTRIBUTES; } public DataKey<KeepType> getKeepDataKey() { return AttributesExtension.ATTRIBUTES_KEEP; } @Override public int size() { return nodeAttributesHashMap.size(); } @Override public boolean isEmpty() { return nodeAttributesHashMap.isEmpty(); } @Override public boolean containsKey(Object key) { return nodeAttributesHashMap.containsKey(key); } @Override public boolean containsValue(Object value) { return nodeAttributesHashMap.containsValue(value); } @Override public ArrayList<AttributesNode> get(Object key) { return nodeAttributesHashMap.get(key); } @Override public ArrayList<AttributesNode> put(Node key, ArrayList<AttributesNode> value) { return nodeAttributesHashMap.put(key, value); } public ArrayList<AttributesNode> put(Node key, AttributesNode value) {<FILL_FUNCTION_BODY>} @Override public ArrayList<AttributesNode> remove(Object key) { return nodeAttributesHashMap.remove(key); } @Override public void putAll(@NotNull Map<? extends Node, ? extends ArrayList<AttributesNode>> m) { nodeAttributesHashMap.putAll(m); } @Override public void clear() { nodeAttributesHashMap.clear(); } @NotNull @Override public Set<Node> keySet() { return nodeAttributesHashMap.keySet(); } @NotNull @Override public Collection<ArrayList<AttributesNode>> values() { return nodeAttributesHashMap.values(); } @NotNull @Override public Set<Entry<Node, ArrayList<AttributesNode>>> entrySet() { return nodeAttributesHashMap.entrySet(); } }
ArrayList<AttributesNode> another = nodeAttributesHashMap.get(key); if (another == null) { another = new ArrayList<>(); nodeAttributesHashMap.put(key, another); } another.add(value); return another;
562
67
629
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/DefinitionExtension.java
DefinitionExtension
extend
class DefinitionExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, Formatter.FormatterExtension { final public static DataKey<Boolean> COLON_MARKER = new DataKey<>("COLON_MARKER", true); final public static DataKey<Integer> MARKER_SPACES = new DataKey<>("MARKER_SPACE", 1); final public static DataKey<Boolean> TILDE_MARKER = new DataKey<>("TILDE_MARKER", true); final public static DataKey<Boolean> DOUBLE_BLANK_LINE_BREAKS_LIST = new DataKey<>("DOUBLE_BLANK_LINE_BREAKS_LIST", false); final public static DataKey<Integer> FORMAT_MARKER_SPACES = new DataKey<>("MARKER_SPACE", 3); final public static DataKey<DefinitionMarker> FORMAT_MARKER_TYPE = new DataKey<>("FORMAT_MARKER_TYPE", DefinitionMarker.ANY); private DefinitionExtension() { } public static DefinitionExtension create() { return new DefinitionExtension(); } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new DefinitionNodeFormatter.Factory()); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new DefinitionItemBlockParser.Factory()); parserBuilder.blockPreProcessorFactory(new DefinitionListItemBlockPreProcessor.Factory()); parserBuilder.blockPreProcessorFactory(new DefinitionListBlockPreProcessor.Factory()); } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) {<FILL_FUNCTION_BODY>} }
if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new DefinitionNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { }
494
57
551
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/DefinitionVisitorExt.java
DefinitionVisitorExt
VISIT_HANDLERS
class DefinitionVisitorExt { public static <V extends DefinitionVisitor> VisitHandler<?>[] VISIT_HANDLERS(V visitor) {<FILL_FUNCTION_BODY>} }
return new VisitHandler<?>[] { new VisitHandler<>(DefinitionItem.class, visitor::visit), new VisitHandler<>(DefinitionList.class, visitor::visit), new VisitHandler<>(DefinitionTerm.class, visitor::visit), new VisitHandler<>(DefinitionItem.class, visitor::visit), };
51
85
136
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/internal/DefinitionItemBlockParser.java
ItemData
parseItemMarker
class ItemData { final boolean isEmpty; final boolean isTight; final int markerIndex; final int markerColumn; final int markerIndent; final int contentOffset; final BasedSequence itemMarker; ItemData(boolean isEmpty, boolean isTight, int markerIndex, int markerColumn, int markerIndent, int contentOffset, BasedSequence itemMarker) { this.isEmpty = isEmpty; this.isTight = isTight; this.markerIndex = markerIndex; this.markerColumn = markerColumn; this.markerIndent = markerIndent; this.contentOffset = contentOffset; this.itemMarker = itemMarker; } } private int getContentIndent() { return itemData.markerIndent + itemData.itemMarker.length() + itemData.contentOffset; } @Override public Block getBlock() { return block; } @Override public boolean isContainer() { return true; } @Override public boolean canContain(ParserState state, BlockParser blockParser, final Block block) { return true; } static ItemData parseItemMarker(DefinitionOptions options, ParserState state, boolean isTight) {<FILL_FUNCTION_BODY>
BasedSequence line = state.getLine(); int markerIndex = state.getNextNonSpaceIndex(); int markerColumn = state.getColumn() + state.getIndent(); int markerIndent = state.getIndent(); BasedSequence rest = line.subSequence(markerIndex, line.length()); final char c1 = rest.firstChar(); if (!(c1 == ':' && options.colonMarker) && !(c1 == '~' && options.tildeMarker)) { return null; } // marker doesn't include tabs, so counting them as columns directly is ok // the column within the line where the content starts int contentOffset = 0; // See at which column the content starts if there is content boolean hasContent = false; for (int i = markerIndex + 1; i < line.length(); i++) { char c = line.charAt(i); if (c == '\t') { contentOffset += Parsing.columnsToNextTabStop(markerColumn + 1 + contentOffset); } else if (c == ' ') { contentOffset++; } else { hasContent = true; break; } } if (hasContent && contentOffset < options.markerSpaces) { return null; } if (!hasContent || options.myParserEmulationProfile == COMMONMARK && contentOffset > options.newItemCodeIndent) { // If this line is blank or has a code block, default to 1 space after marker contentOffset = 1; } return new ItemData(!hasContent, isTight, markerIndex, markerColumn, markerIndent, contentOffset, rest.subSequence(0, 1));
330
430
760
<methods>public non-sealed void <init>() ,public void addLine(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.util.sequence.BasedSequence) ,public boolean breakOutOnDoubleBlankLine() ,public boolean canContain(com.vladsch.flexmark.parser.block.ParserState, com.vladsch.flexmark.parser.block.BlockParser, com.vladsch.flexmark.util.ast.Block) ,public boolean canInterruptBy(com.vladsch.flexmark.parser.block.BlockParserFactory) ,public final void finalizeClosedBlock() ,public com.vladsch.flexmark.util.ast.BlockContent getBlockContent() ,public com.vladsch.flexmark.util.data.MutableDataHolder getDataHolder() ,public boolean isClosed() ,public boolean isContainer() ,public boolean isInterruptible() ,public boolean isParagraphParser() ,public boolean isPropagatingLastBlankLine(com.vladsch.flexmark.parser.block.BlockParser) ,public boolean isRawText() ,public void parseInlines(com.vladsch.flexmark.parser.InlineParser) ,public void removeBlankLines() <variables>private boolean isClosed,private com.vladsch.flexmark.util.data.MutableDataSet mutableData
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/internal/DefinitionListBlockPreProcessor.java
DefinitionListBlockPreProcessor
preProcess
class DefinitionListBlockPreProcessor implements BlockPreProcessor { final private DefinitionOptions options; public DefinitionListBlockPreProcessor(DataHolder options) { this.options = new DefinitionOptions(options); } @Override public void preProcess(ParserState state, Block block) {<FILL_FUNCTION_BODY>} public static class Factory implements BlockPreProcessorFactory { @NotNull @Override public Set<Class<? extends Block>> getBlockTypes() { HashSet<Class<? extends Block>> set = new HashSet<>(); set.add(DefinitionList.class); return set; } @Nullable @Override public Set<Class<?>> getAfterDependents() { HashSet<Class<?>> set = new HashSet<>(); set.add(DefinitionListItemBlockPreProcessor.Factory.class); return set; } @Nullable @Override public Set<Class<?>> getBeforeDependents() { return null; } @Override public boolean affectsGlobalScope() { return true; } @NotNull @Override public BlockPreProcessor apply(@NotNull ParserState state) { return new DefinitionListBlockPreProcessor(state.getProperties()); } } }
Boolean blankLinesInAST = BLANK_LINES_IN_AST.get(state.getProperties()); if (block instanceof DefinitionList) { // need to propagate loose/tight final DefinitionList definitionList = (DefinitionList) block; boolean isTight = definitionList.isTight(); if (options.autoLoose && isTight) { for (Node child : definitionList.getChildren()) { if (child instanceof DefinitionItem) { if (((DefinitionItem) child).isLoose()) { isTight = false; if (!blankLinesInAST) break; } if (blankLinesInAST) { // transfer its trailing blank lines to uppermost level child.moveTrailingBlankLines(); } } } definitionList.setTight(isTight); } if (blankLinesInAST) { definitionList.moveTrailingBlankLines(); } }
322
251
573
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/internal/DefinitionListItemBlockPreProcessor.java
DefinitionListItemBlockPreProcessor
preProcess
class DefinitionListItemBlockPreProcessor implements BlockPreProcessor { final private DefinitionOptions options; Boolean blankLinesInAst; public DefinitionListItemBlockPreProcessor(DataHolder options) { this.options = new DefinitionOptions(options); blankLinesInAst = BLANK_LINES_IN_AST.get(options); } @Override public void preProcess(ParserState state, Block block) {<FILL_FUNCTION_BODY>} public static class Factory implements BlockPreProcessorFactory { @NotNull @Override public Set<Class<? extends Block>> getBlockTypes() { HashSet<Class<? extends Block>> set = new HashSet<>(); set.add(DefinitionItem.class); return set; } @Nullable @Override public Set<Class<?>> getAfterDependents() { return null; } @Nullable @Override public Set<Class<?>> getBeforeDependents() { return null; } @Override public boolean affectsGlobalScope() { return true; } @NotNull @Override public BlockPreProcessor apply(@NotNull ParserState state) { return new DefinitionListItemBlockPreProcessor(state.getProperties()); } } }
if (block instanceof DefinitionItem) { // we chop up the previous paragraph into definition terms and add the definition item to the last one // we add all these to the previous DefinitionList or add a new one if there isn't one final DefinitionItem definitionItem = (DefinitionItem) block; final Node previous = block.getPreviousAnyNot(BlankLine.class); Node trailingBlankLines = new DefinitionList(); Node blankLine = definitionItem.getNext(); if (blankLine instanceof BlankLine) { blankLine.extractChainTo(trailingBlankLines); } if (previous instanceof Paragraph) { final Paragraph paragraph = (Paragraph) previous; Node afterParagraph = previous.getNext(); Node paragraphPrevNonBlank = paragraph.getPreviousAnyNot(BlankLine.class); Node paragraphPrevious = paragraph.getPrevious(); final Node paragraphParent = paragraph.getParent(); definitionItem.unlink(); paragraph.unlink(); state.blockRemovedWithChildren(paragraph); final boolean hadPreviousList; if (options.doubleBlankLineBreaksList) { // intervening characters between previous paragraph and definition terms final BasedSequence interSpace = paragraphPrevNonBlank == null ? BasedSequence.NULL : BasedSequence.of(paragraphPrevNonBlank.baseSubSequence(paragraphPrevNonBlank.getEndOffset(), paragraph.getStartOffset()).normalizeEOL()); hadPreviousList = paragraphPrevNonBlank instanceof DefinitionList && interSpace.countLeading(CharPredicate.EOL) < 2; } else { hadPreviousList = paragraphPrevNonBlank instanceof DefinitionList; } final DefinitionList definitionList = new DefinitionList(); definitionList.setTight(true); final List<BasedSequence> lines = paragraph.getContentLines(); DefinitionTerm definitionTerm = null; int lineIndex = 0; for (BasedSequence line : lines) { definitionTerm = new DefinitionTerm(); ParagraphParser parser = new ParagraphParser(); BlockContent content = new BlockContent(); content.add(line, paragraph.getLineIndent(lineIndex++)); parser.getBlock().setContent(content); parser.getBlock().setCharsFromContent(); definitionTerm.appendChild(parser.getBlock()); definitionTerm.setCharsFromContent(); state.blockParserAdded(parser); definitionList.appendChild(definitionTerm); state.blockAdded(definitionTerm); } // if have blank lines after paragraph need to move them after the last term if (blankLinesInAst && afterParagraph instanceof BlankLine) { while (afterParagraph instanceof BlankLine) { Node next = afterParagraph.getNext(); afterParagraph.unlink(); definitionList.appendChild(afterParagraph); afterParagraph = next; } } definitionList.appendChild(definitionItem); definitionList.takeChildren(trailingBlankLines); if (hadPreviousList) { final DefinitionList previousList = (DefinitionList) paragraphPrevNonBlank; previousList.takeChildren(definitionList); for (Node node : definitionList.getChildren()) { node.unlink(); previousList.appendChild(node); state.blockAddedWithChildren((Block) node); } previousList.setCharsFromContent(); } else { // insert new one, after paragraphPrevious if (paragraphPrevNonBlank != null) { paragraphPrevious.insertAfter(definitionList); } else { if (paragraphParent.getFirstChild() != null) { paragraphParent.getFirstChild().insertBefore(definitionList); } else { paragraphParent.appendChild(definitionList); } } definitionList.setCharsFromContent(); state.blockAddedWithChildren(definitionList); } } else if (previous instanceof DefinitionList) { final DefinitionList previousList = (DefinitionList) previous; definitionItem.unlink(); previousList.appendChild(definitionItem); previousList.takeChildren(trailingBlankLines); previousList.setCharsFromContent(); } }
324
1,043
1,367
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/internal/DefinitionNodeFormatter.java
DefinitionNodeFormatter
render
class DefinitionNodeFormatter implements NodeFormatter { final private DefinitionFormatOptions options; final private ListOptions listOptions; public DefinitionNodeFormatter(DataHolder options) { this.options = new DefinitionFormatOptions(options); this.listOptions = ListOptions.get(options); } @Nullable @Override public Set<Class<?>> getNodeClasses() { return null; } @Nullable @Override public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() { return new HashSet<>(Arrays.asList( new NodeFormattingHandler<>(DefinitionList.class, DefinitionNodeFormatter.this::render), new NodeFormattingHandler<>(DefinitionTerm.class, DefinitionNodeFormatter.this::render), new NodeFormattingHandler<>(DefinitionItem.class, DefinitionNodeFormatter.this::render) )); } private void render(DefinitionList node, NodeFormatterContext context, MarkdownWriter markdown) { context.renderChildren(node); } private void render(DefinitionTerm node, NodeFormatterContext context, MarkdownWriter markdown) { context.renderChildren(node); } private void render(DefinitionItem node, NodeFormatterContext context, MarkdownWriter markdown) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeFormatterFactory { @NotNull @Override public NodeFormatter create(@NotNull DataHolder options) { return new DefinitionNodeFormatter(options); } } }
BasedSequence openMarkerChars = node.getChars().prefixOf(node.getFirstChild().getChars()); BasedSequence openMarker = openMarkerChars.subSequence(0, 1); BasedSequence openMarkerSpaces = openMarkerChars.subSequence(1); if (options.markerSpaces >= 1 && openMarkerSpaces.length() != options.markerSpaces) { CharSequence charSequence = RepeatedSequence.repeatOf(' ', options.markerSpaces); openMarkerSpaces = BasedSequence.of(charSequence); } switch (options.markerType) { case ANY: break; case COLON: openMarker = BasedSequence.of(":").subSequence(0, ((CharSequence) ":").length()); break; case TILDE: openMarker = BasedSequence.of("~").subSequence(0, ((CharSequence) "~").length()); break; } markdown.line().append(openMarker).append(openMarkerSpaces); int count = context.getFormatterOptions().itemContentIndent ? openMarker.length() + openMarkerSpaces.length() : listOptions.getItemIndent(); CharSequence prefix = RepeatedSequence.ofSpaces(count); markdown.pushPrefix().addPrefix(prefix); context.renderChildren(node); markdown.popPrefix(); if (!BLANK_LINES_IN_AST.get(context.getOptions())) { // add blank lines after last paragraph item Node child = node.getLastChild(); if (child instanceof Paragraph && ((Paragraph) child).isTrailingBlankLine()) { markdown.blankLine(); } }
385
427
812
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-definition/src/main/java/com/vladsch/flexmark/ext/definition/internal/DefinitionNodeRenderer.java
DefinitionNodeRenderer
render
class DefinitionNodeRenderer implements NodeRenderer { final private ListOptions listOptions; public DefinitionNodeRenderer(DataHolder options) { this.listOptions = ListOptions.get(options); } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() { HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(DefinitionList.class, this::render)); set.add(new NodeRenderingHandler<>(DefinitionTerm.class, this::render)); set.add(new NodeRenderingHandler<>(DefinitionItem.class, this::render)); return set; } private void render(DefinitionList node, NodeRendererContext context, HtmlWriter html) { html.withAttr().tag("dl").indent(); context.renderChildren(node); html.unIndent().tag("/dl"); } private void render(DefinitionTerm node, NodeRendererContext context, HtmlWriter html) { Node childText = node.getFirstChild(); if (childText != null) { html.srcPosWithEOL(node.getChars()).withAttr(CoreNodeRenderer.TIGHT_LIST_ITEM).withCondIndent().tagLine("dt", () -> { html.text(node.getMarkerSuffix().unescape()); context.renderChildren(node); }); } } private void render(DefinitionItem node, NodeRendererContext context, HtmlWriter html) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new DefinitionNodeRenderer(options); } } }
if (listOptions.isTightListItem(node)) { html.srcPosWithEOL(node.getChars()).withAttr(CoreNodeRenderer.TIGHT_LIST_ITEM).withCondIndent().tagLine("dd", () -> { html.text(node.getMarkerSuffix().unescape()); context.renderChildren(node); }); } else { html.srcPosWithEOL(node.getChars()).withAttr(CoreNodeRenderer.LOOSE_LIST_ITEM).tagIndent("dd", () -> { html.text(node.getMarkerSuffix().unescape()); context.renderChildren(node); }); }
436
172
608
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/Emoji.java
Emoji
collectText
class Emoji extends Node implements DelimitedNode, TextContainer { protected BasedSequence openingMarker = BasedSequence.NULL; protected BasedSequence text = BasedSequence.NULL; protected BasedSequence closingMarker = BasedSequence.NULL; @NotNull @Override public BasedSequence[] getSegments() { return new BasedSequence[] { openingMarker, text, closingMarker }; } @Override public void getAstExtra(@NotNull StringBuilder out) { delimitedSegmentSpanChars(out, openingMarker, text, closingMarker, "text"); } public Emoji() { } public Emoji(BasedSequence chars) { super(chars); } public Emoji(BasedSequence openingMarker, BasedSequence text, BasedSequence closingMarker) { super(openingMarker.baseSubSequence(openingMarker.getStartOffset(), closingMarker.getEndOffset())); this.openingMarker = openingMarker; this.text = text; this.closingMarker = closingMarker; } public BasedSequence getOpeningMarker() { return openingMarker; } public void setOpeningMarker(BasedSequence openingMarker) { this.openingMarker = openingMarker; } public BasedSequence getText() { return text; } public void setText(BasedSequence text) { this.text = text; } public BasedSequence getClosingMarker() { return closingMarker; } public void setClosingMarker(BasedSequence closingMarker) { this.closingMarker = closingMarker; } @Override public boolean collectText(ISequenceBuilder<? extends ISequenceBuilder<?, BasedSequence>, BasedSequence> out, int flags, NodeVisitor nodeVisitor) {<FILL_FUNCTION_BODY>} }
if (BitFieldSet.any(flags, F_FOR_HEADING_ID)) { if (HtmlRenderer.HEADER_ID_ADD_EMOJI_SHORTCUT.get(getDocument())) { out.append(text); } } return false;
458
74
532
<methods>public void <init>() ,public void <init>(@NotNull BasedSequence) ,public void appendChain(@NotNull Node) ,public void appendChild(com.vladsch.flexmark.util.ast.Node) ,public static void astChars(@NotNull StringBuilder, @NotNull CharSequence, @NotNull String) ,public void astExtraChars(@NotNull StringBuilder) ,public void astString(@NotNull StringBuilder, boolean) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int, int) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int) ,public transient int countAncestorsOfType(@NotNull Class<?> []) ,public transient int countDirectAncestorsOfType(@Nullable Class<?>, @NotNull Class<?> []) ,public static void delimitedSegmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public static void delimitedSegmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public int endOfLine(int) ,public void extractChainTo(@NotNull Node) ,public void extractToFirstInChain(@NotNull Node) ,public transient @Nullable Node getAncestorOfType(@NotNull Class<?> []) ,public void getAstExtra(@NotNull StringBuilder) ,public com.vladsch.flexmark.util.sequence.BasedSequence getBaseSequence() ,public @NotNull Node getBlankLineSibling() ,public @NotNull BasedSequence getChars() ,public @NotNull BasedSequence getCharsFromSegments() ,public com.vladsch.flexmark.util.sequence.BasedSequence getChildChars() ,public @NotNull ReversiblePeekingIterator<Node> getChildIterator() ,public transient @Nullable Node getChildOfType(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterable<Node> getChildren() ,public @NotNull ReversiblePeekingIterable<Node> getDescendants() ,public @NotNull Document getDocument() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptyPrefix() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptySuffix() ,public int getEndLineNumber() ,public int getEndOfLine() ,public int getEndOffset() ,public com.vladsch.flexmark.util.sequence.BasedSequence getExactChildChars() ,public @Nullable Node getFirstChild() ,public transient @Nullable Node getFirstChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getFirstChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getFirstInChain() ,public @Nullable Node getGrandParent() ,public @Nullable Node getLastBlankLineChild() ,public @Nullable Node getLastChild() ,public transient @Nullable Node getLastChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getLastChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getLastInChain() ,public static @NotNull BasedSequence getLeadSegment(@NotNull BasedSequence []) ,public Pair<java.lang.Integer,java.lang.Integer> getLineColumnAtEnd() ,public int getLineNumber() ,public @Nullable Node getNext() ,public transient @Nullable Node getNextAny(@NotNull Class<?> []) ,public transient @Nullable Node getNextAnyNot(@NotNull Class<?> []) ,public @NotNull String getNodeName() ,public static transient int getNodeOfTypeIndex(@NotNull Node, @NotNull Class<?> []) ,public transient int getNodeOfTypeIndex(@NotNull Class<?> []) ,public @Nullable Node getOldestAncestorOfTypeAfter(@NotNull Class<?>, @NotNull Class<?>) ,public @Nullable Node getParent() ,public @Nullable Node getPrevious() ,public transient @Nullable Node getPreviousAny(@NotNull Class<?> []) ,public transient @Nullable Node getPreviousAnyNot(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterator<Node> getReversedChildIterator() ,public @NotNull ReversiblePeekingIterable<Node> getReversedChildren() ,public @NotNull ReversiblePeekingIterable<Node> getReversedDescendants() ,public abstract @NotNull BasedSequence [] getSegments() ,public @NotNull BasedSequence [] getSegmentsForChars() ,public com.vladsch.flexmark.util.sequence.Range getSourceRange() ,public int getStartLineNumber() ,public int getStartOfLine() ,public int getStartOffset() ,public int getTextLength() ,public static @NotNull BasedSequence getTrailSegment(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public boolean hasChildren() ,public boolean hasOrMoreChildren(int) ,public void insertAfter(@NotNull Node) ,public void insertBefore(com.vladsch.flexmark.util.ast.Node) ,public void insertChainAfter(@NotNull Node) ,public void insertChainBefore(@NotNull Node) ,public transient boolean isOrDescendantOfType(@NotNull Class<?> []) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtIndex(int) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtStart() ,public void moveTrailingBlankLines() ,public void prependChild(@NotNull Node) ,public void removeChildren() ,public static void segmentSpan(@NotNull StringBuilder, int, int, @Nullable String) ,public static void segmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @Nullable String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String, @NotNull String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public static void segmentSpanCharsToVisible(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public void setChars(@NotNull BasedSequence) ,public void setCharsFromContent() ,public void setCharsFromContentOnly() ,public void setCharsFromSegments() ,public static transient @NotNull BasedSequence spanningChars(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public int startOfLine(int) ,public void takeChildren(@NotNull Node) ,public @NotNull String toAstString(boolean) ,public static @NotNull String toSegmentSpan(@NotNull BasedSequence, @Nullable String) ,public java.lang.String toString() ,public void unlink() <variables>public static final AstNode<com.vladsch.flexmark.util.ast.Node> AST_ADAPTER,public static final com.vladsch.flexmark.util.sequence.BasedSequence[] EMPTY_SEGMENTS,public static final java.lang.String SPLICE,private @NotNull BasedSequence chars,@Nullable Node firstChild,private @Nullable Node lastChild,@Nullable Node next,private @Nullable Node parent,private @Nullable Node prev
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/EmojiExtension.java
EmojiExtension
extend
class EmojiExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, Formatter.FormatterExtension { final public static DataKey<String> ATTR_ALIGN = new DataKey<>("ATTR_ALIGN", "absmiddle"); final public static DataKey<String> ATTR_IMAGE_SIZE = new DataKey<>("ATTR_IMAGE_SIZE", "20"); final public static DataKey<String> ATTR_IMAGE_CLASS = new DataKey<>("ATTR_IMAGE_CLASS", ""); final public static DataKey<String> ROOT_IMAGE_PATH = new DataKey<>("ROOT_IMAGE_PATH", "/img/"); final public static DataKey<EmojiShortcutType> USE_SHORTCUT_TYPE = new DataKey<>("USE_SHORTCUT_TYPE", EmojiShortcutType.EMOJI_CHEAT_SHEET); final public static DataKey<EmojiImageType> USE_IMAGE_TYPE = new DataKey<>("USE_IMAGE_TYPE", EmojiImageType.IMAGE_ONLY); final public static DataKey<Boolean> USE_UNICODE_FILE_NAMES = new DataKey<>("USE_UNICODE_FILE_NAMES", false); private EmojiExtension() { } public static EmojiExtension create() { return new EmojiExtension(); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new EmojiNodeFormatter.Factory()); } @Override public void extend(Parser.Builder parserBuilder) { parserBuilder.customDelimiterProcessor(new EmojiDelimiterProcessor()); } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) {<FILL_FUNCTION_BODY>} }
if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new EmojiNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { htmlRendererBuilder.nodeRendererFactory(new EmojiJiraRenderer.Factory()); }
517
79
596
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiDelimiterProcessor.java
EmojiDelimiterProcessor
getDelimiterUse
class EmojiDelimiterProcessor implements DelimiterProcessor { @Override public char getOpeningCharacter() { return ':'; } @Override public char getClosingCharacter() { return ':'; } @Override public int getMinLength() { return 1; } @Override public boolean canBeOpener(String before, String after, boolean leftFlanking, boolean rightFlanking, boolean beforeIsPunctuation, boolean afterIsPunctuation, boolean beforeIsWhitespace, boolean afterIsWhiteSpace) { return leftFlanking && !"0123456789".contains(before); } @Override public boolean canBeCloser(String before, String after, boolean leftFlanking, boolean rightFlanking, boolean beforeIsPunctuation, boolean afterIsPunctuation, boolean beforeIsWhitespace, boolean afterIsWhiteSpace) { return rightFlanking && !"0123456789".contains(after); } @Override public boolean skipNonOpenerCloser() { return true; } @Override public int getDelimiterUse(DelimiterRun opener, DelimiterRun closer) {<FILL_FUNCTION_BODY>} @Override public Node unmatchedDelimiterNode(InlineParser inlineParser, DelimiterRun delimiter) { return null; } @Override public void process(Delimiter opener, Delimiter closer, int delimitersUsed) { // Normal case, wrap nodes between delimiters in emoji node. // don't allow any spaces between delimiters if (opener.getInput().subSequence(opener.getEndIndex(), closer.getStartIndex()).indexOfAny(CharPredicate.WHITESPACE) == -1) { Emoji emoji = new Emoji(opener.getTailChars(delimitersUsed), BasedSequence.NULL, closer.getLeadChars(delimitersUsed)); opener.moveNodesBetweenDelimitersTo(emoji, closer); } else { opener.convertDelimitersToText(delimitersUsed, closer); } } }
if (opener.length() >= 1 && closer.length() >= 1) { return 1; } else { return 1; }
569
43
612
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiJiraRenderer.java
EmojiJiraRenderer
render
class EmojiJiraRenderer implements NodeRenderer { final public static HashMap<String, String> shortCutMap = new HashMap<>(); static { shortCutMap.put("smile", ":)"); shortCutMap.put("frowning", ":("); shortCutMap.put("stuck_out_tongue", ":P"); shortCutMap.put("grinning", ":D"); shortCutMap.put("wink", ";)"); shortCutMap.put("thumbsup", "(y)"); shortCutMap.put("thumbsdown", "(n)"); shortCutMap.put("information_source", "(i)"); shortCutMap.put("white_check_mark", "(/)"); shortCutMap.put("x", "(x)"); shortCutMap.put("warning", "(!)"); shortCutMap.put("heavy_plus_sign", "(+)"); shortCutMap.put("heavy_minus_sign", "(-)"); shortCutMap.put("question", "(?)"); shortCutMap.put("bulb", "(on)"); shortCutMap.put("star", "(*)"); shortCutMap.put("triangular_flag_on_post", "(flag)"); shortCutMap.put("crossed_flags", "(flagoff)"); } public EmojiJiraRenderer(DataHolder options) { } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() { HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(Emoji.class, this::render)); return set; } private void render(Emoji node, NodeRendererContext context, HtmlWriter html) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new EmojiJiraRenderer(options); } } }
Emoji emoji = (Emoji) node; String shortcut = shortCutMap.get(emoji.getText().toString()); if (shortcut == null) { // output as text html.text(":"); context.renderChildren(node); html.text(":"); } else { html.raw(shortcut); }
527
96
623
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiNodeFormatter.java
EmojiNodeFormatter
getNodeFormattingHandlers
class EmojiNodeFormatter implements NodeFormatter { public EmojiNodeFormatter(DataHolder options) { } @Nullable @Override public Set<Class<?>> getNodeClasses() { return null; } // only registered if assignTextAttributes is enabled @Nullable @Override public Set<NodeFormattingHandler<?>> getNodeFormattingHandlers() {<FILL_FUNCTION_BODY>} void render(Emoji node, NodeFormatterContext context, MarkdownWriter markdown) { markdown.append(node.getOpeningMarker()); markdown.appendNonTranslating(node.getText()); markdown.append(node.getClosingMarker()); } public static class Factory implements NodeFormatterFactory { @NotNull @Override public NodeFormatter create(@NotNull DataHolder options) { return new EmojiNodeFormatter(options); } } }
HashSet<NodeFormattingHandler<?>> set = new HashSet<>(); set.add(new NodeFormattingHandler<>(Emoji.class, EmojiNodeFormatter.this::render)); return set;
242
57
299
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiNodeRenderer.java
EmojiNodeRenderer
render
class EmojiNodeRenderer implements NodeRenderer { final EmojiOptions myOptions; public EmojiNodeRenderer(DataHolder options) { myOptions = new EmojiOptions(options); } @Override public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() { HashSet<NodeRenderingHandler<?>> set = new HashSet<>(); set.add(new NodeRenderingHandler<>(Emoji.class, this::render)); return set; } private void render(Emoji node, NodeRendererContext context, HtmlWriter html) {<FILL_FUNCTION_BODY>} public static class Factory implements NodeRendererFactory { @NotNull @Override public NodeRenderer apply(@NotNull DataHolder options) { return new EmojiNodeRenderer(options); } } }
EmojiResolvedShortcut shortcut = EmojiResolvedShortcut.getEmojiText(node, myOptions.useShortcutType, myOptions.useImageType, myOptions.rootImagePath, myOptions.useUnicodeFileNames); if (shortcut.emoji == null || shortcut.emojiText == null) { // output as text html.text(":"); context.renderChildren(node); html.text(":"); } else { if (shortcut.isUnicode) { html.text(shortcut.emojiText); } else { ResolvedLink resolvedLink = context.resolveLink(LinkType.IMAGE, shortcut.emojiText, null); html.attr("src", resolvedLink.getUrl()); html.attr("alt", shortcut.alt); if (!myOptions.attrImageSize.isEmpty()) html.attr("height", myOptions.attrImageSize).attr("width", myOptions.attrImageSize); if (!myOptions.attrAlign.isEmpty()) html.attr("align", myOptions.attrAlign); if (!myOptions.attrImageClass.isEmpty()) html.attr("class", myOptions.attrImageClass); html.withAttr(resolvedLink); html.tagVoid("img"); } }
215
323
538
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiReference.java
Emoji
getEmojiList
class Emoji { public final String shortcut; public String[] aliasShortcuts; public final String category; public String subcategory; public final String emojiCheatSheetFile; // name part of the file no extension public final String githubFile; // name part of the file no extension public final String unicodeChars; // unicode char codes space separated list public final String unicodeSampleFile; // name part of the file no extension public final String unicodeCldr; public String[] browserTypes; public Emoji(String shortcut , String[] aliasShortcuts , String category , String subcategory , String emojiCheatSheetFile , String githubFile , String unicodeChars , String unicodeSampleFile , String unicodeCldr , String[] browserTypes ) { this.shortcut = shortcut; this.aliasShortcuts = aliasShortcuts; this.category = category; this.subcategory = subcategory; this.emojiCheatSheetFile = emojiCheatSheetFile; this.githubFile = githubFile; this.unicodeChars = unicodeChars; this.unicodeSampleFile = unicodeSampleFile; this.unicodeCldr = unicodeCldr; this.browserTypes = browserTypes; } } private static ArrayList<Emoji> emojiList = null; public static List<Emoji> getEmojiList() {<FILL_FUNCTION_BODY>
if (emojiList == null) { // read it in emojiList = new ArrayList<>(3000); final String emojiReference = EMOJI_REFERENCE_TXT; InputStream stream = EmojiReference.class.getResourceAsStream(emojiReference); if (stream == null) { throw new IllegalStateException("Could not load " + emojiReference + " classpath resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); String line; try { // skip first line, it is column names line = reader.readLine(); while ((line = reader.readLine()) != null) { String[] fields = line.split("\t"); try { String shortcut = fields[0].charAt(0) == ' ' ? null : fields[0]; String category = fields[1].charAt(0) == ' ' ? null : fields[1]; String emojiCheatSheetFile = fields[2].charAt(0) == ' ' ? null : fields[2]; String githubFile = fields[3].charAt(0) == ' ' ? null : fields[3]; String unicodeChars = fields[4].charAt(0) == ' ' ? null : fields[4]; String unicodeSampleFile = fields[5].charAt(0) == ' ' ? null : fields[5]; String unicodeCldr = fields[6].charAt(0) == ' ' ? null : fields[6]; String subcategory = fields[7].charAt(0) == ' ' ? null : fields[7]; String[] aliasShortcuts = fields[8].charAt(0) == ' ' ? EMPTY_ARRAY : fields[8].split(","); String[] browserTypes = fields[9].charAt(0) == ' ' ? EMPTY_ARRAY : fields[9].split(","); final Emoji emoji = new Emoji( shortcut , aliasShortcuts , category , subcategory , emojiCheatSheetFile , githubFile , unicodeChars , unicodeSampleFile , unicodeCldr , browserTypes ); emojiList.add(emoji); //if (emoji.shortcut != null && emoji.unicodeChars == null) { // String type = emoji.githubFile == null ? "cheatSheet " : (emoji.emojiCheatSheetFile == null ? "gitHub " : ""); // System.out.printf("Non unicode %sshortcut %s\n",type, emoji.shortcut); //} } catch (ArrayIndexOutOfBoundsException e) { //e.printStackTrace(); throw new IllegalStateException("Error processing EmojiReference.txt", e); } } } catch (IOException e) { //e.printStackTrace(); throw new IllegalStateException("Error processing EmojiReference.txt", e); } } return emojiList;
394
794
1,188
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiResolvedShortcut.java
EmojiResolvedShortcut
getEmojiText
class EmojiResolvedShortcut { final public EmojiReference.Emoji emoji; final public String emojiText; final public boolean isUnicode; final public String alt; public EmojiResolvedShortcut(EmojiReference.Emoji emoji, String emojiText, boolean isUnicode, String alt) { this.emoji = emoji; this.emojiText = emojiText; this.isUnicode = isUnicode; this.alt = alt; } public static EmojiResolvedShortcut getEmojiText(Emoji node, EmojiShortcutType useShortcutType, EmojiImageType useImageType, String rootImagePath) { return getEmojiText(node.getText().toString(), useShortcutType, useImageType, rootImagePath); } public static EmojiResolvedShortcut getEmojiText(Emoji node, EmojiShortcutType useShortcutType, EmojiImageType useImageType, String rootImagePath, boolean useUnicodeFileName) { return getEmojiText(node.getText().toString(), useShortcutType, useImageType, rootImagePath, useUnicodeFileName); } public static EmojiResolvedShortcut getEmojiText(String emojiId, EmojiShortcutType useShortcutType, EmojiImageType useImageType, String rootImagePath) { return getEmojiText(emojiId, useShortcutType, useImageType, rootImagePath, false); } public static EmojiResolvedShortcut getEmojiText(String emojiId, EmojiShortcutType useShortcutType, EmojiImageType useImageType, String rootImagePath, boolean useUnicodeFileName) {<FILL_FUNCTION_BODY>} }
EmojiReference.Emoji emoji = EmojiShortcuts.getEmojiFromShortcut(emojiId); String emojiText = null; boolean isUnicode = false; String alt = null; if (emoji != null) { String unicodeText = null; String imageText = null; if (useImageType.isUnicode && emoji.unicodeChars != null) { unicodeText = EmojiShortcuts.getUnicodeChars(emoji); } if (useImageType.isImage) { String gitHubFile = null; String cheatSheetFile = null; if (useShortcutType.isGitHub && emoji.githubFile != null) { gitHubFile = EmojiShortcuts.gitHubUrlPrefix + emoji.githubFile; } if (useShortcutType.isEmojiCheatSheet && emoji.emojiCheatSheetFile != null) { if (useUnicodeFileName && emoji.unicodeSampleFile != null) { cheatSheetFile = rootImagePath + emoji.unicodeSampleFile; } else { cheatSheetFile = rootImagePath + emoji.emojiCheatSheetFile; } } imageText = useShortcutType.getPreferred(cheatSheetFile, gitHubFile); } if (imageText != null || unicodeText != null) { if (unicodeText != null) { emojiText = unicodeText; isUnicode = true; } else { emojiText = imageText; } // CAUTION: this exact string is used by html parser to convert emoji from Apple Mail HTML alt = "emoji " + emoji.category + ":" + emoji.shortcut; } } return new EmojiResolvedShortcut(emoji, emojiText, isUnicode, alt);
463
523
986
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-emoji/src/main/java/com/vladsch/flexmark/ext/emoji/internal/EmojiShortcuts.java
EmojiShortcuts
getUnicodeChars
class EmojiShortcuts { final public static String gitHubUrlPrefix = EmojiReference.githubUrl; final private static HashMap<String, Emoji> emojiShortcuts = new HashMap<>(); final private static HashMap<String, Emoji> emojiURIs = new HashMap<>(); final private static HashMap<Emoji, String> emojiUnicodeChars = new HashMap<>(); synchronized public static String getUnicodeChars(Emoji emoji) {<FILL_FUNCTION_BODY>} public static String extractFileName(String emojiURI) { String fileName = new File(emojiURI).getName(); int pos = fileName.indexOf(".png"); if (pos >= 0) { fileName = fileName.substring(0, pos); } return fileName; } public static HashMap<String, Emoji> getEmojiShortcuts() { updateEmojiShortcuts(); return emojiShortcuts; } public static HashMap<String, Emoji> getEmojiURIs() { updateEmojiShortcuts(); return emojiURIs; } public static Emoji getEmojiFromShortcut(String shortcut) { updateEmojiShortcuts(); return emojiShortcuts.get(shortcut); } public static Emoji getEmojiFromURI(String imageURI) { updateEmojiURIs(); return emojiURIs.get(extractFileName(imageURI)); } synchronized private static void updateEmojiShortcuts() { if (emojiShortcuts.isEmpty()) { for (Emoji emoji : EmojiReference.getEmojiList()) { if (emoji.shortcut != null) { emojiShortcuts.put(emoji.shortcut, emoji); } } } } synchronized private static void updateEmojiURIs() { if (emojiURIs.isEmpty()) { // create it for (Emoji emoji : EmojiReference.getEmojiList()) { if (emoji.emojiCheatSheetFile != null) { emojiURIs.put(extractFileName(emoji.emojiCheatSheetFile), emoji); } if (emoji.githubFile != null) { emojiURIs.put(extractFileName(emoji.githubFile), emoji); } if (emoji.unicodeSampleFile != null) { emojiURIs.put(extractFileName(emoji.unicodeSampleFile), emoji); } } } } }
if (emoji == null || emoji.unicodeChars == null) { return null; } String value = emojiUnicodeChars.get(emoji); if (value == null) { String[] unicodePoints = emoji.unicodeChars.replace("U+", "").split(" "); StringBuilder sb = new StringBuilder(16); for (String unicodePoint : unicodePoints) { sb.appendCodePoint(Integer.parseInt(unicodePoint, 16)); } value = sb.toString(); emojiUnicodeChars.put(emoji, value); } return value;
714
174
888
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-enumerated-reference/src/main/java/com/vladsch/flexmark/ext/enumerated/reference/EnumeratedReferenceBase.java
EnumeratedReferenceBase
getReferenceNode
class EnumeratedReferenceBase extends Node implements DelimitedNode, DoNotDecorate, ReferencingNode<EnumeratedReferenceRepository, EnumeratedReferenceBlock> { protected BasedSequence openingMarker = BasedSequence.NULL; protected BasedSequence text = BasedSequence.NULL; protected BasedSequence closingMarker = BasedSequence.NULL; protected EnumeratedReferenceBlock enumeratedReferenceBlock; @NotNull @Override public BasedSequence getReference() { return text; } @Override public EnumeratedReferenceBlock getReferenceNode(Document document) { return enumeratedReferenceBlock; } @Override public EnumeratedReferenceBlock getReferenceNode(EnumeratedReferenceRepository repository) {<FILL_FUNCTION_BODY>} public boolean isDefined() { return enumeratedReferenceBlock != null; } public EnumeratedReferenceBlock getEnumeratedReferenceBlock(EnumeratedReferenceRepository enumeratedReferenceRepository) { return text.isEmpty() ? null : enumeratedReferenceRepository.get(EnumeratedReferenceRepository.getType(text.toString())); } public EnumeratedReferenceBlock getEnumeratedReferenceBlock() { return enumeratedReferenceBlock; } public void setEnumeratedReferenceBlock(EnumeratedReferenceBlock enumeratedReferenceBlock) { this.enumeratedReferenceBlock = enumeratedReferenceBlock; } @NotNull @Override public BasedSequence[] getSegments() { return new BasedSequence[] { openingMarker, text, closingMarker }; } @Override public void getAstExtra(@NotNull StringBuilder out) { delimitedSegmentSpanChars(out, openingMarker, text, closingMarker, "text"); } public EnumeratedReferenceBase() { } public EnumeratedReferenceBase(BasedSequence chars) { super(chars); } public EnumeratedReferenceBase(BasedSequence openingMarker, BasedSequence text, BasedSequence closingMarker) { super(openingMarker.baseSubSequence(openingMarker.getStartOffset(), closingMarker.getEndOffset())); this.openingMarker = openingMarker; this.text = text; this.closingMarker = closingMarker; } public BasedSequence getOpeningMarker() { return openingMarker; } public void setOpeningMarker(BasedSequence openingMarker) { this.openingMarker = openingMarker; } public BasedSequence getText() { return text; } public void setText(BasedSequence text) { this.text = text; } public BasedSequence getClosingMarker() { return closingMarker; } public void setClosingMarker(BasedSequence closingMarker) { this.closingMarker = closingMarker; } }
if (enumeratedReferenceBlock != null || text.isEmpty()) return enumeratedReferenceBlock; enumeratedReferenceBlock = getEnumeratedReferenceBlock(repository); return enumeratedReferenceBlock;
693
50
743
<methods>public void <init>() ,public void <init>(@NotNull BasedSequence) ,public void appendChain(@NotNull Node) ,public void appendChild(com.vladsch.flexmark.util.ast.Node) ,public static void astChars(@NotNull StringBuilder, @NotNull CharSequence, @NotNull String) ,public void astExtraChars(@NotNull StringBuilder) ,public void astString(@NotNull StringBuilder, boolean) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int, int) ,public com.vladsch.flexmark.util.sequence.BasedSequence baseSubSequence(int) ,public transient int countAncestorsOfType(@NotNull Class<?> []) ,public transient int countDirectAncestorsOfType(@Nullable Class<?>, @NotNull Class<?> []) ,public static void delimitedSegmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public static void delimitedSegmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull BasedSequence, @NotNull String) ,public int endOfLine(int) ,public void extractChainTo(@NotNull Node) ,public void extractToFirstInChain(@NotNull Node) ,public transient @Nullable Node getAncestorOfType(@NotNull Class<?> []) ,public void getAstExtra(@NotNull StringBuilder) ,public com.vladsch.flexmark.util.sequence.BasedSequence getBaseSequence() ,public @NotNull Node getBlankLineSibling() ,public @NotNull BasedSequence getChars() ,public @NotNull BasedSequence getCharsFromSegments() ,public com.vladsch.flexmark.util.sequence.BasedSequence getChildChars() ,public @NotNull ReversiblePeekingIterator<Node> getChildIterator() ,public transient @Nullable Node getChildOfType(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterable<Node> getChildren() ,public @NotNull ReversiblePeekingIterable<Node> getDescendants() ,public @NotNull Document getDocument() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptyPrefix() ,public com.vladsch.flexmark.util.sequence.BasedSequence getEmptySuffix() ,public int getEndLineNumber() ,public int getEndOfLine() ,public int getEndOffset() ,public com.vladsch.flexmark.util.sequence.BasedSequence getExactChildChars() ,public @Nullable Node getFirstChild() ,public transient @Nullable Node getFirstChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getFirstChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getFirstInChain() ,public @Nullable Node getGrandParent() ,public @Nullable Node getLastBlankLineChild() ,public @Nullable Node getLastChild() ,public transient @Nullable Node getLastChildAny(@NotNull Class<?> []) ,public transient @Nullable Node getLastChildAnyNot(@NotNull Class<?> []) ,public @NotNull Node getLastInChain() ,public static @NotNull BasedSequence getLeadSegment(@NotNull BasedSequence []) ,public Pair<java.lang.Integer,java.lang.Integer> getLineColumnAtEnd() ,public int getLineNumber() ,public @Nullable Node getNext() ,public transient @Nullable Node getNextAny(@NotNull Class<?> []) ,public transient @Nullable Node getNextAnyNot(@NotNull Class<?> []) ,public @NotNull String getNodeName() ,public static transient int getNodeOfTypeIndex(@NotNull Node, @NotNull Class<?> []) ,public transient int getNodeOfTypeIndex(@NotNull Class<?> []) ,public @Nullable Node getOldestAncestorOfTypeAfter(@NotNull Class<?>, @NotNull Class<?>) ,public @Nullable Node getParent() ,public @Nullable Node getPrevious() ,public transient @Nullable Node getPreviousAny(@NotNull Class<?> []) ,public transient @Nullable Node getPreviousAnyNot(@NotNull Class<?> []) ,public @NotNull ReversiblePeekingIterator<Node> getReversedChildIterator() ,public @NotNull ReversiblePeekingIterable<Node> getReversedChildren() ,public @NotNull ReversiblePeekingIterable<Node> getReversedDescendants() ,public abstract @NotNull BasedSequence [] getSegments() ,public @NotNull BasedSequence [] getSegmentsForChars() ,public com.vladsch.flexmark.util.sequence.Range getSourceRange() ,public int getStartLineNumber() ,public int getStartOfLine() ,public int getStartOffset() ,public int getTextLength() ,public static @NotNull BasedSequence getTrailSegment(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public boolean hasChildren() ,public boolean hasOrMoreChildren(int) ,public void insertAfter(@NotNull Node) ,public void insertBefore(com.vladsch.flexmark.util.ast.Node) ,public void insertChainAfter(@NotNull Node) ,public void insertChainBefore(@NotNull Node) ,public transient boolean isOrDescendantOfType(@NotNull Class<?> []) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtIndex(int) ,public Pair<java.lang.Integer,java.lang.Integer> lineColumnAtStart() ,public void moveTrailingBlankLines() ,public void prependChild(@NotNull Node) ,public void removeChildren() ,public static void segmentSpan(@NotNull StringBuilder, int, int, @Nullable String) ,public static void segmentSpan(@NotNull StringBuilder, @NotNull BasedSequence, @Nullable String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, int, int, @Nullable String, @NotNull String, @NotNull String, @NotNull String) ,public static void segmentSpanChars(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public static void segmentSpanCharsToVisible(@NotNull StringBuilder, @NotNull BasedSequence, @NotNull String) ,public void setChars(@NotNull BasedSequence) ,public void setCharsFromContent() ,public void setCharsFromContentOnly() ,public void setCharsFromSegments() ,public static transient @NotNull BasedSequence spanningChars(com.vladsch.flexmark.util.sequence.BasedSequence[]) ,public int startOfLine(int) ,public void takeChildren(@NotNull Node) ,public @NotNull String toAstString(boolean) ,public static @NotNull String toSegmentSpan(@NotNull BasedSequence, @Nullable String) ,public java.lang.String toString() ,public void unlink() <variables>public static final AstNode<com.vladsch.flexmark.util.ast.Node> AST_ADAPTER,public static final com.vladsch.flexmark.util.sequence.BasedSequence[] EMPTY_SEGMENTS,public static final java.lang.String SPLICE,private @NotNull BasedSequence chars,@Nullable Node firstChild,private @Nullable Node lastChild,@Nullable Node next,private @Nullable Node parent,private @Nullable Node prev
vsch_flexmark-java
flexmark-java/flexmark-ext-enumerated-reference/src/main/java/com/vladsch/flexmark/ext/enumerated/reference/EnumeratedReferenceExtension.java
EnumeratedReferenceExtension
transferReferences
class EnumeratedReferenceExtension implements Parser.ParserExtension , HtmlRenderer.HtmlRendererExtension , Parser.ReferenceHoldingExtension , Formatter.FormatterExtension { final public static DataKey<KeepType> ENUMERATED_REFERENCES_KEEP = new DataKey<>("ENUMERATED_REFERENCES_KEEP", KeepType.FIRST); // standard option to allow control over how to handle duplicates final public static DataKey<EnumeratedReferenceRepository> ENUMERATED_REFERENCES = new DataKey<>("ENUMERATED_REFERENCES", new EnumeratedReferenceRepository(null), EnumeratedReferenceRepository::new); final public static DataKey<EnumeratedReferences> ENUMERATED_REFERENCE_ORDINALS = new DataKey<>("ENUMERATED_REFERENCE_ORDINALS", new EnumeratedReferences(null), EnumeratedReferences::new); // formatter options final public static DataKey<ElementPlacement> ENUMERATED_REFERENCE_PLACEMENT = new DataKey<>("ENUMERATED_REFERENCE_PLACEMENT", ElementPlacement.AS_IS); final public static DataKey<ElementPlacementSort> ENUMERATED_REFERENCE_SORT = new DataKey<>("ENUMERATED_REFERENCE_SORT", ElementPlacementSort.AS_IS); private EnumeratedReferenceExtension() { } public static EnumeratedReferenceExtension create() { return new EnumeratedReferenceExtension(); } @Override public void rendererOptions(@NotNull MutableDataHolder options) { } @Override public void parserOptions(MutableDataHolder options) { } @Override public boolean transferReferences(MutableDataHolder document, DataHolder included) {<FILL_FUNCTION_BODY>} @Override public void extend(Parser.Builder parserBuilder) { //parserBuilder.paragraphPreProcessorFactory(EnumeratedReferenceParagraphPreProcessor.Factory()); parserBuilder.postProcessorFactory(new EnumeratedReferenceNodePostProcessor.Factory()); parserBuilder.customBlockParserFactory(new EnumeratedReferenceBlockParser.Factory()); parserBuilder.linkRefProcessorFactory(new EnumeratedReferenceLinkRefProcessor.Factory()); } @Override public void extend(Formatter.Builder formatterBuilder) { formatterBuilder.nodeFormatterFactory(new EnumeratedReferenceNodeFormatter.Factory()); } @Override public void extend(@NotNull HtmlRenderer.Builder htmlRendererBuilder, @NotNull String rendererType) { if (htmlRendererBuilder.isRendererType("HTML")) { htmlRendererBuilder.nodeRendererFactory(new EnumeratedReferenceNodeRenderer.Factory()); } else if (htmlRendererBuilder.isRendererType("JIRA")) { } } }
if (document.contains(ENUMERATED_REFERENCES) && included.contains(ENUMERATED_REFERENCES)) { return Parser.transferReferences(ENUMERATED_REFERENCES.get(document), ENUMERATED_REFERENCES.get(included), ENUMERATED_REFERENCES_KEEP.get(document) == KeepType.FIRST); } return false;
702
110
812
<no_super_class>
vsch_flexmark-java
flexmark-java/flexmark-ext-enumerated-reference/src/main/java/com/vladsch/flexmark/ext/enumerated/reference/EnumeratedReferenceRepository.java
EnumeratedReferenceRepository
getType
class EnumeratedReferenceRepository extends NodeRepository<EnumeratedReferenceBlock> { private ArrayList<EnumeratedReferenceBlock> referencedEnumeratedReferenceBlocks = new ArrayList<>(); public static String getType(String text) {<FILL_FUNCTION_BODY>} public List<EnumeratedReferenceBlock> getReferencedEnumeratedReferenceBlocks() { return referencedEnumeratedReferenceBlocks; } public EnumeratedReferenceRepository(DataHolder options) { //super(options == null ? KeepType.LAST : EnumeratedReferenceExtension.ENUMERATED_REFERENCES_KEEP.getFrom(options)); super(EnumeratedReferenceExtension.ENUMERATED_REFERENCES_KEEP.get(options)); } @NotNull @Override public DataKey<EnumeratedReferenceRepository> getDataKey() { return EnumeratedReferenceExtension.ENUMERATED_REFERENCES; } @NotNull @Override public DataKey<KeepType> getKeepDataKey() { return EnumeratedReferenceExtension.ENUMERATED_REFERENCES_KEEP; } @NotNull @Override public Set<EnumeratedReferenceBlock> getReferencedElements(Node parent) { HashSet<EnumeratedReferenceBlock> references = new HashSet<>(); visitNodes(parent, value -> { if (value instanceof EnumeratedReferenceBase) { EnumeratedReferenceBlock reference = ((EnumeratedReferenceBase) value).getReferenceNode(EnumeratedReferenceRepository.this); if (reference != null) { references.add(reference); } } }, EnumeratedReferenceText.class, EnumeratedReferenceLink.class); return references; } }
int pos = text.lastIndexOf(':'); if (pos > 0) { return text.subSequence(0, pos).toString(); } else { // use empty type return EnumeratedReferences.EMPTY_TYPE; }
443
68
511
<methods>public void <init>(@Nullable KeepType) ,public void clear() ,public boolean containsKey(@NotNull Object) ,public boolean containsValue(java.lang.Object) ,public @NotNull Set<Map.Entry<String,EnumeratedReferenceBlock>> entrySet() ,public boolean equals(java.lang.Object) ,public @Nullable EnumeratedReferenceBlock get(@NotNull Object) ,public abstract @NotNull DataKey<? extends NodeRepository<EnumeratedReferenceBlock>> getDataKey() ,public @Nullable EnumeratedReferenceBlock getFromRaw(@NotNull CharSequence) ,public abstract @NotNull DataKey<KeepType> getKeepDataKey() ,public abstract @NotNull Set<EnumeratedReferenceBlock> getReferencedElements(com.vladsch.flexmark.util.ast.Node) ,public @NotNull Collection<EnumeratedReferenceBlock> getValues() ,public int hashCode() ,public boolean isEmpty() ,public @NotNull Set<String> keySet() ,public @NotNull String normalizeKey(@NotNull CharSequence) ,public @Nullable EnumeratedReferenceBlock put(@NotNull String, @NotNull EnumeratedReferenceBlock) ,public void putAll(@NotNull Map<? extends String,? extends EnumeratedReferenceBlock>) ,public @Nullable EnumeratedReferenceBlock putRawKey(@NotNull CharSequence, @NotNull EnumeratedReferenceBlock) ,public @Nullable EnumeratedReferenceBlock remove(@NotNull Object) ,public int size() ,public static boolean transferReferences(@NotNull NodeRepository<T>, @NotNull NodeRepository<T>, boolean, @Nullable Map<String,String>) ,public @NotNull List<EnumeratedReferenceBlock> values() <variables>protected final non-sealed com.vladsch.flexmark.util.ast.KeepType keepType,protected final ArrayList<com.vladsch.flexmark.ext.enumerated.reference.EnumeratedReferenceBlock> nodeList,protected final Map<java.lang.String,com.vladsch.flexmark.ext.enumerated.reference.EnumeratedReferenceBlock> nodeMap
vsch_flexmark-java
flexmark-java/flexmark-ext-enumerated-reference/src/main/java/com/vladsch/flexmark/ext/enumerated/reference/EnumeratedReferenceVisitorExt.java
EnumeratedReferenceVisitorExt
VISIT_HANDLERS
class EnumeratedReferenceVisitorExt { public static <V extends EnumeratedReferenceVisitor> VisitHandler<?>[] VISIT_HANDLERS(V visitor) {<FILL_FUNCTION_BODY>} }
return new VisitHandler<?>[] { new VisitHandler<>(EnumeratedReferenceText.class, visitor::visit), new VisitHandler<>(EnumeratedReferenceLink.class, visitor::visit), new VisitHandler<>(EnumeratedReferenceBlock.class, visitor::visit), };
57
77
134
<no_super_class>