Skip to content
accelerando

Tag Archives: grails

Grails: Completely disable stacktrace.log file

24-Mar-09

Regarding my question on twitter about completely disabling the creation of stacktrace.log from a Grails application in production mode, here is my answer:

environments {
    production {
        log4j = {
            appenders {
               null name:'stacktrace'
            }
        }
    }
    development {
    }
}

Be careful: This overwrites all other log4j closures that are made outside the environment specific settings. I found no solution for that.

Background: One of my Grails 1.1 app fails to start on a Tomcat application container deployed on an Oracle Enterprise Linux server because it fails to create the stacktrace.log.

What annoyed me is that i needed to dig around in the Grails source code to find the answer to my question in “src/groovy/org/codehaus/groovy/grails/plugins/logging/Log4jConfig.groovy” within the method “createFullstackTraceAppender()”. Should be stated in the documentation (perfect place here).

Edit: If your Grails 1.1 still fails to start(*) look out for xercesImpl.jar and xml-apis.jar or similar somewhere in your Tomcat 5 directory. These are some kind of Java 1.4 compatibility layers which break things in Grails 1.1. Oracle puts these into common/endorsed. After removing them, everything went fine.

(*) Exception was:

java.lang.RuntimeException: XPathFactory#newInstance() failed to create an XPathFactory for the default object model:
http://java.sun.com/jaxp/xpath/dom with the XPathFactoryConfigurationException: javax.xml.xpath.XPathFactoryConfigurationException:
No XPathFctory implementation found for the object model: http://java.sun.com/jaxp/xpath/dom

Grails’ withFormat block

23-Mar-09

Some things are not really different in Rails and Grails world. The pendant to Rails’ respond_to method is Grails withFormat block.

Both are supposed to render a different content type as requested according to the accept header and and the format parameter.

And both fail to some extend with Internet Explorer 5.5 to 7.0. For a longer explanation see my post on respond_to linked above. In short: First visit always gave me the an Excel File, all subsequent visits the intended html page.

I used nearly the exact solution within Grails 1.0.4 as in Rails:

withFormat {
      xls {
        // Same crap with IE 6/7 as with rails, compared to
        // http://info.michael-simons.eu/2007/08/06/rails-respond_to-method/
        if(params.format == 'xls') {
          def df = new SimpleDateFormat("yyyy-MM-dd")
 
          def report = ExcelReport.findById(params.reportId)          
          if(report == null)
            report = ExcelReport.findByBezeichnung('Absatzprognose')          
 
          response.contentType = 'application/vnd.ms-excel'
			    response.setHeader("content-disposition", "attachment;filename=some_filenname.xls")
          excelService.runExcelReport(
            report.bezeichnung,
            "some_parameter",
            response.outputStream
          )
          return
        }
      }
    }

Grails 1.1 seems to have fixed some issues on this case and a default or empty html {} block in front of any other format like so will do the trick:

withFormat {
      html {
        // depending on your needs
      }
      xls {
        // funny excel stuff
      }
    }

Grails, Hibernate, Current Session Context

12-Feb-09

Graeme was so kind to help me with this problem. My app worked well with Grails 1.0.4 but not in 1.1-beta3 any more.

My first wild guess leading to a

HibernateException: contains is not valid without active transaction

exception was my use of annotated Hibernate classes together with additional constraints in Grails, but Graeme figured out that it was the current session context i configured in hibernate.cfg.xml like so:

<property name="hibernate.current_session_context_class">thread</property>

I used this fragment for various JUnit test and in one case in a J2SE application where the same hibernate classes are needed. Together with a JTA Manager, this fragment is not needed and in case of Grails it has to go.

To run my tests i added the following statement right before opening my session:

final Properties nonJtaEnv = new Properties();
nonJtaEnv.put("hibernate.current_session_context_class", "thread");
 
sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").addProperties(nonJtaEnv).buildSessionFactory();

Grails startup parameter

09-Feb-09

Just some snippets from the doku that I tend to forget:

Run grails on a different port:

grails -Dserver.port=9090 run-app

Run grails with a different environment:

grails prod run-app // production
grails -Dgrails.env=mycustomenv run-app  // mycustomenv

Some random Grails thoughts and tipps

04-Dec-08

Lately i’ve been rambling and ranting a lot on twitter about the Grails framework.

To my surprise, many other developers actually read this tweets and helped me out on some problems. Thanks a lot gals and guys, i really appreciate that. Me rambling isn’t meant to be personal at any time, i guess you know how easily one gets frustrated with too less time and too much stuff to do.

Anyway, here are some shortcuts that could eventually be helpful. I’m gonna add more to this list the next days:

Enabling hibernate filters in the grails session

Took me a little digging through the source code, but i came up with the following idea:

import org.springframework.transaction.support.TransactionSynchronizationManager;
 
class SecurityFilters {
  def sessionFactory
  def filters = {
    login(controller:'*', action:'*') {
      before = {
        // get your user id somewhere
        def whatsoeveruserId = 0
        def sessionHolder =  TransactionSynchronizationManager.getResource(sessionFactory);     
        sessionHolder.getSession().enableFilter("filterByOwner").setParameter("currentUserId", whatsoeveruserId);
      }
    }
  }
}

I want to have some kind of rowlevel security through a Hibernate filter. Through dependency injection i get hold of the sessionFactory and through the TA Manager, i get the current session on which i can enable my filter.

Doing this in a Grails filter, i can combine this with some kinda login mechanism and i’m good to go.

Whitelisting attributes through bindData

To me it’s a bad idea using blacklisting on data binding as i can and will forget attributes that must not be updated through a webform.

With Marc i found the following solution:

bindData(entity, params, entity.properties.collect{it.key} - ['foo', 'bar'])

That way only attributes foo and bar gets updated.

Anyway, with Grails 1.1 this won’t be necessary anymore as Graeme anonced.

Graeme was so kind to comment on this: This feature is already in 1.0.x, i just didn’t find it, have a look at the docu at The Web Layer.

bindData(entity, params,  [include:['foo', 'bar']])

Updates on 2008/12/9

Adding custom errors to a domain class

The grails reference has a handy example for adding custom errors to domain classes, have a look here. This works quite well except that all other errors from databinding are mysteriously gone.

For me, the following steps worked to update a user (change some persistent attributes and the transient attributes password and passwordConfirmation):

bindData(anwender, params, [include:['name', 'vorname', 'password', 'passwordConfirmation']])
 
if(params.password != "" && params.password == params.passwordConfirmation)
  anwender.hashPassword() // As alway, never ever store plaintext passwords ;)
else if(params.password != "") {
  anwender.validate() // IMPORTANT without that step, possible other errors from bindData vanished
  anwender.errors.rejectValue('password', 'user.anwender.passwords_doesnotmatch')
}

Afterwords, hasErrors() show all errors, i.a. non nullable fields and the like.

More thoughts

I somewhat used to hibernate and come along very well with it, even though i’m actually a SQL fan. I guess if my inside into the Spring Framework would be a little bit deeper, some areas wouldn’t be hard to understand.

On the other hand i think that Grails does a great job for J2EE based development and it should do so even more. As always, there is the law of leaky abstractions, but the whole butload of stuff that is the J2EE stack should be abstracted away.

Updates on 2009/2/6

Grails 1.1-beta3

I use hibernate validator in my domain classes (that i created outside of rails as hibernate annotated classes) and i got

java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor

on every insert and update. Hibernate validator 3.0.0.GA is incompatible with the Hibernate version in Grails 1.1-beta3. Problem was gone after upgrading validator to 3.1.0.GA.

Some other stuff:

  • Installed plugins are obviously gone. i.e yui plugin is still in the application folder, it needs to be reinstalled after upgrade (grails install-plugin yui)

    Ok, i see this was done on purpose: “Plugins are now stored in your USER_HOME directory. You will need to re-install your plugins or run” (from the beta2 release note). Not a good decision making this a default imho. I like having my apps pinned to specific plugins.

  • The message method for doing I18n in controllers used to be available in filters. This method seems to be gone. No solution for that so far.
  • Values not bound in a form are not null anymore but 0 in case of numeric values. Bummer! Actually my bad.
  • Some problems solved.

Workshops

25-Oct-07

Right now i’m in Frankfurt / Main, attending the iX Workshop Web Programming with Grails (Link in German).

The speaker, Dierk König, encouraged live blogging, so here we are:

Some ActiveRecord bashing and many, many windows machines around. People fiddling around with their Java Paths, IntelliJ IDEA, which should be way better and more impressive than Eclipse or my nifty little TextMate… In the meantime, everything works fine on a real OS (that is everything else than Windows, for that matter…)

I’m already bored and expecting something more to happen. Everything said in the last 3 hours or so has been written down somewhere on the Internet.

As i don’t want to bore anybody else, i’ll guess i have look at my feedreader.

Hey, the beat goes on, configuring some weird IDE has stopped…

Would anybody really read my live blogging? If a tree falls in a forest…

JEHOVA! He said G-String :)

So again, how are strings called in the Groovy JDK? G Strings?

Hm, breaks are wonderful… Too much to eat, too much coffee…

The guy next to me didn’t manage to get the command line version working neither any IDE… Help is not wished.

At least, there’s a recent issue of german magazin in the conference file… With the title story about Ruby on Rails, hrr, hrr ;) .
Sometimes i think the IT world needs more egomaniac, rockstar-like developers like Heinemeier Hansson

Why on earth does one guy write the code from the beamer down on a sheet of paper while he’s checking his emails at the same time?? Sometimes the outer world seems like a strange place to me. Strange and weird.

Funny thing: Received a 1&1 spam mail about some profiseller foobar this morning. There are two guys from 1&1 at the opposite desk… Well, i’m too good educated…

Is it a good idea to but lawyers and webprogrammers into the same hotel? ;)

“Divs are good for updating thingies on the page”

I guess its obvious that english isn’t my native language (can’t get the thought out of my head that tante is mocking me…), but language and spoken words always creates a frame for thoughts and far to often, a cage… And for that being said, one should pay more attention on how to paraphrase things.

I really hate it if the speakers machine is not prepared well. I really do enjoy giving little demonstrations but i’m fastidious to paranoid that everything is taken care of, tested and proved to be working… If their only 8 hours time, not working improvisation sucks.

I have to say, i really do like Groovy, it’s a chance to get some serious scripting into Java at home… err i wanted to say, at work. People tend to focus on just one language and limiting themselves, but with Groovy i can argue: It’s Java with some fancy things on top. And at least for me, it’s a good thing.

“Mit diesen Dingen kann man beliebig fancy werden” — Argh, my head schmerzts…

I should collect some pudding for the gay bar to see if this guy is really as witty as he writes. Would pudding suffer to pay you or do want some Hägen Dasz?

Party is over… Good night & good fight ;)

Grails 0.6: Modifying JavaScript Libraries

19-Sep-07

Grails has a good mechanism for including JavaScript Libraries to do all that fance Ajax stuff. It all starts with:

<g:javascript library="scripaculous" />

Library can be one of yahoo, prototype, dojo, scriptaculous or rico. It’s a nice fact, that Grails doesn’t force you to use any special of these.

I wanted to change the included javascript source files (I use yahoo and wanted to get the latest release from their servers). In Grails 0.5.6 the core plugins were copied to $APP_HOME/plugins and i could modifiy them inplace. Grails 0.6 cleaned up some stuff so that the core plugins do not flood into the application tree.

I could hack the Grails source files or i can just modify the static member LIBRARY_MAPPINGS in JavascriptTagLib while starting up the application like so:

BootStrap.groovy in $APP_HOME/grails-app/conf

class BootStrap {
     def init = { servletContext ->        
          org.codehaus.groovy.grails.plugins.web.taglib.JavascriptTagLib.LIBRARY_MAPPINGS.yahoo.clear();
          org.codehaus.groovy.grails.plugins.web.taglib.JavascriptTagLib.LIBRARY_MAPPINGS.yahoo + ['anylibrary_file_you_want.js', 'anylibrary_file_you_want2.js', 'etc.js']
     }
     def destroy = {
     }
}

Furthermore, Grails 0.6 introduced the “base” attribute to g:javascript. Base denotes the full path that is prepend to the library file in question. So its possible to use any js file from wherever you want.

Rails and Grails revisited

25-Jun-07

I’ve never thought that my little little post would made such an impact.

While writing that post i was frustrated explaining the Spring configuration to my colleaques again, i was frustrated over the url mappings and so the post was a little harsh.

I don’t think that Hibernate is inferior to Active Record, regarding Spring and ActionController, i cannot tell, i like ActionController just better.

Anyhow, bring all three parts, model, view and controller, together… And see where Rails shines: In ease of use and working right out of the box. No wonder they came up with this whole screencasting things (at least, i never saw this before), it’s just impressing.

Instead of pushing out framework after framework, view technology after view technology (Faces, ADF, etc.), they bundled working things together and i think that’s what people like about RoR.

And i guess there’s a need for such think on the Java side of life as well… If not, why is the Grailsteam working on Grails? To paraphrase my last post positive: They bring good things in a nice package together.

For getting me into groovy i must thank the people behind Grails, this stuff is really cool.

For further reading i recommend the following posts:

Apart from this, can please anyone assure me, that some of the questions on the SCJP exam are a little weird and not really from this world? ;)

Ruby On Rails the Java Way: Grails

21-Jun-07

Why is it, that you have to take at least 2 heavy frameworks (Spring and Hibernate), a scripting addition to Java (Groovy) and build another layer on top of it to achieve a fraction of RoRs functionality? At least, i seems to look nice… a lot of xml configuration madness less, nice urls and so on. Although, i’m afraid of leaky abstraction. Anyway, here you go:

Grails
Groovy

I’ll give it a try, i’ll guess. At least, they have some good and well written tutorials on their sites.

Close
E-mail It