How get first element of string array in jira velocity? - jira

I'm new in velocity and need help.
I have com.atlassian.jira.user.RemoteUser and remoteUser.getDisplayName() returns string which I want to split around matches of the given regular expression. And then get first element of String array, but unfortunately I have:
#set ($userName = $remoteUser.getDisplayName().split(" "))
$userName, Hello!
And have [Ljava.lang.String;#74a70acb as I can understand it is String array.
But if I try try get
#set ($userName = $remoteUser.getDisplayName().split(" ")[0])
$userName, Hello!
I have
org.apache.velocity.exception.ParseErrorException: Encountered "[" at getEncodedBodyFromContent[line 1, column 58] Was expecting one of:
<RPAREN> ...
<WHITESPACE> ...
"-" ...
"+" ...
"*" ...
"/" ...
"%" ...
<LOGICAL_AND> ...
<LOGICAL_OR> ...
<LOGICAL_LT> ...
<LOGICAL_LE> ...
<LOGICAL_GT> ...
<LOGICAL_GE> ...
<LOGICAL_EQUALS> ...
<LOGICAL_NOT_EQUALS> ...
<DOT> ...
If I try #set ($userName = $remoteUser.getDisplayName().split(" ")).get(0)) then I get null pointer exception

Velocity 1.6.4 is more than ten years old and doesn't support arrays.
Velocity 1.7 was released in November 2010 and does supports arrays.
Someone, somewhere, should upgrade something (FYI current version is Velocity 2.2 ...).

I don't know why but $string.split(" ") command doesn't work. After that I thought I had String array, but after $userName = $remoteUser.getDisplayName().split(" ").get($index) I had null pointer exception.
Solution which helped was using indexOf() and substring() commands like this:
#set ($userName = $remoteUser.getDisplayName())
#set ($index = $userName.indexOf(' '))
#set ($surname = $userName.substring(0, $index))
#set ($index = $index + 1)
#set ($name = $userName.substring($index))

Related

Checking if a String container any of a set of Symbols in Dart

I would like to check if a string contains any of the following symbols ^ $ * . [ ] { } ( ) ? - " ! # # % & / \ , > < ' : ; | _ ~ ` + =
I tried using the following
string.contains(RegExp(r'[^$*.[]{}()?-"!##%&/\,><:;_~`+=]'))
But that does not seem to do anything. I am also not able to add the ' symbol.
Questions:
How do I check if a string contains any one of a set of symbols?
How do I add the ' symbol in my regex collection?
When writing such a RegExp pattern, you should escape the special symbols (if you want to search specifically by them).
Also, to add the ' to the RegExp, there is no straightforward way, but you could use String concatenation to work around this.
This is what the final result could look like:
void main() {
final regExp = RegExp(
r'[\^$*.\[\]{}()?\-"!##%&/\,><:;_~`+=' // <-- Notice the escaped symbols
"'" // <-- ' is added to the expression
']'
);
final string1 = 'abc';
final string2 = 'abc[';
final string3 = "'";
print(string1.contains(regExp)); // false
print(string2.contains(regExp)); // true
print(string3.contains(regExp)); // true
}
To ad both ' an " to the same string literal, you can use a multiline (triple-quoted) string.
string.contains(RegExp(r'''[^$*.[\]{}()?\-"'!##%&/\\,><:;_~`+=]'''))
You also need to escape characters which have meaning inside a RegExp character class (], - and \ in particular).
Another approach is to create a set of character codes, and check if the string's characters are in that set:
var chars = r'''^$*.[]{}()?-"'!##%&/\,><:;_~`+=''';
var charSet = {...chars.codeUnits};
var containsSpecialChar = string.codeUnits.any(charSet.contains);

Groovy variable double substitution

I would like to perform double substitution.
When printing:
def y = "\${x}"
def x = "world"
def z = "Hello ${y}"
println z
It prints:
Hello ${x}
When I would like it to print Hello World, I tried performing a double evaluation ${${}}, casting it to org.codehaus.groovy.runtime.GStringImpl, and a desperate ${y.toStrin()}
Edit:
To be more clear I mean this, but in Groovy:
https://unix.stackexchange.com/questions/68042/double-and-triple-substitution-in-bash-and-zsh
https://unix.stackexchange.com/questions/68035/foo-and-zsh
(Why I am doing this?: Because we have some text files that we need evaluate with groovy variables; the variables are many and in different part of the code are different, therefore I would like to have a solution working across all cases, not to have to bind each time each variable, not adding many lines of code)
So with what you have you're escaping the $ so it is just interpreted as a string.
For what you are looking to do I would look into Groovys's templating engines:
http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html
After reading your comment I played around with a few ideas and came up with this contrived answer, which is also probably not quite what you are looking for:
import groovy.lang.GroovyShell
class test{
String x = "world"
String y = "\${x}"
void function(){
GroovyShell shell = new GroovyShell();
Closure c = shell.evaluate("""{->"Hello $y"}""")
c.delegate = this
c.resolveStrategry = Closure.DELEGATE_FIRST
String z = c.call()
println z
}
}
new test().function()
But it was the closest thing I could come up with, and may lead you to something...
If I understand right, you are reading y from somewhere else. So you want to evaluate y as a GString after y and then x have been loaded. groovy.util.Eval will do this for simple cases. In this case, you have just one binding variable: x.
def y = '${x}'
def x = 'world'
def script = "Hello ${y}"
def z = Eval.me('x', x, '"' + script + '".toString()') // create a new GString expression from the string value of "script" and evaluate it to interpolate the value of "x"
println z

Weird antlr grammar rule

I have found an old file that define antlr grammar rules like that:
rule_name[ ParamType *param ] > [ReturnType *retval]:
<<
$retval = NULL;
OtherType1 *new_var1 = NULL;
OtherType2 *new_var2 = NULL;
>>
subrule1[ param ] > [ $retval ]
| subrule2 > [new_var2]
<<
if( new_var2 == SOMETHING ){
$retval = something_related_to_new_var2;
}
else{
$retval = new_var2;
}
>>
{
somethingelse > [new_var_1]
<<
/* Do something with new_var_1 */
$retval = new_var_1;
>>
}
;
I'm not an Antlr expert and It's the first time that i see this kind of semantic for a rule definition.
Does anybody know where I can find documentation/informations about this?
Even a keyword for a google search is welcome.
Edit:
It should be ANTLR Version 1.33MR33.
Ok, I found! Here is the guide:
http://www.antlr2.org/book/pcctsbk.pdf
I quote the interesting part of the pdf that answer to my question.
1) Page 47:
poly > [float r]
: <<float f;>>
term>[$r] ( "\+" term>[f] <<$r += f;>> )*
;
Rule poly is defined to have a return value called $r via the "> [float r]" notation; this is similar to the output redirection character of UNIX shells. Setting the value of $r sets the return value of poly. he first action after the ":" is an init-action (because it is the first action of a rule or subrule). The init-action defines a local variable called f that will be used in the (...)* loop to hold the return value of the term.
2) Page 85:
A rule looks like:
rule : alternative1
| alternative2
...
| alternativen
;
where each alternative production is composed of a list of elements that can be references to rules, references to tokens, actions, predicates, and subrules. Argument and return value definitions looks like the following where there are n arguments and m return values:
rule[arg1,...,argn] > [retval1,...,retvalm] : ... ;
The syntax for using a rule mirrors its definition:
a : ... rule[arg1,...,argn] > [v1,...,vm] ...
;
Here, the various vi receive the return values from the rule rule, each vi must be an l-value.
3) Page 87:
Actions are of the form <<...>> and contain user-supplied C or C++ code that must be executed during the parse.

Lua String Split

Hi I've got this function in JavaScript:
function blur(data) {
var trimdata = trim(data);
var dataSplit = trimdata.split(" ");
var lastWord = dataSplit.pop();
var toBlur = dataSplit.join(" ");
}
What this does is it take's a string such as "Hello my name is bob" and will return
toBlur = "Hello my name is" and lastWord = "bob"
Is there a way i can re-write this in Lua?
You could use Lua's pattern matching facilities:
function blur(data) do
return string.match(data, "^(.*)[ ][^ ]*$")
end
How does the pattern work?
^ # start matching at the beginning of the string
( # open a capturing group ... what is matched inside will be returned
.* # as many arbitrary characters as possible
) # end of capturing group
[ ] # a single literal space (you could omit the square brackets, but I think
# they increase readability
[^ ] # match anything BUT literal spaces... as many as possible
$ # marks the end of the input string
So [ ][^ ]*$ has to match the last word and the preceding space. Therefore, (.*) will return everything in front of it.
For a more direct translation of your JavaScript, first note that there is no split function in Lua. There is table.concat though, which works like join. Since you have to do the splitting manually, you'll probably use a pattern again:
function blur(data) do
local words = {}
for m in string.gmatch("[^ ]+") do
words[#words+1] = m
end
words[#words] = nil -- pops the last word
return table.concat(words, " ")
end
gmatch does not give you a table right away, but an iterator over all matches instead. So you add them to your own temporary table, and call concat on that. words[#words+1] = ... is a Lua idiom to append an element to the end of an array.

Is is possible to have strings evaluate as variables in groovy?

I am playing with grails and groovy. I wondered if its possible to do something like this.
def inbuiltReqAttributes = ['actionName','actionUri','controllerName','controllerUri']
inbuiltReqAttributes.each() { print " ${it} = ? " };
what would i put in the ? to get groovy to evaluate the current iterator value as a variable e.g. to do it the long way
print " actionName = $actionName "
Thanks
I believe off the top of my head, this should work:
print " ${it} = ${this[ it ]}"
Or:
print " ${it} = ${getProperty( it )}"
But i'm not at a computer to 100% verify this atm...
Try this:
inbuiltReqAttributes.each() {
evaluate("value = ${it}")
print "$it = $value"
}

Resources