Posts Tagged Eclipse

Spring Integration with Eclipse Using Maven

Integrate the Spring Framework into your next Eclipse-based project using Apache Maven. Learn how to install, configure, and integrate these three leading Java development tools. All source code for this post is available on GitHub.

 

Introduction

Although there is a growing adoption of Java EE 6 and CDI in recent years, Spring is still a well-entrenched, open-source framework for professional Java development. According to GoPivotal’s website, “The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications. Spring focuses on the ‘plumbing’ of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.”

Similar to Spring in terms of wide-spread adoption, Eclipse is leading Java IDE, competing with Oracle’s NetBeans and JetBrain’s IntelliJ. The use of Spring within Eclipse is very common. In the following post, I will demonstrate the ease of integrating Spring with Eclipse, using Maven.

Maven is a marketed as a project management tool, centralizing a project’s build, reporting and documentation. Conveniently, Maven is tightly integrated with Eclipse. We will use Maven for one of its best known features, dependency management. Maven will take care of downloading and managing the required Spring artifacts into our Eclipse-based project.

Note there are alternatives to integrating Spring into Eclipse, using Maven. You can download and add the Spring artifacts yourself, or go full-bore with GoPivotal’s Spring Tool Suite (STS). According to their website, STS is an Eclipse-based development environment, customized for developing Spring applications.

The steps covered in this post are as follows:

  1. Download and install Maven
  2. Download and install the Eclipse IDE
  3. Linking the installed version of Maven to Eclipse
  4. Creating a new sample Maven Project
  5. Adding Spring dependencies to the project
  6. Demonstrate a simple example of Spring Beans and ApplicationContext
  7. Modify the project to allow execution from an external command prompt

Installing Maven

Installing Maven is simple process, requiring minimal configuration:

  1. Download the latest version of Maven from the Apache Maven Project website. At the time of this post, Maven is at version 3.1.1.
  2. Assuming you are Windows, unzip the ‘apache-maven-3.1.1’ folder and place in your ‘Program Files’ directory.
  3. Add the path to Maven’s bin directory to your system’s ‘PATH’ Environmental Variable.
Adding Maven bin Directory to PATH Environmental Variable

Adding Maven bin Directory to PATH Environmental Variable

We can test our Maven installation by opening a new Command Prompt and issuing the ‘mvn -version’ command. The command should display the installed version of Maven, Maven home directory, and other required variables, like your machine’s current version of Java and its location. To learn other Maven commands, try ‘mvn -help’.

Checking Maven is Installed Correctly

Checking Maven is Installed Correctly

Installing Eclipse IDE

Installing Eclipse is even easier:

  1. Download the latest version of Eclipse from The Eclipse Foundation website. There are several versions of Eclipse available. I chose ‘Eclipse IDE for Java EE Developers’, currently Kepler Service Release 1.
  2. Similar to Maven, unzip the ‘eclipse’ folder and place in your ‘Program Files’ directory.
  3. For ease of access, I recommend pinning the main eclispe.exe file to your Start Menu.
Downloading Eclipse IDE for Java EE Developers

Downloading Eclipse IDE for Java EE Developers

Linking Maven to Eclipse

The latest version of Eclipse comes pre-loaded with the ‘M2E – Maven Integration for Eclipse’ plug-in. There is no additional software installs required to use Maven from within Eclipse. Eclipse also includes an embedded runtime version of Maven (currently 3.04). According to the Eclipse website wiki, the M2E plug-in uses the embedded runtime version of Maven when running Maven builder, importing projects and updating project configuration.

Latest Version of Eclipse Kepler SR1 with M2E Installed

Latest Version of Eclipse Kepler SR1 with M2E Installed

Although Eclipse contains an embedded version of Maven, we can configure M2E to use our own external Maven installation when launching Maven using Run as… -> M2 Maven actions. To configure Maven to use the version of Maven we just installed:

  1. Go to Windows -> Preferences -> Maven -> Installations window. Note the embedded version of Maven is the only one listed and active.
  2. Click Add… and select the Maven folder we installed in your Program Files directory. Click OK.
  3. Check the box for new installation we just added instead of the embedded version. Click OK.
Adding Installed Version of Maven to Eclipse

Adding Installed Version of Maven to Eclipse

Adding Installed Version of Maven to Eclipse

Adding Installed Version of Maven to Eclipse

Adding Installed Version of Maven to Eclipse

Adding Installed Version of Maven to Eclipse

Sample Maven Project

To show how to integrate Spring into a project using Maven, we will create a Maven Project in Eclipse using the Maven Quickstart Archetype template. The basic project will show the use of Spring Beans and an ApplicationContext IoC container. On a scale of 1 to 10, with 10 being the most complex Spring example, this project is barely a 1! However, it will demonstrate that Spring is working in Eclipse, with minimal effort thanks to Maven.

To create the project:

  1. File -> New Project -> Other…
  2. Search on ‘maven’ in the Wizards text box and select ‘Maven Project’.
  3. Select the Maven Quickstart Archetype.
  4. Specify the Archetype parameters.
Creating a New Maven Project - Using Wizard

Creating a New Maven Project – Using Wizard

Creating a New Maven Project - Project Location

Creating a New Maven Project – Project Location

Creating a New Maven Project - Choosing Archetype

Creating a New Maven Project – Choosing Archetype

Creating a New Maven Project - Archetype Parameters

Creating a New Maven Project – Archetype Parameters

Spring Dependencies

Once the Maven Quickstart project is created, we will add the required Spring dependencies using Maven:

  1. Open the Maven Project Object Model (POM) file and select the Dependencies tab.
  2. Use the The Central Repository website to find the Dependency Information for spring-core and Spring-context artifacts (jar files).
  3. Add… both Spring Dependencies to the pom.xml file.
  4. Right-click on the project and click Maven -> Update Project…
Adding Spring Dependencies to pom.xml - Dependencies Tab

Adding Spring Dependencies to pom.xml – Dependencies Tab

Adding Spring Dependencies to pom.xml - Artifact Details for spring-core

Adding Spring Dependencies to pom.xml – Artifact Details for spring-core

Adding Spring Dependencies to pom.xml - Adding spring-context

Adding Spring Dependencies to pom.xml – Adding spring-context

Adding Spring Dependencies to pom.xml - Spring Dependencies Added

Adding Spring Dependencies to pom.xml – Spring Dependencies Added

Adding Spring Dependencies to pom.xml - Dependencies Added to Project

Adding Spring Dependencies to pom.xml – Dependencies Added to Project

We now have a Maven-managed Eclipse project with our Spring dependencies included. Note the root of the file paths to the jar files in the Maven Dependencies project folder is the location of our Maven Repository. This is where all the dependent artifacts (jar files) are stored. In my case, the root is ‘C:\Users\{user}\.m2\repository’. The repository location is stored in Eclipse’s Maven User Setting’s Preferences (see below).

Project Object Model File (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.blogpost.maven</groupId>
<artifactId>maven-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>maven-spring</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<description>Project for blog post about the use of Spring with Eclipse and Maven.</description>
</project>
view raw pom.xml hosted with ❤ by GitHub

Location of Local Maven Repository

Local Maven Repository Location

Sample Code

Next add the supplied Code to the project. We will add two new java classes and a Spring configuration file. We will replace the contents of main App class with our sample code. Steps are as follows:

  1. Add the supplied Vehicle.java and MaintainVehicle.java class files to the project, in the same classpath as the App.java class.
  2. Add the supplied Beans.xml Spring configuration file to the project at the ‘src/main/java’ folder.
  3. Open the App.java class file and replace the contents with the supplied App.java class file.

The sample Spring application is based on vehicles. There are three Spring Beans defined in the xml-based Spring configuration file, representing three different vehicles. The main App class uses an ApplicationContext IoC Container to instantiate three Vehicle POJOs from the Spring Beans defined in the Beans.xml Spring configuration. The main class then instantiates an instance of the MaintainVehicle class, passes in the Vehicle objects and calls MaintainVehicle’s two methods.

Location of New Files in Project Explorer

Location of New Files in Project Explorer

Spring Configuration File (Beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="vehicle1" class="com.blogpost.maven.maven_spring.Vehicle">
<property name="make" value="Mercedes-Benz" />
<property name="model" value="ML550" />
<property name="year" value="2010" />
<property name="color" value="Silver" />
<property name="type" value="SUV" />
</bean>
<bean id="vehicle2" class="com.blogpost.maven.maven_spring.Vehicle">
<property name="make" value="Jaguar" />
<property name="model" value="F-Type" />
<property name="year" value="2013" />
<property name="color" value="Red" />
<property name="type" value="Convertible" />
</bean>
<bean id="vehicle3" class="com.blogpost.maven.maven_spring.Vehicle">
<property name="make" value="Suzuki" />
<property name="model" value="SVF 650" />
<property name="year" value="2012" />
<property name="color" value="Black" />
<property name="type" value="Motorcycle" />
</bean>
</beans>
view raw Beans.xml hosted with ❤ by GitHub

Main Method Class (App.java)

package com.blogpost.maven.maven_spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(
"Beans.xml");
MaintainVehicle maintain = new MaintainVehicle();
// vehicle1 bean
Vehicle obj1 = (Vehicle) context.getBean("vehicle1");
System.out.printf("I drive a %s.\n", obj1.getLongDescription());
System.out.printf("Is my %s tuned up? %s\n",
obj1.getShortDescription(), obj1.getServiced());
maintain.serviceVehicle(obj1);
System.out.printf("Is my %s tuned up, yet? %s\n\n", obj1.getMake(),
obj1.getServiced());
// vehicle2 bean
Vehicle obj2 = (Vehicle) context.getBean("vehicle2");
System.out.printf("My wife drives a %s.\n", obj2.getLongDescription());
System.out.printf("Is her %s clean? %s\n", obj2.getShortDescription(),
obj2.getWashed());
maintain.washVehicle(obj2);
System.out.printf("Is her %s clean, now? %s\n\n", obj2.getMake(),
obj2.getWashed());
// vehicle3 bean
Vehicle obj3 = (Vehicle) context.getBean("vehicle3");
System.out.printf("Our son drives his %s too fast!\n", obj3.getType()
.toLowerCase());
}
}
view raw App.java hosted with ❤ by GitHub

Running the Application

If successful, the application will output a series of messages to the Console. The first few messages in red are Spring-related messages, signifying Spring is working. The next messages in black are output by the application. The messages show that the three Spring Beans are successfully instantiated and passed to the MaintainVehicle object, where it’s methods were called. If the application would only buy me that Silver Mercedes!

Successful Console Output of Java Application

Successful Console Output of Java Application

Running the Application from a Command Prompt

All the source code for this project is available on GitHub. Note the pom.xml contains a some extra configuration information not shown above. The extra configuration information is not necessary for running the application from within Eclipse. However, if you want to run the application from an external Command Prompt, you will need the added configuration. This extra configuration ensures that the project is correctly packaged into a jar file, with all the necessary dependencies to run. Extra configuration includes an additional logging dependency, a resource reference to the Spring configuration file, one additional property, and three maven plug-in references for compiling and packaging the jar.

To run the java application from an external Command Prompt:

  1. Open a new Command Prompt
  2. Change current directory to the project’s root directory (local GitHub repository in my case)
  3. Run a ‘mvn compile’ command
  4. Run a ‘mvn package’ command (downloads dependencies and creates jar)
  5. Change the current directory to the project’s target sub-directory
  6. Run a ‘dir’ command. You should see the project’s jar file
  7. Run a ‘java -jar {name-of-jar-file.jar}’ command.

You should see the same messages output in Eclipse, earlier.

Running Application from External Command Prompt

Running Application from External Command Prompt

, , , , , , , , , , ,

10 Comments

Setting Up the Nexus 7 for Development with ADT on Ubuntu

Recently, I purchased a Google Nexus 7. Excited to being development with this Android 4.2 device, I first needed to prepare my development environment. The process of configuring my Ubuntu Linux-based laptop to debug directly on the Nexus 7 was fairly easy once I identified all necessary steps. I thought I would share my process for those who are trying to do the same. Note the following steps assume you already have Java installed on you development computer. Also, that your Nexus 7 is connected via USB.

Configuration

1) Install ADT Bundle: Download and extract the Android Developer Tools (ADT) Bundle from http://developer.android.com/sdk/index.html. I installed the Linux 64-bit version for use on my Ubuntu 12.10 laptop. The bundle, according to the website, includes ‘the essential Android SDK components and a version of the Eclipse IDE with built-in ADT to streamline your Android app development.’

2) Install IA32 Libraries: Install the ia32 shared libraries using Synaptic Package Manager, or the following command, ‘sudo apt-get install ia32-libs’. I received some initial errors with ADT, until I found a post on Stack Overflow that suggested loading the libraries; they did the trick.

3) Configure Nexus 7 to Auto-Mount: To auto-mount the Nexus 7 on your computer, you need to make some changes to your computer’s system configuration. Follow this post to ‘configure your Ubuntu computer to directly access your Nexus 7 exported filesystem in MTP mode as soon as you plug it to a USB port.’, ‘http://bernaerts.dyndns.org/linux/247-ubuntu-automount-nexus7-mtp‘. It looked a bit intimidating at first, but it actually turned out to be pretty easy and only took a few minutes.

Mounting Nexus 7 on Desktop

Nexus 7 Device Mounted on Desktop via USB

4) Setup ADT to Debug Nexus 7: To debug on the Nexus 7 from ADT via USB, according to this next post, ‘you need to add a udev rules file that contains a USB configuration for each type of device you want to use for development.’ Follow the steps in this post, ‘http://developer.android.com/tools/device.html‘ to create the rules file, similar to step 3.

Adding the Android Debug Rule (step 4)

Adding the Android Debug Rule (step 4)

5) Setup Nexus 7 for USB Debugging: The post mentioned in step 4 also discusses setting up you Nexus 7 to enable USB debugging. The post instructs you to ‘go to Settings > About phone and tap ‘Build number seven times. Return to the previous screen to find Developer options.’ From there, check the ‘USB debugging’ box. There are any more options you may wish to experiment with, later.

Displaying the Nexus 7 Developer Options (step 5)

Displaying the Nexus 7 Developer Options (step 5)

Confirming USB Debugging is Connected on Nexus 7

Confirming USB Debugging is Connected on Nexus 7

6) Update you Software: After these first five steps, I suggest updating your software and restarting your computer. Run the following command to make sure your system is up-to-date, ‘sudo apt-get update && sudo apt-get upgrade’. I always run this before and after any software installations to make sure my system is current.

After completing step 3, the Nexus 7 device should appear on your Launcher. However, it is not until steps 4 and 5 that it will appear in ADT.

Demonstration

Below is a simple demonstration of  debugging an Android application on the Nexus 7 from ADT, via USB. Although ADT allows you to configure an Android Virtual Device (AVD), direct debugging on the Nexus 7 is substantially faster. The Nexus 7 AVD emulation was incredibly slow, even on my 64-bit, Core i5 laptop.

Creating a Simple 'Hello World' Application in ADT

Creating a Simple ‘Hello World’ Application in ADT

Choosing the Nexus 7 from Android Device Chooser

Choosing the Nexus 7 from Android Device Chooser

Debugging the Hello World Application on Nexus 7

Debugging the Hello World Application on Nexus 7

, , , , , , , , ,

2 Comments