Skip to content

Commit

Permalink
feat: provide aliases for several rule tools (#925)
Browse files Browse the repository at this point in the history
  • Loading branch information
tangcent authored Feb 27, 2023
1 parent 002db5a commit c7be7b1
Show file tree
Hide file tree
Showing 7 changed files with 421 additions and 404 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,14 @@ import kotlin.reflect.*
import kotlin.reflect.full.allSuperclasses
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.functions
import kotlin.text.appendLine

/**
* <p>Util operations for rule.</p>
* For rules only.
* @see StandardJdkRuleParser
*/
@ScriptTypeName("tool")
class RuleToolUtils {
object RuleToolUtils {

//region any

Expand All @@ -46,12 +45,15 @@ class RuleToolUtils {
null -> {
null
}

is Array<*> -> {
any
}

is Collection<*> -> {
any.toTypedArray()
}

else -> {
arrayOf(any)
}
Expand All @@ -63,15 +65,19 @@ class RuleToolUtils {
null -> {
null
}

is Array<*> -> {
any.toMutableList()
}

is List<*> -> {
any
}

is Collection<*> -> {
any.toMutableList()
}

else -> {
listOf(any)
}
Expand Down Expand Up @@ -1032,43 +1038,37 @@ class RuleToolUtils {
ToolUtils.copy2Clipboard(str)
}

companion object {

val INSTANCE = RuleToolUtils()

private val excludedMethods = Arrays.asList(
"hashCode",
"toString",
"equals",
"getClass",
"clone",
"notify",
"notifyAll",
"wait",
"finalize"
)

private val TO_LINE_PATTERN = Pattern.compile("[A-Z]+")

private val typeMapper = KV.create<String, String>()
.set("java.lang.String", "string")
.set("java.lang.Long", "long")
.set("java.lang.Double", "double")
.set("java.lang.Short", "short")
.set("java.lang.Integer", "int")
.set("java.lang.Object", "object")
.set("kotlin.String", "string")
.set("kotlin.Array", "array")
.set("kotlin.Int", "int")
.set("kotlin.Unit", "void")
.set("kotlin.collections.List", "array")
.set("kotlin.Any", "object")
.set("kotlin.Boolean", "bool")
.set("kotlin.collections.Map", "map")
.set("kotlin.collections.Set", "array")
.set("kotlin.CharArray", "array<char>")
.set("kotlin.Function0", "func")
.set("kotlin.Function1", "func")

}
private val excludedMethods = listOf(
"hashCode",
"toString",
"equals",
"getClass",
"clone",
"notify",
"notifyAll",
"wait",
"finalize"
)

private val TO_LINE_PATTERN = Pattern.compile("[A-Z]+")

private val typeMapper = KV.create<String, String>()
.set("java.lang.String", "string")
.set("java.lang.Long", "long")
.set("java.lang.Double", "double")
.set("java.lang.Short", "short")
.set("java.lang.Integer", "int")
.set("java.lang.Object", "object")
.set("kotlin.String", "string")
.set("kotlin.Array", "array")
.set("kotlin.Int", "int")
.set("kotlin.Unit", "void")
.set("kotlin.collections.List", "array")
.set("kotlin.Any", "object")
.set("kotlin.Boolean", "bool")
.set("kotlin.collections.Map", "map")
.set("kotlin.collections.Set", "array")
.set("kotlin.CharArray", "array<char>")
.set("kotlin.Function0", "func")
.set("kotlin.Function1", "func")
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,18 @@ import com.itangcent.suv.http.HttpClientProvider
import com.itangcent.utils.TemplateKit
import java.nio.charset.Charset
import javax.script.*
import kotlin.collections.set

abstract class StandardJdkRuleParser : ScriptRuleParser() {

@Inject
private var httpClientProvider: HttpClientProvider? = null
private lateinit var httpClientProvider: HttpClientProvider

@Inject
protected val localStorage: LocalStorage? = null
protected lateinit var localStorage: LocalStorage

@Inject
protected val sessionStorage: SessionStorage? = null
protected lateinit var sessionStorage: SessionStorage

private var scriptEngine: ScriptEngine? = null

Expand All @@ -56,12 +57,12 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
synchronized(this) {
if (scriptEngine != null) return scriptEngine!!
scriptEngine = buildScriptEngine()
initScripEngine(scriptEngine!!)
}
if (scriptEngine == null) {
unsupported = true
throw UnsupportedScriptException(scriptType())
}
initScripEngine(scriptEngine!!)
return scriptEngine!!
}

Expand All @@ -72,14 +73,14 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
override fun initScriptContext(scriptContext: ScriptContext, context: RuleContext) {
val engineBindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE)
engineBindings.putAll(toolBindings)
engineBindings["logger"] = logger
engineBindings.set("logger", "LOG", logger!!)
engineBindings["localStorage"] = localStorage
engineBindings["session"] = sessionStorage
engineBindings["helper"] = Helper(context.getPsiContext())
engineBindings["httpClient"] = httpClientProvider!!.getHttpClient()
engineBindings["files"] = actionContext.instance(Files::class)
engineBindings["config"] = actionContext.instance(Config::class)
engineBindings["runtime"] = Runtime(context)
engineBindings.set("session", "S", sessionStorage)
engineBindings.set("helper", "H", Helper(context.getPsiContext()))
engineBindings["httpClient"] = httpClientProvider.getHttpClient()
engineBindings.set("files", "F", actionContext.instance(Files::class))
engineBindings.set("config", "C", actionContext.instance(Config::class))
engineBindings.set("runtime", "R", Runtime(context))
}

@Inject
Expand Down Expand Up @@ -183,7 +184,7 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
defaultFileName: String?,
onSaveSuccess: () -> Unit,
onSaveFailed: (String?) -> Unit,
onSaveCancel: () -> Unit
onSaveCancel: () -> Unit,
) {
saveWithUI(
content,
Expand All @@ -204,7 +205,7 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
defaultFileName: String?,
onSaveSuccess: () -> Unit,
onSaveFailed: (String?) -> Unit,
onSaveCancel: () -> Unit
onSaveCancel: () -> Unit,
) {
saveWithUI(
content,
Expand All @@ -226,7 +227,7 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
defaultFileName: String?,
onSaveSuccess: () -> Unit,
onSaveFailed: (String?) -> Unit,
onSaveCancel: () -> Unit
onSaveCancel: () -> Unit,
) {
fileSaveHelper!!.saveBytes(
{
Expand All @@ -246,15 +247,15 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {
fun save(
content: String,
charset: String,
path: String
path: String,
) {
save(content, Charsets.forName(charset)!!.charset(), path)
}

private fun save(
content: String,
charset: Charset,
path: String
path: String,
) {
FileUtils.forceSave(path, content.toByteArray(charset))
}
Expand Down Expand Up @@ -290,9 +291,14 @@ abstract class StandardJdkRuleParser : ScriptRuleParser() {

init {
val bindings: Bindings = SimpleBindings()
bindings["tool"] = RuleToolUtils.INSTANCE
bindings["regex"] = RegexUtils.INSTANCE
bindings.set("tool", "T", RuleToolUtils)
bindings.set("regex", "RE", RegexUtils)
toolBindings = bindings
}

fun Bindings.set(name: String, alias: String, value: Any) {
this[name] = value
this[alias] = value
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ class HttpSettingsHelper {
val HOST_RESOLVERS: Array<(String) -> String?> = arrayOf({
if (it.startsWith("https://raw.githubusercontent.com")) {
val url = if (it.endsWith("/")) it else "$it/"
return@arrayOf RegexUtils.INSTANCE.extract("https://raw.githubusercontent.com/(.*?)/.*",
return@arrayOf RegexUtils.extract("https://raw.githubusercontent.com/(.*?)/.*",
url, "https://raw.githubusercontent.com/$1")
}
return@arrayOf null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import java.util.regex.Pattern
* Refactoring from {@url https://github.com/aoju/bus/blob/master/bus-core/src/main/java/org/aoju/bus/core/utils/PatternUtils.java}
*/
@ScriptTypeName("regex")
class RegexUtils {
object RegexUtils {

private val cache = WeakHashMap<RegexWithFlag, Pattern>()
private val cacheLock = ReentrantReadWriteLock()
Expand Down Expand Up @@ -191,7 +191,12 @@ class RegexUtils {
return findAll(pattern, content, group, collection)
}

private fun <T : MutableCollection<String>> findAll(pattern: Pattern?, content: String?, group: Int, collection: T?): T? {
private fun <T : MutableCollection<String>> findAll(
pattern: Pattern?,
content: String?,
group: Int,
collection: T?,
): T? {
if (null == pattern || null == content) {
return null
}
Expand Down Expand Up @@ -293,17 +298,6 @@ class RegexUtils {
return value
}

companion object {

private const val GROUP_VAR_PATTERN = "\\$(\\d+)"
val GROUP_VAR = Pattern.compile(GROUP_VAR_PATTERN)!!

val REGEX_KEYWORD = setOf('$', '(', ')', '*', '+', '.',
'[', ']', '?', '\\', '^', '{', '}', '|')

val INSTANCE = RegexUtils()
}

private class RegexWithFlag(private val regex: String?, private val flag: Int) {

override fun hashCode(): Int {
Expand Down Expand Up @@ -335,5 +329,12 @@ class RegexUtils {
}

}


private const val GROUP_VAR_PATTERN = "\\$(\\d+)"
private val GROUP_VAR = Pattern.compile(GROUP_VAR_PATTERN)!!

private val REGEX_KEYWORD = setOf(
'$', '(', ')', '*', '+', '.',
'[', ']', '?', '\\', '^', '{', '}', '|'
)
}
Loading

0 comments on commit c7be7b1

Please sign in to comment.