Groovy/Grails Contains with Lowercase - java

I want to check a list contains a specific string .
before checking all entries in list as well as sting should be in. lowercase
I tried like this
def venueName = params.name
def venueNameLists = Venue.executeQuery("select name from Venue")
if(venueNameLists.toLowerCase().contains(venueName.toLowerCase())){
error = true;
log.debug("save :: duplicate name")
flash.message = "Venue name already exist";
render(view: "create", model: [venueInstance: new Venue(params)])
return
}
gives error
No signature of method: java.util.ArrayList.toLowerCase() is applicable for argument types: () values: []. Stacktrace follows:
groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.toLowerCase() is applicable for argument types: () values: []

I agree with aiolos: use constraints or try to find instance by name ignore case. But to fix this your way try *. (spread operator):
venueNameLists*.toLowerCase().contains(venueName.toLowerCase())

If you would like to check a duplicate entry before saving an element, use constraints on your domain class. Here you could use unique constraint or implement your own if you need it case insensitive.
If you need to check it manually, try this:
def venueWithNameFromParams = Venue.findByNameIlike(params.name) // ignore case
if(venueWithNameFromParams){
// venueName is in venueNameList
}

If you were looking how to check if multiple strings contains a word, while ignoring case-sensitive, use (?i) on a regex of words.
For example, the following will be positive condition:
word = "YES"
word.matches(/(?i)yes|ok|true/)

Related

Spring Boot Spel expression concatenate variables and convert them to lower case?

Consider this method signature that I have
#Cacheable(
key="#name+'::'+#age+'::'+#country"
)
public User validate(String name, String age, String country) {
...
}
Notice the key that I have. Currently I am able to concatenate the name, age and country variables. But on top of concatenating them, I also want to convert the entire expression into a lowercase value.
For example if someone called this method like so: validate("John","24","USA"),
then I want my key to be resolved as: john::24::usa. Notice all the uppercase letters have become lowercase.
TLDR; how to write a spel expression which concatenates multiple variables and converts the entire result into lowercase?
Expression exp = new SpelExpressionParser()
.parseExpression("(#foo + '::' + #bar).toLowerCase()");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("foo", "XXX");
ctx.setVariable("bar", "YYY");
System.out.println(exp.getValue(ctx));
xxx::yyy

Groovy - ArrayList remove brackets

I've parsed the Below Json file and retrieve the username value.
"LogInFunctionTest": [
{
"TestCaseID": "Login-TC_02",
"TestScenario": "Negative Case - Login with unregistered username and Password",
"TestData": [
{
"UserName": "usernameX",
"Password": "passwordX"
}
]
Using the below code to retrieve the UserName Value.
def InputJSON = new JsonSlurper().parse(new File(fileName))
def testDataItem = InputJSON.LogInFunctionTest.find { it.TestCaseID == Login-TC_02 }.TestData.UserName
Output - [usernameX]
After this, I want to remove the brackets from the above.
'Remove brackets from arraylist'
testDataItem = testDataItem.substring(1, testDataItem.length() - 1)
I'm getting the below exception
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.length() is applicable for argument types: () values: []
Possible solutions: last(), last(), init(), init(), get(int), get(int)
Anyone guide us on how to remove the brackets from the output?
testDataItem is a list of UserNames as TestData contains a list
That's why when it's displayed to you, it has [] round it...
If you just want the first one in the list, then you can do:
def testDataItem = InputJSON
.LogInFunctionTest
.find { it.TestCaseID == 'Login-TC_02' }
.TestData
.UserName
.first()
(ie: put a call to first() at the end)
Obviously, if there's two of them, you'll only be getting the first one
You could also get the first one with .UserName[0], but .first() is more descriptive
testDataItem = testDataItem.get(0)
might do the job.
Looks like you're reading a list of Strings, not a String.
Technically you referred to 'TestData' as a List with the brackets above so proper reference should be:
TestData[0].UserName
... or since it's all contained in the 'LogInFunctionTest' List:
LogInFunctionTest[0].TestData[0].UserName
That is if you are not going to loop/iterate through them.

How to return a value from ANTLR action?

I'd like to know how:
return a runtime value from a rule action
access that value from the parent rule's action.
With ANTLR I want to build a custom tree using actions (not listeners/visitors which are too complex). And I'd like to have a parser implementation where each action knows about its children but not about its parent.
It is possible to access parent action's $variables but instead I'd like to access runtime values returned from children (and I don't know how).
For example with Ruby's treetop I can build a custom tree like below. Is this approach available for ANTLR too?
// sample input: "hello joe"
grammar Test
rule greeting
'hello' name {
// here `name.value` returns an instance of Name (below)
return new Greeting(name.value)
}
end
rule name
ID {
return new Name(ID.text)
}
end
It is possible to (pseudo) return a custom value from action via assigning a special field which can be accessed from outside then:
greeting returns [MyGreeting value] : 'hello' name
{
$value = new MyGreeting();
System.out.println("statement with name " + $name.value); // accessing
};
name returns [MyName value] : ID
{
$value = new MyName(); // assigning
System.out.println("name...");
};

Trying to get a unique version of a List of strings that is case insensitive

I have a list of strings, and I want to make a unique version of it in order to calculate a type token ratio. It needs to be case insensitive in order to function properly, and I'm unsure as to how I should approach it. This is in java, which I forgot to mention in the title. This is the java.util.List, not the java.awt.List.
Edit: I decided to talk more about the code. The class this is necessary for has an object called Case that has the original list.
Book Case = new Book(String x);
public float getTTRatio(){
//insert creation of unique list here.
}
The List is called words, and is to be filled with the words of a text file, so the call for the List I need to make unique is Case.words. I need to make it so that I can do this as the return value for the method, where unique is the name of the List that is filled with only the unique words and is case insensitive:
return unique.size/Case.words.size();
Since you only need the size you can do that with a Set of upper case words:
Set<String> unique = new HashSet<>();
for (String word : Case.words) {
// Adds only if the same uppercase String wasn't added before
unique.add(word.toUpperCase());
}
return (float) unique.size() / Case.words.size(); // convert one of the ints to float

Xtend/Xpand find and replace (rule)

Is it possible set a rule that will allow an Xpand method to output a specified string of text depending on the input. For example:
«FOR a:e.attributes»
Type = «a.eClass.name»
Value = «a.name.toFirstUpper»
«ENDFOR»
The above code may output:
Type = StringAttribute
Value = String1
Type = IntegerAttribute
Value = 123
How would I make this output:
Type = String
Value = String1
Type = int
Value = 123
I know this can be done with if statements but I would like to be able it to be more or less automatic. It would be a waste to have to specify such rules every time I need to output these details in the same file. Could someone show me what kind of code I could use to achieve this? Thank you.
I suggest that you create a reusable Xtend helper
toSimpleName(String inp):
switch (inp) {
case "StringAttribute" : "String"
case "IntegerAttribute" : "int"
// ...more cases here...
default : inp
}
;
and then call it from your Xpand template like this:
«FOR a:e.attributes»
Type = «a.eClass.name.toSimpleName()»
Value = «a.name.toFirstUpper»
«ENDFOR»

Categories

Resources