2014-12-10 61 views
3

Groovy in Action提供以下代碼,通過SecureASTCustomizer爲DSL提供安全性。在Groovy中實現DSL白名單

// @author: Groovy in Action 
import org.codehaus.groovy.control.* 
import org.codehaus.groovy.control.customizers.* 

def secure = new SecureASTCustomizer() 

secure.with { 
        closuresAllowed = false 
        methodDefinitionAllowed = false 
        importsWhitelist = [] 

        staticImportsWhitelist = [] 
        staticStarImportsWhitelist = ['java.lang.Math'] 

        tokensWhitelist = [ 
        PLUS, MINUS, MULTIPLY, DIVIDE, MOD, POWER, 
        PLUS_PLUS, MINUS_MINUS, 
        COMPARE_EQUAL, COMPARE_NOT_EQUAL, 
        COMPARE_LESS_THAN, COMPARE_LESS_THAN_EQUAL, 
        COMPARE_GREATER_THAN, COMPARE_GREATER_THAN_EQUAL, 
        ] 

        constantTypesClassesWhiteList = [ 
        Integer, Float, Long, Double, BigDecimal, 
        Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE 
        ] 

        receiversClassesWhiteList = [ 
        Math, Integer, Float, Double, Long, BigDecimal 
        ] 

        statementsWhitelist = [ 
        BlockStatement, ExpressionStatement 
        ] 

        expressionsWhitelist = [ 
        BinaryExpression, ConstantExpression, 
        MethodCallExpression, StaticMethodCallExpression, 
        ArgumentListExpression, PropertyExpression, 
        UnaryMinusExpression, UnaryPlusExpression, 
        PrefixExpression, PostfixExpression, 
        TernaryExpression, ElvisOperatorExpression, 
        BooleanExpression, ClassExpression 
        ] 
} 

def config = new CompilerConfiguration() 
config.addCompilationCustomizers(secure) 

def shell = new GroovyShell(config) 

x = shell.evaluate ''' 
    5 + 10 
    println("exiting...") 
    System.exit(0) 
''' 

println x 

但是,當我運行此代碼時,出現運行時錯誤。

如何修復錯誤以獲得工作示例 - 即執行數學運算的DSL,不允許任何其他類型的命令,如System.exit(0)

>groovy WhiteListSimple.groovy 
Caught: groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer 
groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer 
     at WhiteListSimple$_run_closure1.doCall(WhiteListSimple.groovy:14) 
     at WhiteListSimple.run(WhiteListSimple.groovy:6) 

回答

2

​​和朋友現在都在

import static org.codehaus.groovy.syntax.Types.* 

而且你還需要

import org.codehaus.groovy.ast.stmt.* // for the classes in `statementsWhitelist` 
import org.codehaus.groovy.ast.expr.* // for the classes in `expressionsWhitelist` 

考慮,這本書是2009年和你使用的是現在一個時髦範圍2.3,包或類的位置只是隨着時間的推移而變化,或者源代碼從來沒有工作過。

您可能想要考慮一個IDE,它可以幫助您找到課程/爲您創建import