grails/groovy braces syntax question - grails

I'm working with an example that I can't understand what the braces do -- the ones around the "Logout" in the second "out" statement below. I guess the string is passed as a closure but I'm not getting the syntax beyond that. Can you please clarify? Note the output of the code looks like the following:
John Doe [Logout]
class LoginTagLib {
def loginControl = {
if(request.getSession(false) && session.user){
out << "Hello ${session.user.login} "
out << """[${link(action:"logout",
controller:"user"){"Logout"}}]"""
} else {
out << """[${link(action:"login",
controller:"user"){"Login"}}]"""
}
}
}
Thanks Much

The link tag takes attributes and a body, and as a regular GSP tag it's called like this:
<g:link action="logout" controller="user">Logout</g:link>
To invoke it as a method like you're doing, you need a way to pass the text ('Logout') to render in the link. If you look at the source of the tag (click "Show Source" at the bottom of http://grails.org/doc/latest/ref/Tags/link.html) you'll see that the 2nd argument is body, and it's a Closure (although that's not clear from the code, but that's always the case for 2-parameter tags). {"Logout"} is a Closure that returns "Logout" since it's the last expression, so it's used as the body.

Actually the output should be
Hello John Doe [Logout]
Essentially, if there is a session and a user write Hello user and create a link pointing to a logout action with the label Logout.
{ "Logout" } is a closure equivalent to { return "Logout"; } as the last statement is used for a return value if none is explicitly stated.

I am not able to get the output like below
Hello John Doe [Logout]
Here is the output I am getting
Hello jdoe [Logout

Related

How to show String new lines on gsp grails file?

I've stored a string in the database. When I save and retrieve the string and the result I'm getting is as following:
This is my new object
Testing multiple lines
-- Test 1
-- Test 2
-- Test 3
That is what I get from a println command when I call the save and index methods.
But when I show it on screen. It's being shown like:
This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3
Already tried to show it like the following:
${adviceInstance.advice?.encodeAsHTML()}
But still the same thing.
Do I need to replace \n to or something like that? Is there any easier way to show it properly?
Common problems have a variety of solutions
1> could be you that you replace \n with <br>
so either in your controller/service or if you like in gsp:
${adviceInstance.advice?.replace('\n','<br>')}
2> display the content in a read-only textarea
<g:textArea name="something" readonly="true">
${adviceInstance.advice}
</g:textArea>
3> Use the <pre> tag
<pre>
${adviceInstance.advice}
</pre>
4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:
<div class="space">
</div>
//css code:
.space {
white-space:pre
}
Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:
Class Advice {
String advice
static constraints = {
advice(nullable:false, minSize:1, maxSize:255)
}
/*
* In this scenario with a a maxSize value, ensure you
* set your own setter to trim any hidden \r
* that may be posted back as part of the form request
* by end user. Trust me I got to know the hard way.
*/
void setAdvice(String adv) {
advice=adv.trim()
}
}
${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
This is how i solve the problem.
Firstly make sure the string contains \n to denote line break.
For example :
String test = "This is first line. \n This is second line";
Then in gsp page use:
${raw(test?.replace("\n", "<br>"))}
The output will be as:
This is first line.
This is second line.

Check if entered text is valid in Xtext

lets say we have some grammar like this.
Model:
greeting+=Greeting*;
Greeting:
'Hello' name=ID '!';
I would like to check whether the text written text in name is a valid text.
All the valid words are saved in an array.
Also the array should be filled with words from a given file.
So is it possible to check this at runtime and maybe also use this words as suggestions.
Thanks
For this purpose you can use a validator.
A simple video tutorial about it can be found here
In your case the function in the validator could look like this:
public static val INVALID_NAME = "greeting_InvalidName"
#Check
def nameIsValid(Greeting grt) {
val name = grt.getName() //or just grt.Name
val validNames = NewArrayList
//add all valid names to this list
if (!validNames.contains(name)) {
val errorMsg = "Name is not valid"
error(errorMsg, GreetingsPackage.eINSTANCE.Greeting_name, INVALID_NAME)
}
}
You might have to replace the "GreetingsPackage" if your DSL isn't named Greetings.
The static String passed to the error-method serves for identification of the error. This gets important when you want to implement Quickfixes which is the second thing you have asked for as they provide the possibility to give the programmer a few ideas how to actually fix this particular problem.
Because I don't have any experience with implementing quickfixes myself I can just give you this as a reference.

Prevent URL value from being cut off while passing to conrtroller

I think the issue is with the UrlMapping file or some configuration file that I don't know about but I didn't see it addressed in this site so I'm posting for help.
I have a UrlMappings.groovy with:
"/lookupMap/$fromVal/$toVal/xml/$id**" (controller:"lookup, action:"returnMapXml", formats=['xml'], method:"GET")
and the controller is:
def returnMapXml = {
if (params.id) {
print params.id + "\n";
try {
def result = getLookup.result(params.fromVal, params.toVal, params.id)
render ...yadda yadda
}
}
}
This is a REST service. My problem happens when someone enters an ID value with either a pound sign (#) or question mark (?), the value is truncated at that character. For example the output of ID (per the print line in the code) for this: localhost:8080/productdefinition/lookupMap/Denver/Toronto/carton OR container OR box? OR bag would be carton OR container OR box It removes the ? and everything after it. This happens somewhere either before it gets to the UrlMappings file or when that directs the call to the controller. Either way, how can I stop this and where, which file do I fix this in? I don't have access to the server so I can't alter any URL encodings; this has to be a code update. Any help/direction would be appreciated.

Grails: How do I print in the cmd console?

I wanna print a few values in the console, how do I do this?
Every time I get into a function, I want it to print a line with whatever text, I just wanna know if I'm getting into the function, and for some if-else statements.
Mostly for debugging.
If you mean "print to the console output panel", then you simply need to use println:
println "Hello, world"
Results in printed output:
groovy> println "Hello, world"
Hello, world
If that's not what you mean, can you clarify your question to be more specific?
you might want to consider grails built in logging functionality which provides the same functionality as println plus more
http://grails.github.io/grails-doc/3.0.x/guide/single.html#logging
in your app just say
log.info "Hello World"
to print something everytime you enter an action in a controller you can do something like this
class UserController {
def beforeInterceptor = {
log.info "Entering Action ${actionUri}"
}
def index = {
}
def listContributors = {
}
}
this will print out to the log whenever the controller methods are entered because of the controller interceptor
The regular java System.out.println("Your stuff"); works too.

Grails link taglib use outside of GSP

I'm trying to use the taglib call there's attribute parameters, but also the stuff inside the tag itself which the link taglib uses. I can't find the attribute to pass in to a g.link() call to have it render the text of the link. I've tried 'body' and 'link' and 'text' and 'linkText' already - none of those work.
I'm expecting to be able to call
g.link(action:"foo", controller:"bar", _____:"text of the link here")
but don't know what to put in _____
Usually you do it like this:
g.link(action:"foo", controller:"bar", "text of the link here")
The link text doesn't need to be the last parameter, it may appear anywhere:
g.link("text of the link here", action:"foo", controller:"bar")
.
Usage with closure:
Instead of the string you can use a closure which returns a string:
g.link(action:"foo", controller:"bar", {"text of the link here"})
And, as with any groovy closure which is the last parameter for a method call, you can put it after the closing parentheses:
g.link(action:"foo", controller:"bar") {"text of the link here"}
There is no parameter to pass in (for better or for worse).
To get the text in the link, you pass it as a closure.
g.link(action:"foo", controller:"bar") { "text of the link here" }
For the sake of completeness, since it's not mentioned in the docs: if you are calling the tags (as metod calls) inside your own taglib, you can use the closure to output any other content (using out <<) inside the outer tag. For example:
out << g.form(method: "post", controller: "login") {
out << "Name: " << g.textField(name: "name") << "<br>"
out << "Password: " << g.passwordField(name: "password") << "<br>"
out << g.submitButton(name: "login")
}

Resources