Grails redirect after uploadForm - grails

I am trying to redirect a page after a g:uploadForm has submitted.
my g:uploadForm action is save.
the save is as follows:
#Transactional
def save(DesignCategory designCategoryInstance) {
if (designCategoryInstance == null) {
notFound()
return
}
if (designCategoryInstance.hasErrors()) {
respond designCategoryInstance.errors, view: 'create'
return
}
def disotypeFile = request.getFile('disotype1')
if(!disotypeFile.empty){
print('here')
def fname = disotypeFile.getOriginalFilename()
def fileAtt = new FileAttachment()
fileAtt.originalFilename = fname
fileAtt.newFilename = "disotype-"
fileAtt.fileURI = '/Users/work/Desktop/files/' + fileAtt.newFilename
disotypeFile.transferTo(new File(fileAtt.fileURI))
response.sendError(200, 'Done')
fileAtt.save(flush: true)
designInstance.disotype = fileAtt;
}
designCategoryInstance.save flush: true, failOnError:true
flash.message = message(code: 'default.created.message', args: [message(code: 'designCategoryInstance.label', default: 'DesignCategory'), designCategoryInstance.id])
redirect designCategoryInstance
}
This gives the following error:
Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.. Stacktrace follows:
Message: Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.
This does work if i take out the
def disotypeFile = request.getFile('disotype1')
but obviously I cannot get the file.
any ideas?

Try to remove line:
response.sendError(200, 'Done')

Related

Want to Delete and Insert in same Action

I have one action in my controller that upload csv file with list of numbers.
Now the process is first I need to delete existing data from the table on certain condition then insert fresh data.
My snippet code is as follows..
Controller:
#Transactional
def uploadFile() {
if(!params?.updateExisting){
println "Going to call service to delete records"
myService.deleteNumbers()
def newList = Number.findAllByDeleted(false)
println "NEW LS:"+newList
//HERE I'm GETTING BLANK
}
def file = request.getFile("fileCsv")
file.inputStream
.splitEachLine(',') { fields ->
Number.withNewTransaction {
def number = fields[0]?.toString().replaceAll(" ","").replaceAll("-","")
Number numberInstance = new Number()
def numberExist = Number.findAllByNumberAndDeleted(number, false)
//HERE NUMBER IS STILL EXIST
if(!numberExist){
numberInstance.number = number
numberInstance.save(flush:true)
count++
}else{
println "Number exist: "+number
}
}
}
redirect(uri:'/number/list')
}
myService:
#Transactional
def deleteNumbers(){
Number.findAll().each {
it.deleted = true
it.save(flush: true)
}
}
After calling service method deleteNumbers I'm getting blank list NEW LS:[], But then def numberExist = Number.findAllByNumberAndDeleted(number, false) returns me a number means already exist.
Thanks..
Try removing Number.withNewTransaction closure. Your code should work..

Grails/SpringSecurity core and customizing logout behaviour

I'm using grails 2.3.7 with SpringSecurityCore 2.0 .. I have two separate signon screens tailored for specific devices with the appropriate one triggered by accessing a specific controller. To do this I customized the loginController ..
/**
* Show the login page.
*/
def auth() {
def config = SpringSecurityUtils.securityConfig
if (springSecurityService.isLoggedIn()) {
redirect uri: config.successHandler.defaultTargetUrl
return
}
String whereFrom = session.SPRING_SECURITY_SAVED_REQUEST.requestURI
def rdt = whereFrom.contains('RDT')
// Redirect for RDT as required ..
String view = rdt ? 'rauth' : 'auth'
String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
session.rdt = rdt
render view: view, model: [postUrl: postUrl,
rememberMeParameter: config.rememberMe.parameter]
}
which seems to work well .. On logout I want again to redirect to an appropriate screen .. I'm trying to use the session attribute I store on login along with a (admittedly old) link I found (http://grails.1312388.n4.nabble.com/Parameter-quot-logoutSuccessUrl-quot-in-spring-security-core-td2264147.html) to redirect back to an appropriate page ..
/**
* Index action. Redirects to the Spring security logout uri.
*/
def index() {
if (!request.post && SpringSecurityUtils.getSecurityConfig().logout.postOnly) {
response.sendError HttpServletResponse.SC_METHOD_NOT_ALLOWED // 405
return
}
// TODO put any pre-logout code here
def rdt = session.rdt
session.rdt = null
// redirect uri: "/j_spring_security_logout?spring-security-redirect=$logoutUrl"
if (rdt) {
def link = g.createLink(controller: "RDT")
def redirectUrl = "${SpringSecurityUtils.securityConfig.logout.filterProcessesUrl}?spring-security-redirect=${link}"
redirectStrategy.sendRedirect request, response, redirectUrl
} else {
redirectStrategy.sendRedirect request, response, SpringSecurityUtils.securityConfig.logout.filterProcessesUrl // '/j_spring_security_logout'
}
response.flushBuffer()
}
Both options return me to the 'default' auth login screen and not my alternate rauth one even with the addition of the extra parameter .. How can I route back to an appropriate screen ?? Thanks
In the end I manually set the session variables to null, invalidate the session and a standard redirect ... works ..

remoteFunction won't work without render

Here is a fragment of my javascript code:
${remoteFunction(controller: 'job', action: 'updateTimeStamp', update: 'randomString', params: '{timeStamp:timeStamp, sessionId:sessionId}')};
var jobIsDone = ${remoteFunction(controller: 'job', action: 'jobIsDone', params: '{sessionId:sessionId}')};
The first line works as expected, and the second one gives me 404 exception. jobIsDone() method doesn't render anything. I couldn't find proper explanation of remoteFunction tag, but as far as I understood it can be used without rendering, am I mistaken?
Here are the controller methods:
def updateTimeStamp(){
timeStampMap.putAt(params.sessionId, params.timeStamp)
def randomString = bcvjobService.saySomething()
render "<p>${randomString}</p>"
}
def jobIsDone(){
if (jobDone.get(params.sessionId)){
return true
}
else return false
}
Try with this:
def jobIsDone(){
if (jobDone.get(params.sessionId)){
response.sendError(200,"ok")
}
else {
response.sendError(500,"error")
}
}
This will prevent the 404 not found. If you want that come back a true or false with a JSON for example is:
def jobIsDone(){
def result = [error:true]
if (jobDone.get(params.sessionId)){
result.error = false
}
render result as JSON
}

Django 'the view page didn't return an HttpResponse object.'

I am a newbie for Django. I have had an error like title during making pages.
my system information is Django1.2, Ubuntu12.
There already has been same as my error on stackorverflow - http://goo.gl/bK5msW
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['eamil']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
return render_to_response('registration/register.html', variables)
Looking like some issue with indentation, this should work for you.
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
return render_to_response('registration/register.html', variables)

webflow in grails application

how can i redirect to the same state more than one time using web flow
ex:
on('submit'){
def destinationInstance = Destination.get(params.destination)
def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to('flowList')
what i need is how to enter to this state more than one time until destinations ends
thx
on('submit'){
def destinationInstance = Destination.get(params.destination)
def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to{
(condition or while loop or for loop)
if success then
return "<state name>"
else
return "flowList"
}
Reference:
http://livesnippets.cloudfoundry.com/docs/guide/2.%20Grails%20webflow%20plugin.html
Well, you'd probably have something like the following code, which is untested but may give you a general idea.
def destinationFlow = {
initialize {
action {
flow.destination = Destination.get(params.id)
}
on('success').to 'destinationList'
}
destinationList {
render(view: 'destinationList')
on('addDestination') {
def destinationGroup = DestinationGroup.get(params.destinationGroupId)
flow.destination.addToDestinationGroups(destinationGroup)
}.to 'destinationList'
on('finish').to 'done'
}
done {
flow.destination.save()
redirect(...) // out of the flow
}
}
You'll need buttons on your destinationList view that invoke the 'addDestination' or 'finish' actions. See the WebFlow documentation and Reference Guide.

Resources