Skip to content

Instantly share code, notes, and snippets.

@tuhuynh27
Created September 2, 2021 22:48
Show Gist options
  • Save tuhuynh27/e70e2b517712cdbdbc1c6251df35409a to your computer and use it in GitHub Desktop.
Save tuhuynh27/e70e2b517712cdbdbc1c6251df35409a to your computer and use it in GitHub Desktop.
Validating JSONP callback function name in Java
package com.tuhuynh.tradebot;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.regex.Pattern;
public class Main {
private static final Map<String, Boolean> testMap = new HashMap<>();
public static void main(String[] args) {
testMap.put("hello", true);
testMap.put("alert()", false);
testMap.put("test()", false);
testMap.put("a-b", false);
testMap.put("23foo", false);
testMap.put("foo23", true);
testMap.put("$210", true);
testMap.put("_bar", true);
testMap.put("some_var", true);
testMap.put("$", true);
testMap.put("somevar", true);
testMap.put("function", false);
testMap.put(" somevar", false);
testMap.put("$.ajaxHandler", true);
testMap.put("$.23", false);
testMap.put("array_of_functions[42]", true);
testMap.put("array_of_functions[42][1]", true);
testMap.put("$.ajaxHandler[42][1].foo", true);
testMap.put("array_of_functions[42]foo[1]", false);
testMap.put("array_of_functions[]", false);
testMap.put("myFunction[123].false", false);
testMap.put("myFunction .tester", false);
testMap.put("_function", true);
testMap.put("petersCallback1412331422[12]", true);
testMap.put(":myFunction", false);
testMap.forEach((k, v) -> {
boolean result = JSONPValidator.validateCallbackFunctionName(k);
System.out.println("\"" + k + "\" " + (result == v ? "passed" : "failed") + " as " + (result ? "valid" : "invalid"));
});
}
public static class JSONPValidator {
private static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList("break", "do", "instanceof", "typeof", "case", "else", "new", "var", "catch", "finally",
"return", "void", "continue", "for", "switch", "while", "debugger", "function", "this",
"with", "default", "if", "throw", "delete", "in", "try", "class", "enum", "extends",
"super", "const", "export", "import", "implements", "let", "private", "public", "yield",
"interface", "package", "protected", "static", "null", "true", "false"));
private static final Pattern pattern = Pattern.compile("^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\\[(?:\"\".+\"\"|\\'.+\\'|\\d+)\\])*?$");
public static boolean validateCallbackFunctionName(String functionName) {
return Arrays.stream(functionName.split("\\."))
.allMatch(segment -> pattern.matcher(segment).matches() && !reservedWords.contains(segment));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment