Saturday, July 31, 2010

Spring ApplicationContext inside JSR-168 Portlet

Use following code to get Spring ApplicationContext inside portlet

PortletContext portletContext = this.getPortletContext();
ApplicationContext context = PortletApplicationContextUtils.getWebApplicationContext(portletContext);

then use context to retrieve beans

context.getBean("beanName");

Note : spring-webmvc-portlet.jar is required.

Another more generic way of accessing Spring Application Context
http://mdshannan1.blogspot.com/2010/11/easy-access-to-spring.html

Friday, July 16, 2010

Writing Secure Ajax Portlets for Liferay using DWR

Liferay PortletSession cannot be shared with DWR Servlet Session however using following technique we can copy required information from Liferay Session to Application Session

request.getPortletSession().setAttribute("remoteUser", request.getRemoteUser(), PortletSession.APPLICATION_SCOPE);


Access above session data inside DWR

public String test(HttpSession session) {

/**
* s1 == portal session
* s2 == DWR session
*
* s1 expires before s2 --> s2 will also expire (Tested)
* s2 expires before s1 --> s2 invalidates and should work after reload (Tested)
* s1 & s2 expires --> user reloads and relogins both should work
*
*/

String userId = (String) session.getAttribute("remoteUser");
if (userId == null) {
session.invalidate();
return "Page reload is required!";
}
return userId;
}

the above code is pretty self explanatory and safe way of exposing DWR services in a Portal Architecture.

have fun....

Tuesday, July 13, 2010

Tomcat Database Connection Pooling (JPA)

Follow these simple steps to setup Database Connection Pooling inside Tomcat 6.x

Step 1

Add following element to conf/context.xml file. This Resource will be avaible to all Applications deployed

<Resource name="jdbc/SampleDb" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="3" maxWait="10000"
username="" password=""
driverClassName=""
url=""/>

provide values for all attributes (username, password, driverClassName, url etc)

Step 2
Add following to web.xml of your Application

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/SampleDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Step 3
Refer JNDI Data source inside your persistence.xml

If you want to use JTA use this configuration

<persistence-unit name="SamplePU" transaction-type="JTA">
<jta-data-source>java:/comp/env/jdbc/SampleDB</jta-data-source>
..
</persistence-unit>

and for non JTA
<persistence-unit name="SamplePU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:/comp/env/jdbc/SampleDB</non-jta-data-source>
..
</persistence-unit>