i am trying to use cookie in grails 3.
i tried this plugin but i don't know why its not work at all..
cookieService.setCookie('username', customer?.email)
and i use this code for call it from gsp
<g:cookie name="username"/>
i also tried this way..
def cokusername = cookieService.setCookie('username', customer?.email)
println "cookieService.getCookie('username') = "+cookieService.getCookie('username')
redirect(controller: "toko",cokusername: cokusername)
and this is in my tokoController.groovy index :
def index={
def toko = CifLogo.executeQuery("from CifLogo order by rand()",[max: 10])
// def itemRandom = Item.executeQuery("from Item where cif = :cif order by rand()",[max:12,cif:cif])
def awdf = cookieService.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
[tokoList:toko,cokusername:awdf]
}
i have no idea to retrieve my cookie. :(
update
def index(){
def toko = CifLogo.executeQuery("from CifLogo order by rand()",[max: 10])
// def itemRandom = Item.executeQuery("from Item where cif = :cif order by rand()",[max:12,cif:cif])
def awdf = cookieService.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
[tokoList:toko,cokusername:awdf]
}
i tried to print cookie like this..
def awdf = request.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
request.cookies.each { println "${it.name} == ${it.value}" }
and this is what the result
From what I can see this line:
redirect(controller: "toko",cokusername: cokusername)
Should be:
redirect(controller: "toko",params:[cokusername: cokusername])
Also actions using closures in grails 3 will have undesired results. You should change to methods. Hence this line:
def index={
SHould be:
def index(){
Apart from this it seems the cookieService code should work fine, so I can only assume its being caused my the closure index that should be a method.
Another thing could be the fact that you are doing a redirect, which will clear the request and not persist any cookies that were set before the redirect
I don't know why, but maybe it's a bug.
i use this code to setCookie
cookieService.setCookie(name:"username", value: customer?.email, maxAge: 24*60*60, path: "/")
after read this code.
and i cannot deleteCookie with this code.
cookieService.deleteCookie(cookieService.findCookie("username"))
because when i print cookieService.findCookie("username") it returns javax.servlet.http.Cookie#78cbf320
and method deleteCookie(Cookie cookie) from this link
so i think it mustbe deleted.
but still availlable.
so i can answer this question about setCookie not deleteCookie
i also tried this way to delete cookie..but still failed.
CookieService.setCookie(name:"username", value: "", maxAge: 0, path: "/")
Related
I have a task where my Jenkins job needs two parameters for build. The first specifies the application name and can be either QA, Dev, Prod etc and the second is a server which is dependent on the first one.
Example: If I chose the app name as QA, the second parameter should display values like QAServer1, QAServer2, QAServer3.
I'm using Active Choices Plugin (https://wiki.jenkins.io/display/JENKINS/Active+Choices+Plugin) to get this done but facing an problem in fetching the second parameter contents.
Snapshots:
For obtaining the second parameter, I've written a Groovy code which reads the respective files of the selected first parameter and gets the details.
code:
#!/usr/bin/env groovy
import hudson.model.*
def Appliname = System.getenv("APPNAME")
//println Appliname
def list1 = []
def directoryName = "C:/Users/Dev/Desktop/JSONSTest"
def fileSubStr = Appliname
def filePattern = ~/${fileSubStr}/
def directory = new File(directoryName)
def findFilenameClosure =
{
if (filePattern.matcher(it.name).find())
{
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
String listAsString = "[\'${list1.join("', '")}\']"
println "return"+listAsString
}
}
directory.eachFileRecurse(findFilenameClosure)
The above code will print the output as return['QAServer1', 'QAServer2'] which i want to use it as input for the second parameter.
Snapshot of Second parameter:
Somehow the Groovy script is not being executed and second parameter value remains empty. How can i get this done dynamically. Am i following the right away to it. Kindly help me figure out. TIA
Would you like to try below change
From:
def findFilenameClosure =
{
if (filePattern.matcher(it.name).find())
{
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
String listAsString = "[\'${list1.join("', '")}\']"
println "return"+listAsString
}
}
directory.eachFileRecurse(findFilenameClosure)
To:
directory.eachFileRecurse {
if (filePattern.matcher(it.name).find()) {
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
}
}
return list1
I have a method:
def nameToCode(nameStr){
def ret = resortService.getResort("all")
//this gets like 180 objects with various properties like name, code, etc.
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findByName(nameStr) //this doesn't work
println(code)
return code
}
I'm trying to call this method and send it a name. It's then supposed to go find the name in the map, if it finds it it's supposed to return the name's code. This is supposed to be simple but I've been searching everywhere and can't figure out how to do this. I'll appreciate any help. Thanks
you are using a gorm method on a standard map:
Instead of :
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findByName(nameStr) //this doesn't work
Try:
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findAll{name==nameStr}
Now willing to do integration test as below but problem is that
MerchantTier.executeUpdate('update MerchantTier..........'),
here update does not working
but if I make update with
def merchant = MerchantTier.get(params.id.toLong())
merchant.setValue(merchantTierVal)
instead of execute update it works
Is there is any prolem with executeUpdate Query?
def merchantTier
def setup() {
merchantTier = new MerchantTier(
startTier: tier,
endTier: tier,
value: 2.02).save(flush: true)
}
void "for given merchantTierId update merchantTier"(){
setup:
params = [id:merchantTier.id,tierVal:2]
when:
testData = updateIndividualSuperResellerTier(params)
then:"return data"
merchantTier.value==params.tierVal
}
def updateIndividualSuperResellerTier(params) {
def merchantTierVal = 0
if (params.tierVal) {
merchantTierVal = params.tierVal.toDouble()
}
def merchantTier = MerchantTier.get(params.id.toLong())
def updateMerchantTier = MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: merchantTierVal, mtId: params.id.toLong()])
}
There seems to be no problem with executeUpdate, the problem here could be, that executeUpdate did not return an object, it just return the number of rows updated so updateMerchantTier doesnot contain updatedObject.
Also you should again fetch the object as it is updated by executeUpdate in your void "for given merchantTierId update merchantTier"() then: statement
then:"return data"
merchantTier.value==params.tierVal
here merchantTier is still an old object hence will not be having value equal to params.tierVal
in your other case you are using setter explicitly to set the property and hence it passed your Integration test.
def merchant = MerchantTier.get(params.id.toLong())
merchant.setValue(merchantTierVal)
hope this helps. Thanks
I have the following problem:
My object route contains a list of routepoints. When I alter this list, the changed list is saved. But when the next method accesses the list, it seems like the change reverted. I ruled some kind of transaction rollback out, b/c on the end of the altering method, i acces the list by loading it from the database and it still has the right (altered) size. Here's the code:
First the altering method:
def removeStationFromRoute(station){
def driver = Driver.get(Integer.valueOf(requestAccessService.getParams().userId))
def route = driver.routes.find{
it.routeDate == new Date().clearTime()
}
def rp = Routepoint.findByStation(station)
route.routepoints.remove(rp)
def newRoute = driver.routes.find{ it.routeDate == new Date().clearTime()}
println 'new route size: ' + newRoute.routepoints.size()
def newRoute2 = Route.get(route.id)
println 'new route from db size: ' + newRoute2.routepoints.size()
}
Both prints return a size of 5, which is correct. Right after this method is carried out, this method is executed:
def getDriverRoute(){
def driver = User.get(Long.valueOf(params.userId))
def route = driver.routes.find{ it.routeDate == new Date().clearTime()}
println 'serialized route size: ' + route.routepoints.size()
def routeString = jobService.serializeRoute(route)
log.info('Route with ' + route.routepoints.size() + " stations serialized for User " + driver.encodeAsHTML())
render routeString
}
Which prints a size of 6, as if no change happened to the list. I already tried saving the driver, the route and the routepoint after the change is made in the "removeStationFromRoute"-List, as well as checking the three objects for errors. Didn't help.
Thanks for any ideas what to do!
I guess you have a 1-N relationship between Route and Routepoints? Something like
class Route {
static hasMany = [routepoints: Routepoint]
}
class Routepoint {
static belongsTo = [route: Route]
}
You should not add/remove routpoints using the add/remove methods of the Collection interface. Instead you should use the addTo*/removeFrom* GORM methods, e.g.
route.addToRoutepoints(routepoint)
route.removeFromRoutepoints(routepoint)
Firstly,
After you have used route.removeFromRoutepoints(routepoint)
to remove the mapping of the Routepoint with Route in the first method, the Route Object Still needs to be persisted using .save/.merge method.(Check here )
Secondly.
In hibernate, using Domain.get(id) will not always hit the Database, IF the object already cached in the Hibernate session. Check here
Hope it helps...
My Grails code has a search function that redirects to another controller action after performing a findAllBy query:
def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [results: results])
findAllByBar returns an ArrayList with models, as expected, but after the redirect the receiving action gets a String array. Worse, when there is only one result it doesn't even get an array, it just gets a String.
Given that I have to iterate through the results in the receiving view, doing it on a string will meticulously print every letter individually. We can all agree that that's probably not the ideal behaviour.
A redirect results in a new GET request with the parameters in the querystring, e.g. /controller/result?foo=bar&baz=123 - you can't put objects there since it's just a string.
You could put the ids of the objects in the params and load them in the result action:
def action1 = {
def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [resultIds: results.id.join(',')])
}
def result = {
def resultIds = params.resultIds.split(',')*.toLong()
def results = Foo.getAll(resultIds)
}
or put them in Flash scope:
def action1 = {
flash.results = Foo.findAllByBar(baz)
redirect(action: "result")
}
def result = {
def results = flash.results
}
It sounds like you want to use the chain method instead of the redirect method. Chain lets you pass a model as a parameter similar to render.
An example would be:
chain(action:'result',model:[results:results])
Heres a link for further information:
http://www.grails.org/doc/latest/ref/Controllers/chain.html