Showing posts with label SpringSource dm Server. Show all posts
Showing posts with label SpringSource dm Server. Show all posts

Saturday, September 19, 2009

RESTful Web Services with Spring 3 Experience

Arjen Poutsma introduced REST support in Spring 3 through his two blogs REST in Spring 3: @MVC and REST in Spring 3: RestTemplate. Follow his instructions and Spring 3 PetClinic sample application, I got RESTful Web Service working in my Open Toast Project.

Just to provide a very simple service "get member object by member id", I created a new Web bundle project "org.opentoast.rest" by copying "org.opentoast.web" project. There is only one Java class in new project, MemebrController:

@Controller
public class MemberController
{
    protected final Log log = LogFactory.getLog(getClass());
    
    private MemberManager memberManager;
    
    @Autowired
    public MemberController(MemberManager memberManager){
        this.memberManager = memberManager;
    }
    
    @RequestMapping(value="/members/{memberId}", method = RequestMethod.GET)
    public ModelAndView getMember(@PathVariable("memberId") Long id) {
        Member m = memberManager.getMemberById(id);
        ModelAndView mav = new ModelAndView("member");
        mav.addObject("member", m);
        return mav;
    }
}

It provides one RESTful service in the method getMember(). It is annotated by @RequestMapping with URI template /members/{memberId}. Using @PathVariable("memberId"), the request member id is passed to parameter id. So with the injected MemberManager, we can get the Member object by id and pass to returned ModelAndView object. The view name is "member", and result member object is put into model with key "member" as well.

To setup REST support, there are few changes in config file module-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xsi:schemaLocation="
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
   http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

 <context:component-scan base-package="org.opentoast.rest.controller"/>

 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
   
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
 
 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
 
 <bean id="member" class="org.springframework.web.servlet.view.xml.MarshallingView">
  <property name="contentType" value="application/vnd.opentoast.rest+xml"/>
  <property name="marshaller" ref="marshaller"/>
  <property name="modelKey" value="member"/>
 </bean>

 <oxm:jaxb2-marshaller id="marshaller">
  <oxm:class-to-be-bound name="org.opentoast.domain.Member"/>
 </oxm:jaxb2-marshaller>

</beans>

Since we only want to support REST service with customized content type, we don’t need ContentNegotiatingViewResolver , so only one view resolver is set in the context: org.springframework.web.servlet.view.BeanNameViewResolver. It will resolve view named "member" to bean "member", which is an instance of org.springframework.web.servlet.view.xml.MarshallingView. The content type is "application/vnd.opentoast.rest+xml", modelKey is "member" and reference to jaxb2 marshaller bean "marshaller".

The web.xml sets servlet with org.springframework.web.servlet.DispatcherServlet, named opentoastrest, and maps to /*:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">

 <display-name>Open Toast RESTful</display-name>

 <context-param>
  <param-name>contextClass</param-name>
  <param-value>com.springsource.server.web.dm.ServerOsgiBundleXmlWebApplicationContext</param-value>
 </context-param>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /META-INF/spring/module-context.xml
   /META-INF/spring/osgi-context.xml
  </param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>opentoastrest</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value></param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>opentoastrest</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

You can check out the code from Google Code by running

svn checkout http://opentoastproject.googlecode.com/svn/tags/opentoast_20090919 opentoast

Then inside opentoast folder, run

mvn package

to build the whole application. Copy the par file at opentoast/org.opentoast.par/target/OpenToast.par to springsource dm Server pickup folder, and start dm Server.

To test the RESTful Web Service, here is a client example code:

package org.opentoast.client;

import java.util.HashMap;
import java.util.Map;

import org.opentoast.domain.Member;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.client.RestTemplate;

public class RestClient
{
    RestTemplate restTemplate;
    
    public RestClient(RestTemplate template)
    {
        this.restTemplate = template;
    }
    
    public void testMember()
    {
        Map<String, String> vars = new HashMap<String, String>();
        vars.put("memberId", "1");
        Member result = restTemplate.getForObject(
                "http://localhost:8080/opentoastrest/members/{memberId}",
                Member.class, vars);
        System.out.println(result);
    }
    
    public static void main(String[] args)
    {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "/org/opentoast/client/appContext.xml");
        RestClient client = (RestClient)ac.getBean("restClient");
        client.testMember();
    }
}
With xml config file /org/opentoast/client/appContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:oxm="http://www.springframework.org/schema/oxm"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

 <bean id="restClient" class="org.opentoast.client.RestClient">
  <constructor-arg ref="restTemplate"/>
 </bean>

 <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
  <property name="messageConverters">
   <list>
    <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
     <constructor-arg ref="marshaller"/>
     <property name="supportedMediaTypes">
      <list>
       <bean class="org.springframework.http.MediaType">
        <constructor-arg value="application"/>
        <constructor-arg value="vnd.opentoast.rest+xml"/>
       </bean>
      </list>
     </property>
    </bean>
   </list>
  </property>
 </bean>

 <oxm:jaxb2-marshaller id="marshaller">
  <oxm:class-to-be-bound name="org.opentoast.domain.Member"/>
 </oxm:jaxb2-marshaller>
 
</beans>
Run this test client program and you will get print out:

[Member 1: Jane Smith]

One big question I have now is "Do I need to expose my rich domain model as REST object model?"

JAXB2 marshaller requires Member class to be annotated with @XmlRootElement. And my domain model class Member is already annotated with persistent API, so now it looks like:

@XmlRootElement
@Entity
@Table(name = "MEMBER")
public class Member extends BaseEntity
{
...

If I don't want REST client to see my rich domain model, I have to use DTO model, and map between those two models. That will defeat the purpose of Domain Driven Design. If I expose my rich domain model classes to client, it will be more problematic when I try to use GWT as client application running inside browser. So far I haven't found a good solution for GWT + REST.

Monday, September 14, 2009

Release s2dm Maven Plugin 0.0.3

Open Toast Project Maven Plugin for Spring Source dm Server Development 0.0.3 was released.

After Spring Bundlor released 1.0M5, I tried and got it working with my project.

Still have trouble with M2Eclipse, the Maven Dependencies classpath of web project doesn't include depending projects in workspace (domain and service projects). So I have to manually add those two projects to web project Java Build Path.

The 0.0.3 release can be used to set up Eclipse workspace, and build par.

To use that plugin, in parent pom.xml, setup plugin repository to

 <pluginRepositories>
  <!-- Maven 2 Plugin for S2DM -->
  <pluginRepository>
   <id>opentoast.maven.s2dm.plugin</id>
   <url>http://opentoastproject.googlecode.com/svn/mavenrepo</url>
  </pluginRepository>
 
  <!-- SpringSource milestone -->
  <pluginRepository>
   <id>com.springsource.repository.bundles.milestone</id>
   <name>SpringSource Enterprise Bundle Repository</name>
   <url>http://repository.springsource.com/maven/bundles/milestone</url>
  </pluginRepository>

 </pluginRepositories>

So go to project root directory /opentoast, and type

mvn org.opentoast:maven-s2dm-plugin:0.0.3:eclipse

It will generate all eclipse setting files, such as /project, .classpath, .settings/org.eclipse.wst.common.project.facet.core.xml, etc. It also generates a dummy MANIFEST.MF file at generated/META-INF/MANIFEST.MF under each bundle project folder. The trick is the .classpath will include the generated folder as classpathentry, so STS bundlor will automatically update it with template.mf settings.

To build the whole application into a par, just type mvn package under opentoast, it will use dm-par goal to package par artifact.

So far STS does not work with dm Server 2.0.0.M4, so I just use STS to edit code, and use command line to build par, then deploy to local running dm Server pickup folder. I will try to get the application running inside STS later. Hope dm Server and Spring 3 can be released before Christmas, so I can play with them during winter break.

Monday, May 4, 2009

Setup Development Environment

My dream development environment consists of all open source tools:

  • Eclipse as IDE
  • Maven as build tool
  • Subversion as source code control
  • And an open source server: SpringSource dm Server

Recently there are many interesting announcements from SpringSource, like Spring dm Server 2.0M1, Spring Roo. I don't have time to follow those new trends, especially when they are just in alpha or beta stages. I want to focus on business application development and get my project done. So I just pick the released products from Open Source world, like dm Server 1.0.2.RELEASE.

I spent some time on BND and Maven Bundle Plugin, and tried to generate manifest from maven pom, but found it is too hard. SpringSource dm Server has an issue with Hibernate, you have to add "import-scope:=application" and put all bundles into a par file. See my questions at forum Where is the documentation about "import-scope:=application"?

Bundlor from SpringSource is also interesting, but I don't have time to learn another beta product, so I choose to manually create/maintain manifest files. Ideally I want to put all dependency info into pom, and derive manifest from pom. Maybe I will try again after Bundlor and dm Server 2.0 release after summer.

In order to continue my project, I just cleaned up my S2DM Maven plugin code and released 0.0.2. Open Toast Maven Plugin for SpringSource dm Server 0.0.2 has 2 goals now, one is to setup Eclipse config for OSGi projects, another is to generate par file. I code the plugin for Open Toast project, but it is generic enough for all Web application based on SpringSource dm Server. So feel free to use it and give me feedback.

Here is a brief description about how to setup environment for Open Toast Project:

1. Download and install Eclipse Ganymede SR2.

2. Install Subclipse eclipse plugin from http://subclipse.tigris.org/update_1.6.x

3. Install Spring IDE 2.2.2 and dm Server Tools 1.1.2 from http://www.springsource.org/update/e3.4. I have problem with dm Server Tools 1.1.3M1, but 1.1.2 seems very stable.

4. Download and unzip SpringSource dm Server 1.0.2.RELEASE, and set up a server runtime in Eclipse at localhost.

5. In Eclispe, open dm Server Repository Browser and download required dependencies:

  • Hibernate JPA Library 3.3.2.GA. It will include related bundles.
  • CGLIB 2.1.3. Not sure why it is not included in Hibernate library.
  • dbcp 1.2.2.osgi
  • commons.pool 1.4.0
  • hsqldb 1.8.0.9

6. Check out code from Google Code by any SVN client application, like TortoiseSVN, the url is http://opentoastproject.googlecode.com/svn/trunk/opentoast. You can also add svn repository for this url in Eclipse.

7. In command line, go to root directory of downloaded project, with parent pom.xml and 5 sub folders, run mvn org.opentoast:maven-s2dm-plugin:0.0.2:eclipse to set up eclipse config. Then import all projects into Eclipse. It may take a while to build those projects inside eclipse, and finally all compiler errors should be resolved.

8. In Eclipse, add org.opentoast.par into SpringSource dm Server v1.0 at localhost, and start the server. The console will display:

[2009-05-04 19:18:48.296] main                      Server starting.
[2009-05-04 19:18:49.365] main                      OSGi telnet console available on port 2401.
[2009-05-04 19:18:53.191] main                      Boot subsystems installed.
[2009-05-04 19:18:55.266] main                      Base subsystems installed.
[2009-05-04 19:18:57.053] server-dm-14              Installing profile 'web'.
[2009-05-04 19:18:58.737] server-dm-14              Installed profile 'web'.
[2009-05-04 19:18:58.944] server-dm-5               Creating HTTP/1.1 connector with scheme http on port 8080.
[2009-05-04 19:18:58.995] server-dm-5               Creating HTTP/1.1 connector with scheme https on port 8443.
[2009-05-04 19:18:59.028] server-dm-5               Creating AJP/1.3 connector with scheme http on port 8009.
[2009-05-04 19:18:59.072] server-dm-5               Starting ServletContainer.
[2009-05-04 19:18:59.892] server-dm-6               Server open for business with profile 'web'.
[2009-05-04 19:19:00.558] Deployer Recovery         Creating web application '/'.
[2009-05-04 19:19:00.936] async-delivery-thread-1   Starting web application '/'.
[2009-05-04 19:19:03.158] Deployer Recovery         Deployment of 'com.springsource.server.servlet.splash' version '1.0.2.RELEASE' completed.
[2009-05-04 19:19:03.526] Deployer Recovery         Creating web application '/admin'.
[2009-05-04 19:19:03.850] async-delivery-thread-1   Starting web application '/admin'.
[2009-05-04 19:19:04.377] Deployer Recovery         Deployment of 'com.springsource.server.servlet.admin' version '1.0.2.RELEASE' completed.
[2009-05-04 19:19:04.391] fs-watcher                Processing 'INITIAL' event for file 'server.admin.splash-1.0.2.RELEASE.jar'.
[2009-05-04 19:19:04.399] fs-watcher                File 'server.admin.splash-1.0.2.RELEASE.jar' already deployed.
[2009-05-04 19:19:04.404] fs-watcher                Processing 'INITIAL' event for file 'server.admin.web-1.0.2.RELEASE.jar'.
[2009-05-04 19:19:04.412] fs-watcher                File 'server.admin.web-1.0.2.RELEASE.jar' already deployed.
[2009-05-04 19:19:09.200] nection(2)-192.168.0.100  Creating web application '/opentoast'.
[2009-05-04 19:19:12.528] service-monitor-thread-1  Mandatory reference '&memberRepository' in bundle 'org.opentoast.par-0.0.1-org.opentoast.service' version '0.0.1' is waiting for service with filter '(&(objectClass=org.opentoast.domain.MemberRepository)(com.springsource.server.app.name=org.opentoast.par-0.0.1))'.
[2009-05-04 19:19:12.533] service-monitor-thread-1  Mandatory reference '&entityManagerFactory' in bundle 'org.opentoast.par-0.0.1-org.opentoast.service' version '0.0.1' is waiting for service with filter '(&(objectClass=javax.persistence.EntityManagerFactory)(com.springsource.server.app.name=org.opentoast.par-0.0.1))'.
[2009-05-04 19:19:12.830] server-dm-11              Reference '&entityManagerFactory' in bundle 'org.opentoast.par-0.0.1-org.opentoast.service' version '0.0.1' was satisfied by service with filter '(&(objectClass=javax.persistence.EntityManagerFactory)(com.springsource.server.app.name=org.opentoast.par-0.0.1))'.
[2009-05-04 19:19:12.837] server-dm-11              Reference '&memberRepository' in bundle 'org.opentoast.par-0.0.1-org.opentoast.service' version '0.0.1' was satisfied by service with filter '(&(objectClass=org.opentoast.domain.MemberRepository)(com.springsource.server.app.name=org.opentoast.par-0.0.1))'.
[2009-05-04 19:19:13.040] async-delivery-thread-1   Starting web application '/opentoast'.
[2009-05-04 19:19:13.769] nection(2)-192.168.0.100  Deployment of 'org.opentoast.par' version '0.0.1' completed.
If you open browser at http://localhost:8080/opentoast/home.htm, it will display current memebrs.

If you run mvn package, it will build final par file at org.opentoast.par/target/OpenToast.par. You can drop it under dm server pickup folder and start the server in command line. Of course, you have to add dependencies into springsource-dm-server-1.0.2.RELEASE\repository\bundles\usr folder before starting.

Wednesday, March 25, 2009

Simple Web Application with SpringSource dm Server (Updated)

I posted my experience of developing web application on SpringSource dm Server, then struggled with Maven, OSGi for last several weeks, didn't know some people asked me questions about the Simple Web Application with SpringSource dm Server. I apologize for not setting comment notification.

So here is the updated tutorial:

1. Download and install Eclipse Ganymede SR2. Install Spring IDE 2.2.2 and dm Server Tools 1.1.2 from http://www.springsource.org/update/e3.4. Download and unzip SpringSource dm Server 1.0.2.RELEASE, and set up a server runtime in Eclipse at localhost.

2. Create a new SpringSource dm Server Bundle Project in Eclipse. Project name is "org.simple.web". Set Java source folder to src/main/java. Next, set symbolic name same as project name, the module type is "Web", and set target runtime to SpringSource dm Server. Next, web context path is "simple", and dispatcher servlet url pattern is "*.htm".

3. After project creation, move the META-INF folder from src/main/java to src/main/resources folder and add the resources folder to Java build source path in Eclipse.

Update the MANIFEST.MF :

Manifest-Version: 1.0
Bundle-Version: 1.0.0
Bundle-Name: Simple Web Bundle
Bundle-ManifestVersion: 2
Bundle-Description: A very simple Spring DM Web Bundle
Bundle-SymbolicName: org.simple.web
Import-Bundle: com.springsource.javax.servlet
 ,com.springsource.javax.servlet.jsp
 ,com.springsource.org.apache.taglibs.standard
 ,org.springframework.core
 ,org.springframework.beans
 ,org.springframework.context
 ,org.springframework.context.support
 ,org.springframework.web
 ,org.springframework.web.servlet
Module-Type: Web
Web-ContextPath: simple
Web-DispatcherServletUrlPatterns: *.htm

The SpringSource dm Server Tool automatically sets up Bundle Dependencies.

4. Add spring config files. Create folder src/main/resources/META-INF/spring, and add module-context.xml, osgi-context.xml.

src/main/resources/META-INF/spring/module-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

 <context:component-scan base-package="org.simple.web"/>

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"
   p:suffix=".jsp"/>

</beans>

src/main/resources/META-INF/spring/osgi-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
   xmlns="http://www.springframework.org/schema/osgi"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:beans="http://www.springframework.org/schema/beans"
   xsi:schemaLocation="http://www.springframework.org/schema/osgi  
       http://www.springframework.org/schema/osgi/spring-osgi.xsd
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans:beans>

5. Create folder "src/main/resources/MODULE-INF", this is the folder for all the web content. Add index.html to MODULE-INF folder:

src/main/resources/MODULE-INF/index.html

<html>
<head>
  <meta http-equiv="Refresh" content="0; URL=home.htm">
</head>
</html>

The index.html redirects to home page "home.htm", and invoke Spring MVC code.

6. Add a very simple jsp file for the home page, just display welcome messag and list all members from backend:

src/main/resources/MODULE-INF/WEB-INF/jsp/home.jsp

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
 <head><title>Open Toast</title></head>
 
 <body>
  <h2>Welcome to Open Toast Project</h2>
  
  <h3>Current Members:</h3>
  <ul>
  <c:forEach items="${members}" var="member">
  <li><c:out value="${member.name}"/>
  </li>
  </c:forEach>
  </ul>
 </body>
</html>

7. Add Spring MVC controller class and support class for home page:

src/main/java/org/simple/web/HomePageController.java

package org.simple.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/home.htm")
public class HomePageController {
    public HomePageController() {
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<Member> members = new ArrayList<Member>();
        members.add(new Member("Yuan Ji"));
        return new ModelAndView("home", "members", members);
    }
}

src/main/java/org/simple/web/Member.java

package org.simple.web;

public class Member {
    private String name;

    public Member(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

8. Add org.simple.web project to SpringSource dm Server, and start the server. Open browser to http://localhost:8080 and click admin console. click /simple, you can see the home page of Open Toast Project.

Tuesday, January 13, 2009

Add Maven Support to dm Server Bundle Project

It took me several weekends to get maven working with my simple Web application.

My first approach was to use Apache Maven Eclipse Plugin, and add some tricks to work around its limitations. See my comments in Spring Forum dm Server Tooling and Maven: is it possible?

The issue is Maven Eclipse Plugin has not considered dm Server facet settings yet, so you have to manually add WTP project facet setting for dm Server in .settings\org.eclipse.wst.common.project.facet.core.xml file. There maybe some other ways to work around, but not neat.

Then I was thinking about extending its Mojo class org.apache.maven.plugin.eclipse.EclipsePlugin, and by adding additional project natures, build commands, etc. and we were done, just like M2EclipseMojo does. Although hadn't programmed Maven Plugin before, by reading tutorial and source code of Maven Eclipse Plugin, I thought it should be easy.

Setting up a plugin project is easy by following the Plugin Developer's document. Then I spent a whole morning struggling with NPE. First subclassed EclipsePlugin in my plugin project as S2DMEclipseMojo, and in the mojo, added dm Server related config for eclipse, similar to M2EclipseMojo. Theoretically it should work. But the project injected to the plugin was always null.

Tried all kinds of ways to figure out what's wrong, but no clue. Then started to search around in the Internet. Suddenly found this JIRA issue of Maven MPLUGIN-56 Inter-plugin Mojo inheritance. Hmm, Plexus should use JDK 5 annotation instead of javadoc annotation.

Anyway, the problem was found, so the dumb solution was to create a mojo class by copying code from EclipsePlugin and its superclass. After many tests and reviews, I found quite a lot of code is dealing with dependencies. Since we already use dm Server Tool to handle bundle dependency through MANIFEST.MF file, and we can use M2Eclipse plugin in Eclipse to handle unit test related dependencies like junit, easy mock, why not remove all those messy code? So a very simple mojo class was done and tested, seems it meets our needs. See the source code for S2DMEclipseMojo

This is my first Maven Plugin Project, very exciting. Then spent another weekend to get it released as 0.0.1, add documentation, publish to Google Code. It is very nice that we can use Google Code SVN service to publish our Web site and maven repository. See Open Toast Maven Plugin for SpringSource dm Server v0.0.1. The trick is you have to add svn property for all html files as "text/html" mime type. Maybe there is a easy way to do that, I don't know.

To use this plugin is very easy, simply by adding plugin repository in your project pom.xml, like:

 
  
  
   opentoast.maven.s2dm.plugin
   http://opentoastproject.googlecode.com/svn/mavenrepo
  
 

and then in your project root, type

mvn org.opentoast:maven-s2dm-plugin:0.0.1:eclipse

It will add Eclipse settings for the project, so you can import into Eclipse. Suppose you already set up your Eclipse with M2Eclipse and dm Server Tool plugins. You may have to run "Spring Tools - Refresh Bundle Dependencies" to get rid of compiler errors.

To use dm Server Tool with M2Eclipse, I apply another trick learned from Spring forum, that put all bundle dependencies to a profile, so M2Eclipse Plugin cannot find them.

The complete pom for my simple Web application is like this:



 4.0.0

 org.simple
 org.simple.web
 jar
 Simple Web Bundle
 0.0.1-SNAPSHOT

 
  
  3.2.2
  2.5.6.A
  1.1.2.A
  1.0.1
  1.5.0
  2.5.0
  2.1.0
  1.1.2
  4.5.0
  2.3.0
 

 
  
   bundle

   

    
    
     org.springframework
     org.springframework.beans
     
     ${spring.version}
     provided
    
    
     org.springframework
     org.springframework.core
     
     ${spring.version}
     provided
    
    
     org.springframework
     org.springframework.context
     
     ${spring.version}
     provided
    
    
     org.springframework
     org.springframework.context.support
     
     ${spring.version}
     provided
    
    
     org.springframework
     org.springframework.web
     
     ${spring.version}
     provided
    
    
     org.springframework
     org.springframework.web.servlet
     
     ${spring.version}
     provided
    

    
     javax.servlet
     com.springsource.javax.servlet
     
     ${servlet.version}
     provided
    

    
     javax.servlet
     com.springsource.javax.servlet.jsp
     
     ${jsp.version}
     provided
    

    
     org.apache.taglibs
     com.springsource.org.apache.taglibs.standard
     
     ${jstl.version}
     provided
    
   
  
 

 
   
   
    org.easymock
    com.springsource.org.easymock
    ${easymock.version}
    test
   
   
    org.junit
    com.springsource.org.junit
    ${junit.version}
    test
   

   
    org.springframework
    org.springframework.test
    ${spring.version}
    test
   
 
 
 
  
   
   
    org.apache.maven.plugins
    maven-compiler-plugin
    
     1.6
     1.6
    
   

   
    org.apache.maven.plugins
    maven-jar-plugin
    
     
      src/main/resources/META-INF/MANIFEST.MF
      
     
    
   

  
 
 
 
  
  
   opentoast.maven.s2dm.plugin
   http://opentoastproject.googlecode.com/svn/mavenrepo
  
 
 
 
    
   com.springsource.repository.bundles.release
   SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases
   http://repository.springsource.com/maven/bundles/release
  
  
   com.springsource.repository.bundles.external
   SpringSource Enterprise Bundle Repository - External Bundle Releases
   http://repository.springsource.com/maven/bundles/external
  
  
 

See my post Simple Web Application with SpringSource dm Server for other details.

Next step is to focus on Open Toast Project again, and get the whole system running. One goal of open toast project is to set up infrastructure so I can work on business later or easily create new projects. However, it is too long to get infrastructure done, especially when using cutting edge technologies. But isn't it fun?

Sunday, December 14, 2008

Simple Web Application with SpringSource dm Server

(Please see the updated tutorial. 2009/03/25)

Finally I got a very simple Web application working with SpringSource dm Server. The goal is to set up a complete Web application development environment with Eclipse as IDE, Maven as build tool, SpringSource dm Server as deployment environment.

The process is very simple, but still took me a lot of time to figure out the best practice.

1. Set up IDE. Extract downloaded eclipse newest version eclipse-jee-ganymede-SR1-win32.zip to S2DM. And install Spring IDE (2.2.1.v200811281800), Spring dm Server Tool (1.1.0.v200811281800). I also installed M2Eclipse plugin (0.9.6.20080905-0917). 
Extract downloaded SpringSource dm Server 1.0.1.RELEASE to S2DM. Set up a server runtime in Eclipse for SpringSource dm Server v1.0 at localhost.

2. Create a new SpringSource dm Server Bundle project in Eclipse. Name is "org.simple.web"
The module type is "Web", context path is "simple", and dispatcher servlet url pattern is "*.htm".

3. After project creation, move the META-INF folder from src/main/jave to src/main/resources folder and add the resources folder to Java build source path in Eclipse.

Update the MANIFEST.MF :
Manifest-Version: 1.0
Bundle-Version: 1.0.0
Bundle-Name: Simple Web Bundle
Bundle-ManifestVersion: 2
Bundle-Description: A very simple Spring DM Web Bundle
Bundle-SymbolicName: org.simple.web
Import-Bundle: com.springsource.javax.servlet
 ,com.springsource.javax.servlet.jsp
 ,com.springsource.org.apache.taglibs.standard
 ,org.springframework.core
 ,org.springframework.beans
 ,org.springframework.context
 ,org.springframework.context.support
 ,org.springframework.web
 ,org.springframework.web.servlet
Module-Type: Web
Web-ContextPath: simple
Web-DispatcherServletUrlPatterns: *.htm
The SpringSource dm Server Tool automatically sets up Bundle Dependencies.
4. Copy spring config files from PetClinic sample project. Create folder src/main/resources/META-INF/spring, and copy module-context.xml, osgi-context.xml.

5. Follow Craig Walls "Spring In Action" Second Edition Chapter 13 Handling wweb request, to create a simple Spring MVC Web application, but using new SpringSource dm Server OSGi-centric web application directory structure.

Create folder "src/main/resources/MODULE-INF", this is the folder for all the web content.

Add index.html to MODULE-INF folder:
<html>
<head>
  <meta http-equiv="Refresh" content="0; URL=home.htm">
</head>
</html>
The index.html redirects to home page "home.htm"

Add a very simple jsp file for the home page, just display welcome messag and list all members from backend:
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html
 <head><title>Open Toast</title></head>
 
 <body>
  <h2>Welcome to Open Toast Project</h2>
  
  <h3>Current Members:</h3>
  <ul>
  <c:forEach items="${members}" var="member">
  <li><c:out value="${member.name}"/>
  </li>
  </c:forEach>
  </ul>
 </body>
</html>

And I have to change taglib uri to get rid of this exception:
org.apache.jasper.JasperException: /WEB-INF/jsp/home.jsp(11,2) According to TLD or attribute directive in tag file, attribute items does not accept any expressions

Add Spring MVC controller for home page:
src/main/java/org/simple/web/HomePageController.java
@Controller
@RequestMapping("/home.htm")
public class HomePageController{
  public HomePageController(){}

  @RequestMapping(method=RequestMethod.GET)
  public ModelAndView handleRequest(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    List members = new ArrayList();
    members.add(new Member("Yuan Ji"));
    return new ModelAndView("home", "members", members);
  }
}
src/main/java/org/simple/web/Member.java
public class Member {
  private String name;

  public Member(String name){
    this.name = name;
  }
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}
So when redirect to "/home.htm", it will map to HomePageController, and the return view is "home", which is mapped to WEB-INF/jsp/home.jsp

6. Add org.simple.web project to SpringSource dm Server, and start the server.

In Admin Console, you can see the deployed applications include org.simple.web. 

Click the link "/simple", open the simple web application.