I hope some one can help me out here. I am trying to create an upload program that can upload one or more mp3 files and add their attributes to a database (song title, album, etc). I'm not sure if the problems I am encountering is because of a database issue or because I don't really understand how CommonsMultipartFile works. Anyway, here is my code"
View:
<g:form name="fileupload" url="[action:'uploads',controller:'fileResource']" method="POST" enctype="multipart/form-data">
<span>Add files...</span>
<input type="file" name="files" multiple>
</g:form>
fileResource:
def uploads = {
Collection result = []
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("files");
println"one"
moveFile(file)
println"three"
result << [name: file.originalFilename, size:file.size]
}
render result as JSON
}
private moveFile(CommonsMultipartFile file){
println"two"
try{
def userId = getUserId()
def newFileName = java.util.UUID.randomUUID().toString()
def userGuid = SecUser.get(userId.id).uid
def webRootDir = servletContext.getRealPath("/")
File myFile = new File( webRootDir + "/myUsers/${userGuid}/music",newFileName + ".")
file.transferTo(myFile)
MP3File mp3file = new MP3File(myFile);
String duration = mp3file.getAudioHeader().getTrackLength()
String bitRate = mp3file.getAudioHeader().getBitRate()
String encodingType = mp3file.getAudioHeader().getEncodingType()
String getFormat = mp3file.getAudioHeader().getFormat()
String trackLength = mp3file.getAudioHeader().getTrackLength()
String fileName = file.originalFilename
String artistName = ""
String albumName = ""
String songName = ""
def getArtistId=""
try{
if (mp3file.hasID3v2Tag()){
//println("has id3v2 tag")
ID3v24Tag id3v24tag = mp3file.getID3v2TagAsv24();
artistName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_ARTIST).trim())
albumName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_ALBUM).trim())
songName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_TITLE).trim())
}else if (mp3file.hasID3v1Tag()) {
//println("has id3v1 tag")
ID3v1Tag tag = mp3file.getID3v1Tag();
artistName = tag.getFirst(FieldKey.ARTIST).trim()
albumName = tag.getFirst(FieldKey.ALBUM).trim()
songName = tag.getFirst(FieldKey.TITLE).trim()
}
else{
println("this format not yet supported:" + getFormat)
}
}catch (Exception ex) {
log.error("ERROR: FILE NOT PROCESSED")
}
try{
def oArtist = ""
def c = Artist.createCriteria()
def getMyArtist = c.get {
eq('artistName', artistName )
secUser {
eq('id', userId.id)
}
}
if (getMyArtist == null){
//artist does not exist
// 1c. add artist
// 1d. add album
// 1e. add song
// 1f. move song
// 1g. DONE
oArtist= new com.jason.score.Artist(
artistName : artistName ,
secUser : userId.id
)
userId.addToArtist(oArtist).save(flush:true)
def oAlbum = new Album
(
albumName: albumName
)
oArtist.addToAlbum(oAlbum).save(flush:true)
def oSong = new Song
(
fileLocation: webRootDir + "myUsers/${userGuid}/music/",
songBitRate: bitRate,
songDuration: duration,
songEncodeType: encodingType,
songName: songName
)
oAlbum.addToSong(oSong).save(flush:true)
}else{
//artist exists with that username
//need album name and artist id
def d = Album.createCriteria()
def getMyAlbum = d.get {
eq('albumName', albumName )
artist {
eq('id', getMyArtist.id)
}
}
if(getMyAlbum == null){
// 3. add album
// 3a. add song
// 3b. move song
// 3c. DONE
Artist findArtist = Artist.get(getMyArtist.id)
def oAlbum = new Album
(
albumName: albumName
)
findArtist.addToAlbum(oAlbum).save(flush:true)
def oSong = new Song
(
fileLocation: webRootDir + "myUsers/${userGuid}/music/",
songBitRate: bitRate,
songDuration: duration,
songEncodeType: encodingType,
songName: songName
)
oAlbum.addToSong(oSong).save(flush:true)
}else{
//album does exist
//check if song exists with album id
def e = Song.createCriteria()
def getMySong = e.get {
eq('songName', songName )
album {
eq('id', getMyAlbum.id)
}
}
if (getMySong==null){
Album findAlbum = Album.get(getMyAlbum.id)
def oSong = new Song
(
fileLocation: webRootDir + "myUsers/${userGuid}/music/",
songBitRate: bitRate,
songDuration: duration,
songEncodeType: encodingType,
songName: songName
)
findAlbum.addToSong(oSong).save(flush:true)
}else{
//it already exists, so do nothing
}
}
}
}catch (Exception ex){
log.error("ERROR: ADDING TO DB: " + ex)
}
}catch (Exception ex){
log.error("error" + ex)
}
}
private getUserId(){
return SecUser.get(springSecurityService.principal.id)
}
private getUser(){
return SecUser.get(springSecurityService.principal)
}
The error I am getting is:
2012-01-02 14:25:25,314 [http-8080-1] ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.jason.score.SecUser#1]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1792)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2435)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2335)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2635)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:115)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168)
at org.codehaus.groovy.grails.orm.hibernate.events.PatchedDefaultFlushEventListener.performExecutions(PatchedDefaultFlushEventListener.java:46)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.springframework.orm.hibernate3.HibernateTemplate$28.doInHibernate(HibernateTemplate.java:883)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.flush(HibernateTemplate.java:881)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod$1.doInHibernate(SavePersistentMethod.java:58)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:339)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod.performSave(SavePersistentMethod.java:53)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod.doInvokeInternal(AbstractSavePersistentMethod.java:179)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod.invoke(AbstractDynamicPersistentMethod.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:188)
....
2012-01-02 14:25:25,379 [http-8080-1] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [POST] /com.jason.score/fileResource/uploads
Stacktrace follows:
org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [com.jason.score.SecUser] with identifier [1]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.jason.score.SecUser#1]
at java.lang.Thread.run(Thread.java:662)
Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.jason.score.SecUser#1]
... 1 more
The error is due to Hibernate. There is likely an error in your criteria queries. This looks like a likely candidate
oAlbum.addToSong(oSong).save(flush:true)
Those should be separate operations. The criteria queries should be encapsulated by methods in the service layer. For operations this simple, you probably won't see much benefit from using criteria over GORM's dynamic finders.
You're also trying to do way too much in one place. Refactor your controller to use a service to do these operations. Break moveFile() up into multiple methods to parse the MP3File, then pass that to another method to add it to the user's songs.
You shouldn't need to use the user's ID if you create the relationship directly in the domain.
Write some tests for each atomic piece and it should make the error easier to find.
Related
I am receiving NumberFormatException error in my Grails code which is to sort movies into a database. The error suggests it is from the cron plugin. I have done my research and I have been trying to catch the error by using NumberFormatException but to no avail. I think the problem lies in the IndexService. Any help would be much appreciated.
The exact error is:
2014-07-25 10:09:07,779 [quartzScheduler_Worker-1] ERROR listeners.ExceptionPrinterJobListener - Exception occurred in job: Grails Job
Message: java.lang.NumberFormatException: For input string: "N/A"
I am using:
Grails version: 2.4.2
Groovy version: 2.3.3
JVM version: 1.7.0_51
quartz - 1.0.2
My code:
IndexService
package movie
import groovy.io.FileType
import groovy.json.JsonSlurper
class IndexService {
static transactional = false
def grailsApplication
private cleanText(String title)
{
//split string into array via .,+,[,] etc...
def splitTitle=(title.toLowerCase()).tokenize('+.[]!£$%^+=~#:; \t \n \r \f / \\ { } # & - ( )')
//Get rid of extention
splitTitle.remove(splitTitle.size()-1)
//Get rid of Dvdrip and author
//unwanted phrases
def unwanted=["dvdrip","eng","www","torentz","3xforum","bugz","ro","maxspeed","xvid","720p","bluray","yify","1080p","hd","x264","RARBG","mp3","mp4","flv","brrip","rip"]
//Get rid of dates
//get 2000 to current date to put into the unwanted list
for(i in 2000..3000){unwanted.add(i.toString())}
//def empty string to put all our cleaned up text into
def cleanedText = ""
//cleaning up word mess...
splitTitle.each {word->
if(!unwanted.contains(word))
{
cleanedText=cleanedText+word+" "
}
}
//returning with +'s
return (cleanedText[0..-2]).replaceAll("\\s","+")
}
def getInfo(String title)
{
//returned nice with +
def cleanTitle=cleanText(title)
//define my reader
def scan = new JsonSlurper()
def scanner =scan.parseText(("http://www.omdbapi.com/?i=&plot=full&t="+cleanTitle).toURL().text)
if(scanner.Response=="True")
{
/*
organisied like this:
String artwork
String title
Date dateReleased
String userRated
String lengthOfFilm
String genre
String plot
float rating
*/ //returns our info we have scraped
return [
true,
scanner.Poster,
scanner.Title,
new Date(scanner.Released),
scanner.Rated,
scanner.Runtime,
scanner.Genre,
scanner.Plot,
scanner.imdbRating.toFloat()/10
]
}
else
{
return [null,cleanTitle]
}
}
def indexFiles()
{
//returns fileLocation
def fileLocation=grailsApplication.config.grails.movie.location
//Setup as file object
def dir = new File(fileLocation)
//recurse all files
dir.eachFileRecurse (FileType.FILES) { file ->
println(file)
//only create a record if no file test if record exists
if(!Record.findByPathToFile(file.getCanonicalPath())) {
//get record propreties set
def record = new Record()
record.pathToFile = file.getCanonicalPath()
//call to get data of a film returns as a list
def info = getInfo(file.getName())
//check if everthing is alright
info.each{print(it)}
if (info[0] == null) {
try {
//set fallback propeties
record.artwork = null
record.title = info[1].replaceAll("\\+"," ")
record.genre = null
record.dateReleased = new Date(file.lastModified())
record.lengthOfFilm = null
record.plot = null
record.rating = 0
record.userRated = null
record.save(failOnError: true)
}
catch (NumberFormatException e) {
//catch any errors
log.error("Error caught :${e} \n")
}
}
else
{
try
{
//set good propeties
record.artwork = info[1]
record.title = info[2]
record.genre = info[6]
record.dateReleased = info[3]
record.lengthOfFilm = info[5]
record.plot = info[7]
print(info[8])
record.rating = info[8]
record.userRated = info[4]
record.save(failOnError: true)
}
catch (NumberFormatException e) {
//catch any errors
info.each
{
print(it)
}
log.error("Error caught :${e} \n")
}
}
}
}
}
}
Record domain
package movie
class Record {
//static searchable = true
//data will be recieved via http://www.omdbapi.com/
String artwork
String title
Date dateReleased
String pathToFile
String userRated
String lengthOfFilm
String genre
String plot
float rating
static constraints = {
artwork nullable: true
title nullable: false, unique: true
dateReleased nullable: false
pathToFile nullable: false
userRated nullable: true
lengthOfFilm nullable: true
genre nullable: true
plot nullable: true, maxSize: 2000
rating nullable: true
}
}
And finally IndexJob
package movie
class IndexJob {
static triggers = {
/*
cronExpression: "s m h D M W Y"
| | | | | | `- Year [optional]
| | | | | `- Day of Week, 1-7 or SUN-SAT, ?
| | | | `- Month, 1-12 or JAN-DEC
| | | `- Day of Month, 1-31, ?
| | `- Hour, 0-23
| `- Minute, 0-59
`- Second, 0-59
*/
cron name: "indexTrigger", cronExpression: "0 0/1 * * * ? *"
}
def indexService
def execute() {
indexService.indexFiles()
}
}
Try this:
package movie
import groovy.io.FileType
import groovy.json.JsonSlurper
class IndexService {
static transactional = false
def grailsApplication
private cleanText(String title)
{
//split string into array via .,+,[,] etc...
def splitTitle=(title.toLowerCase()).tokenize('+.[]!£$%^+=~#:; \t \n \r \f / \\ { } # & - ( )')
//Get rid of extention
splitTitle.remove(splitTitle.size()-1)
//Get rid of Dvdrip and author
//unwanted phrases
def unwanted=["dvdrip","eng","www","r5","unique","torentz","3xforum","bugz","ro","maxspeed","xvid","720p","bluray","yify","1080p","hd","x264","RARBG","mp3","mp4","flv","brrip","rip"]
//Get rid of dates
//get 2000 to current date to put into the unwanted list
for(i in 2000..3000){unwanted.add(i.toString())}
//def empty string to put all our cleaned up text into
def cleanedText = ""
//cleaning up word mess...
splitTitle.each {word->
if(!unwanted.contains(word))
{
cleanedText=cleanedText+word+" "
}
}
//returning with +'s
return (cleanedText[0..-2]).replaceAll("\\s","+")
}
def getInfo(String title)
{
//returned nice with +
def cleanTitle=cleanText(title)
//define my reader
def scan = new JsonSlurper()
def scanner =scan.parseText(("http://www.omdbapi.com/?i=&plot=full&t="+cleanTitle).toURL().text)
if(scanner.Response=="True")
{
/*
organisied like this:
String artwork
String title
Date dateReleased
String userRated
String lengthOfFilm
String genre
String plot
float rating
*/ //returns our info we have scraped
def imdb = scanner.imdbRating
if (imdb.equalsIgnoreCase("n/a")) {
imdb = "0"
}
return [
true,
scanner.Poster,
scanner.Title,
new Date(scanner.Released),
scanner.Rated,
scanner.Runtime,
scanner.Genre,
scanner.Plot,
imdb.toFloat()/10
]
}
else
{
return [null,cleanTitle]
}
}
def indexFiles()
{
//returns fileLocation
def fileLocation=grailsApplication.config.grails.movie.location
//Setup as file object
def dir = new File(fileLocation)
//recurse all files
dir.eachFileRecurse (FileType.FILES) { file ->
//only create a record if no file test if record exists
if(Record.findByPathToFile(file.getCanonicalPath())==null) {
//get record propreties set
def record = new Record()
record.pathToFile = file.getCanonicalPath()
//call to get data of a film returns as a list
def info = getInfo(file.getName())
//check if everthing is alright
if (info[0] == null) {
try {
//set fallback propeties
record.artwork = null
record.title = info[1].replaceAll("\\+"," ")
record.genre = null
record.dateReleased = new Date(file.lastModified())
record.lengthOfFilm = null
record.plot = null
record.rating = 0
record.userRated = null
record.save(failOnError: true)
}
catch (Exception e) {
//catch any errors
//log.error("Error caught :${e} \n")
}
}
else
{
try
{
//set good propeties
record.artwork = info[1]
record.title = info[2]
record.genre = info[6]
record.dateReleased = info[3]
record.lengthOfFilm = info[5]
record.plot = info[7]
record.rating = info[8]
record.userRated = info[4]
record.save(failOnError: true)
}
catch (Exception e) {
catch any errors
log.error("Error caught :${e} \n")
}
}
}
}
}
}
It took me an hour to work that out!
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>
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} ... />
I am entering values(URLs) in the text box and when I click the next button, validation runs whether the entered url values are valid or not.
if the urls are not valid then i display the error as below
if(valid == false){
this.errors.reject("Incorrect URL is entered for "+countries.get(countryCode)+" - please ensure to use a correct URL for More Games.")
return [];
}
Once the error is shown, its clearing the entered values and need to enter the values again. How can I restrict clearing the values(i think the page is getting loaded again) or to restrict the page to load again.
here is the command -
class DeliveryMoreGamesURLCommand implements Command {
private static final LOG = LogFactory.getLog(DeliveryController.class)
def wrapperService = ApplicationHolder.application.getMainContext().getBean("wrapperService");
def customerService = ApplicationHolder.application.getMainContext().getBean("customerService");
def countryService = ApplicationHolder.application.getMainContext().getBean("countryService");
def helperService = ApplicationHolder.application.getMainContext().getBean("helperService");
def ascService = ApplicationHolder.application.getMainContext().getBean("ascService");
Hashtable<String, String> countries;
public LinkedHashMap<String, Object> preProcess(sessionObject, params, request) {
Delivery delivery = (Delivery) sessionObject;
def customer = Customer.get(delivery.customerId);
def contentProvider = ContentProvider.get(delivery.contentProviderId);
def deployment = Deployment.get(delivery.deploymentId);
def operatingSystem = OperatingSystem.get(delivery.operatingSystemId);
countries = wrapperService.getCountries(deployment, operatingSystem);
def sortedCountries = countries.sort { a, b -> a.value <=> b.value };
def urls = ascService.getMoreGamesUrlsPerTemplates(deployment, operatingSystem);
def moreGamesUrls = new Hashtable<String,String>();
countries.each { country ->
String countryCode = countryService.getTwoLetterCountryAbbreviation(country.key);
String url = customerService.getMoreGamesUrl(customer, contentProvider, countryCode);
if ("".equals(url)) {
url = urls.get(country.key);
if (url == null) {
url = "";
}
}
moreGamesUrls.put(country.key, url); // We need to use the existing country code if the channels are deployed with three letter country codes
}
return [command: this, countries: sortedCountries, moreGamesUrls: moreGamesUrls]
}
public LinkedHashMap<String, Object> postProcess(sessionObject, params, request) {
Delivery delivery = (Delivery) sessionObject;
def urls = params.gamesUrls;
LOG.debug("urls from gsp :"+urls)
try{
urls.eachWithIndex { u, i ->
String countryCode = u.key;
String url = urls["${u.key}"]
if(url != ""){
Boolean valid = helperService.isURLValid(url)
if(valid == false){
this.errors.reject("Incorrect URL is entered for "+countries.get(countryCode)+" - please ensure to use a correct URL for More Games.")
return [];
}
}
}
}catch (Exception ex) {
logger.warn("Incorrect URL is entered", ex)
return [];
}
def moreGamesUrls = new Hashtable<String, String>();
urls.eachWithIndex { u, i ->
String countryCode = u.key;
String url = urls["${u.key}"]
moreGamesUrls.put(countryCode, url);
}
delivery.countries = countries;
delivery.moreGamesUrls = moreGamesUrls;
LOG.debug("moreGamesUrls after edit=${delivery.moreGamesUrls}");
return null;
}
}
from the command preprocess the data will be rendered and after clicking the next button, the postprocess will be invoked and the validation for the url...
Resolved this issue by implementing moreGamesUrls as a global variable(which stored the values even after the error is thrown)
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¬e.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.