使用参数从Groovy调用方法 [英] invokeMethod from Groovy with parameters

查看:1477
本文介绍了使用参数从Groovy调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从下面的类中调用groovy方法

.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import com.ABC.csm.context.AppCtxProperties;

import com.ABC.csm.context.AppContext;


public class LicenseInfo
{
private StringBuffer licenseInformation;

public LicenseInfo(){
licenseInformation = new StringBuffer();
}

public StringBuffer getLicenseInformation(){
return licenseInformation;

$ b $ public void fetchLicenseInformation(HashMap< String,String> params,Map env)
{
ArrayList< String> licenseList = fetchLicenses(params);




}

private ArrayList< String> fetchLicenses(HashMap< String,String> params,Map env)
{

ArrayList< String> licenseList = new ArrayList< String>();



返回licenseList;





$ b $ p

所以这是我正在尝试做什么

  //获取用户参数
HashMap< String,String> params = IntermediateResults.get(userparams)

//获取环境变量
Map env = AppContext.get(AppCtxProperties.environmentVariables)

Object [] arguments = new Object [2]
arguments.putAt(userparams,params)
arguments.putAt(env,env)

GroovyShell shell = new GroovyShell()
脚本infa9LicenseScript = shell.parse(plugins.infa9.LicenseInfo)

infa9LicenseScript.invokeMethod(fetchLicenseInformation,arguments)
字符串lic =(String)infa9LicenseScript.invokeMethod(getLicenseInformation, null)

我将参数传递给 fetchLicenseInformation 正确?我需要传递 HashMap< String,String> ,Map 请帮我使用参数调用groovy方法

错误:线程main中的异常groovy.lang .MissingPropertyException:No such property:userparams for class:[Ljava.lang.Object;



更新

  public List< String> fetchLicenses(Map< String,String> params,Map env){
// ['a','b','c']
ArrayList< String> licenseList = new ArrayList< String> ;
字符串infacmdListLicensesCommand = null;
$ b $ if(System.getProperty(os.name)。contains(Win))
{infacmdListLicensesCommand = env.get(INFA_HOME)
+/
+ params.get(dn)+-un+ params.get(un)+-pd
+ params。 (pd)+-sdn+ params.get(sdn)+-hp
+ params.get(dh)+:+ params.get(dp );}
else
{infacmdListLicensesCommand = env.get(INFA_HOME)
+/isp/bin/infacmd.sh ListLicenses -dn//这是第71行,其中抛出异常
+ params.get(dn)+-un+ params.get(un)+-pd
+ params.get(pd)+ -sdn+ params.get(sdn)+-hp
+ params.get(dh)+:+ params.get(dp);}

try {
Process proc = Runtime.getRuntime()。exec(infacmdListLicensesCommand);

InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null; ((line = br.readLine())!= null){
System.out.println(line);
while
licenseList.add(line);
}
int exitVal = proc.waitFor();
System.out.println(Process exit value is:+ exitVal);

catch(IOException io){
io.printStackTrace();
} catch(InterruptedException ie){
ie.printStackTrace();
} / *结束catch * /
返回licenseList;
}

异常
线程main中的异常groovy.lang.MissingMethodException:方法没有签名:java.lang.String.positive()适用于参数类型:()values:[]
可能的解决方案:notify() ,org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
,org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unaryPlus(ScriptBytecodeAdapter。)中的tokenize(),size()
。 java:764)
infa9.LicenseInfo.fetchLicenses(Infa9LicensesUtil.groovy:71)

解决方案

正确...我在文件夹 ./ test / LicenseInfo.groovy b






$ public class LicenseInfo {
StringBuffer licenseInformation

public LicenseInfo(){
licenseInformation = new StringBuffer()
}

public void fetchL许可信息(Map< String,String> params,Map env){
List< String> licenseList = fetchLicenses(params,env)
printlnList is $ licenseList
}

public List< String> fetchLicenses(Map< String,String> params,Map env){
['a','b','c']
}
}
./ 里面创建了这个groovy脚本

> Test.groovy

  //创建一些参数... 
def params = [name:'tim',value:'text']

//伪造一个env Map
def env = [something:'whatever']

//从脚本加载类
def liClass = new GroovyClassLoader()。parseClass(new File('test / LicenseInfo.groovy'))

//运行方法
liClass.newInstance()。fetchLicenseInformation(params,env)

执行命令

  groovy Test.groovy 

打印出来:

 列表是[a,b,c] 



更新后编辑



正值你得到的错误是由于th通过Groovy解析器的工作方式......当连接字符串时, + 不能放在下一行的开头, + 必须在前一行中结尾(因为groovy中行的结尾是分号是可选的,所以解析器无法知道你正在添加到前一行)

这将起作用:

  if(System.getProperty(os.name)。包含(Win)){
infacmdListLicensesCommand = env.get(INFA_HOME)+/isp/bin/infacmd.bat ListLicenses -dn+
params.get(dn)+ -un+ params.get(un)+-pd+
params.get(pd)+-sdn+ params.get(sdn)+-hp +
params.get(dh)+:+ params.get(dp)
}
else {
infacmdListLicensesCommand = env.get(INFA_HOME )+/isp/bin/infacmd.sh ListLicenses -dn+
params.get(dn)+-un+ params.get( un)+-pd+
params.get(pd)+-sdn+ params.get(sdn)+-hp+
params.get( dh)+:+ params.get(dp)
}

这将是一个更为Groovy做同样事情的方式:

  boolean isWindows = System。 getProperty(os.name)。contains(Win)
//作为用于格式化目的的3个项目列表
infacmdListLicensesCommand = [
$ env.INFA_HOME / isp /bin/infacmd.${isWindows?'bat':'sh'} ListLicenses
-dn $ params.dn -un $ params.un -pd $ params.pd -sdn $ params.sdn
-hp $ params.dh:$ params.dp] .join('')//然后将它们连接在一起

println infacmdListLicensesCommand //打印出来看它是一样的如前


I want to invoke groovy method from the given below class

 package infa9

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import com.ABC.csm.context.AppCtxProperties;

import com.ABC.csm.context.AppContext;


 public class LicenseInfo
{
private StringBuffer licenseInformation;

public LicenseInfo() {
    licenseInformation = new StringBuffer();
}

public StringBuffer getLicenseInformation(){
    return licenseInformation;
}

public void fetchLicenseInformation(HashMap<String,String> params,Map env)
{
    ArrayList<String> licenseList = fetchLicenses(params);
    .
    .
    .

}

private ArrayList<String> fetchLicenses(HashMap<String,String> params,Map env)
{

    ArrayList<String>licenseList = new ArrayList<String>();
    .
    .
    .
return licenseList;

}

}

So this is what I am trying to do

//getting user parameters
HashMap<String,String> params = IntermediateResults.get("userparams")

//getting environment variables
Map env=AppContext.get(AppCtxProperties.environmentVariables)

Object[] arguments=new Object[2]
arguments.putAt("userparams", params)
arguments.putAt("env", env)

GroovyShell shell = new GroovyShell()
Script infa9LicenseScript = shell.parse("plugins.infa9.LicenseInfo")

   infa9LicenseScript.invokeMethod(fetchLicenseInformation, arguments)
   String lic=(String)infa9LicenseScript.invokeMethod(getLicenseInformation,null)

Am I passing the parameters to fetchLicenseInformation correctly?? I need to pass HashMap<String,String> ,Map Please help me invoke a groovy method with parameters

Error: Exception in thread "main" groovy.lang.MissingPropertyException: No such property: userparams for class: [Ljava.lang.Object;

Update

public List<String> fetchLicenses( Map<String,String> params, Map env ) {
//[ 'a', 'b', 'c' ]
  ArrayList<String>licenseList = new ArrayList<String>();
    String infacmdListLicensesCommand = null;

    if (System.getProperty("os.name").contains("Win"))
    {   infacmdListLicensesCommand = env.get("INFA_HOME")
                + "/isp/bin/infacmd.bat ListLicenses -dn "
                + params.get("dn") + " -un " + params.get("un") + " -pd "
                + params.get("pd") + " -sdn " + params.get("sdn") + " -hp "
                + params.get("dh") + ":" + params.get("dp");}
    else
    {   infacmdListLicensesCommand = env.get("INFA_HOME")
                + "/isp/bin/infacmd.sh ListLicenses -dn "  //this is line no 71, where exception is thrown
                + params.get("dn") + " -un " + params.get("un") + " -pd "
                + params.get("pd") + " -sdn " + params.get("sdn") + " -hp "
                + params.get("dh") + ":" + params.get("dp");}

    try {
        Process proc = Runtime.getRuntime().exec(infacmdListLicensesCommand);

        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            licenseList.add(line);
        }
        int exitVal = proc.waitFor();
        System.out.println("Process exit value is: " + exitVal);

    }catch (IOException io) {
        io.printStackTrace();
    }catch (InterruptedException ie) {
        ie.printStackTrace();
    } /* end catch */
return licenseList;
 }

Exception Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: [] Possible solutions: notify(), tokenize(), size() at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unaryPlus(ScriptBytecodeAdapter.java:764) at infa9.LicenseInfo.fetchLicenses(Infa9LicensesUtil.groovy:71)

解决方案

Right...I created this groovy script LicenseInfo.groovy inside a folder ./test/:

package test

public class LicenseInfo {
  StringBuffer licenseInformation

  public LicenseInfo() {
    licenseInformation = new StringBuffer()
  }

  public void fetchLicenseInformation( Map<String,String> params, Map env ) {
    List<String> licenseList = fetchLicenses( params, env )
    println "List is $licenseList"
  }

  public List<String> fetchLicenses( Map<String,String> params, Map env ) {
    [ 'a', 'b', 'c' ]
  }
}

inside the current folder ./, I created this groovy script Test.groovy:

// Make some params...
def params = [ name:'tim', value:'text' ]

// Fake an env Map
def env = [ something:'whatever' ]

// Load the class from the script
def liClass = new GroovyClassLoader().parseClass( new File( 'test/LicenseInfo.groovy' ) )

// Run the method
liClass.newInstance().fetchLicenseInformation( params, env )

When I execute the command

groovy Test.groovy

it prints out:

List is [a, b, c]

Edit after update

The positive errors you are getting are due to the way the Groovy parser works... You cannot put the + on the start of the next line when joining Strings, the + has to be trailing on the previous line (as semi-colons are optional for the end of lines in groovy, there is no way for the parser to know you are adding on to the previous line)

This will work:

if (System.getProperty("os.name").contains("Win")) {
  infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.bat ListLicenses -dn " +
                               params.get("dn") + " -un " + params.get("un") + " -pd " +
                               params.get("pd") + " -sdn " + params.get("sdn") + " -hp " +
                               params.get("dh") + ":" + params.get("dp")
}
else {
  infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.sh ListLicenses -dn " +
                               params.get("dn") + " -un " + params.get("un") + " -pd " +
                               params.get("pd") + " -sdn " + params.get("sdn") + " -hp " +
                               params.get("dh") + ":" + params.get("dp")
}

And this would be a more Groovy way of doing the same thing:

boolean isWindows = System.getProperty("os.name").contains("Win")
// Do it as a list of 3 items for formatting purposes
infacmdListLicensesCommand = [
  "$env.INFA_HOME/isp/bin/infacmd.${isWindows?'bat':'sh'} ListLicenses"
  "-dn $params.dn -un $params.un -pd $params.pd -sdn $params.sdn"
  "-hp $params.dh:$params.dp" ].join( ' ' ) // then join them back together

println infacmdListLicensesCommand // print it out to see it's the same as before

这篇关于使用参数从Groovy调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆