Groovy is the preferred scripting in JMeter
We advise using Apache Groovy or any language that supports the Compilable interface of JSR223.
The following code in JSR233 Sampler works in Java but not in Groovy
String a= "0"+"1" +
"2"
+"3";
log.info(a);
I found the reasons for + operator not to work as expected,
but what is the solution is I want to concatenate several variables to a script?
I failed to use answer of using three quotes """The row Id is: ${row.id}..."""
Currently I use Java as script language and use JMeter ${variable} although is also not recommended:
In this case, ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}
String text ="...<id>${id}</id><id2>${id2}</id2>...";
What's a better approach in groovy in such case?
EDIT:
Try using << but different error where it split to new line
String text ="<id>" <<vars["id1"] << "<id><id2>"
<< vars["id2"] << "<id2>";
Receives an error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script12.groovy: 2: unexpected token: << # line 2, column 1.
<< vars["id2"] << "<id2>";
Groovy uses the new line character to indicate end of statement except in cases where it knows the next line must extend the current one. Numerous binary operators on the start of the next line are supported. The '+' and '-' operators have binary and unary variants and currently (Groovy versions at least up to 2.5.x) don't support those operators at the start of the next line. You can place the operator on the end of the previous line (as in your first line) or use the line continuation character at the end of the previous line:
String a = "0" + "1" +
"2" \
+ "3"
log.info(a)
Why don't you use :
String text ="<id>" <<vars["id1"] << "<id><id2>" << vars["id2"] << "<id2>";
It works for me
If I had a hashmap to concat like yours, I would try:
def vars = ["id": "value", "id2": "value2", "id3": "value3"]
String text = ""
vars.each { k, v ->
text += "<${k}>${v}</${k}>"
}
println text
Related
I'm trying to delete the beginning of a path that has '\' and ' ' in it. I seem to be getting the some issues saying escape character issue at character 3.
Example:
SomePath: C:\Users\ADMINISTRATOR\App Play\blah\blah
SomePath.replaceFirst('C:\\Users\\ADMINISTRATOR\\App Play\\', '');
Path should be blah\blah
I've tried:
SomePath.replaceFirst("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceFirst("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
SomePath.replaceAll("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceAll("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceAll("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
Just gave it a try... the examples with four backslashes work for me:
def somePath = "C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah"
println somePath
somePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
The problem is that the string needs one escaping \ and since the replaceFirst uses a regexp, the regexp-engine needs another \ to escape the \. The result are four backslashes.
Btw: you can use string operations to get your path, but you could also try file operations like this:
def root= new File("C:\\Users\\ADMINISTRATOR\\App Play\\")
def full= new File("C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah")
def relPath = root.toPath().relativize( full.toPath() ).toFile()
println relPath
(taken from https://gist.github.com/ysb33r/5804364)
You can tackle this problem differently. You could tokenize your input path using \ as a delimiter and then you could pick the last 2 elements (blah and blah) or skip first 4 elements (C:, Users, ADMINISTRATOR, App Play). It depends which assumption is easier to deduct for you. Consider following example:
def somePath = 'C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah'
// Build a new path by accepting the last 2 parts of the initial path
assert 'blah\\blah' == somePath.tokenize('\\')[-2..-1].join('\\')
// Build a new path by skipping the first 4 parts from initial path
assert 'blah\\blah' == somePath.tokenize('\\').drop(4).join('\\')
First option works better if you want only two last parts from the initial path. Second option works better if you can expect final path like blah\blah\blahhhh because you don't know how many nested children initial path contains and you want to start building a new path right after \App Play\ .
This is a Peter Norvig's repl function:
def repl(prompt='lis.py> '):
"A prompt-read-eval-print loop."
while True:
val = eval(parse(raw_input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
"Convert a Python object back into a Scheme-readable string."
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
Which works:
>>> repl()
lis.py> (define r 10)
lis.py> (* pi (* r r))
314.159265359
lis.py> (if (> (* 11 11) 120) (* 7 6) oops)
42
lis.py>
I'm trying to write program with the same functionality in Java, tried classes from Java docs, but nothing works like that; any idea? Thanks.
A REPL is called REPL because it is a Loop that Reads and Evaluates code and Prints the results. In Lisp, the code is literally:
(LOOP (PRINT (EVAL (READ))))
In an unstructured language, it would be something like:
#loop:
$code ← READ;
$res ← EVAL($code);
PRINT($res);
GOTO #loop;
That's where the name comes from.
In Java, it would be something like:
while (true) {
Code code = read(System.in);
Object res = eval(code);
System.out.println(res);
}
But, there are no methods corresponding to READ or EVAL in Java or the JRE. You will have to write read, eval, and Code yourself. Note that read is essentially a parser for Java, and eval is an interpreter for Java. Both the syntax and the semantics for Java are described in the Java Language Specification, all you have to do is read the JLS and implement those two methods.
The regular expression is
String regex = "^[\\p{IsHangul}\\p{IsDigit}]+";
And whenever i do
text.matches(regex);
It works fine in my system but not in some of the system.
I am not able to track the issue.
Thank you in advance.
Exception:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown character property name {Hangul} near index 13
^[\p{IsHangul}\p{IsDigit}]+
^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.charPropertyNodeFor(Pattern.java:2437)
at java.util.regex.Pattern.family(Pattern.java:2412)
at java.util.regex.Pattern.range(Pattern.java:2335)
at java.util.regex.Pattern.clazz(Pattern.java:2268)
at java.util.regex.Pattern.sequence(Pattern.java:1818)
at java.util.regex.Pattern.expr(Pattern.java:1752)
at java.util.regex.Pattern.compile(Pattern.java:1460)
at java.util.regex.Pattern.<init>(Pattern.java:1133)
at java.util.regex.Pattern.compile(Pattern.java:823)
at java.util.regex.Pattern.matches(Pattern.java:928)
at java.lang.String.matches(String.java:2090)
at com.mycompany.helper.ApplicationHelper.main(ApplicationHelper.java:200)
According to Using Regular Expressions in Java:
Java 5 fixes some bugs and adds support for Unicode blocks. ...
Make sure you're using Java 5+ in the server.
It seems that Java version you are using is not able to recognise Hangul as correct script character so you can try to create your own character class which will cover same range as Hongul from newer versions of Java.
From what I see in code in source code of Character.UnicodeScript on Java 8 Hangul refers to Unicode ranges
1100..11FF
302E..302F
3131..318F
3200..321F
3260..327E
A960..A97F
AC00..D7FB
FFA0..FFDF
so maybe try with such pattern
Pattern.compile("^["
+ "\u1100-\u11FF"
+ "\u302E-\u302F"
+ "\u3131-\u318F"
+ "\u3200-\u321F"
+ "\u3260-\u327E"
+ "\uA960-\uA97F"
+ "\uAC00-\uD7FB"
+ "\uFFA0-\uFFDF"
+ "\\p{IsDigit}]+");
I am trying to match a Java version in HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall by iterating over the subkeys within Uninstall. I am trying to match a regular expression to Java 7 Update 40, but the regex is matching all DisplayName entries. Below is the code:
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Dim oReg
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\default:StdRegProv")
Dim sPath, aSub, sKey
Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
objRegEx.Global = False
sPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, aSub
For Each sKey In aSub
disName = "HKLM" & "\" & sPath & "\" & sKey & "\DisplayName"
unString = "HKLM" & "\" & sPath & "\" & sKey & "\UninstallString"
reDisName = objShell.RegRead(disName)
reUnString = objShell.RegRead(unString)
'Wscript.echo(reDisName)
If objRexEx.Test( reDisName ) Then
Wscript.echo "Match"
End If
'Wscript.echo ObjShell.RegRead(disName)
'Wscript.echo ObjShell.RegRead(unString)
Next
Sorry if the formatting is off, I put a ctrl-k in front of each code line. This is my first time posting here so go easy...
You should start all your scripts with Option Explicit and Dim all your variables. Then you wouldn't need sln's eagle eyes to spot your typo:
Option Explicit
Dim objRegEx : Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
output:
cscript 19188400.vbs
...\19188400.vbs(4, 1) Microsoft VBScript runtime error: Variable is undefined: 'objRedEx'
If you insist on using a global On Error Resume Next (a most dangerous mal-practice) then you should disable it until your script is thoroughly debugged. Keeping the OERN in a script known to have even the slightest problem is inviting desaster. Asking for help with code containing a global OERN is futile. So run you program without the OERN and see if the cause for its misbehaviour in't obvious.
Diagnostic output should be as specific as possible. Your WScript.Echo "Match" just shows that the statement is executed; a WScript.Echo "Match", disname would be a bit better. Using .Execute and looking at the Match's details could be more revealing.
The .Pattern should be more specific to. If you look for java updates, anchoring a literal "java" at the start of the string, and asking for "upgrade" instead of "\w{6}" may help to avoid false positives. OTOH, my display names don't look like
Java 7 Update 19
but like
Java(TM) 6 Update 19
and who knows what the next owner of Java will put into the display name.
You seem to have a few typo's
objRedEx.IgnoreCase = True
...
If objRexEx.Test( reDisName ) Then
I know I can do it as follows:
String s = "Hello";
int maxLength = 10;
System.out.print(getSpaces((maxLength - s.length()) / 2) + s + getSpaces((maxLength - s.length()) / 2));
But I need to do it in a simple way. According to this page: Printf for Java Specification 3.0 (Section 9. flags):
I can center the text using ^ as a flag with printf() like this:
String s = "Hello";
int maxLength = 10;
System.out.printf("%^" + maxLength + "s", s);
But I got this error:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '^'
What is the correct way to use ^ flag with printf()?
The format String syntax, including information on specifiers and flags can be found here: java.util.Formatter.
I don't see use of ^ as a flag anywhere in this documentation.
I believe that your specification in the link above isn't for standard Java but rather for a 3rd party library called Lava3 Printf produced by SharkySoft. Please let us know if this is the library you are using, or if you're trying to do this coding with core Java.