Showing posts with label Maven. Show all posts
Showing posts with label Maven. Show all posts

Wednesday, October 8, 2014

Jython - Calling Python from Java

Let's say you do most of your development in Java, however, there is some existing Python code you need to reuse. In this post, I'll show you how to use Jython to call Python from Java.

Write a Java wrapper class:
public class JythonDemo {

    public int testMe(int num1, int num2) {
        PythonInterpreter python = new PythonInterpreter();

        python.set("num1", num1);
        python.set("num2", num2);
        python.exec("num3 = num1 + num2");
        PyObject num3 = python.get("num3");

        return Integer.parseInt(num3.toString());

    }
}

If using Maven, here is your pom.xml:
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.noushin</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo</description>

    <dependencies>
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.5.2</version>
        </dependency>
    </dependencies>

</project>
Just call testMe(), and that'll run your Python code:
JythonDemo jythonDemo = new JythonDemo();
int result = jythonDemo.testMe();


Wednesday, April 23, 2014

Spring & Hive

Getting Spring & Hive integration working wasn't a breeze, but I got it. Here is what I had to do:

First, a typical BookRepository class:
package com.noushin.spring.ht.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hive.HiveTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * This class handles accessing books in Hadoop using Hive.
 * 
 * @author nbashir
 * 
 */
@Repository
public class BookRepositroy {

   @Autowired
   private HiveTemplate hiveTemplate;

   public void showTables() {
      List<String> tables = hiveTemplate.query("show tables;");
      System.out.println("tables size: " + tables.size());
   }

   public Long count() {
      return hiveTemplate.queryForLong("select count(*) from books;");
   }
}
Next a typical Service layer class:
package com.noushin.spring.ht.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.noushin.spring.ht.dao.BookRepositroy;

/**
 * This class handles any business logic related to handling books.
 * 
 * @author nbashir
 *
 */
@Component
public class BookService {

   @Autowired 
   BookRepositroy bookRepo;
   
   public Long count() {
      return bookRepo.count();
   }

   public void showTables() {
      bookRepo.showTables();
   }
 }

Here is the pom file you need:
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.noushin.spring</groupId>
    <artifactId>ht</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>ht</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.hadoop.version>1.0.2.RELEASE</spring.hadoop.version>
        <hadoop.version>1.2.1</hadoop.version>
        <hive.version>0.10.0</hive.version>
        <spring.version>4.0.3.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring Data -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop</artifactId>
            <version>${spring.hadoop.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>${hadoop.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-builtins</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>
        
    </dependencies>
    
</project>

You application-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:context="http://www.springframework.org/schema/context"
    xmlns:hdp="http://www.springframework.org/schema/hadoop" xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">

    <context:property-placeholder location="hive.properties" />

    <!-- Activate annotation configured components -->
    <context:annotation-config />

    <!-- Scan components for annotations within the configured package -->
    <context:component-scan base-package="com.noushin.spring.ht" />

    <hdp:hive-client-factory id="hiveClientFactory"
        host="${hive.host}" port="${hive.port}">
        <hdp:script>
            ADD JARS /usr/lib/hive/lib/books.jar;
        </hdp:script>
    </hdp:hive-client-factory>

    <hdp:hive-template id="hiveTemplate" />

</beans>


Your hive.properties:
hive.host=your-hive-server
hive.port=10000
hive.url=jdbc:hive://${hive.host}:${hive.port}/default

And finally a main class to start and run your app:
package com.noushin.spring.ht;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.noushin.spring.ht.service.BookService;

/**
 * Main class to demonstrate accessing MongoDB with Spring Data and MongoTemplate.
 * 
 * @author nbashir
 *
 */
public class HadoopMain {

   public static void main(String[] args) {
      try {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
         if (ctx != null) {
            BookService service = ctx.getBean(BookService.class);
            service.showTables();
            Long count = service.count();
            System.out.println("result  : " + count);        
         }
      }
      catch (Exception ex) {
         System.out.println("HadoopMain encountered an error and ended.");
      }
   }
}

Monday, January 14, 2013

Spring 3 & JMS

Here is a quick way to develop a simple application using Jms.  You will need the following components:

  • Apache ActiveMQ
  • Spring
  • Java
  • Maven
 
Install ActiveMQ on Ubuntu. The latest download bundle is available at ActiveMQ download page.

Example (Running ActiveMQ 5.7.0 on Ubuntu):

1. Download apache-activemq-5.7.0-bin.tar.gz.

2. Untar the bundle:

tar zxvf apache-activemq-5.7.0-bin.tar.gz

3. Configure and start Activemq

cd apache-activemq-5.7.0
bin/activemq setup newConfig
bin/activemq start

4. Verify Activemq is running:

netstat -an |grep 61616
or
Go to Admin console by visiting http://localhost:8161/admin/

5. Create a basic Jms queue for testing:

Use Admin console.
Select Queues
Create a new queue called TestQ.

Once you have created a Jms queue, you need to write classes to produce and consume messages that are transmitted via the newly created queue.

We will utilize Spring to transmit messages over JMS queues. Since this type of delivery is point to point, you need message producers at one end and message consumers at the other end.

JMS Message Producer

1. Create a context file called: ~/workspace/jms/src/main/resources/application-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.noushin.spring.jms" />
    <context:annotation-config />

    <!-- ActiveMQ destinations to use -->
    <amq:queue id="destination" physicalName="TestQ" />
    
    <!-- ActiveMQ broker URL -->
    <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:61616" />

    <!-- Spring JMS ConnectionFactory -->
    <bean id="singleConnectionFactory" 
          class="org.springframework.jms.connection.SingleConnectionFactory"
          p:targetConnectionFactory-ref="jmsFactory"/>
    
    <!-- Spring JMS Producer Configuration -->
    <bean id="jmsProducerTemplate" class="org.springframework.jms.core.JmsTemplate"
        p:connectionFactory-ref="singleConnectionFactory"
        p:defaultDestination-ref="destination"/>
        
</beans>


2. Create a class that produces messages and sends them over Jms. Lets call it MessageProducer.
package com.noushin.spring.jms.producer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {

   final static Logger logger = Logger.getLogger(MessageProducer.class);

   @Autowired
   private JmsTemplate jmsTemplate;

   public void produce() throws Exception {
      
      if (jmsTemplate != null) {
         MessageCreator mc = new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
               try {
                  TextMessage message = session.createTextMessage("This is a message.");
                  return message;
               } 
                catch (JMSException je) {
                  logger.error("JMS Exception : ", je);
                  return null;
               }
            }
         };
         jmsTemplate.send(mc);
      }
   }
}

3. Here is the pom.xml to successfully run this example
<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/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.noushin.spring</groupId>
    <artifactId>jms</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>jms</name>
    <url>http://maven.apache.org</url>

    <properties>
        <activemq.version>5.2.0</activemq.version>
        <junit.version>4.10</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.2.0.RELEASE</spring.version>
    </properties>

    <repositories>
        <repository>
            <id>springsource-repo</id>
            <name>SpringSource Repository</name>
            <url>http://repo.springsource.org/release</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
                <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
            <version>${activemq.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-optional</artifactId>
            <version>${activemq.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean-spring</artifactId>
            <version>3.7</version>
        </dependency>
    </dependencies>
</project>

4. After running MessageProducer.main, you should see a message added to TestQ queue.

5. Use ActiveMQ admin console to verify the above steps: http://localhost:8161/admin/queues.jsp

JMS Message Consumer

Now we need to write a class that consumes the messages in the queue waiting to be processed. In this example, I will create a second project.

1.   Create a context file called: ~/workspace/jmsc/src/main/resources/application-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jms="http://www.springframework.org/schema/jms" 
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">

    <context:component-scan base-package="com.noushin.spring.jms" />
    <context:annotation-config />

    <!-- ActiveMQ destinations to use -->
    <amq:queue id="destination" physicalName="TestQ" />

    <!-- ActiveMQ broker -->
    <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:61616" />

   <!-- JMS Consumer Configuration -->
    <bean id="jmsConsumerConnectionFactory" 
          class="org.springframework.jms.connection.SingleConnectionFactory"
          p:targetConnectionFactory-ref="jmsFactory" />
        
    <jms:listener-container container-type="default" 
                            connection-factory="jmsConsumerConnectionFactory"
                            acknowledge="auto">
        <jms:listener destination="TestQ" ref="messageConsumer" />
    </jms:listener-container>

</beans>

2.  Create a class that consumes messages as they arrive on the queue. Let's call it MessageConsumer.
package com.noushin.spring.jms.consumer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumer implements MessageListener {

   final static Logger logger = Logger.getLogger(MessageConsumer.class);

   private int numOfMessages = 0;

   public void onMessage(Message message) {
      try {
         numOfMessages++;
         if (message instanceof TextMessage) {
            TextMessage tm = (TextMessage) message;
            String msg = tm.getText();
            logger.info(">>>>>Processed message: " + msg + " - numOfMessages : " + numOfMessages);
         }
      } catch (JMSException e) {
         logger.error(e.getMessage(), e);
      }
   }
}

3. You can use the same pom file you used for MessageProducer. Make sure to change your project name in the pom file.

4. To test your app, write a JUnit
package com.noushin.spring.jmsc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest {

   @Test 
   public void testApp() {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
    }
}

5. As soon as application context is initialized, go to ActiveMQ admin console and notice the messages you produced in the first project are now removed from the queue. You should also see messages logging the results of executing onMessage method in MessageConsumer class.
2013-01-10 11:50:24,365 [org.springframework.jms.listener.DefaultMessageListenerContainer#0-1] INFO  com.noushin.spring.jms.consumer.MessageConsumer - Processed message: this is a test. - numOfMessages : 2

6. That's all folks. Have fun with Jms :)

Saturday, January 12, 2013

Spring & Testing

I think unit testing Spring components is really cool. You can have a separate application context just for testing purposes, which will not conflict with your application's runtime context when developing.

Here is a couple of steps you need to take to test your components using Spring testing.

1. Add the following dependency to your pom file:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>org.springframework.test</artifactId>
    <version>${spring.version}</version>
    <scope>test</scope>
</dependency>
where
    <spring.version>3.2.0.RELEASE</spring.version>

2. In your test/resources folder, your need to a create a package matching the your Test class, and create a context file with a name that matches your Test class name.

Here is an example:

Lets say you are testing a class called MessageProducer.
package com.noushin.spring.jms.producer;

import java.io.IOException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {

   final static Logger logger = Logger.getLogger(MessageProducer.class);

   @Autowired
   private JmsTemplate jmsTemplate;

   public void produce() throws Exception {
      
      if (jmsTemplate != null) {
         MessageCreator mc = new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
               try {
                  String jmsMessage = FileUtils.readFileToString(FileUtils.toFile(this.getClass().getResource("/jms-message.txt")));
                  TextMessage message = session.createTextMessage(jmsMessage);
                  logger.info(">>>>>Sending message: " + jmsMessage);
                  return message;
               } 
               catch (IOException ioe) {
                  logger.error("File not found : ", ioe);
                  return null;
               }
               catch (JMSException je) {
                  logger.error("JMS Exception : ", je);
                  return null;
               }
            }
         };
         jmsTemplate.send(mc);
      }
   }
}

3. Here is your JUnit test case, ~workspace/jms/src/test/java/com/noushin/spring/jms/producer/MessageProducerTest.java
package com.noushin.spring.jms.producer;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MessageProducerTest {
   
   @Autowired
   protected MessageProducer producer;
   
   @Test
   public void testProduce() {
      try {
         producer.produce();
         assert(true);
      } 
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

4. Corresponding test context is at ~workspace/jms/src/test/resources/com/noushin/spring/jms/producer/MessageProducerTest-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.noushin.spring.jms" />
    <context:annotation-config />

    <!-- ActiveMQ destinations to use -->
    <amq:queue id="destination" physicalName="TestQ" />
    
    <!-- ActiveMQ broker URL -->
    <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:61616" />

    <!-- Spring JMS ConnectionFactory -->
    <bean id="singleConnectionFactory" 
          class="org.springframework.jms.connection.SingleConnectionFactory"
          p:targetConnectionFactory-ref="jmsFactory"/>
    
    <!-- Spring JMS Producer Configuration -->
    <bean id="jmsProducerTemplate" class="org.springframework.jms.core.JmsTemplate"
        p:connectionFactory-ref="singleConnectionFactory"
        p:defaultDestination-ref="destination"/>
        
</beans>

Alternatively, if there is a context configuration that can be reused by test classes in different packages, you can specify its location on classpath:
@ContextConfiguration(locations={"classpath:/com/noushin/spring/jms/producer/MessageProducerTest-context.xml"})

5. If in Eclipse, right click your test class and run it as JUnit Test. :)

Monday, April 25, 2011

Setting up Eclipse for developing web based applications using SVN, Maven and Tomcat.

1. Download "Eclipse IDE for Java EE Developers" from http://www.eclipse.org/downloads/

2. Add subversive:

• On main menu, choose Help > Install New Software. The available Software dialog appears.
• In the Work with list, select Helios - http://download.eclipse.org/releases/helios. A list of software packages appears.
• Expand the Collaboration node.
• Scroll the list and check box for Subversive Team Provider (incubation)
• Check other options in the dialog as desired and click the Next button. The Install Details screen appears in the dialog.
• Click the Next button, accept the license and click Finish. Subversive will download and install.
• It is recommended to accept the option to restart Eclipse.

Once Eclipse is restarted, try to import from SVN. "Subversive Connector Discovery" window will pop up.
Select "SVN Kit 1.3.5" or the latest number. Select Next and accept user agreement.

At this point, the trick is to abort the import process and restart eclipse. You should be able ti import again.

To list the installed plugin: Help>Install New Software, and selected "already installed?"

Eclipse IDE for Java Developers 1.3.2.20110218-0812 epp.package.java
Subversive SVN Connectors 2.2.2.I20110124-1700 org.polarion.eclipse.team.svn.connector.feature.group
Subversive SVN Team Provider (Incubation) 0.7.9.I20110207-1700 org.eclipse.team.svn.feature.group
SVNKit 1.3.5 Implementation (Optional) 2.2.2.I20110124-1700 org.polarion.eclipse.team.svn.connector.svnkit16.feature.group

3. Add m2eclipse

• On main menu, choose Help > Install New Software. The available Software dialog appears.
• In the Work with list, add http://m2eclipse.sonatype.org/sites/m2e
• Select Maven Integration for Eclipse and accept license agreement.
• Maven Maven will download and install. Restart Eclipse.

To list the installed plugin: Help>Install New Software, and selected "already installed?"

Eclipse IDE for Java Developers 1.3.2.20110218-0812 epp.package.java
Maven Integration for Eclipse (Required) 0.12.1.20110112-1712 org.maven.ide.eclipse.feature.feature.group
Subversive SVN Connectors 2.2.2.I20110124-1700 org.polarion.eclipse.team.svn.connector.feature.group
Subversive SVN Team Provider (Incubation) 0.7.9.I20110207-1700 org.eclipse.team.svn.feature.group
SVNKit 1.3.5 Implementation (Optional) 2.2.2.I20110124-1700 org.polarion.eclipse.team.svn.connector.svnkit16.feature.group

4. Download "Tomcat 7" from http://tomcat.apache.org/download-70.cgi

5. In Eclipse, Select Window>Show View>Servers. This will add a new tab to the bottom window. Select "Servers" tab and right click to select New>Server. Select Apache>Tomcat v7.0 Server and provide the required information such as the directory where you installed Tomcat, etc.

At this point, you should be ready to create a new "Dynamic Web Project" that can be added to your Tomcat server or import an existing Maven project from a SVN repository. In order to run an imported Maven project on Tomcat you need to issue the following command from a shell:

mvn eclipse:eclipse -Dwtpversion=1.5

The trick is to go back to eclipse and change the following Project properties:
Java Compiler : Make sure Java version is set to 1.6 or higher
Project Facets : Select Dynamic Web Module to use the appropriate Java version.

Tips

1. If you get a "java.lang.OutOfMemoryError: PermGen space" when running Tomcat in Eclipse, edit eclipse.ini to modify your JVM settings.

On MacOS, you can find eclipse.ini in ~eclipse/Eclipse.app/Contents/MacOS.
Your settings should look something like, making sure each item is on a new line:
-vmargs
-Xms128m
-Xmx512m
-XX:MaxPermSize=512m

To verify your settings in Eclipse, Select About Eclipse>Installation Details>Configuration.

2. You may get a "ClassNotFoundException" when running your web app on a Tomcat server. The exception is in reference to a class in a jar file that is already added as a Maven dependency and exists in target//WEB-INF/lib, however Tomcat still throws the exception when running.

Here is the solution:

Check your "Problems" tab for warnings such as:

"Classpath entry org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER will not be exported or published. Runtime ClassNotFoundExceptions may result. "

You can achieve the same by selecting your project's properties->Deployment Assembly->Add->Java Build Path Entries.

Select the row corresponding to your project and perform a "Quick Fix" by right clicking it. Select "Mark the associated raw classpath entry as a publish/export dependencies."