invokeMethod из Groovy с параметрами - PullRequest
1 голос
/ 27 сентября 2011

Я хочу вызвать метод groovy из приведенного ниже класса

 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;

}

}

Так вот, что я пытаюсь сделать

//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)

Передаю ли я параметры fetchLicenseInformationправильно??Мне нужно передать HashMap<String,String> ,Map Пожалуйста, помогите мне вызвать Groovy метод с параметрами

Ошибка: Exception in thread "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>();
    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 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)

1 Ответ

2 голосов
/ 27 сентября 2011

Правильно ... Я создал этот отличный скрипт LicenseInfo.groovy внутри папки ./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' ]
  }
}

внутри текущей папки ./, я создал этот отличный скрипт 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 )

Когда я выполняю команду

groovy Test.groovy

, она печатает:

List is [a, b, c]

Редактировать после обновления

Вы видите positive ошибкиполучение происходит из-за того, как работает анализатор Groovy ... Вы не можете поставить + в начале следующей строки при присоединении к строкам, + должен следовать за предыдущей строкой (так как точки с запятой не обязательны)для конца строк в groovy парсер не сможет узнать, что вы добавляете к предыдущей строке)

Это будет работать:

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")
}

И это будетбольше Groovy способ сделать то же самое:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...