【问题标题】:Groovy returns error when trying to split on newline尝试在换行符上拆分时,Groovy 返回错误
【发布时间】:2018-03-21 23:37:40
【问题描述】:

我是否尝试在换行符上拆分消息并使用以下脚本:

    def mesType = "";
def lines = message.getPayload().split("\n");

if ( lines[0][0..6] == '123456' ||  lines[1][0..6] == '123456') {
    mesType = "MES1";
}

if ( lines[0][0..7] == '654321' ||  lines[1][0..7] == '654321') {
    mesType = "MES2";
}

if ( lines[0][0..7] == '234561' ||  lines[1][0..7] == '234561') {
    mesType = "MES3";
}

message.setProperty('mesType', mesType);

return message.getPayload();

但是当我使用它时,我的日志文件中出现以下错误:

groovy.lang.MissingMethodException: No signature of method: [B.split() is applicable for argument types: (java.lang.String) values: {"\n"} (javax.script.ScriptException)

当我将分割线更改为以下内容时:

def lines = message.getPayload().toString().split("\n");

我收到一个错误,指出数组已超出界限,因此看起来它仍然没有对换行符执行任何操作。

传入的消息 (message.getPayload) 是来自文件系统的消息,并且包含换行符。它看起来像这样:

ABCDFERGDSFF
123456SDFDSFDSFDSF
JGHJGHFHFH

我做错了什么?使用 Mule 2.X 收集消息

【问题讨论】:

    标签: groovy mule


    【解决方案1】:

    看起来message.payload 返回一个byte[],您需要将其返回到一个字符串中:

    def lines = new String( message.payload, 'UTF-8' ).split( '\n' )
    

    应该得到它:-)

    另外,我更喜欢这样写:

    def mesType = new String( message.payload, 'US-ASCII' ).split( '\n' ).take( 2 ).with { lines ->
        switch( lines ) {
            case { it.any { line -> line.startsWith( '123456' ) } } : 'MES1' ; break
            case { it.any { line -> line.startsWith( '654321' ) } } : 'MES2' ; break
            case { it.any { line -> line.startsWith( '234561' ) } } : 'MES3' ; break
            default :
              ''
        }
    }
    

    而不是大量具有范围字符串访问的if...else 块(即:如果您得到一行只有 3 个字符的行,或者有效负载中只有 1 行,那么您的块将失败)

    使用 Groovy 1.5.6,您会遇到以下问题:

    def mesType = new String( message.payload, 'US-ASCII' ).split( '\n' )[ 0..1 ].with { lines ->
    

    请保持手指交叉,有效载荷中至少有 2 行

    或者你需要引入一个方法来从一个数组中获取最多 2 个元素

    你能试试吗:

    可能是 with 在 1.5.6 中中断(不确定)...尝试将其展开回原来的样子:

    def lines = new String( message.payload, 'US-ASCII' ).split( '\n' )[ 0..1 ]
    def mesType = 'empty'
    if(      lines.any { line -> line.startsWith( '123456' ) } ) mesType = 'MES1'
    else if( lines.any { line -> line.startsWith( '654321' ) } ) mesType = 'MES2'
    else if( lines.any { line -> line.startsWith( '234561' ) } ) mesType = 'MES3'
    

    【讨论】:

    • 编码是否必要?它不是 XML,而是以 UTF-8 以外的其他编码接收和编码的 ASCII 文件
    • 指定编码通常是个好习惯。试试US-ASCII
    • 当我使用您喜欢的解决方案时,它会说:[Ljava.lang.String;.take() is applicable for argument types: (java.lang.Integer) values: {2} (groovy.lang.MissingMethodException)
    • 啊……你用的是什么版本的 groovy? take 仅在 Groovy 1.8.1 中添加到数组中
    • 不知道。我们使用 Mule 2.X,知道其中包含哪个 Groovy 版本吗?
    【解决方案2】:
    def lines = "${message.getPayload()}".split('\n');
    

    这种方法也应该有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2014-12-22
      • 2020-07-25
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多