Showing posts with label grails. Show all posts
Showing posts with label grails. Show all posts

Monday, September 24, 2018

Label not showing in Chart.js with Grails

Leave a Comment

I wish to pass data from a Grails controller to a chart.js chart in a Grails view. My code will not display the chart labels correctly. The issue is that labels (an arrayList of dates) is not being read correctly as an array of strings in Javascript which is causing Chart.js not to display.

Can anyone offer any help?

Any help would be gratefully received. Thanks in advance! My code is here:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script> <script>         var userResult = ${userResultMap as JSON};         var data = userResult.result;         var labels = userResult.dateCreated;       var config = {         type: 'line',         data: {             labels: testDate,             datasets: [{                 label: 'Clinical FRE',                 backgroundColor: '#7A564A',                 borderColor: '#7A564A',                 data: result,                 fill: false             }]         },         options: {             legend: {                 display: false             },             tooltips: {                 enabled: false             },             responsive: true,             scales: {                 yAxes: [{                     gridLines: {                         drawBorder: false,                         color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']                     },                     ticks: {                         min: 0,                         max: 100,                         stepSize: 10,                         callback: function (value) {                             return value + "%"                         }                     }                 }]             }         }     };  window.onload = function createChart(data) {     var ctx = document.getElementById('myChart').getContext('2d');     window.myLine = new Chart(ctx, config) };  </script> 

Data is sent from controller using ModelandView command:

@Secured('ROLE_USER') def home() {     try {         SecUser user = springSecurityService.currentUser         Participant p = Participant.findByUser(user)         Result userResults = Result.findByUser(user)         def userResultsList         def riskLevelMap         def iconClassMapList = []         def riskLevelMapList = []         def colourNameList = []         Map userResultMap = [:]          if (userResults!= null){             userResultsList = userResults.list()             if(userResultsList != null)             userResultsList.each {list->                 iconClassMapList.add(previousTestsService?.getIconType(list))                 riskLevelMap = riskAdviceService?.riskLevel(list.result)                 riskLevelMapList.add(riskLevelMapList)                 colourNameList.add(riskLevelMap?.colourName)             }               userResultMap.put("result",userResultsList?.result)                             userResultMap.put("dateCreated",userResultsList?.dateCreated)             println userResultMap             println userResultsList.dateCreated             println(userResultsList.dateCreated.getClass())          }          return new ModelAndView('home', [user: user, participant: p, username: user.username,userResultsList: userResultsList,iconClassMapList:iconClassMapList,colourNameList:colourNameList,userResultMap:userResultMap])      } catch (Exception ex) {         log.error(ex.printStackTrace())     } } 

Sample data: data - [13.7] labels - [2018-09-17 16:39:00.0]

4 Answers

Answers 1

You would need to convert your array, object whatever you are using to JSON for JavaScript to understand it.

<g:javascript>         var testDate = ${userResultsList.dateCreated}         var result = ${userResultsList.result as JSON}    // make sure grails.converters.JSON is imported </g:javascript> 

Answers 2

Make sure userResultsList(userListMap) data must be in the form below from the controller.

    Map userResultMap = [:]     List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]     List result = [50, 56, 23, 42]     userResultMap.put("dateCreated",dateCreated)     userResultMap.put("result",result) 

Then you need to parse the userResultMap data as JSON if not parsed and do similar like this in gsp page:

<script>     var userResult = ${userResultMap as JSON};     var result = userResult.result;     var labels = userResult.dateCreated; </script> 

Answers 3

The main issue here is that grails automatically escapes values as HTML upon insertion in the GSP page. You can suppress this by adding the advice

<%@ expressionCodec="none" %> 

at the beginning of the GSP page.

Be aware that your application will be less secure after the change. Especially if the data can contain user-created input people might start messing with your application.

Here is a running example using Grails 3.3.8 based on the test data supplied by @Kumar Chapagain, thank you very much.

In the controller you don't need to package the data in a ModelAndView, as this is done automatically by Grails. Just return a map with the needed entries. I prefer to convert the map to JSON within the controller and not in the gsp page as it keeps the control where it belongs and the GSP more simple.

Controller:

package g338  import grails.converters.JSON  class ChartController {      def index() {          Map userResultMap = [:]         List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]         List result = [50, 56, 23, 42]         userResultMap.put("dateCreated",dateCreated)         userResultMap.put("result",result)          [ userResultMap: userResultMap as JSON ]     } } 

gsp page: views/chart/index.gsp

<%@ expressionCodec="none" %> <!doctype html> <html> <head>     <meta name="layout" content="main"/>     <title>Welcome to Grails</title> </head> <body>     <canvas id="myChart"></canvas>     <g:javascript>     var result = ${userResultMap};     var data = result.result;     var labels = result.dateCreated;      var config = {         type: 'line',         data: {             labels: labels,             datasets: [{                 label: 'Clinical FRE',                 backgroundColor: '#7A564A',                 borderColor: '#7A564A',                 data: result,                 fill: false             }]         },         options: {             legend: {                 display: false             },             tooltips: {                 enabled: false             },             responsive: true,             scales: {                 yAxes: [{                     gridLines: {                         drawBorder: false,                         color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']                     },                     ticks: {                         min: 0,                         max: 100,                         stepSize: 10,                         callback: function (value) {                             return value + "%"                         }                     }                 }]             }         }     };      window.onload = function createChart(data) {         var ctx = document.getElementById('myChart').getContext('2d');         window.myLine = new Chart(ctx, config)     };      </g:javascript>  </body> </html> 

Answers 4

var labels = userResult.dateCreated;       var config = {         type: 'line',         data: {             labels: testDate, 

you are using labels: testDate, but assigning labels to labels try

var testDate = userResult.dateCreated; **labels: testDate** 
Read More

Tuesday, June 12, 2018

Make Postman test - Grails

Leave a Comment

I have the following test of a grails integration:

def http = new HTTPBuilder(loginUrl) http.request( POST, TEXT ) {     headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'     send URLENC, [j_username: username, j_password: password]      response.success = { resp, reader ->         loggedIn = ! reader.text.contains("j_username")     } } 

I'm trying to mount the test in Postman, but I'm not sure if I'm doing it correctly because of this send URLENC, [j_username: username, j_password: password]

I put the POST type route, and put something like:

{     j_username: username,     j_password: password } 

And the headers parameters:

'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4' 'Content-type' = 'Application/json' 

But it is always returning my login form in the body, does anyone know how to mount this test?

UPDATE

Actually in other projects I follow the reference and it works well. However I have developed the grails response part, did not leave an api/login route, and I believe that the login is done by the same web route /login/auth, but I can not validate the test by postman, but on the web logo perfectly.

UPDATE 2

I believe that in the project that receives my login request, to try to facilitate, they have made access to the api by the same web, and this request that is mounted in the integration, do not make a json type request, because of "send URLENC", Can someone please explain to me how to put this call in postman?

1 Answers

Answers 1

If you have the default Spring Security and Spring Security REST config, here how I do it :

Body of the Postman call

Header of the Postman call

Read More

Thursday, May 4, 2017

Grails 3 accessing node_modules

Leave a Comment

Starting on a Grails 3 app and trying to use a node plugin. My custom javascript is located under grails-app/assets/javascripts but when I run gradle build it installs the node_modules folder under my root project directory. This folder has all my JS libraries and I'm unable to access them from my within grails-app/assets/javascripts.

Is there a way to install node_modules under grails-app? Do I need to specify the directory in my build.gradle?

Here's my node and grunt plugins in my build.gradle.

classpath "com.moowork.gradle:gradle-node-plugin:0.12" classpath "com.moowork.gradle:gradle-grunt-plugin:0.12"

apply plugin:"com.moowork.node" apply plugin:"com.moowork.grunt"

1 Answers

Answers 1

You can change the location of the node_modules folder.

First, upgrade the node and grunt plugins to version 0.13

classpath "com.moowork.gradle:gradle-node-plugin:0.13" classpath "com.moowork.gradle:gradle-grunt-plugin:0.13" 

Second, add the following to your build.gradle file:

node { nodeModulesDir = file("grails-app") } 

This will create the node_modules folder under grails-app (i.e. grails-app/node_modules)

Read More

Monday, April 3, 2017

Unable to run grails test-app :cucumber

Leave a Comment

So I've looked through other peoples problems but they dont match what I'm seeing so thought I'd post it up to see if anyone else has had this issue and has a suggested solution

Im running a grails app in 2.3.5 and have cucumber 1.2.0

I've set up a really basic feature file in the functional folder that reads as follows: -

Feature:   As a user   If I enter the incorrect password I need a warning message   So I know i did something wrong   Scenario:   Given I enter the wrong login credentials   When I click sign in   Then Display a login error 

Now I know this shouldn't work as yet but Im going one step at a time to see the process as Im new to cucumber and grails.

The app runs fine if I use the command

grails run-app -Dgrails.server.port.http=8090

If I then try running the cucumber test via

grails test-app :cucumber (with or without the port specification above) I get the following explosion...

Configuring Shiro ...  Shiro Configured | Error 2017-03-15 08:28:35,222 [localhost-startStop-1] ERROR context.GrailsContextLoader  - Error initializing the application: null Message: null     Line | Method ->> 2076 | contains       in java.lang.String - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |    207 | canAutoMigrate in grails.plugin.databasemigration.MigrationUtils |     43 | autoRun . . .  in grails.plugin.databasemigration.MigrationRunner |     87 | doCall         in DatabaseMigrationGrailsPlugin$_closure2 |    262 | run . . . . .  in java.util.concurrent.FutureTask |   1145 | runWorker      in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . . .  in java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run            in java.lang.Thread | Error 2017-03-15 08:28:35,247 [localhost-startStop-1] ERROR context.GrailsContextLoader  - Error initializing Grails: null Message: null     Line | Method ->> 2076 | contains       in java.lang.String - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |    207 | canAutoMigrate in grails.plugin.databasemigration.MigrationUtils |     43 | autoRun . . .  in grails.plugin.databasemigration.MigrationRunner |     87 | doCall         in DatabaseMigrationGrailsPlugin$_closure2 |    262 | run . . . . .  in java.util.concurrent.FutureTask |   1145 | runWorker      in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . . .  in java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run            in java.lang.Thread | Error 2017-03-15 08:28:35,251 [localhost-startStop-1] ERROR [localhost].[/Copper]  - Exception sending context initialized event to listener instance of class org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener Message: Error executing bootstraps; nested exception is java.lang.NullPointerException     Line | Method ->>  262 | run       in java.util.concurrent.FutureTask - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run       in java.lang.Thread  Caused by NullPointerException: null ->> 2076 | contains  in java.lang.String - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |    207 | canAutoMigrate in grails.plugin.databasemigration.MigrationUtils |     43 | autoRun . in grails.plugin.databasemigration.MigrationRunner |     87 | doCall    in DatabaseMigrationGrailsPlugin$_closure2 |    262 | run . . . in java.util.concurrent.FutureTask |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run       in java.lang.Thread | Error 2017-03-15 08:28:35,271 [localhost-startStop-1] ERROR core.StandardContext  - Error listenerStart | Error 2017-03-15 08:28:35,280 [localhost-startStop-1] ERROR core.StandardContext  - Context [/myProject] startup failed due to previous errors | Server running. Browse to http://localhost:8080/myProject | Server stopped | Error Fatal error running tests: No WebApplicationContext found: no ContextLoaderListener registered? (Use --stacktrace to see the full trace) | Tests FAILED  - view reports in /Users/me/Projects/myProject/target/test-reports | Error Error executing script TestApp: java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? (Use --stacktrace to see the full trace) 

I have 0 idea what any of this means and googling any of it with a grails/cucumber context doesnt seem to really bring anything of sense back, any suggestions or questions welcome!

0 Answers

Read More

Monday, April 18, 2016

How to avoid CouldNotDetermineHibernateDialectException error?

Leave a Comment

I'm upgrading oracle from 10 to 12 and for this specific project I got this error:

<[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1460078994317> <BEA-101162> <User defined listener org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.codehaus.groovy.grails.orm.hibernate.exceptions.CouldNotDetermineHibernateDialectException: Could not determine Hibernate dialect for database name [Oracle]!. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.codehaus.groovy.grails.orm.hibernate.exceptions.CouldNotDetermineHibernateDialectException: Could not determine Hibernate dialect for database name [Oracle]! 

Seems like it's not recognizing the configuration I've added on DataSource:

dataSource {     pooled = true     driverClassName = "oracle.jdbc.OracleDriver"     dialect = "org.hibernate.dialect.Oracle10gDialect" } 

We are using Java 8 and we have those dependencies on the code:

runtime 'com.oracle:ojdbc7:12.1.0.2' runtime(group: 'com.oracle', name: 'ons', version: '10.2.0.3') 

The thing is that it's working for the other project (that have the same structure as this one, but for some reason it's not working here)

Is there anything missing or anything I can to find the problem and solve the issue?

1 Answers

Answers 1

This problem happened for java version 1.7.0_25. By upgrading java 1.7.0_25 to another upper version will help you to resolve the issue. Sometimes downgrade to 1.6.X also works. But upgrading is best solution.

It is fixed in Grails 2.2.3. But in Grails 2.2.3, It is still broken for OpenJDK 1.7.0_25 on Linux, Oracle's JDK does work though.

Credit goes to @aeischeid


A step by step solution is given in this tutorial: Connect Grails with Oracle 11g Example Configuration

Resource Link:

  1. How do I avoid 'Could not determine Hibernate dialect for database name [H2]!'?

UPDATE

Suggestion - 1:

From this tutorial, I got two suggestions, please try this 2 issues- You need to install the Grails H2 plugin. Add

compile ":h2:0.2.6" 

to grails-app/conf/BuildConfig.groovy, in the plugins block.

Suggestion - 2:

In DataSource.groovy, they are case sensitive. So please check is there anything(like username or others) with case mismatching.

Resource Link: MASSIVE ERROR ON GRAILS RUN-APP

Suggestion - 3:

danielnaber gives some suggestions grails compile --refresh-dependencies and/or grails clean might help. You will need to configure database access in grails-app/conf/DataSource.groovy (development for grails run-app and production for grails war)

Suggestion - 4:

From this tutorial Remove your DataSource.groovy file and rebuild the WAR after doing a grails clean, which will disable the default file based data source

Currently it is trying to create a database on the file system but failing because you do not have the permission to do so.

Suggestion - 5:

You can take a look in https://github.com/Netflix/Lipstick/issues/8

Suggestion - 6:

While you're in there you should fix the cache provider warning you're seeing too - change the value for 'cache.provider_class' in the hibernate block to

   cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'  

Please give a try of 6 suggestions. Hope it can help you.

Read More

Wednesday, April 13, 2016

Connection already closed

Leave a Comment

I'm using Grails 2.5.3 and Tomcat7 and after 8 hours of app deployment our logs start blowing up with connection already closed issues. A good assumption is that MySql is killing the connection after the default wait time of 8 hrs.

By way of the docs my pool seems to be configured correctly to keep the idle connections open but it doesn't seem to be the case.

What might be wrong with my connection pool setting?

dataSource {   pooled = true   url = 'jdbc:mysql://******.**********.us-east-1.rds.amazonaws.com/*****'   driverClassName = 'com.mysql.jdbc.Driver'   username = '********'   password = '******************'   dialect = org.hibernate.dialect.MySQL5InnoDBDialect   loggingSql = false   properties {     jmxEnabled = true     initialSize = 5     timeBetweenEvictionRunsMillis = 10000     minEvictableIdleTimeMillis = 60000     validationQuery = "SELECT 1"     initSQL = "SELECT 1"     validationQueryTimeout = 10     testOnBorrow = true     testWhileIdle = true     testOnReturn = true     testOnConnect = true     removeAbandonedTimeout = 300     maxActive=100      maxIdle=10      minIdle=1     maxWait=30000     maxAge=900000     removeAbandoned="true"     jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.StatementCache;"    } }  hibernate {   cache.use_second_level_cache=true   cache.use_query_cache=true   cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' } 

Also, I have confirmed that the dataSource at runtime is an instance of (org.apache.tomcat.jdbc.pool.DataSource)

UPDATE We think we may have found the problem! We were storing a domain class in the http session and after reading a bit about how the session factory works we believe that the stored http object was somehow bound to a connection. When a user accessed the domain class form the http session after 8 hours we think that hibernate stored a reference to the dead connection. It's in production now and we are monitoring.

2 Answers

Answers 1

Our url usually looks alike:

url = "jdbc:mysql://localhost/db?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true" 

Check out also encoding params if you don't want to face such an issue.

Answers 2

I've had this issue with a completely different setup. It's really not fun to deal with. Basically it boils down to this:

  1. You have some connection somewhere in your application just sitting around while Java is doing some sort of "other" processing. Here's a really basic way to reproduce:

    Connection con = (get connection from pool); Sleep(330 seconds); con.close();

    1. The code is not doing anything with the database connection above, so tomcat detects it as abandoned and returns it to the pool at 300 seconds.

    2. Your application is high traffic enough that the same connection (both opened and abandoned in the above code) is opened somewhere else in the application in a different part of code.

    3. Either the original code hits 330 seconds and closes the connection, or the new code picks up the connection and finished and closes it. At this point there are two places using the same connection and one of them has closed it.

    4. The other location of code using the same connection then tries to either use or close the same connection

    5. The connection is already closed. Producing the above error.

Read More

Thursday, April 7, 2016

Parsing FORM-ENCODED parameters with GRAILS (chargify webhooks)

Leave a Comment

I have a GRAILS 3 controller that receive an HTTP post from a webservice (Chargify) with this format (the payload section has about 100 entries with a lot of sub-fields):

POST / HTTP/1.1 Accept: */*; q=0.5, application/xml Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded X-Chargify-Webhook-Id: 81309408 X-Chargify-Webhook-Signature: xxxxxxxxxxxxx X-Chargify-Webhook-Signature-Hmac-Sha-256: yyyyyyyyyyyyyy Content-Length: 48 User-Agent: Ruby X-Newrelic-Id: xxxxxx X-Newrelic-Transaction: aaaaaaaaaaaaaa= Host: myhost.test.it  id=81197881&event=statement_settled&payload[site][id]=12345&payload[site][subdomain]=test-sandbox 

Is there any way with GRAILS to parse the "payload" part and convert it dynamically to a POJO (or also a simple hashmap)?. Chargify use this strange format not recognized by GRAILS framework and I'm unable to parse it automatically.

Is there anyone to help me for parsing? Advance thanks for helping.

1 Answers

Answers 1

Can you try this ?

def readChargify() {     String requestData = request.reader.text     def reqMap = org.grails.web.util.WebUtils.fromQueryString(requestData) } 
Read More