grails - Grails NumberFormatException

标签 grails groovy cron

我在NumberFormatException代码中收到Grails错误,该错误是将电影分类到数据库中。该错误表明它来自cron插件。我已经完成了研究,并且一直在尝试使用NumberFormatException捕获错误,但无济于事。我认为问题出在IndexService。任何帮助将非常感激。

确切的错误是:

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" 

我在用:
Grails version: 2.4.2
Groovy version: 2.3.3
JVM version: 1.7.0_51
quartz - 1.0.2

我的代码:

索引服务
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")
                    }
                }
            }
        }
    }
}

记录域
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
    }
}

最后是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()

    }
}

最佳答案

试试这个:

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")
                    }
                }
            }
        }
    }
}

我花了一个小时才解决这个问题!

关于grails - Grails NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24959483/

相关文章:

javascript - MEAN 应用程序通过 API 调用在应用程序加载时使用 node-cron 设置 cron 作业

java - 运行战时出现 Grails 异常 : NoSuchMethodError

html - 将字符串转换为函数

grails - 更改 app.servlet.version 不会影响 web.xml

java - 使用 Gradle 和 Groovy/Spock 测试 Java 6 库或应用程序

java - 在本地 Maven 存储库中发布存档

unix - cron 命令每 12 小时运行一次

java - Spring SimpleTriggerContext 获取正确的 nextExecutionTime

grails - Grails 2.0.0 JUnit测试@RunWith注释等效

grails - grails 是否支持在 gsp 页面中使用 JSTL 核心 taglib 中的 "forEach"?