Technical blog

September 5, 2010

Annotation based Spring MVC, how tos

Filed under: java, spring — Tags: , , — paawak @ 11:26

I will list here the common how to-s for the new Annotation based Spring MVC. Please note that I am using Spring version 3.0.0.RELEASE. This is a bit, only a small bit, different from the version 2.5.x. So, if you are using 2.5.x, you have to tweak things a bit before you get the same effect.

Consider the following screen:

samplehtml

The fantatstic thing about Spring MVC is it lets you take an Object Oriented approach while designing the Model (Form Bean) and lets you bind that seamlessly to the View (JSP Form).  For the above scenario, we can break down the top section into a list of rows. I would denote the row with a class having select, itemName, price… attributes, as shown below (this is an inner class in my ItemBean class, which is my Form Bean):

    public static class ItemRow {
 
        private boolean selected;
        private String itemName;
        private float price;
        private int quantity;
 
        ...
    }

Then, in my ItemBean class, I can have a List of ItemRow, as shown:

public class ItemBean {
 
    private List<ItemRow> items;
    private float totalPrice;
    private Date expectedDelivery;
...
}

How do I display/bind my Model to View?

This is how the View (Item.jsp) looks like:

                                           <c:forEach var="item" items="${command.items}" varStatus="count">
						<tr>
							<td>
								<form:checkbox id="chkSelect" path="items[${count.index}].selected" />
							</td>
							<td>
								<c:out value="${item.itemName}"/>
							</td>
							<td>
								<input id="txtUnitPrice" type="text" disabled="disabled" value="${item.price}" size="4"/>
							</td>
							<td>								
								<form:input id="txtQuantity" path="items[${count.index}].quantity" size="3" disabled="${!item.selected}"/>
							</td>
							<td>
								<input id="txtItemPrice" type="text" readonly="readonly" value="${item.price * item.quantity}" size="6"/>
							</td>
						</tr>
						</c:forEach>
                                                <tr>
							<td style="height:30px;">
							</td>
						</tr>
						<tr>
							<td colspan="3">
								Total Price:
							</td>
							<td>
								<form:input id="txtTotalPrice" path="totalPrice" readonly="true" size="6" />
							</td>
						</tr>

Especially note the

path=”items[${count.index}].selected”

in the form:checkbox tag. This is the key. It binds a particular index of the items in the ItemBean class to the JSP.

How to map a given url to my Controller method

After the introduction of Annotation @Controller, all Spring MVC controllers have become like MultiActionController, that is, you can handle multiple requests in the same controller. Mapping a url is very simple: you should annotate any public method with the @RequestMapping(”/DesiredUrl.do”). Of course, you should make sure:

1.> The class is annotated with @Controller
2.> The following line is present in the Spring context file:

<context:component-scan base-package="com.swayam.demo.web.controller" />

The method can have a motley combination of parameters and return type. Read the javadocs for details. This annotation takes an optional parameter method, which can be any enum RequestMethod type. If you do not specify anything, your method will handle all types of requests like GET, POST, DELETE, etc.

How do I pre-load or customise my Form Bean before it reaches my controller method?

In Spring MVC, the framework creates an instance of the Form Bean and binds it to the fields in JSP in case of a POST. In many cases, I would like to customise the Form Bean before it starts binding to the JSP fields. In older versions of Spring MVC, this was done by overriding the formBackingObject() method in AbstractFormController.
With annotations, you do it by specifying the @ModelAttribute before the FormBean attribute in the request handler method and then again on a public method returning the customised Form Bean as shown below:

    @RequestMapping(value = "/checkout.htm", method = RequestMethod.POST)
    public ModelAndView checkout(
            @ModelAttribute("postBean") ItemBean formBean,
            BindingResult errors) {
 
        ModelAndView model = new ModelAndView();
        model.addObject("command", formBean);
...
        return model;
 
    }
 
    @ModelAttribute("postBean")
    public ItemBean initBeanForPost() {
 
        ItemBean bean = new ItemBean();
        populateBean(bean, true);
        return bean;
 
    }

Note that its always a good practice to specify the name in the @ModelAttribute annotation. This way you can pre-load different beans for different methods. As shown in the example above, the name specified in the @ModelAttribute annotation in the request handler method checkout() and that in the method initBeanForPost() should be an exact match. By the way, this works for GET as well as POST or any other request type.

How do I do the validation?

Spring version 3.x onwards, doing validations have become very easy. I will describe this in the following few steps:

1. Write a Validator

Your validator should implement the Validator interface. It has two methods that you need to override. The supports() method makes sure that the Validator can validate a given FormBean. The validate() method does the actual job of validating. A typical Validator will look like this:

class ItemValidator implements Validator {
 
    @Override
    public void validate(Object target, Errors errors) {
 
        ItemBean bean = (ItemBean) target;
 
        if (bean.getTotalPrice() == 0) {
            errors.rejectValue("totalPrice", "noItemsSelected");
        }
 
    }
 
    @Override
    public boolean supports(Class<?> clazz) {
        return clazz == ItemBean.class;
    }
 
}

2. Set the Validator

You do this in a public method annotated with @InitBinder in the controller.

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest webRequest) {
 
        if (binder.getTarget() instanceof ItemBean) {
 
            binder.setValidator(new ItemValidator());
 
        }
 
    }

I am setting the validator inside the if (binder.getTarget() instanceof ItemBean) block as otherwise I get an ugly exception in case there are any validation errors. I am putting the stack trace below:


java.lang.IllegalStateException: Invalid target for Validator [com.swayam.demo.web.controller.ItemController$1@11e7cc6]: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object ‘postBean’ on field ‘totalPrice’: rejected value [0.0]; codes [noItemsSelected.postBean.totalPrice,noItemsSelected.totalPrice,noItemsSelected.float,noItemsSelected]; arguments []; default message [null]] with root cause
java.lang.IllegalStateException: Invalid target for Validator [com.swayam.demo.web.controller.ItemController$1@11e7cc6]: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object ‘postBean’ on field ‘totalPrice’: rejected value [0.0]; codes [noItemsSelected.postBean.totalPrice,noItemsSelected.totalPrice,noItemsSelected.float,noItemsSelected]; arguments []; default message [null]
at org.springframework.validation.DataBinder.setValidator(DataBinder.java:472)
at com.swayam.demo.web.controller.ItemController.initBinder(ItemController.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.initBinder(HandlerMethodInvoker.java:329)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.updateModelAttributes(HandlerMethodInvoker.java:691)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:417)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)

3. Use @Valid before the Form Bean

This is a new feature added in release 3.x. Now the validation happens with JSR-303 Bean Validation API. You can find the jar here. If you are using Maven, you can add the following dependency:

		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

This is how you use it:

    @RequestMapping(value = "/checkout.htm", method = RequestMethod.POST)
    public ModelAndView checkout(
            @Valid ItemBean formBean,
            BindingResult errors) {
 
        ModelAndView model = new ModelAndView();
...
        return model;
 
    }

The Form Bean is validated with the set Validator by the framework. Note that for Spring 2.5.x, you need to make the call to validator manually inside the handler method:

...
        Validator validator = new ItemValidator();
        validator.validate(formBean, errors);    
...

In my Validator, how do I use messages from properties file for i18n?

Lets say, my properties file is Messages.properties located at /com/swayam/demo/web/res/. The contents are:

noItemsSelected=You have not selected any items

I have to create an instance of MessageSource in my Spring conf file as shown:

	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>com.swayam.demo.web.res.Messages</value>
			</list>
		</property>
	</bean>

Now I can use the property key in my validate() method as shown:

    @Override
    public void validate(Object target, Errors errors) {
 
        ItemBean bean = (ItemBean) target;
 
        if (bean.getTotalPrice() == 0) {
            errors.rejectValue("totalPrice", "noItemsSelected");
        }
 
    }

How to display the Validation messages on my JSP?

First, from the controller, you have to pass an instance of BindingResult to the JSP.

    @RequestMapping(value = "/checkout.htm", method = RequestMethod.POST)
    public ModelAndView checkout(
            @Valid ItemBean formBean,
            BindingResult errors) {
 
        ModelAndView model = new ModelAndView();
        model.addObject("command", formBean);
 
        if (errors.hasErrors()) {
            model.setViewName("Item");
            model.addObject("errors", errors);
        } else {
            model.setViewName("Checkout");
        }
 
        return model;
 
    }

And this is how the JSP looks like:

		<c:if test="${ not empty errors.allErrors }"> 
		<div style="text-align:center; color:red;">
			<ul>
				<c:forEach var="error" items="${errors.allErrors}">
					<li><spring:message code="${error.code}"  text="${error.defaultMessage}"/></li>
				</c:forEach>
			</ul>
		</div>
		</c:if>

How do I bind a complex object to my JSP form field?

Often we have to display a complex object as text. The best example I can take is that of a Date. Its a java.util.Date in the model. How do I map this to a text field in my JSP? You have to extend the PropertyEditorSupport and override the following methods:
1. getAsText(): Converts an Object to its String representation. Used for displaying a model object in the JSP.
2. setAsText(String text): Converts the text from the input field to the complex object that the model understands.
A typical implementation would look like this:

class DateEditorSupport extends PropertyEditorSupport {
 
    private static final Logger LOG = Logger.getLogger(DateEditorSupport.class);
 
    private final Format formatter;
 
    DateEditorSupport(String dateFormat) {
        formatter = new SimpleDateFormat(dateFormat);
    }
 
    public String getAsText() {
 
        String date = null;
 
        Object value = getValue();
 
        if (value instanceof Date) {
 
            date = formatter.format(value);
 
        } else {
            throw new java.lang.IllegalArgumentException("Expecting a "
                    + Date.class.getName() + " class, got "
                    + value.getClass().getName());
        }
 
        return date;
 
    }
 
    public void setAsText(String text) {
 
        try {
 
            Date date = (Date) formatter.parseObject(text);
            setValue(date);
 
        } catch (ParseException e) {
            LOG.fatal("error setting date for String: " + text, e);
        }
 
    }
 
}

Then, in the @InitBinder method, you need to register this against the class:

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest webRequest) {
 
        binder.registerCustomEditor(Date.class, new DateEditorSupport(
                "dd/MM/yyyy"));
 
    }

Putting it all together

You will find the sources here. Its an Eclipse project, using Maven. In order to get all the libraries, install Maven and run:
mvn eclipse:clean eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true -Dwtpversion=2.0
You can also run the war file directly and go to http://localhost:8080/SpringMVC/ to see it in action.

August 28, 2010

[How To] Convert a Maven Project to Eclipse Web Project

Filed under: java — Tags: — paawak @ 12:18

Eclipse WTP has this nice feature where it allows you to deploy, run and debug Web Applications from the IDE. You start by going to the Server View, adding the target server (like Apache Tomcat in our case) and then adding the Web Project to the server. This is how the view looks like:

addremovewebprojects_1

But I have often faced this problem: when I run mvn eclipse:eclipse on a Maven Web Project to convert it to an Eclipse project, it is not recognised as a Web Project by Eclipse. When I right-click on the server and select Add Remove Projects, it does not appear in the option box. But to me  mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true is indispensable as it downloads and links all the sources and JavaDocs, which comes very handy. On the other hand if I cannot add my project as a Web Project in Eclipse, running and debugging becomes a big issue. So how do I reconcile these two?

Solution 1: Specify the WTP Version

While running mvn eclipse:eclipse, specify the WTP Version by passing the -Dwtpversion=2.0 argument. The command looks like:

mvn eclipse:clean eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true -Dwtpversion=2.0

Note that as of this writing, the supported versions of WTP are  1.0, 1.5, 2.0 and R7.

Solution 2: Convert it to a Facted Project

Right click on the project, go to Properties, then select Project Facets.

converttofacetedproject

Another dialog appears having the available facets.

selectdynamicwebproject

Select Dynamic Web Module.

Solution 3: Manual editing

I like this best as it gives lot of flexibility around configuration. First you need to modify the .project file as shown:

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>MyWebProject</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
			<arguments>
			</arguments>
		</buildCommand>
		<buildCommand>
			<name>org.eclipse.jdt.core.javabuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
		<buildCommand>
			<name>org.eclipse.wst.common.project.facet.core.builder</name>
			<arguments>
			</arguments>
		</buildCommand>
		<buildCommand>
			<name>org.eclipse.wst.validation.validationbuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
		<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
		<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
		<nature>org.eclipse.jdt.core.javanature</nature>
		<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
	</natures>
</projectDescription>

Then, inside the .settings directory, you need to create two files called org.eclipse.wst.common.component and org.eclipse.wst.common.project.facet.core.xml.

org.eclipse.wst.common.component

<?xml version="1.0" encoding="UTF-8"?>
<project-modules id="moduleCoreId" project-version="1.5.0">
    <wb-module deploy-name="MyWebProject">
        <wb-resource deploy-path="/" source-path="/src/main/webapp"/>
        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
        <property name="context-root" value="MyWebProject"/>
        <property name="java-output-path" value="/MyWebProject/build/classes"/>
    </wb-module>
</project-modules>

org.eclipse.wst.common.project.facet.core.xml

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="Apache Tomcat v7.0"/>
  <fixed facet="jst.web"/>
  <fixed facet="wst.jsdt.web"/>
  <fixed facet="java"/>
  <installed facet="java" version="1.6"/>
  <installed facet="jst.web" version="3.0"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

August 22, 2010

Creating an EAR with Maven

Filed under: java — Tags: , — paawak @ 00:50

Maven is the build tool of choice for many people due to the simplicity and flexibility of use. The real strength of Maven is vetted when handling real complex projetcs consisting of tens of modules, each requiring elaborate build requirements.

I had faced an uphill task of Mavenising one of our EAR projects. As is the typical case, our project consisted of a EJB module and a WAR module, package together in a EAR module. It was a bit complex as we had to deploy the same application in JBoss and Glassfish. I will write some of that experience here.

Let us consider an enterprise application having a structure as show below:

Project Structure

I will briefly explain what the modules stand for:

  1. swayam-ear: This is the enterprise application
  2. swayam-ejb: Is the EJB module
  3. swayam-war: Is the web module
  4. swayam-shared: Has the ejb remote interfaces. As the name indicates, its shared by the sawaym-ejb and the swayam-war modules
  5. swayam-ear-builder: Used for building all the modules

I am using Netbeans (6.8) and Glassfish for convinience. But you can pretty much use anything.

I have kept things pretty simple. This is how the Remote interface looks like (its a Stateless Session Bean):

@Remote
public interface MySessionBeanRemote {
 
    String sayHello();
 
}

And this is how I access it from the servlet:

...
MySessionBeanRemote remoteBean = InitialContext.doLookup(MySessionBeanRemote.class.getName());
...

Mavenising the EJB

We will use the maven-ejb-plugin for this. This is how the pom looks like:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.swayam.eardemo</groupId>
    <artifactId>swayam-ejb</artifactId>
    <version>1.0.0</version>
 
    <packaging>ejb</packaging>
    <name>swayam-ejb</name>
 
    <build>
        <sourceDirectory>${basedir}/src</sourceDirectory>
 
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-ejb-plugin</artifactId>
                <configuration>
                    <ejbVersion>3.0</ejbVersion>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
 
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.swayam.eardemo</groupId>
            <artifactId>swayam-shared</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
 
</project>

Note that the packaging is ejb and not jar.

Mavenising the WAR

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.swayam.eardemo</groupId>
    <artifactId>swayam-war</artifactId>
    <version>1.0.0</version>
 
    <packaging>war</packaging>
    <name>swayam-war</name>
 
    <pluginRepositories>
        <pluginRepository>
            <id>maven.java.net</id>
            <name>Java.net Maven2 Repository</name>
            <url>http://download.java.net/maven/2</url>
        </pluginRepository>
    </pluginRepositories>
 
    <build>
        <finalName>swayam-war</finalName>
        <sourceDirectory>${basedir}/src/java</sourceDirectory>
 
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${basedir}/web</directory>
                            <excludes>
                                <exclude>CVS/**</exclude>
                                <exclude>WEB-INF/lib/*</exclude>
                            </excludes>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <dependencies>
        <dependency>
            <groupId>com.swayam.eardemo</groupId>
            <artifactId>swayam-shared</artifactId>
            <version>1.0.0</version>
        </dependency>                
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>    
 
</project>

Mavenising the EAR

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.swayam.eardemo</groupId>
    <artifactId>swayam-ear</artifactId>
    <version>1.0.0</version>
 
    <packaging>ear</packaging>
    <name>swayam-ear</name>
 
    <pluginRepositories>
        <pluginRepository>
            <id>maven.java.net</id>
            <name>Java.net Maven2 Repository</name>
            <url>http://download.java.net/maven/2</url>
        </pluginRepository>
    </pluginRepositories>
 
    <build>
        <finalName>swayam-ear</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <modules>
                        <webModule>
                            <groupId>com.swayam.eardemo</groupId>
                            <artifactId>swayam-war</artifactId>
                            <bundleFileName>swayam-war.war</bundleFileName>
                            <contextRoot>/swayam-war</contextRoot>
                        </webModule>
                        <ejbModule>
                            <groupId>com.swayam.eardemo</groupId>
                            <artifactId>swayam-ejb</artifactId>
                            <bundleFileName>swayam-ejb.jar</bundleFileName>
                        </ejbModule>
                    </modules>
                </configuration>
            </plugin>
 
        </plugins>
    </build>
 
    <dependencies>
        <dependency>
            <groupId>com.swayam.eardemo</groupId>
            <artifactId>swayam-war</artifactId>
            <version>${swayam-version}</version>
            <type>war</type>
        </dependency>
        <dependency>
            <groupId>com.swayam.eardemo</groupId>
            <artifactId>swayam-ejb</artifactId>
            <version>${swayam-version}</version>
            <type>ejb</type>
        </dependency>
    </dependencies>
 
    <properties>
        <swayam-version>1.0.0</swayam-version>
    </properties>
 
</project>

The most important thing here is the type tag inside the dependency tag. Without this, it will not work.

Putting it all together

Its often very cumbersome to build these modules one by one manually when one of them changes. This is more so in a development environment. So, I will conclude with one pom for building all the modules at one go. This pom is present in the swayam-ear-builder module.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.swayam.eardemo</groupId>
  <artifactId>swayam-ear-builder</artifactId>
  <packaging>pom</packaging>
  <version>1.0.0</version>
  <name>swayam-ear-builder</name>
 
  <modules>
    <module>../swayam-ear</module>
    <module>../swayam-ejb</module>
    <module>../swayam-war</module>
    <module>../swayam-shared</module>
  </modules>
 
</project>

Note that the path of the modules are relative to the pom.
You can build the EAR project and deploy it on Glassfish or JBoss. Once successfully deployed, you can open http://localhost:8080/swayam-war/EjbInvoker This is how it looks like:

screenshot-servlet-ejbinvoker-google-chrome

Resources

  1. Sources
  2. Binaries

August 21, 2010

[How To] Configure GTalk on Kopete

Filed under: linux — Tags: , — paawak @ 01:10

Kopete is one of the most versatile and cool Instant Messenger for Linux. Its lot better and more secure and feature rich than Pidgin. GTalk is based on the open source XMPP Protocol, Jabber compatible.

While entering the new account details, select Jabber:

Select type as "Jabber"

Enter your full email id.

Go to the connection tab. Check the Override default server information check-box and enter the server as talk.google.com, the port as 5223. Also check these check boxes:

  1. Use protocol encryption

  2. Allow plain text password authentication

Connection details

Save this information and you should be done.

Tweaking MySQL on Fedora

Filed under: database, linux — Tags: , — paawak @ 00:57

MySQL is installed on Fedora and most Linuxes by default. Its just about some tweaking before you can use it. I am detailing some of the rather useful commands.

To Install MySQL and start it

mysql_install_db
mysqld_safe &

Make MySQL case insensitive

This is useful when the DB Script is also expected to run on Windows server.

vi /etc/my.cnf

[mysqld]
lower_case_table_names=1

To change the root password

mysql>

update user set password=password(”newPassword”)  where user=’root’;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

grant all on *.* to ‘root’@'192.168.%’ identified by ‘newPassword’;

FLUSH PRIVILEGES;

Adding a user

mysql>

insert into user (host, user, password) values(’localhost’,'newUser’,password(’xx123′));

insert into  host(host,db,Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv)  values(’localhost’,'dbName’,'Y’,'Y’,'Y’,'Y’,'Y’,'Y’);

grant all on dbName.* to ‘newUser’@'localhost’ identified by ‘xx123′;

FLUSH PRIVILEGES;

[How To] Enable VPN on Linux by PPTP

Filed under: linux — Tags: , , — paawak @ 00:41

PPTP is an wonderful utility to enable VPN on a Linux box. Its secure and compatible with Windows network. I first heard about PPTP from (this wonderful guy called) Nikolaj. I have learnt how to set it up from him.

I am detailing the steps here:

1> Install PPTP

yum install pptp

2> vi /etc/ppp/options.pptp

###############################################################################

# $Id: options.pptp,v 1.2 2005/08/20 13:16:38 quozl Exp $

#

# Sample PPTP PPP options file /etc/ppp/options.pptp

# Options used by PPP when a connection is made by a PPTP client.

# This file can be referred to by an /etc/ppp/peers file for the tunnel.

# Changes are effective on the next connection. See “man pppd”.

#

# You are expected to change this file to suit your system. As

# packaged, it requires PPP 2.4.2 or later from http://ppp.samba.org/

# and the kernel MPPE module available from the CVS repository also on

# http://ppp.samba.org/, which is packaged for DKMS as kernel_ppp_mppe.

###############################################################################


# Lock the port

lock

# Authentication

# We don’t need the tunnel server to authenticate itself

noauth

persist

debug

# We won’t do EAP, CHAP, or MSCHAP, but we will accept MSCHAP-V2

refuse-eap

refuse-chap

refuse-mschap


# Compression

# Turn off compression protocols we know won’t be used

nobsdcomp

nodeflate


# Encryption

# (There have been multiple versions of PPP with encryption support,

# choose with of the following sections you will use. Note that MPPE

# requires the use of MSCHAP-V2 during authentication)


# http://ppp.samba.org/ the PPP project version of PPP by Paul Mackarras

# ppp-2.4.2 or later with MPPE only, kernel module ppp_mppe.o

# {{{

# Require MPPE 128-bit encryption

#require-mppe-128

# }}}


# http://polbox.com/h/hs001/ fork from PPP project by Jan Dubiec

# ppp-2.4.2 or later with MPPE and MPPC, kernel module ppp_mppe_mppc.o

# {{{

# Require MPPE 128-bit encryption

#mppe required,stateless

# }}}


lcp-echo-failure 36

lcp-echo-interval 5

lcp-max-failure 0

3> vi /etc/ppp/chap-secrets

# Secrets for authentication using CHAP

# client                  server        secret                        IP addresses


VPNUserName      PPTP       VPNPassword         *

4> Create a file called /etc/ppp/peers/my-company-vpn

#pty “pptp my-company.com –nolaunchpppd”

name VPNUserName

remotename PPTP

require-mppe-128

file /etc/ppp/options.pptp

ipparam my-company-vpn

5> Then on the prompt:

pptp my-company.com call my-company-vpn

6> After 10/15 seconds, on the prompt:

route -n

You should see something like:

Kernel IP routing table

Destination Gateway Genmask Flags Metric Ref Use Iface

192.168.1.162 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0

87.61.21.102 192.168.1.1 255.255.255.255 UGH 0 0 0 eth0

192.168.1.0 0.0.0.0 255.255.255.0 U 1 0 0 eth0

If you see ppp0, it means you have successfully connected to the VPN.

7> Add required routes

route add -host 192.168.1.30 gw 192.168.1.162

Where 192.168.1.30 is my internal company IP.

8> After that, to resolve the domains by names

vi /etc/resolv.conf

#to use when connected to the VPN my-company.com

domain my-office.my-company.com

#this, is the most important line: courtesy: Nikolaj

search my-office.my-company.com

#nameserver 192.168.1.1

nameserver 192.168.1.4

nameserver 192.168.1.5

Further reading:

[How To] Rip VCD on Linux

Filed under: linux — Tags: , — paawak @ 00:03

I have always had problems while playing VCDs on my Linux machine. The VCD file system is still not supported by the Linux kernel. But all is not lost. We have an utility called vcdxrip. This is the command:

vcdxrip -i /dev/sr0 -v -p -t 1 –nofiles –nosegments

Here i denotes the mount point of the CDROM drive,  t denotes the Track Number. This way, a VCD can be ripped from a Linux machine. I have tested this on Fedora (10) and it works great.

May 20, 2010

Playing mp3 on Fedora

Filed under: linux — Tags: , — paawak @ 00:07

By default, the codecs to play mp3/mp4 are not included due to licensing issues. First you need to add the non-standard repositories:

rpm -ivh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm
rpm -ivh http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm
rpm –import /etc/pki/rpm-gpg/RPM-GPG-KEY-rpmfusion-*

That done, if you just double click on a mp3 file (starting Fedora 8 onwards), it will pop-up a dialogue saying that you must install missing codecs.  Click on yes and go along.

You can also explicitly install them like this:

yum install gstreamer-plugins-ugly gstreamer-plugins-bad gstreamer-ffmpeg

Further reading:

May 19, 2010

[JBoss/Maven] org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new SAX parser

Filed under: java — Tags: , — paawak @ 01:09

Sometimes when using spring framework or apache commons libraries on JBoss server [JBoss - 5.1.0], when it is built by maven, you get the following exception:

org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new SAX
parser
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:100)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.processContextConfig(JBossContextConfig.java:549)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.init(JBossContextConfig.java:536)
at
org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:279)
at
org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at
org.apache.catalina.core.StandardContext.init(StandardContext.java:5436)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:4148)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
at
org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at
org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at $Proxy38.start(Unknown Source)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at
org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at
org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at
org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at
org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at
org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at
org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
at
org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1210)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
at
org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
at
org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at
org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
at
org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:361)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.activateProfile(AbstractProfileService.java:306)
at
org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:271)
at
org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
at org.jboss.Main.boot(Main.java:221)
at org.jboss.Main$1.run(Main.java:556)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.jboss.xb.binding.JBossXBException: Failed to create a new
SAX parser
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:97)
at
org.jboss.xb.binding.UnmarshallerImpl.(UnmarshallerImpl.java:56)
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:96)
… 74 more
Caused by: java.lang.ClassCastException:
org.apache.xerces.parsers.StandardParserConfiguration cannot be cast to
org.apache.xerces.xni.parser.XMLParserConfiguration
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.(Unknown
Source)
at org.apache.xerces.jaxp.SAXParserImpl.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserFactoryImpl.newSAXParser(Unknown
Source)
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:92)
… 76 more
2010-05-18 14:04:41,262 ERROR
[org.jboss.web.tomcat.service.deployers.JBossContextConfig] (main) XML
error parsing: jboss.web/localhost/context.xml.default
org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new SAX
parser
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:100)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.processContextConfig(JBossContextConfig.java:549)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.init(JBossContextConfig.java:537)
at
org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:279)
at
org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at
org.apache.catalina.core.StandardContext.init(StandardContext.java:5436)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:4148)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
at
org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at
org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at $Proxy38.start(Unknown Source)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at
org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at
org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at
org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at
org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at
org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at
org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
at
org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1210)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
at
org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
at
org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at
org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
at
org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:361)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.activateProfile(AbstractProfileService.java:306)
at
org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:271)
at
org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
at org.jboss.Main.boot(Main.java:221)
at org.jboss.Main$1.run(Main.java:556)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.jboss.xb.binding.JBossXBException: Failed to create a new
SAX parser
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:97)
at
org.jboss.xb.binding.UnmarshallerImpl.(UnmarshallerImpl.java:56)
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:96)
… 74 more
Caused by: java.lang.ClassCastException:
org.apache.xerces.parsers.StandardParserConfiguration cannot be cast to
org.apache.xerces.xni.parser.XMLParserConfiguration
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.(Unknown
Source)
at org.apache.xerces.jaxp.SAXParserImpl.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserFactoryImpl.newSAXParser(Unknown
Source)
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:92)
… 76 more
2010-05-18 14:04:41,272 ERROR
[org.jboss.web.tomcat.service.deployers.JBossContextConfig] (main) XML
error parsing: WEB-INF/context.xml
org.jboss.xb.binding.JBossXBRuntimeException: Failed to create a new SAX
parser
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:100)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.processContextConfig(JBossContextConfig.java:549)
at
org.jboss.web.tomcat.service.deployers.JBossContextConfig.init(JBossContextConfig.java:540)
at
org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:279)
at
org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at
org.apache.catalina.core.StandardContext.init(StandardContext.java:5436)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:4148)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
at
org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
at
org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at
org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at $Proxy38.start(Unknown Source)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at
org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at
org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at
org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at
org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at
org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at
org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at
org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at
org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
at
org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1210)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
at
org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
at
org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at
org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
at
org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:361)
at
org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at
org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at
org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at
org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at
org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at
org.jboss.system.server.profileservice.repository.AbstractProfileService.activateProfile(AbstractProfileService.java:306)
at
org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:271)
at
org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
at org.jboss.Main.boot(Main.java:221)
at org.jboss.Main$1.run(Main.java:556)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.jboss.xb.binding.JBossXBException: Failed to create a new
SAX parser
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:97)
at
org.jboss.xb.binding.UnmarshallerImpl.(UnmarshallerImpl.java:56)
at org.jboss.xb.binding.UnmarshallerFactory
$UnmarshallerFactoryImpl.newUnmarshaller(UnmarshallerFactory.java:96)
… 74 more
Caused by: java.lang.ClassCastException:
org.apache.xerces.parsers.StandardParserConfiguration cannot be cast to
org.apache.xerces.xni.parser.XMLParserConfiguration
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.parsers.SAXParser.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.(Unknown
Source)
at org.apache.xerces.jaxp.SAXParserImpl.(Unknown Source)
at org.apache.xerces.jaxp.SAXParserFactoryImpl.newSAXParser(Unknown
Source)
at
org.jboss.xb.binding.parser.sax.SaxJBossXBParser.(SaxJBossXBParser.java:92)
… 76 more

This is caused by the presence of the xml-apis.jar and xerces-impl.jar.

Solution:

In the pom.xml, exclude these two jars in the dependency. Example:

 
<dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.2.1</version>
        <exclusions>
                <exclusion>
                    <groupId>xml-apis</groupId>
                    <artifactId>xml-apis</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>xerces</groupId>
                    <artifactId>xerces</artifactId>
                </exclusion>
        </exclusions>
</dependency>

May 8, 2010

JAX-WS with JBoss

Filed under: java — Tags: , , , — paawak @ 18:39

JBoss supports JAX-WS out of the box. There is not much configuration files needed, only a servlet-mapping in the web.xml. This is how the web-service java file looks like:

 
package com.swayam.demo.webservice;
 
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
 
/**
 *
 * @author paawak
 */
@WebService()
public class UserService {
 
    /**
     * Web service operation
     */
    @WebMethod(operationName = "addUser")
    public Boolean addUser(@WebParam(name = "userName")
    String userName) {
 
        System.out.println("add user");
 
        return Boolean.TRUE;
 
    }
 
}

Its a POJO with a @WebService annotation. All you have to do is map this as a servlet in the desired context. Though this is not a servlet per-se, the JBoss web container does the rest. This is how the web.xml looks like:

 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
    <servlet>
        <servlet-name>UserService</servlet-name>
        <servlet-class>com.swayam.demo.webservice.UserService</servlet-class>
        <load-on-startup>1</load-on-startup>
        </servlet>
    <servlet-mapping>
        <servlet-name>UserService</servlet-name>
        <url-pattern>/UserService</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

After deploying, you can access the webservice by http://localhost:8080/JBossWebServiceTest/UserService?wsdl.

You can find the sources here and the war here.

Older Posts »

Powered by WordPress