Monday, July 2, 2012

Postgres not asking for password

Problem


After creating a new user with password in postgres and trying to login using the new user, postgres never asks for a password

 Solution

Modify the pg_hba.conf file and change trust to md5, as follows:

local   all         all                               md5
# IPv4 local connections:
host    all         all         127.0.0.1/32          md5
# IPv6 local connections:
host    all         all         ::1/128               md5

Tuesday, June 26, 2012

Grails springsecurity core plugin 1.2.7.3 - BadCredentialsException

Problem:


I've recently upgraded to use the latest spring security plugin version 1.2.7.3.
After running s2-quickstart command as suggested in the documentation, the User, Role and UserRole domain objects were created.

I wanted to prepopulate the database with a default user by adding the following in Bootstrap.groovy:

Bootstrap.groovy
    def init = { servletContext ->                
        
        User existingUser = User.findByUsername('bob')
        
        if (existingUser == null) {                                    
            User u = new User(username: 'bob', enabled: true, password: 'password')          
            boolean saved = u.save(flush:true)
        }
        
    }


I started up the application and tried to login.
However when I try to authenticate I got a BadCredentialsException:

Investigation:


After a few hours of debugging, I noticed the way in which passwords were encoded have changed.
In the User domain class we see the following methods:

User.groovy
    def beforeInsert() {        
        encodePassword()
    }

    def beforeUpdate() {
        
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {        
        password = springSecurityService.encodePassword(password)        
    }

As you can see, immediately before the User object is inserted to the database it will replace the password with an encoded password. 

I decided to log how the password was being encoded by modifying the encodePassword method as follows:


    protected void encodePassword() {
        System.out.println("encoding password: "+password)
        password = springSecurityService.encodePassword(password)
        System.out.println("to "+this.password)
    }

After running the application, I could see that the encodePassword method was being called twice!! In other words, it was re-encoding an already encoded password. Hence when I try to login I get the BadCredentialsException.

Solution:

 I modified the User.groovy class to remove any automated encoding of the password, and I manually set the encoded password myself.



Thursday, May 31, 2012

Fix for PortletGrailsPlugin for Grails 2.x


 Problem:


Using the Grails Portlet plugin version 0.9.1 within a Grails 2.0.0 environment I get the following error:

Caused by MissingMethodException: No signature of method: org.codehaus.groovy.grails.plugins.web.ControllersGrailsPlugin.registerControllerMethods()

 Solution:

 We get this problem because in the lastet version of Grails 2.x, the "registerControllerMethods()" method no longer exists, and nobody is currently maintaining the plugin at the moment. But I've been working hard to find a solution so here it is.


In the PortletsGrailsPlugin.groovy file change the following from:


         def controllersPlugin = new ControllersGrailsPlugin()
         controllersPlugin.registerControllerMethods(mc, ctx)


To this:
         def enhancer = new MetaClassEnhancer()
         enhancer.addApi(new ControllersApi(getManager()))
         enhancer.enhance mc

Wednesday, May 30, 2012

Grails groovy.lang.MissingPropertyException: No such property: portletResponse

Problem:

Using the Grails Porlet plugin, I submitted an action request which would in turn invoke the actionView method of the generated portlet. However I received the following error, when I try to use the auto injected variable 'portletResponse':

groovy.lang.MissingPropertyException: No such property: portletResponse

Discussion:


I decided to dump out all the attributes for the request object as follows:

    def actionView = {
        logger.info("actionView")
        
        
        for (String attrName : request.getAttributeNames()) {
            logger.info("Name="+attrName+"    Value="+request.getAttribute(attrName))
        }
        portletResponse.setRenderParameter("prp-1", "value-1"); // <-- portletResponse is supposed to be auto injected
    }

Then when I viewed the output I saw the following in the logs:

2012-05-30 23:48:28,703 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.servlet.include.request_uri    Value=/apf-portal/Apf/invoke
2012-05-30 23:48:28,703 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.servlet.include.context_path    Value=/apf-portal
2012-05-30 23:48:28,704 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.servlet.include.servlet_path    Value=/Apf
2012-05-30 23:48:28,704 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.servlet.include.path_info    Value=/invoke
2012-05-30 23:48:28,704 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=com.liferay.portal.kernel.servlet.PortletServletConfig    Value=org.apache.catalina.core.StandardWrapperFacade@19a5b51
2012-05-30 23:48:28,704 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=grails.portlet.name    Value=Apf
2012-05-30 23:48:28,705 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=grails.portlet.config    Value=com.liferay.portlet.PortletConfigImpl@1647724
2012-05-30 23:48:28,707 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.portlet.config    Value=com.liferay.portlet.PortletConfigImpl@1647724
2012-05-30 23:48:28,708 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=com.liferay.portal.kernel.servlet.PortletServletResponse    Value=com.liferay.portal.kernel.servlet.StringServletResponse@faa1b4
2012-05-30 23:48:28,708 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=INVOKER_FILTER_URI    Value=/Apf/invoke
2012-05-30 23:48:28,717 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.portlet.response    Value=com.liferay.portlet.ActionResponseImpl@13a1d01
2012-05-30 23:48:28,718 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=PORTLET_ID    Value=Apf_WAR_apfportal
2012-05-30 23:48:28,730 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=com.liferay.portal.kernel.servlet.PortletServletRequest    Value=com.liferay.portal.servlet.NamespaceServletRequest@3858a8
2012-05-30 23:48:28,731 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.portlet.portlet    Value=org.codehaus.grails.portlets.GrailsDispatcherPortlet@9a5b5c
2012-05-30 23:48:28,740 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=WINDOW_STATE    Value=normal
2012-05-30 23:48:28,740 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=org.codehaus.groovy.grails.WEB_REQUEST    Value=ServletWebRequest: uri=/c/portal/layout;client=127.0.0.1;session=ED170D76D6BB5AF372ED336B020604E5;user=2
2012-05-30 23:48:28,754 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.portlet.lifecycle_phase    Value=ACTION_PHASE
2012-05-30 23:48:28,754 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=javax.portlet.request    Value=com.liferay.portlet.ActionRequestImpl@14480c8
2012-05-30 23:48:28,761 [http-bio-8080-exec-104] INFO  portal.ApfPortlet  - Name=com.liferay.portal.kernel.servlet.PortletServletFilterChain    Value=com.liferay.portlet.FilterChainImpl@62fa4e

As you can see, the attributes highlighted in red can give you access to the portletRequest and portletResponse objects.

Solution:

After dumping out the attributes you can now get the PortletRequest and PortletResponse as follows:


        PortletResponse portletResponse = request.getAttribute("javax.portlet.response")
        PortletRequest portletRequest = request.getAttribute("javax.portlet.request")


grails portlet plugin actionView not invoked

Problem:


I was using the Grails plugin for creating Portlets found here: http://grails.org/plugin/portlets

I created the Portlet code by invoking the following command: 
grails create-portlet MyFirst

This automatically created the Portlet class which contains the following code snippet:


    def actionView = {
        //TODO Define action phase for 'view' portlet mode
        portletResponse.setRenderParameter("prp-1", "value-1");
    }

The following the instructions as documented, I invoke the following command to generate the view for the portlet:

grails generate-portlet-views com.company.MyFirst
It creates several files with one of them being the view.gsp file. This file has a snippet as shown:


<form action="${portletResponse.createActionURL()}">
    <input type="submit" value="Submit"/>
</form>


The trouble was, when I goto submit the form, the actionView method never gets invoked. Only the renderView method get's invoked:

Solution 

The problem was that the form did not declare a POST method. I modified the view.gsp as follows:


<form action="${portletResponse.createActionURL()}" method="post">
    <input type="submit" value="Submit"/>
</form>

Reference:

 

Tuesday, May 29, 2012

Native SQL query using Hibernate causes ArrayIndexOutOfBounds

Problem:


In hibernate I was trying to use a native SQL query to retrieve records from the database when I encountered an ArrayIndexOutOfBoundsException on the following piece of code:


                String sql = "SELECT * FROM fcs f"
                SQLQuery query = session.createSQLQuery(sql)                
                //query.setString(0, barcode.toString())
                try {
                    list = query.list()   // <-- ERROR HERE
                } catch(Exception e) {
                    //e.printStackTrace()
                    logger.error(e)
                    ByteArrayOutputStream baos = new ByteArrayOutputStream()
                    PrintWriter pw = new PrintWriter(baos)
                    e.printStackTrace(pw)
                    pw.close()
                    byte[] array = baos.toByteArray()
                    String exp = new String(array)
                    logger.error(exp)
                }

As you can see, I managed to dump out the stacktrace which looked as follows:


Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
   at org.hibernate.type.TypeHelper.disassemble(TypeHelper.java:146)
   at org.hibernate.cache.StandardQueryCache.put(StandardQueryCache.java:106)

The important thing to notice about this stacktrace is that the error happens out of the StandardQueryCache.

Solution:


In grails, by default the standard query cache was enabled. To workaround the issue, I've disable it in the DataSource.groovy file as follows:


hibernate {
    cache.use_second_level_cache = false
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}

References:


Grails Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

Problem: 

When using mySQL Hibernate to convert a database value to a Timestamp I get the following error:

Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

 Solution:

 append the zeroDateTimeBehaviour=convertToNull parameter to end of the URL configuration as follows:

jdbc:mysql://localhost:3306/facs?zeroDateTimeBehavior=convertToNull

References: