I am getting following error when i run groovy:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Users\kbekur\MuleStudio\workspace\GroovyTest\src\com\test\SQLGroovy.groovy: 3: unexpected token: # # line 3, column 2.
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2')
^
1 error
And my code is:
#Grapes([
#GrabConfig(systemClassLoader = true)
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2')
])
import groovy.sql.Sql
def db = [url:'jdbc:hsqldb:hsql://localhost/testdb', user:'sa', password:'', driver:'org.hsqldb.jdbc.JDBCDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
println 'Some GR8 projects:'
sql.eachRow('select * from Persons') { row ->
println "${row.lastname.padRight(10)} ($row.personid)"
}
After analysis, I have found that
You can't annotate a statement.
You should put the grab annotation on an import, for instance.
I am not clear with above statement, what changes I need to make to fix compilation issue and load the jars.
I am referring the code from: jars, system class loader
You need a comma between the two items in the #Grapes list, ie:
#Grapes([
#GrabConfig(systemClassLoader = true),
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2')
])
You can also remove the #Grapes part, to give just:
#GrabConfig(systemClassLoader = true)
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2')
(no comma is needed here, as they are no longer in a List)
Related
I am attempting to read xmls stored in one column of an Excel spreadsheet and fire them to a server using HTTP Sampler and then store the response xml in the same Excel.
This is the structure of my test plan in JMeter:
However I have encountered and error.
I am not able to pinpoint the exact place where the error is taking place but I have obtained the error message from the Results Tree are as follows:
for the JSR223 Sampler
Response message: javax.script.ScriptException: Sourced file: inline
evaluation of: import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.us . . . '' : Typed variable declaration :
Attempt to resolve method: parseInt() on undefined variable or class
name: INTEGER : at Line: 6 : in file: inline evaluation of:import
org.apache.poi.xssf.usermodel.XSSFWorkbook; import
org.apache.poi.xssf.us . . . '' : INTEGER .parseInt ( vars .get (
"counter" ) ) in inline evaluation of: ``import
org.apache.poi.xssf.usermodel.XSSFWorkbook; import
org.apache.poi.xssf.us . . . '' at line number 6
The error in the HTTP Request Sampler's Response Data tab reads as:
Exception occured: Parsing xml error, xml string is:${RQI}
BeanShell Assertion error is :
Assertion error: true Assertion failure: false Assertion failure
message: org.apache.jorphan.util.JMeterException: Error invoking bsh
method: eval In file: inline evaluation of: ``import
org.apache.poi.xssf.usermodel.XSSFWorkbook; import
org.apache.poi.xssf.us . . . '' Encountered ":" at line 6, column 65.
This is the code that I had used in the JSSR223 Sampler in the While Controller:
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import java.io.*;
int i = INTEGER.parseInt(vars.get("counter"));
XSSFRow row = vars.getObject("book").getSheetAt(0).getRow(i);
vars.putObject("row", row);
for (int j = 1; j <= vars.getObject("book").getSheetAt(0).getRow(0).getLastCellNum(); j++) {
if (row.getCell(j) == null) {
row.createCell(j).setCellValue("");
}
}
String payload = row.getCell(1).toString();
vars.put("RQI",payload);
//String password = row.getCell(2).toString();
// vars.put("password",password);
//String expectedResult = row.getCell(5).toString();
// vars.put("expectedResult",expectedResult);
Please assist. Also, feel free to ask for more information as I have left out the code for the other JSR223 Samplers in this post for brevity. Thank you in advance.
You must change this line:
INTEGER.parseInt(vars.get("counter"));
to this one
Integer.parseInt(vars.get("counter"));
check out Integer class JavaDoc - Integer.parseInt()
You should be using JSR223 Test Elements instead of Beanshell test elements and you should be using Groovy language in the JSR223 Test Elements
You might find How to Implement Data Driven Testing in your JMeter Test reference useful.
I'm getting an error as follows
Groovy script throws an exception of type class
java.util.regex.PatternSyntaxException with message =
Unexpected internal error near index 1
\
^
from the Split statement as follows:
String strClassPath = System.getProperty("java.class.path");
String[] path = strClassPath.split(System.getProperty("file.separator"));
How should I make this work correctly for both UNIX and Windows systems (that's why I'm using "file.separator")
Many thanks in advance
This calls java's split(String regexp). So your input must be a regexp (or must be quoted):
import java.util.regex.Pattern
def cp = {path, sep ->
path.split(Pattern.quote(sep))
}
assert cp('C:\\window\\something\\groovy.jar', '\\') == ['C:', 'window', 'something', 'groovy.jar']
assert cp('/usr/local/share/groovy.jar', '/') == ['', 'usr', 'local', 'share', 'groovy.jar']
So much for the regexp/split. If you are after the path, you might be better off using Path. e.g.
assert new File('/usr/local/share/groovy.jar').toPath().collect()*.toString() == ['usr', 'local', 'share', 'groovy.jar']
I am trying to parse an yaml file in Groovy. However I am facing issue while typecasting the result to Map object.
Here is my logic
import org.yaml.snakeyaml.Yaml
import java.util.Map
Reader reader = null
int tokenCount = 0
def Map map = null
StringTokenizer st = new java.util.StringTokenizer("Country.State.City", ".")
reader = new FileReader("filepath")
String val = null
Yaml yaml = new Yaml()
map = (Map) yaml.load(reader)
tokenCount = st.countTokens()
for (i=1; i < tokenCount; i++) {
String token = st.nextToken()
map = (Map) map.get(token)
}
val = map.get(st.nextToken()).toString()
However I am getting error at line:
map = (Map) map.get(token)
where it says:
"org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'some value' with class 'java.lang.String' to class 'java.util.Map' error at line: 15"..
Where I am going wrong?
your provided yaml file is syntactically incorrect. This is a fixed version:
location: C:\\Users\\amah11\\Desktop\\New folder
type: hi
Header:
Code:
Start: 0
End: 2
value: H00
Owner:
Start: 3
End: 5
value: AIM
User:
Start: 6
End: 8
Value: AIM
number: 1
Note that Code: **Static** in the original messes things up. And all the keys on the final level need a space after the : (e.g. Start:3 is wrong).
The actual error message is:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Static Start:0 End:2 value:H00' with class 'java.lang.String' to class 'java.util.Map'
which is rather clear in showing, that there is something wrong with the original file.
You might want to consider using an editor, that detects errors like this right away.
An alternative to the original code, would be the use of inject on the tokenizer:
def map = new Yaml().load(new FileReader("cardconfig.yml"))
println new StringTokenizer('Header.Code.End', '.').inject(map) { r, s -> r.get(s) }
BTW: you don't need to import java.util in groovy.
Using Scala Scripting Engine in 2.11 Milestone 7, how do I get a typed value back from the script engine? I'm getting error messages like "mypackage.Holler cannot be cast to mypackage.Holler".
Here is the use case (reduced to essentials). I want to use scripts to prepare and configure objects of a standard type that I will process in my main program. I have a trait:
package mypackage
trait Holler {
def shout: Unit
}
I have a user script in Scala, saved in the file /home/me/Foo.scala
object Foo extends mypackage.Holler {
def shout: Unit = println("Hello World!")
}
When I run this script using IMain.eval(Reader), I expect that the object Foo will be returned since it is the result of the last statement. Here is a program, including a couple useful printouts to run the script:
package mypackage
import javax.script.ScriptEngineManager
import scala.tools.nsc.interpreter.IMain
object Runner {
def main(args: Array[String]): Unit = {
// Create the script engine
val javaxEngine = new ScriptEngineManager().getEngineByName("scala")
val scalaEngine = javaEngine.asInstanceOf[IMain]
// Configure script engine to use the Java classpath
val useJavaClassPath = scalaEngine.settings.usejavacp.tryToSet(List("true"))
println("Use Java CP? " + useJavaClassPath)
val script = new java.io.FileReader("/home/me/Foo.scala")
val result = scalaEngine.eval(script)
println("Script Result Type: " + result.getClass.getName)
println("Defined Symbols: " + scalaEngine.definedSymbolList)
val myHoller = result.asInstanceOf[mypackage.Holler]
}
}
The script runs just fine under the script engine. But the result cannot be cast to Holler. The output of this program is as follows:
Use Java CP? Some(List(true))
Script Result Type: $line3.$read$$iw$$iw$Foo$
Defined Symbols: List(value engine, object iw$Foo)
Exception in thread "main" java.lang.ClassCastException: $line3.$read$$iw$$iw$Foo$ cannot be cast to mypackage.Holler
This tells me that the classpath is successfully recognized by the script engine, and that the Foo object is being constructed. But the trait mypackage.Holler (from the common classpath) inside the script is different from the trait mypackage.Holler in the main program.
If I add the following lines to the script:
Foo.shout
val result: Holler = Foo
I see:
The shout method being exercised ("Hello World!" prints out),
"result" is added to the list of defined symbols
result is clearly compatible with type Holler.
I can bind a "catcher" object to the script engine. Its code looks like this:
package mypackage
class Catcher {
var item: Holler = null
}
And I bind with
val mycatcher = new Catcher
scalaEngine.bind("catcher", mycatcher)
scalaEngine.eval("catcher = Foo")
Now "catcher" shows up in the list of defined symbols to the script engine and I can use the catcher to go into the script engine with a command like
scalaScriptEngine.eval("catcher.item = result")
But then I get strange "compile time" ClassCastExceptions saying:
mypackage.Holler cannot be cast to mypackage.Holler
If I make the "item" in the Catcher an Any, then I don't get the exception until I do
mycatcher.item.asInstanceOf[Holler]
in the main program. But I still get pretty much the same exception. It is as if two incompatible class loaders are being used with the same classpath. So how, from the main program, do I access the Foo object as an instance of Holler (which it clearly implements in the script engine)?
I am loading a class and doing some sql select statements, it seems that import groovy.sql.Sql needs to be imported. How can I load some library while loading a class?
My code (works fine if I remove Sql operations)
def fClass = new GroovyClassLoader().parseClass( new File( 'plugin/Pi.groovy' ) )
result=fClass.newInstance().buildTags( params, i9piparams, "userRoleCount")
pi.groovy
public class Pi{
def result
private def getDbUrl(dbdriver,dbhost,dbport,dbname)
{
return "$dbdriver:#$dbhost:$dbport:$dbname"
}
public def buildTags(Map<String,String> params,Map<String,String> i9piparams,def i9piType)
{
println params
println i9piparams
/*some Sql operation*/
Driver="oracle.jdbc.driver.OracleDriver"
dbdriver="jdbc:oracle:thin"
def url=getDbUrl(dbdriver,params.tns,i9piparams.dbport,i9piparams.dbname)
def sql = Sql.newInstance(url,params.u,params.x,Driver)
sql.eachRow("select name, value from v\$parameter where name = 'open_cursors'"){ row ->
result.name=row.name
result.value=row.value
}
}
}
Output
[pd:admin, u:zx5531d, tns:foner, dh:abds, dn:D35531, dp:11531, un:admin, x:cx15531]
[:, dbname:orcl, dbport:1521, dbtype:oracle]
Exception in thread "main" groovy.lang.GroovyRuntimeException: Could not find matching constructor for: groovy.sql.Sql(org.codehaus.groovy.runtime.GStringImpl, groovy.util.slurpersupport.Attributes, java.lang.String, java.lang.String)
.
.
.
Can you try changing your line:
def sql = Sql.newInstance(url,params.u,params.x,Driver)
to
def sql = Sql.newInstance( url, 'zx5531d', params.x, Driver )
What I suspect is that you need to call text() on the attributes when you read them from the XML, so that you get a String rather than a groovy.util.slurpersupport.Attributes class.
Also, why has Driver got a capital initial letter?
And (not sure what parameter is), but you probably want to change:
"select name, value from v\$parameter where name = 'open_cursors'"
to
"select name, value from v\${Sql.expand(parameter)} where name = 'open_cursors'"