Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

Wednesday, June 8, 2016

Intellij and Grails 3 Command Failure

File this one under "doh, thats obvious" but I completely spaced out as to why my Intellij commands to generate new grails resources - like creating a new taglib
 

Would fail with an error like:

"C:\Program Files\Java\jdk1.8.0_45\bin\java" -XX:+TieredCompilation [...] \lib\grails-rt.jar" org.grails.cli.GrailsCli create-taglib <className> Error |
Command [create-taglib] error: Profile [org.grails.profiles:base:3.1.6] declares and invalid dependency on parent profile [org.grails.profiles:base:3.1.6] (Use --stacktrace to see the full trace)

The solution is to ensure the intellij SDK settings are set to the same level of grails SDK specific within your gradle file. I had upgraded to grails 3.1.6 within my build, but IntelliJ uses its own settings to define which grails binary to use for generating classes.




(Notice how Intellij still thinks my project is using 3.1.8 although I had downgraded to 3.1.6 - another curious feature that may crop up later)

Friday, April 15, 2016

Switching Environments in Grails 3 BootStrap

Over the iterations of grails, the best method to do this has changed. But if you want to execute grails code only within a specific environment in grails 3, you can use the static methods on the grails.util.Environment class.

Eg:

switch (Environment.getCurrent()) {

    case Environment.DEVELOPMENT:
        20.times {
            //do some thing
        }
        break;
    case Environment.PRODUCTION:
        2.times {
            //do some other thing
        }
        break;
}

Tuesday, February 21, 2012

Searching Multiple Data Sources in Grails

Have you got domain classes mapped to multiple datasources? The Searchable plugin will mysteriously not be building indexes for domain classes in your secondary datasources by default. The following explains a way to change the behavior.

This is taken from my personal experience, and information compiled from a helpful thread archived on Grails, found here. We are going to need to redefine some beans.

Step 1:
Open conf/spring/resources.groovy


add in the following bean:


import org.compass.gps.device.hibernate.HibernateGpsDevice //need this import for new datasource
import grails.plugin.searchable.internal.compass.config.SessionFactoryLookup //need this import to get correct sessionfactory class


beans = {


/* ~ your other beans here */



compassGpsDevice(HibernateGpsDevice) { bean ->
bean.destroyMethod = "stop"
name = "hibernate"
sessionFactory = { SessionFactoryLookup sfl ->
sessionFactory = ref('sessionFactory_datasourceName') 
}//replace datasourceName with the name of the datasource as defined in conf/DataSource.groovy
fetchCount = 5000
}
}


Step 2:
You could stop here if this was the only datasource that contained indexable classes, but continue to add each compassGPSdevices for each additional datasource (including the default), making sure they are unique names ie:



anotherUniquecompassGpsDevice(HibernateGpsDevice) { bean ->
bean.destroyMethod = "stop"
name = "unqiueHibernateName"
{ SessionFactoryLookup sfl ->
sessionFactory = ref('sessionFactory_uniquedatasource') 
}
fetchCount = 5000
 }


then finally we need to combine all of these datasources into one SingleCompassGps for searchable. Add this last bean:


import org.compass.gps.impl.SingleCompassGps

compassGps(SingleCompassGps) {
compass = ref('compass')
gpsDevices = [compassGpsDevice, anotherUniqueCompassGpsDevice /* ~add the other sources in here */ ]
}

Thanks to the original thread for guidance. Hopefully this compilation of guidance will help someone else save some time. The major additions beyond the original thread are to use the sessionfactorylookup. You can see these objects in SearchableGrailsPlugin.groovy - we are simply re defining them with new datasources!





Friday, February 17, 2012

Undocumented? Grails scaffolding feature. Widgets

Present in old docs, but weirdly not the latest, you can request a different widget on scaffolded pages for your domain class.

In the domain's scaffold closure:


def constraints = {
        myStringField(widget:'textarea')
}

Thursday, February 16, 2012

Fun fact: Grails GString's require double quotes

Will work:


def element = "<script type=\"text/javascript\" src=\"${g.resource(dir: 'folder', file: 'file.js')}\"></script>"
out <<  element.toString()


Wont work:


def element = '<script type="text/javascript" src="${g.resource(dir: "folder", file: "file.js")}"></script>'
out <<  element.toString()


And by "wont work" the groovy expressions in the GString will not be evaluated, they will be delivered literally. Note the double quotes beginning and ending the GString in the first example.

I knew this. Yet I was dissecting why my unit test was failing for over an hour. Turns out junit can't detect silly human error! Since I re-learnt this lesson, I thought I would share it with you, blogosphere!

Friday, January 20, 2012

Grails Codec file location and extension

If you are just beginning out in Grails development, the creation of custom codecs can greatly increase productivity. Codecs help you code/decode (funny that) strings. Grails ships with a bunch of them already, but when you feel like you want to create you own, greate a groovy class file (extension .groovy), with the name ending in "Codec" in your projects graips-app/utils folder. Remember that if you want to place these files in packages, you will need to create the additional folder structure to match the package structure. A sample codec structure is shown below. This file would be in the folder grails-app/utils/org/mycompany/:


package org.mycompany
import /* imports here */

class SampleCodec{
  static encode = { str ->
   /* Coding data goes here */
  }

static decode = { str ->
   /* Decoding data goes here */
  }

}

Once you start your grails app, Spring will inject the methods encodeAsSample() and decodeSample() to the Java.lang.String class.

Start creating custom hash codes for your passwords now!

Tuesday, December 27, 2011

Basic Grails custom tag testing errors

You may encounter an error such as the following:

"No such property: out<or other method name> in package.classname "


This comes from writing the taglibtest like all the tutorials out on the web had said to, e.g. using:

class DateTagLib {
def thisYear = {
out << Calendar.getInstance().get(Calendar.YEAR)
'' //return empty text
 }
}

This problem arises from the newer versions of grails producing UNIT tests rather than INTEGRATION tests. In the unit environment, the Grails engine is not active to inject the dynamically created methods, such as validate, out.

So how do I resolve this? It runs just fine on the test webpage its included on. The test was failing when the tag clearly worked.



Three things to fix:

  1. Make sure your test case is extending TagLibUnitTestCase.
  2. Make sure you are calling super.setUp() in your test constructor
  3. Make a call to mockTagLib(YourTagClassHere) at the beginning of your test method.


So a basic test case for a custom tag (as shown above) might look like the following:


package yourpackage
import grails.test.*
class DateTagLibTests extends TagLibUnitTestCase  {
  def dateTagLib


  void setUp(){
 super.setUp()
 
    dateTagLib = new DateTagLib()

  }


  void testThisYear() {
 mockTagLib(DateTagLib)
    String expected = Calendar.getInstance().get(Calendar.YEAR)
    assertEquals("the years don't match", expected, dateTagLib.thisYear().toString())
  }
}

Wednesday, December 21, 2011

Changing syntax highlighting for Groovy/Grails in Eclipse

Looking for something a little easier on the eyes?
By combining the Eclipse color theme plugin with some specific groovy settings, you can make working with groovy much more 'visually' appealing.

1) Install the eclipse color theme plugin. Help->Eclipse Marketplace...->Search for "Eclipse Color Theme". Select a dark theme (or really any one of your choosing). You might notice some elements are not being colored correctly however, namely brackets and operators. To fix these last few elements we can manually change their color to something that suits.

2) Window->Preferences->Groovy->Editor. In this settings page you will find the rest of the settings you need to change. Set the operator, bracket colors to something more visible (and any other fine tweaks you may wish)

Enjoy!