dissabte, 23 de juliol del 2011

Zeep o'Tron for Liferay 6

Hi back!

Since my last post I've received some requests about a working sample for Liferay 6. Ok then...here it goes!
First there are some things I have to tell you....

Since some libraries and packages have changed from Liferay 5.2.3 to Liferay 6, I had to do some refactoring, so, taking advantage of this, I've made some modifications to the Zeep o'Tron version for Liferay 5.2.3.

As I told in some other posts, one of the features of Zeep o'Tron was the possibility to override/add your own Spring beans to Liferay core. Since Liferay already provides the possibility to add your own services through the service tag in hook's definition files, I've eliminated this feature from Zeep o'Tron. Maybe I missed something when taking that decision, so, if you think of any situation where adding your own Spring beans could be an advantage, just let me know, and I'll put it back.

Another thing that has been changed is the way Struts and Tiles configurations are loaded. In previous version, Zeep o'Tron just scanned any deployed hook for classes and libs and added them to Liferay's classloader, then, looked for a "struts-config.xml" file under hook's WEB-INF directory, scanned it, and added those configs to Liferay's struts configs. Finally, searched for a "tiles-defs.xml" file, under the same directory, and added those Tiles configurations to Liferay's Tiles configurations.
Thinking about it, I find it too much aggressive, I mean Zeep o'Tron  was applied to each and every deployed hook, and, sometimes, it makes no sense. That's why I've decided to modify the version for Liferay 6 to make it work different, so that not only you can choose which hooks will be parsed by Zeep o'Tron, but which kind of configurations you want to be loaded, and which files contain those configs.
How does it work now? From now on, when a hook is deployed, Zeep o'Tron will look for a file called zeep-o-tron.properties under hook's WEB-INF directory. If it is found, it will check for two properties: 'struts.file.path' and 'tiles.file.path'. If there is a filled 'struts.file.path' property, Struts configurations found in that file (the one represented in the property value) will be loaded into Liferay's Struts configurations, overriding and adding whatever is needed. Besides, all classes and libs found in the hook will be added to Liferay's classloader, so that we can make sure that all classes needed by those configurations are available to Liferay.
At last, something similar is done for Tiles configurations: if a value is found for the property 'tiles.file.path', that file is parsed and all Tiles configurations found in there, added to Liferay's Tiles definitions.
You can take a look at the same hook for the details.

So, the sample hook you'll find in this entry, will work exactly as that shown in Liferay Portal Server: avoiding use of extension. JAR and sample for Liferay 5.2.3, except by the Spring part:

  1. Install Zeep o'Tron for Liferay 6 the same way as explained for Liferay 5.2.3
  2. Start Liferay, and deploy the sample hook provided later on in this entry 
  3. Create an event in the Calendar portlet and have a look at the logs (remember the sample hook outputs to the logs just by using System.out) to check Zeep o'Tron's Struts functionality
  4. Try to see the details of an event, to check Zeep o'Tron's Tiles functionallity
For more details about the testing the sample hook, check out the blog entry related to Zeep o'Tron for Liferay 5.2.3 (and remember to avoid the Spring part, of course!).

Finally, here you can download Zeep o'Tron for Liferay 6, and a sample hook. Sorry for uploading the artifacts in such a place, but found nothing better..

Enjoy!!


Have any idea on how to improve it? Just let me know!

dimecres, 13 de juliol del 2011

Liferay Portal Server: avoiding use of extension. JAR and sample for Liferay 5.2.3

Hi!

Since I posted my set of entries called "Liferay Portal Server: avoiding use of extension" (1, 2 and 3), I've received a rush of visits so, it looks like there is some interest in Zeep 'oTron. So I decided to package it and upload some samples.

My first sample is for Liferay 5.2.3 (bundled with Tomcat 6). So, if you want to try it, just download the zeep-o-tron-liferay_5_2_3.jar, deploy it, start your Liferay Portal Server, and test the sample (zeep-o-tron_demo_hook.war).

I've already explained how to install Zeep O'Tron in another post, but I'll repeat so that you don't need to look for it:
  1. Copy zeep-o-tron-liferay_5_2_3.jar in LIFERAY_HOME/tomcat-6.0.18/webapps/ROOT/WEB-INF/lib
  2. Edit web.xml and locate the servlet named 'Main Servlet'. Then, in that servlet definition:
    • comment out the servlet-class tag
    • add you own servlet-class tag with 'com.blogspot.aigloss.hook.hotdeploy.servlet.HotdeployMainServlet' as value
    • add an init-param with 'configFactory' as param-name, and 'com.blogspot.aigloss.hook.hotdeploy.config.ModuleConfigFactory' as param value
    • now, the Main Servlet from your web.xml, shoul look like this:
      <servlet>
         <servlet-name>Main Servlet</servlet-name>
         <!--servlet-class>com.liferay.portal.servlet.MainServlet</servlet-class-->
         <servlet-class>com.blogspot.aigloss.hook.hotdeploy.servlet.HotdeployMainServlet</servlet-class>
         <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
         </init-param>
         <!--zeep o'tron -->
         <init-param>
            <param-name>configFactory</param-name>
            <param-value>com.blogspot.aigloss.hook.hotdeploy.config.ModuleConfigFactory</param-value>
         </init-param>
         <!--   -->
         <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
         </init-param>
         <init-param>
            <param-name>detail</param-name>
            <param-value>0</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
      </servlet>
  3. Edit your portal-ext.properties and add 'com.blogspot.aigloss.hook.hotdeploy.portal.HookHotdeployListener' as a new hot.deploy.listener. If you have'nt defined any, you can just add the following:
  4. hot.deploy.listeners=\ com.liferay.portal.deploy.hot.PluginPackageHotDeployListener,\ com.liferay.portal.deploy.hot.HookHotDeployListener,\ com.liferay.portal.deploy.hot.LayoutTemplateHotDeployListener,\ com.liferay.portal.deploy.hot.PortletHotDeployListener,\ com.liferay.portal.deploy.hot.ThemeHotDeployListener,\ com.liferay.portal.deploy.hot.ThemeLoaderHotDeployListener,\ com.liferay.portal.deploy.hot.MessagingHotDeployListener,\ com.blogspot.aigloss.hook.hotdeploy.portal.HookHotdeployListener
Ok! Zeep O'Tron is already installed. Now, let's test the sample.
Open your browser, login, and go to a blank page. Add the Calendar portlet.
Now create an event and look at the server logs; back to the browser, click the recently created event and check out its details. Back to the calendar main page, and delete the event. Take a look at the logs again...
Nothing special, uh?!

Ok, let's deploy the sample. Just leave it in LIFERAY_HOME/deploy and let Liferay do its work...
Now repeat what you did again:

  1. Create an event and take a look at the logs....you find a message like this: 'THE CONFIGURATION FOR THIS ACTION HAS BEEN MODIFIED BY ZEEP O'TRON!!!!!' . Of course the sample overrides the action 'com.liferay.portlet.calendar.action.EditEventAction' to output that log to the console...
  2. Now let's take a look at the event's details...can't see the details? That's it! The sample overrides the Tiles configuration called 'portlet.calendar.view_event' to output that message on the screen instead of the event details...
  3. Finally, go back, and delete the event. Check out the logs...see that message?! Yes! As you can read in the message, the hook has overriden the spring bean called 'com.liferay.portlet.calendar.service.CalEventLocalService.impl'
Of course, later versions of Liferay already allow you to override spring services, just remember I developed this for Liferay 5.1.2. By the way, you can take advantage of overriding Struts and Tiles configurations. Of course, if you can override, you can add! 

Last but not least, since all this has been made from a hook, there is no need to demonstrate that all the classes used to override Struts actions, ans Spring beans have been added to Liferay's classloader...so you can take advantage of this too.

Hope you like it!

You can find a version for Liferay 6 (tested in LF 6.0.6) here!

dissabte, 9 de juliol del 2011

Injecting Spring beans in web service handlers

Whenever you have a handler defined for a web service (follow this link for an example) you'll propably find out that any Spring bean you try to inject in your handler results in being null...
It is just beacuse the responsible for instantiating the handler is the underlying web service technology (p.e.: JAX-WS, Axis,...), and that technology is not aware of your Spring context.

Of course there are some workarounds for this problem. 
One approach, could be to:
  1. define the handler class as a singleton Spring bean
  2. inject all the services you need
  3. make sure all those services are thread-safe
  4. make the variables on the handler class, that will store those, services static
This way, when the application starts, the Spring context will be loaded, the "handler bean" created and the service injected. Whenever the handler needs to be instantiated by, for example, JAX-WS, it will have the service injected already (since the variable is static), so you'll be able to use it...

However, keep in minf the cons for this approach: you'll probably end up with a phantom singleton bean in your heap that will never be used.

divendres, 8 de juliol del 2011

Adding handlers to Spring web services

In my previous related entry I showed how easy it was to create a web service using Spring-WS and annotations. Now, we're discussing how to add a handler to the web service. In particular, we will add a handler that will extract the user requesting the service from a SAML token attached to it.

To add a handler to oour existing web service, we just need to files:
  • the handler implementation
  • an XML file (aka bingings file) defining the handler chain for the web service
Finally, we will just need to wire them.

Creating the handler implementation

To implement the hanlder, we just need to create a class that implements the interface javax.xml.ws.handler. This interface will force us to implement the following methods:

  • handleMessage
  • handleFault
  • close
  • getHeaders
Since in this sample we just want to validate the user requesting (extracting it from a SAML token) our service, we're only implementing the handleMessage method:

package com.blogspot.aigloss.springws.handler;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;

import org.opensaml.common.xml.SAMLConstants;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SAMLHandler implements SOAPHandler {
 private static String WS_SECURITY_URI =
   "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

 public boolean handleMessage(SOAPMessageContext smc) {
   SOAPFaultException exception = null;
   Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
   if (!outboundProperty.booleanValue()) {
     Element assertionElement;
     try {
       // get SOAP Header
       SOAPHeader sh = smc.getMessage().getSOAPHeader();
       if (sh == null) {
         // throw SOAPFaultException
       }
       // check for wsse:security element under SOAP Header
       Node wsse = sh.getFirstChild();
       if (wsse == null || !"Security".equals(wsse.getLocalName())
           || !WS_SECURITY_URI.equals(wsse.getNamespaceURI())) {
         //throw SOAPFaultException exception
       }

       // check for SAML assertion under wsse:security element
       assertionElement = (Element) wsse.getFirstChild();
       if (assertionElement == null
           || !"Assertion".equals(assertionElement.getLocalName())
           || !SAMLConstants.SAML20_NS.equals(assertionElement.getNamespaceURI())) {
         //throw SOAPFaultException exception
       }
       String user = null;
       //DON'T USE DOM! USE XPATH INSTEAD!!
       NodeList nodeList = assertionElement.getElementsByTagName("saml:NameID");
       if(nodeList.getLength() == 1) {
         user = nodeList.item(0).getTextContent();
       } else {
         //NameID not found under assertion token --> throw SOAPFaultException
       }
       if(exception == null) {
         //validate user
       }
     } catch (Exception e) {
       //throw SOAPFaultException exception
     }
     if(exception != null) {
       throw exception;
     }
   }
   return true;
 }

 public boolean handleFault(SOAPMessageContext context) {
   return false;
 }

 public void close(MessageContext context) {
 }

 public Set getHeaders() {
   return null;
 }
}


Note I've retrieved the NameId element content form the SAML token using DOM (code in red). I've done it just to tell you this is not the best way to retrieve it. Instead, use Xpath to get it.

Creating the bindings file


To inform the web service that there is one or more handler who want to manage the request, we need to create a handler chain. A handler chain is just a sequence of handlers that need to be applied in an specific order. It is defined in an XML file like this:


<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
   <handler-chain>
      <handler>
       <handler-name>SAMLHandler</handler-name>
         <handler-class>com.blogspot.aigloss.ws.handler.SAML2Handler</handler-class>
      </handler>
   </handler-chain>
</handler-chains>


Linking the bindings file with the handler implementation

Right now we have the implementation of our handler, and the definition on our handler chain.  So, finally, we just have to wire one with the other so that it all makes sense (and, of course, get it to work!). To get that wire, we're annotating the service endpoint class with javax.jws.HandlerChain:

@HandlerChain(file="myservice_bindings.xml")

Since we haven't specified any path for the file, we'll put it in the same directory as the service endpoint. For example, if you're working with Maven, you could put it into the same path as your service endpoint implementation but, instead of having it under /src/main/java, under /src/main/resources.

dimarts, 5 de juliol del 2011

Creating Spring web services using annotations

In this entry, I'm about to show how easy it is to create a web service using Spring-WS using annotations. Spring-WS makes it very easy to publish webservices so that you can publish your already existing services. It is based on JAX-WS, so it is great for application servers like Weblogic, since it uses the same web service technology stack.

To create a Spring-WS based web service, we just need to implement one class: the endpoint. By the way, since we are using Spring, usually it'd be better to implement the logic for the web service in its own service class, so that's the way we're going to take...

To create the enpoint class we just need to create a class extending org.springframework.web.context.support.SpringBeanAutowiringSupport and annotated by javax.jws.WebService. Once we have this class, any method representing an operation in the service, will have to be annotated by javax.jws.WebMethod.

Supose we want to publish a web service called GreetingsService with an operation sayHi. In this case, we'd create the following endpoint class:

import javax.jws.WebMethod;
import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

@WebService(serviceName="greetingsService")
public class GreetingsServiceEndpoint extends SpringBeanAutowiringSupport {

   @Autowired
   private GreetingsService greetingsService;

   @WebMethod
   public String sayHi() {
      return greetingsService.sayHi();
   }
}
Of course, we're not going into details about the GreetingService definition nor into how to configura my app to use Spring.

If we package and deploy this service, the url http://localhost:7001/springws-sample/greetingsService?wsdl (I'm currently using Weblogic), will return the following WSDL:
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is
   Oracle JAX-WS 2.1.5. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is
   Oracle JAX-WS 2.1.5. -->
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:tns="http://endpoint.springws.aigloss.blogspot.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://endpoint.springws.aigloss.blogspot.com/"
   name="greetingsService">
   <types>
      <xsd:schema>
         <xsd:import namespace="http://endpoint.springws.aigloss.blogspot.com/"
            schemaLocation="http://localhost:7001/springws-sample/greetingsService?xsd=1" />
      </xsd:schema>
   </types>
   <message name="sayHi">
      <part name="parameters" element="tns:sayHi" />
   </message>
   <message name="sayHiResponse">
      <part name="parameters" element="tns:sayHiResponse" />
   </message>
   <portType name="GreetingsServiceEndpoint">
      <operation name="sayHi">
         <input message="tns:sayHi" />
         <output message="tns:sayHiResponse" />
      </operation>
   </portType>
   <binding name="GreetingsServiceEndpointPortBinding" type="tns:GreetingsServiceEndpoint">
      <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
         style="document" />
      <operation name="sayHi">
         <soap:operation soapAction="" />
         <input>
            <soap:body use="literal" />
         </input>
         <output>
            <soap:body use="literal" />
         </output>
      </operation>
   </binding>
   <service name="greetingsService">
      <port name="GreetingsServiceEndpointPort" binding="tns:GreetingsServiceEndpointPortBinding">
         <soap:address
            location="http://localhost:7001/springws-sample/greetingsService" />
      </port>
   </service>
</definitions>

In the following entry, I'll explain how add a handler to the web service so that we can, for example, extract the user from a SAML token sent within the request to the web service,