Pages

Wednesday, April 23, 2014

Building Hello World with Maven

Good evening America, it has recently come to my attention [pop culture ref] that Maven is a popular software project management and comprehension tool for Java-based projects. (Where have I been the last few years?) Maven is based on the concept of a Project Object Model (POM), an XML representation of the project. To get started with Maven, we’ll use our old friend, Hello World, previously covered it in the post Java, Apache Ant and Hello World. In that post, we used Apache Ant, a Java library and command-line tool that can build Java files. The Wikipedia page for Maven describes one of key differences between Maven and Ant as this:
Using Maven, the user provides only configuration for the project, while the configurable plug-ins do the actual work of compiling the project, cleaning target directories, running unit tests, generating API documentation and so on. In general, users should not have to write plugins themselves. Contrast this with Ant and make, in which one writes imperative procedures for doing the aforementioned tasks.
In this post, we'll cover the following:

Task 1: Quick Install of the Java SDK on Different Linux Flavors

(top)

Since Maven depends on the Java SDK being installed, we’ll show examples of quickly getting the Java SDK on three different Linux flavors. We’ll focus on Linux systems, though Maven works for Windows and Mac OS/X as well.

We tried these instructions on the big three cloud providers, with different Linux flavors. We tried Amazon Web Services (AWS) EC2 Instances, Google Compute Instances (GCE), and Azure Linux-Basic Virtual Instances. The cloud providers aren't that interesting for what we are doing here, other than to show that you can do follow this steps  here using any of the providers. But, for completeness, we show the combination of provider and Linux flavor we tried.

GCE, Azure withCen CentOS

sudo yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel
ls -l /usr/lib/jvm/
export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
java -version

GCE with Debian

sudo apt-get update
sudo apt-get install default-jdk
java -version

AWS, Azure with Ubuntu

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
sudo apt-get install oracle-java7-set-default
java -version

Azure with SUSE

These instructions follow the route of downloading the Java JDK as an .rpm (e.g., jdk-8u5-linux-x64.rpm), transferring the .rpm to the SUSE instance, and then installing. You can find the latest version of the Java JDK to use at Java Downloads.

scp jdk-8u5-linux-x64.rpm susu-instance:.      # copy .rpm to the instance
ssh suse-instance                              # log on to the instance
sudo rpm -ivh jdk-8u5-linux-x64.rpm
java -version

Example of Azure Portal and Three Different Linux Instances



Task 2: Quick Install of Maven

(top)

On any of the Linux-based systems we installed the Java SDK on in Task 1, we can now install Maven. Here we'll just give the relevant commands. You should review http://maven.apache.org/download.cgi for details, in particular to change the download URL and determine the latest version.

You must have the Java SDK installed. You can check by running $java –version. If you try to run Maven without Java, you will get an message like "Error: JAVA_HOME is not defined correctly."

curl http://apache.spinellicreations.com/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.tar.gz | tar xvz -C "$HOME"
export M2_HOME="$HOME"/apache-maven-3.2.5
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
mvn --version


Task 3: Build Hello World with No Dependencies

(top)

  1. Create a directory called hello-world.
    $ mkdir hello-world

  2. In the hello-world directory create subdirectories src/main/java.
    cd hello-world
    mkdir -p src/main/java
    cd src/main/java

  3. In the java directory, create a HelloWorld.java file with this code:
    package com.travelmarx.demos; 
    public class HelloWorld { 
        public static void main(String[] args) { 
            System.out.println("Hello World");
        } 
    }

    You can use the cat command to paste content into a file.

    cat > HelloWorld.java
    ...paste content...
    CTRL + C

  4. In the root directory (hello-world), create a file called pom.xml and put in the following contents:
    <project>
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.travelmarx.demos</groupId>
      <artifactId>hello-world</artifactId>
      <version>1</version>
       <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
              <execution>
                <goals>
                  <goal>java</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <mainClass>com.travelmarx.demos.HelloWorld</mainClass>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

  5. Run the example.
    mvn install
    mvn exec:java
    # or
    mvn -q exec:java
    Note that a target directory was created. It contains the output of the build, including the JAR used to when executing the program.

Task 4: Build Hello World with a Dependency and an Input Argument

(top)

Let's create use a version of HelloWorld.java that has a dependency on log4j, a common logging and tracing API. Also, let make the Java program take an input argument.
All we have to really do for the dependency is declare the right dependency coordinate in the pom.xml file and then we are set to go. You can find coordinates from Maven Repository.
  1. Clean up the previous install (i.e., remove the /target directory). Run this in the root of hello-world.
    mvn clean
  2. Create a new version of the HelloWorld.java file with the following content:
    package com.travelmarx.demos;
    import org.apache.log4j.BasicConfigurator;
    import org.apache.log4j.Logger;
     
    public class HelloWorld {
     public static Logger log = Logger.getLogger(HelloWorld.class);
     public static void main(String[] args) {
      BasicConfigurator.configure();     
          log.debug("hi there from the logger");
          System.out.println("hello world " + args[0]);
     }
    }
  3. Modify the pom.xml file and add the <dependencies> XML node.
    <project>
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.travelmarx.demos</groupId>
      <artifactId>hello-world</artifactId>
      <version>1</version>
      <dependencies>
      <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
      </dependency>
      </dependencies>
       <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
              <execution>
                <goals>
                  <goal>java</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <mainClass>com.travelmarx.demos.HelloWorld</mainClass>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
  4. Compile the project as before but run it slightly differently to take in the the argument.
    mvn install
    mvn exec:java -Dexec.args="test"
    
    You should see something like this in the output:
    [com.travelmarx.demos.HelloWorld.main()] 
    DEBUG com.travelmarx.demos.HelloWorld  - hi there from the logger
    hello world test
    
back to the top

No comments:

Post a Comment

All comments go through a moderation process. Even though it may not look like the comment was accepted, it probably was. Check back in a day if you asked a question. Thanks!