[ Tutorial ] Maven – Install Maven and Create New Maven Project via Command Prompt

This tutorial covers how to install Maven and creating a Maven project.  At the time of this writing this entry (May 28, 2014) the stable version of maven is 3.2.1.

1. Download and Install Apache Maven

1.1. Download Maven

First things first: download maven (http://maven.apache.org/download.cgi)

Under the section that says This is the current stable version of Maven, click on “apache-maven-3.2.1-bin.zip”.  It will download a zip file that you will extract.  This needs to be installed manually.  What I prefer to do is create a folder called dev in a C drive (I’m using Windows 7), and inside that folder, I create another folder called tools.  This is where I extract all other tools.

1.2. Set up System Environment Variables

Next step is to set the environment variable for maven.  Open up ‘Computer’, then on top of the window, click on the button that says ‘System Properties’.

image-003

To the left is a link that says ‘Advanced System Settings’, it will bring a pop up window.

image-004

At the bottom right of the new pop up window, click on a button that says ‘Environment Variables…’ and that will bring another pop up window.

image-005

Under the System Variables section, we need to create a new variable; this tells your computer which directory to look at to run maven.  Click ‘New…’ and do the following:

Variable Name: MAVEN_HOME
Variable Value: C:\dev\tools\apache-maven-3.2.1 (Only if you extracted maven in the C:\dev\tools directory; different if you extracted it elsewhere)

pic

Click OK.  Still under the System Variables section, scroll down until you find PATH variable, and click ‘Edit…’

Environment variables, such as PATH, can also have multiple values; each value needs to be separated by a semicolon. At the end of the Variable value, add a semicolon if there isn’t any, and type the following:

%MAVEN_HOME%\bin;

Please do not delete the variable value that was already set for the PATH variable. If you do, other programs dependent on that value might not work properly! If you’re doing it correctly, it should look something like this:

pic2

(WARNING: this does not check for the syntax.  So if you typed it wrong, your computer will not know where to look for to run maven!)

At this point, you are all set and ready to run maven and create a new maven project.  Click OK.

1.3. Test for Successful Installation

Now open up a command prompt (click start button, type in cmd and hit enter)

run the following command:

mvn -version

… and you should see the following:

image-006

if you do, you installed maven successfully.  Now let’s create a maven project.

2. Create New Maven Project

Creating a maven project is ridiculously easy.  Only thing I would worry about is to be careful when typing in the command correctly.

First off, use the cd (change directory) command to go to the directory where you will be creating a project.  What I prefer personally is to create it in C:\dev\workspace directory.  After you open up the command prompt, type in cd \dev\workspace or whichever directory you decide to work on.

image-007

Now type in the following command:

mvn archetype:generate -DgroupId=com.appname.app -DartifactId=app-name -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

and hit enter.  It should create a new project.  At the end, the command prompt will read BUILD SUCCESS.  Next step is to build the project package.  Change the directory to app-name (cd app-name) and type in the following command:

mvn package

and hit enter.  Again, at the end of it will read BUILD SUCCESS. At this point, you’re all set.  Thanks for reading, and happy developing.

[ Tutorial ] Maven – Connect to a ZooKeeper in Java

This tutorial will cover how to connect to ZooKeeper in Java with Maven project.

(Click here to download the source code for this tutorial)

1. What is Apache Maven?

Apache Maven (or just Maven) is simply “a software project management and comprehension tool.” (from http://maven.apache.org)  In this case, Maven is designed to help you with downloading what’s called dependency – think of them as the external JAR files you need to explicitly download and include them in your build path.

1.1. Create Maven Project

Maven utilizes POM (Project Object Model); this is what makes Maven very useful.  You specify the required dependencies here, and after updating the project, it will automatically download the dependencies for you.

First step is to create a Maven project.  (How to create Maven project). Under the maven project you just created, you will see an xml file called pom.xml.

1.2. Configure Project

Image

Open that, and edit it as follows:

<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>zook</groupId>
    <artifactId>zook</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <name>zook</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.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
        </dependency>
    </dependencies>
</project>

Right click on your project > Maven > Update Project (or Alt + F5).  This usually works for me if “Force Update of Snapshots/Releases” is checked.

Image

Then click OK.

This enables you to use any classes included in that zookeeper dependency.

2. Connect to ZooKeeper

2.1. ZooKeeper Connector Class

Next step is to create a new class, let’s call it ZkConnector.

Here, you are going to import 6 following classes:

import java.io.IOException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

ZkConnector class is for your program to interact with ZooKeeper server.  We will declare two global variables here:

ZooKeeper zookeeper;
java.util.concurrent.CountDownLatch connectedSignal = new java.util.concurrent.CountDownLatch(1);

and write three different methods.  First method connects to the ZooKeeper server by passing a hosts argument.  Another method tells ZooKeeper server to shut down, and the third method gets the instance of live ZooKeeper server.

2.2. Connect method

public void connect(String host) throws IOException, InterruptedException {
    zookeeper = new ZooKeeper(host, 5000, 
                              new Watcher() {
                                  public void process(WatchedEvent event) {
                                      if (event.getState() == KeeperState.SyncConnected) {
                                          connectedSignal.countDown();
                                      }
                                  }
                              });
                              connectedSignal.await();
}

2.3. Close method

public void close() throws InterruptedException {
    zookeeper.close();
}

2.4. Getter method:

public ZooKeeper getZooKeeper() {
    if (zookeeper == null || !zookeeper.getState().equals(States.CONNECTED)) {
        throw new IllegalStateException("ZooKeeper is not connected.");
    }
    return zookeeper;
}

3. Test ZooKeeper Connection

3.1. Tester Class

Let’s test this class to see if it works.

We’re going to create another class, call it ZkConnectTest. This class will import 5 classes as follows:

import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

Many methods in the zookeeper API throw exceptions.  We need to add a throws declaration to the main method of three exceptions: IOException, InterruptedException, KeeperException.  Another way is to enclose the exception throwing statements with try... catch, but we’ll make our main method throw those exceptions.

First, let’s declare a new ZooKeeper variable, call it zk.

ZooKeeper zk;

Next, create a new instance of the ZkConnector class, let’s call it zkc.

ZkConnector zkc = new ZkConnector();

In the last 3 lines, we are going to:

  • connect to the zookeeper
  • let zk be the instance of the zookeeper connected
  • and create a new znode, just to see if it worked correctly.
zkc.connect("localhost");
zk = zkc.getZooKeeper();
zk.create("/newznode", "new znode".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

3.2. Run an Instance of ZooKeeper

Save your source code and let’s create the ZooKeeper instance.  We need to have an instance of ZooKeeper running in order for your program to work. Open up a command prompt (if you’re using windows), or a terminal (Mac or Linux users) and type in the following command:

Windows users: zkServer.cmd
Mac/Linux users:  ./zkServer.sh -start

3.3. Interact With ZooKeeper as Client

Next, we are going to connect to the zookeeper as a client.  Open up another command prompt (windows) or a terminal (Mac or Linux) and type in the following command:

Windows users: zkCli.cmd
Mac/Linux users: ./zkCli.sh -server:2181

In the client window, type in the following command: ls /

If you have not created any znodes yet, you should only get zookeeper znode.  This is implemented in the zookeeper by default, and it cannot be destroyed.  What we just did was print a list of all children znodes of the root (/) znode.

Go back to the program we wrote, and run it.

Then go back to the client window, and type in the ls / command.  If you see the newznode, then we successfully wrote a program to connect to the zookeeper. Thanks for reading, and happy zookeeping.

(Click here to download the source code for this tutorial)