Uploading an avatar to my profile in grails error - grails

I am new to grails and developing a web application such that a user updates profile details along with an avatar. I have a user controller that contains the logic to upload and save the avatar image. Unfortunately after choosing the avatar then upload, I get the this error which has troubled me for days:
No signature of method: eafya.User.current() is applicable for argument types: (grails.web.servlet.mvc.GrailsHttpSession) values: [Session Content: org.grails.FLASH_SCOPE = org.grails.web.servlet.GrailsFlashScope#d7b602 loggedOnUser = eafya.Patient : 1 messages = [] loginAudit = eafya.LoginAudit : 19 ] Possible solutions: count(), create(), ident(), collect(), insert(), collect(groovy.lang.Closure)
here is the controller:
package eafya
class UserController {
def current(){}
def select_avatar(){
}
def upload_avatar() {
def user = User.current(session) // or however you select the current user
// Get the avatar file from the multi-part request
def f = request.getFile('avatar')
// List of OK mime-types
def okcontents = ['image/png', 'image/jpeg', 'image/gif']
if (! okcontents.contains(f.getContentType())) {
flash.message = "Avatar must be one of: ${okcontents}"
render(view:'select_avatar', model:[user:user])
return;
}
// Save the image and mime type
user.avatar = f.getBytes()
user.avatarType = f.getContentType()
log.info("File uploaded: " + user.avatarType)
// Validation works, will check if the image is too big
if (!user.save()) {
render(view:'select_avatar', model:[user:user])
return;
}
flash.message = "Avatar (${user.avatarType}, ${user.avatar.size()} bytes) uploaded."
redirect(action:'show')
}
def avatar_image() {
def avatarUser = User.get(params.id)
if (!avatarUser || !avatarUser.avatar || !avatarUser.avatarType) {
response.sendError(404)
return;
}
response.setContentType(avatarUser.avatarType)
response.setContentLength(avatarUser.avatar.size())
OutputStream out = response.getOutputStream();
out.write(avatarUser.avatar);
out.close();
}
}

Related

How to save to a file system directory in Grails

I am trying to save an uploaded file into the file system directory, and allow other users to download it.
I am currently saving it in my database and not in my file system directory. Here is my code:
class Document {
String filename
byte[] filedata
Date uploadDate = new Date()
static constraints = {
filename(blank: false, nullable:false)
filedata(blank: true, nullable: true, maxSize:1073741824)
}
}
and my controller for uploading the file is:
class DocumentController {
static allowedMethods = [delete: "POST"]
def index = {
redirect(action: "list", params: params)
}
def list() {
params.max = 10
[documentInstanceList: Document.list(params), documentInstanceTotal: Document.count()]
}
def uploadPage() {
}
def upload() {
def file = request.getFile('file')
if(file.isEmpty())
{
flash.message = "File cannot be empty"
}
else
{
def documentInstance = new Document()
documentInstance.filename = file.getOriginalFilename()
documentInstance.filedata = file.getBytes()
documentInstance.save()
}
redirect (action: 'list')
}
}
I think you could do a fuction similar to the one below:
boolean upload(MultipartFile uploadFile, String fileUploadDir){
String uploadDir = !fileUploadDir.equals('') ?: 'C:/temp' //You define the path where the file will be saved
File newFile = new File("$uploadDir/${uploadFile.originalFilename}"); //You create the destination file
uploadFile.transferTo(newFile); //Transfer the data
/**You would need to create an independent Domain where to store the path of the file or have the path directly in your domain*/
}
Since you will only need to save the path of the file you could add a string to your domain to store it or you could create an independent domain to store the data of your file. You will also need to add try/catch statements where needed.
And to retrieve the file you would need to add to your controller something like the next code:
File downloadFile = new File(yourFileDomain?.pathProperty) //get the file using the data you saved in your domain
if(downloadFile){ //Set your response properties
response.characterEncoding = "UTF-8"
response.setHeader "Content-disposition", "attachment; filename=\"${yourFileDomain?.fileNameProperty}\"" //add the header with the filename you saved in your domain you could also set a default filename
//response.setHeader "Content-disposition", "attachment; filename=\"myfile.txt\""
response.outputStream << new FileInputStream(downloadFile)
response.outputStream.flush()
return
}
Hope this helps, any comments are welcome.

delete an existing file in grails

I am saving image files in my web folder. But at the time of saving or suppose a user want to change his picture than i want to delete the old picture and save the new one with the same file name. But I am failing after trying. Can anyone please help me on this please? Here is all my action below :
my save action >>>
def savePicture = {
String message = ""
def user = User.findById(1)
def userId = user.id
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("productPic");
def okcontents = ['image/png', 'image/jpeg', 'image/gif']
if (! okcontents.contains(f.getContentType())) {
message = "Avatar must be one of: ${okcontents}"
render(view:'uploadForm', model:[message: message])
return;
}
String type = f.getContentType().substring(6)
String baseImageName = java.util.UUID.randomUUID().toString();
baseImageName = "user${user.id}"
// Saving image in a folder assets/channelImage/, in the web-app, with the name: baseImageName
def downloadedFile = f //.getFile( "product.baseImage" )
String fileUploaded = fileUploadService.uploadFile( downloadedFile, "${baseImageName}.${type}", "assets/channelImage/" )
if( fileUploaded ){
user.avatarType = type
user.save()
message = "File Saved Successfully."
redirect(action: 'show', params: [userId: userId])
}
}
my service action where I am trying to delete before save >>>
def String uploadFile( MultipartFile file, String name, String destinationDirectory ) {
def serveletContext = ServletContextHolder.servletContext
def storagePath = serveletContext.getRealPath( destinationDirectory )
def storagePathDirectory = new File("${storagePath}/${name}").delete()
// Store file
if(!file.isEmpty()){
file.transferTo( new File("${storagePath}/${name}") )
println("Saved File: ${storagePath}/${name}")
return "${storagePath}/${name}"
}else{
println "File: ${file.inspect()} was empty"
return null
}
}
my show method in controller >>>
def show = {
Long uid = Long.parseLong(params.userId)
def avatarUser = User.get(uid)
String link = "user${avatarUser.id}.${avatarUser.avatarType}"
[link:link]
}
my view page >>>
<g:if test="${link}">
<img src="${resource(dir: 'assets/channelImage', file: "${link}")}" />
</g:if>

displaying errors in grails without refreshing the page

I have a page with dynamic list boxes(selecting value from the first list populates the values in the second list box).
The validation errors for the list boxes are working fine, but while displaying the error messages the page is getting refreshed and the selected values are been set to initial status(need to select the values again in the list boxes)
The page is designed to add any number of list boxes using ajax calls, so adding and selecting the values again is going to be a rework.
Could you help me in displaying the validation errors and keeping the selected values as they are(previously I faced a similar situation which was resolved by replacing local variables of preprocess and postprocess with a global variable, this time no luck with that approach)
Any hints/help would be great
static constraints = {
deviceMapping(
validator: {val, obj ->
Properties dm = (Properties) val;
def deviceCheck = [:];
if (obj.customErrorMessage == null) {
for (def device : dm) {
if (device.key == null || "null".equalsIgnoreCase(device.key)) {
return ["notSelected"];
}
deviceCheck.put(device.key, "");
}
if (deviceCheck.size() != obj.properties["numberOfDevices"]) {
return ["multipleDevicesError"];
}
}
}
)
customErrorMessage (
validator: {
if ("sameDeviceMultipleTimes".equals(it)) {
return ['sameDeviceMultipleTimes']
}
}
)
}
public LinkedHashMap<String, Object> preProcess(sessionObject, params, request) {
Submission submission = (Submission) sessionObject;
def selectedFileName = sessionObject.fileName;
logger.debug("submission.deviceMapping :"+submission.deviceMapping)
try {
Customer customer = Customer.get(submission.customerId);
OperatingSystem operatingSystem = OperatingSystem.get(submission.operatingSystemId)
def ftpClientService = new FtpClientService();
def files = ftpClientService.listFilesInZip(customer.ftpUser, customer.ftpPassword, customer.ftpHost, customer.ftpToPackageDirectory, selectedFileName, operatingSystem, customer.ftpCustomerTempDirectory);
def terminalService = new TerminalService();
OperatingSystem os = OperatingSystem.get(submission.getOperatingSystemId());
def manufacturers = terminalService.getAllDeviceManufacturersForType(os.getType());
logger.debug("manufacturers after os type :"+manufacturers)
logger.debug("files in preprocess :"+files)
def devicesForFiles = [:]
files.each { file ->
def devicesForThisFile = [];
submission.deviceMapping.each { device ->
if (device.value == file.fileName) {
String manufacturer = terminalService.getManufacturerFromDevice("${device.key}");
def devicesForManufacturer = terminalService.getDevicesForManufacturerAndType(manufacturer, os.getType());
devicesForThisFile.push([device:device.key, manufacturer: manufacturer, devicesForManufacturer: devicesForManufacturer]);
}
}
devicesForFiles.put(file.fileName,devicesForThisFile);
}
logger.debug("devicesForFiles :"+devicesForFiles)
return [command: this, devicesForFiles: devicesForFiles, files: files, manufacturers: manufacturers];
} catch (Exception e) {
logger.warn("FTP threw exception");
logger.error("Exception", e);
this.errors.reject("mapGameToDeviceCommand.ftp.connectionTimeOut","A temporary FTP error occurred");
return [command: this];
}
}
public LinkedHashMap<String, Object> postProcess(sessionObject, params, request) {
Submission submission = (Submission) sessionObject;
Properties devices = params.devices;
Properties files = params.files;
mapping = devices.inject( [:] ) { map, dev ->
// Get the first part of the version (up to the first dot)
def v = dev.key.split( /\./ )[ 0 ]
map << [ (dev.value): files[ v ] ]
}
deviceMapping = new Properties();
params.files.eachWithIndex { file, i ->
def device = devices["${file.key}"];
if (deviceMapping.containsKey("${device}")) {
this.errors.reject("You cannot use the same device more than once");
return [];
//customErrorMessage = "sameDeviceMultipleTimes";
}
deviceMapping.put("${device}", "${file.value}");
}
if (params.devices != null) {
this.numberOfDevices = params.devices.size(); //Used for the custom validator later on
} else {
this.numberOfDevices = 0;
}
//logger.debug("device mapping :"+deviceMapping);
submission.deviceMapping = mapping;
return [command: this, deviceMapping: mapping, devicesForFiles: devicesForFiles ];
}
}
The problem is in your gsp page. Be sure that all field are initialised with a value
<g:text value="${objectInstance.fieldname}" ... />
Also the way it is selecting values is through id, so be sure to set it as well:
<g:text value="${objectInstance.fieldname}" id=${device.manufacturer.id} ... />

Quartz Schedular in Grails

I have OperationLog class and I create 1000 records with the information which supplied by another class called Validator.
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
[operationLogInstanceList: OperationLog.list(params), operationLogInstanceTotal: OperationLog.count()]
}
def create = {
def operationLogInstance = new OperationLog()
operationLogInstance.properties = params
operationLogInstance.validator = Validator.get(params.validatorId)
operationLogInstance.operation = Operation.get(params.operationId)
return [operationLogInstance: operationLogInstance]
}
def save = {
int i = 0;
1000.times {
def operationLogInstance = new OperationLog(params)
operationLogInstance.validator = Validator.get((i));
operationLogInstance.save(flush: true)
i ++;
}
redirect(action: "list")
}
}
My question is this. How can I create these records one by one with the help of quartz scheduler and each should be saved in 5 minutes.
Note: I created a job (MyJob.groovy) already. I have my execute and triggers method all empty.
As far as I understand you, you get data from the user? And you want to save this data 1000 times, every 5 minutes one?
So you want to call a service to do this (the data as a parameter)?
So this could be done via Threads (anywhere, should also work in controllers...
Thread.start {
1000.times {
def operationLogInstance = new OperationLog(params)
println(params.validator)
operationLogInstance.validator = Validator.get(params.validator.id);
operationLogInstance.save(flush: true)
}
wait(300000)
}
May be there is a OperationLog.withSession { ... } necessary around it.
Alternatively you could feed a quatz job (using a service that save the logs you want to save...)looking like this:
class OperationLogJob {
static triggers = {
simple name:'Operation Save', startDelay:0, repeatInterval:300000
}
def sessionRequired = true
def concurrent = false
def operationsLogService
def execute() {
def operationLogInstance = operationsLogService.getLogsToSave()
if(operationLogInstance) {
operationLogInstance.validator = Validator.get(params.validator.id);
operationLogInstance.save(flush: true)
}
}
}
}
The operationsLogService.getLogsToSave() method returns (and deletes) a value from a stack that you can fill in the controller method (eg. 1000.times {operationsLogService.addLog(log) })

removeFrom* not working and with no errors

I have what I think is a simple problem but have been unable to solve...
For some reason I have a controller that uses removeFrom*.save() which throws no errors but does not do anything.
Running
Grails 1.2
Linux/Ubuntu
The following application is stripped down to reproduce the problem...
I have two domain objects via create-domain-class
- Job (which has many notes)
- Note (which belongs to Job)
I have 3 controllers via create-controller
- JobController (running scaffold)
- NoteController (running scaffold)
- JSONNoteController
JSONNoteController has one primary method deleteItem which aims to remove/delete a note.
It does the following
some request validation
removes the note from the job - jobInstance.removeFromNotes(noteInstance).save()
deletes the note - noteInstance.delete()
return a status and remaining data set as a json response.
When I run this request - I get no errors but it appears that jobInstance.removeFromNotes(noteInstance).save() does nothing and does not throw any exception etc.
How can I track down why??
I've attached a sample application that adds some data via BootStrap.groovy.
Just run it - you can view the data via the default scaffold views.
If you run linux, from a command line you can run the following
GET "http://localhost:8080/gespm/JSONNote/deleteItem?job.id=1&note.id=2"
You can run it over and over again and nothing different happens. You could also paste the URL into your webbrowser if you're running windows.
Please help - I'm stuck!!!
Code is here link text
Note Domain
package beachit
class Note
{
Date dateCreated
Date lastUpdated
String note
static belongsTo = Job
static constraints =
{
}
String toString()
{
return note
}
}
Job Domain
package beachit
class Job
{
Date dateCreated
Date lastUpdated
Date createDate
Date startDate
Date completionDate
List notes
static hasMany = [notes : Note]
static constraints =
{
}
String toString()
{
return createDate.toString() + " " + startDate.toString();
}
}
JSONNoteController
package beachit
import grails.converters.*
import java.text.*
class JSONNoteController
{
def test = { render "foobar test" }
def index = { redirect(action:listAll,params:params) }
// the delete, save and update actions only accept POST requests
//static allowedMethods = [delete:'POST', save:'POST', update:'POST']
def getListService =
{
def message
def status
def all = Note.list()
return all
}
def getListByJobService(jobId)
{
def message
def status
def jobInstance = Job.get(jobId)
def all
if(jobInstance)
{
all = jobInstance.notes
}
else
{
log.debug("getListByJobService job not found for jobId " + jobId)
}
return all
}
def listAll =
{
def message
def status
def listView
listView = getListService()
message = "Done"
status = 0
def response = ['message': message, 'status':status, 'list': listView]
render response as JSON
}
def deleteItem =
{
def jobInstance
def noteInstance
def message
def status
def jobId = 0
def noteId = 0
def instance
def listView
def response
try
{
jobId = Integer.parseInt(params.job?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in jobId " + params.job?.id)
log.debug(ex.getMessage())
}
if (jobId && jobId > 0 )
{
jobInstance = Job.get(jobId)
if(jobInstance)
{
if (jobInstance.notes)
{
try
{
noteId = Integer.parseInt(params.note?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in noteId " + params.note?.id)
log.debug(ex.getMessage())
}
log.debug("note id =" + params.note.id)
if (noteId && noteId > 0 )
{
noteInstance = Note.get(noteId)
if (noteInstance)
{
try
{
jobInstance.removeFromNotes(noteInstance).save()
noteInstance.delete()
message = "note ${noteId} deleted"
status = 0
}
catch(org.springframework.dao.DataIntegrityViolationException e)
{
message = "Note ${noteId} could not be deleted - references to it exist"
status = 1
}
/*
catch(Exception e)
{
message = "Some New Error!!!"
status = 10
}
*/
}
else
{
message = "Note not found with id ${noteId}"
status = 2
}
}
else
{
message = "Couldn't recognise Note id : ${params.note?.id}"
status = 3
}
}
else
{
message = "No Notes found for Job : ${jobId}"
status = 4
}
}
else
{
message = "Job not found with id ${jobId}"
status = 5
}
listView = getListByJobService(jobId)
} // if (jobId)
else
{
message = "Couldn't recognise Job id : ${params.job?.id}"
status = 6
}
response = ['message': message, 'status':status, 'list' : listView]
render response as JSON
} // deleteNote
}
I got it working... though I cannot explain why.
I replaced the following line in deleteItem
noteInstance = Note.get(noteId)
with the following
noteInstance = jobInstance.notes.find { it.id == noteId }
For some reason the jobInstance.removeFromNotes works with the object returned by that method instead of .get
What makes it stranger is that all other gorm functions (not sure about the dynamic ones actually) work against the noteInstance.get(noteId) method.
At least it's working though!!
See this thread: http://grails.1312388.n4.nabble.com/GORM-doesn-t-inject-hashCode-and-equals-td1370512.html
I would recommend using a base class for your domain objects like this:
abstract class BaseDomain {
#Override
boolean equals(o) {
if(this.is(o)) return true
if(o == null) return false
// hibernate creates dynamic subclasses, so
// checking o.class == class would fail most of the time
if(!o.getClass().isAssignableFrom(getClass()) &&
!getClass().isAssignableFrom(o.getClass())) return false
if(ident() != null) {
ident() == o.ident()
} else {
false
}
}
#Override
int hashCode() {
ident()?.hashCode() ?: 0
}
}
That way, any two objects with the same non-null database id will be considered equal.
I just had this same issue come up. The removeFrom function succeeded, the save succeeded but the physical record in the database wasn't deleted. Here's what worked for me:
class BasicProfile {
static hasMany = [
post:Post
]
}
class Post {
static belongsTo = [basicProfile:BasicProfile]
}
class BasicProfileController {
...
def someFunction
...
BasicProfile profile = BasicProfile.findByUser(user)
Post post = profile.post?.find{it.postType == command.postType && it.postStatus == command.postStatus}
if (post) {
profile.removeFromPost(post)
post.delete()
}
profile.save()
}
So it was the combination of the removeFrom, followed by a delete on the associated domain, and then a save on the domain object.

Resources