How do I install third-party libraries in Maven repository?

Sometimes when the required libraries / dependencies is not available in the Maven Central Repository we need to manually install it to our local repository. This library must be placed in the correct directory in our local repository to enable Maven to find it. The default location is under the ${user.home}/.m2/repository.

To make this job easier Maven provide a maven-install-plugin that will help us to install the third-party library in the correct place. The following command shows how to do it.

The long command ūüôā

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
        -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Where:

  • -Dfile = path to the third-party library file
  • -DgroupId = the groupId of the library
  • -DartifactId = the artifactId of the library
  • -Dversion = the version number of the library
  • -Dpackaging = the library packaging

An example to install an Oracle JDBC library to your local repository is:

mvn install:install-file -Dfile=ojdbc7.jar -DgroupId=com.oracle \
        -DartifactId=ojdbc7 -Dversion=12.1.0.2 -Dpackaging=jar

The simple command ūüôā

If you have the pom.xml file, you can install it with the following command:

mvn install:install-file \
        -Dfile=<path-to-file> \
        -DpomFile=<path-to-pomfile>

Where:

  • -Dfile = path to the third-party library file
  • -DpomFile = the location to the library pom.xml file

Starting with the Maven version 2.5 you can use even a simpler command. When the library is build by Maven, a pom.xml file will be placed under the META-INF directory. This pom.xml file will be used by default when we install the library. To install a library all you need is the following command:

mvn install:install-file -Dfile=<path-to-file>

How do I run FTP server in OS X?

I need to test FTP client codes, so I need to find an FTP server for testing my codes. After searching for a while I find out that OS X already equipped FTP server. I am currently using OS X El Capitan 10.11.*.

Let’s now test the FTP server on OS X with the following steps:

  • Launch the Terminal.app
  • Type the following command to start the FTP server.
sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist
  • Connect to the FTP server by running ftp localhost command.
  • We’ll be asked to enter the username and password.
$ ftp localhost
Trying ::1...
Connected to localhost.
220 ::1 FTP server (tnftpd 20100324+GSSAPI) ready.
Name (localhost:wsaryada): wsaryada
331 User wsaryada accepted, provide password.
Password: 
230 User wsaryada logged in.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>
  • If we see the messages above and the ftp> prompt means that the FTP server works and ready to accept our command.
  • We can also try to access the FTP server using a browser. In the URL box type ftp://localhost to connect. We need to supply username and password to login.
  • To exit or close the connection to FTP server we can run the exit command.
  • Finally, to shutdown the FTP server we run:
sudo -s launchctl unload -w /System/Library/LaunchDaemons/ftp.plist

After the FTP server ready, I can now continue to create some test program to access the FTP server. There are already some examples you can find in the Apache Commons Net category that use the FTPClient library to access FTP server.

How to use Google’s Maven Central mirror?

The following configuration will use Google’s mirror of the Maven Central repository. Alter your ${M2_HOME}/conf/settings.xml or ${user.home}/.m2/settings.xml to add the mirror as seen in the following configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<settings>
    .
    .
    <mirrors>
        <mirror>
            <id>google-maven-central</id>
            <name>Google Maven Central</name>
            <url>//maven-central.storage.googleapis.com</url>
            <mirrorOf>central</mirrorOf>
        </mirror>
    </mirrors>
    .
    .
</settings>

How to configure a proxy in Maven settings?

When we work behind a proxy server we need to configure Maven to be able to connect to the internet. To enable proxy we can configure Maven settings.xml file, either in ${M2_HOME}/conf/settings.xml or ${user.home}/.m2/settings.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<settings>
    .
    .
    <proxies>
        <proxy>
            <id>my-proxy</id>
            <active>true</active>
            <protocol>http</protocol>
            <host>proxy.example.org</host>
            <port>8080</port>
            <username>username</username>
            <password>password</password>
            <nonProxyHosts>*.example.org|*.example.com</nonProxyHosts>
        </proxy>
    </proxies>
    .
    .
</settings>

The <proxy> element in the configuration above contains the information about the proxy server. These include information about the host, port, username and password. Set these elements to match your proxy server configuration.

How do I specify the Java compiler version in a pom.xml file?

When you need to compile a project for a specific Java version you can configure maven compiler plugin to set the source and the target version. The following pom.xml file configuration show you how to do it.

<project>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>    

Invalid value for the source and the target version in our project will make our project compilation process failed. For example when we try to use the diamond operator (<>) which available in Java 7, while the maven compiler plugin is set to version 1.5, can produce compiler error like this:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project servlet-example: Compilation failure
[ERROR] /Users/wsaryada/Studio/kodejava.org/webapp-example/servlet-example/src/main/java/org/kodejava/example/servlet/SessionCounter.java:[10,51] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)

How do I install Gradle in OS X?

In this post we will learn how to install Gradle in OS X. The following steps will guide our installation process to make Gradle available in our OS X machine. But before we start let’s take a look at the definition from wikipedia about Gradle.

Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven of declaring the project configuration.

Gradle installation steps:

Download Gradle

To download visit Gradle download page. Download the complete distribution which includes binaries, sources and offline documentation. When I write this post the latest release of Gradle is version 2.10 (gradle-2.10-all.zip).

Upacking Gradle and Configure Environment Variables

  • Open Terminal.app.
  • Create a new directory sudo mkdir /usr/local/gradle.
  • Extract the downloaded Gradle distribution archive by executing sudo unzip gradle-2.10-all.zip -d /usr/local/gradle.
  • Edit .bash_profile in your home directory to add GRADLE_HOME variable with the following line export GRADLE_HOME=/usr/local/gradle/gradle-2.10
  • Also update the PATH variable to include $GRADLE_HOME/bin. If you don’t already have the PATH variable add the following line export PATH=$GRADLE_HOME/bin:$PATH
  • Run source ~/.bash_profile to executes the update version of .bash_profile. Or you can open a new Terminal.app to make this changes active.

Running the Installation

To test Gradle installation open the Terminal.app and execute gradle -v command. If your installation was correct you will see something like the following output:

$ gradle -v

------------------------------------------------------------
Gradle 2.10
------------------------------------------------------------

Build time:   2015-12-21 21:15:04 UTC
Build number: none
Revision:     276bdcded730f53aa8c11b479986aafa58e124a6

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:          1.8.0_20 (Oracle Corporation 25.20-b23)
OS:           Mac OS X 10.11.2 x86_64

How do I install Oracle Java in Ubuntu Server 14.04?

The easiest way to install Oracle Java (JDK) in Ubuntu is to use the WebUpd8 PPA. A PPA (Personal Package Archive) is a special software repository for uploading source packages to be build and published as an APT repository by Launchpad. This PPA will download the required files from Oracle and install JDK7 / JDK8 / JDK9.

The steps:

  • Login to Ubuntu server.
  • sudo apt-add-repository ppa:webupd8team/java

The apt-add-repository command add the ppa to the current repository. You will be prompted with information message about installation instructions with the detail url. You need to press ENTER key to continue the process to add the repository.

apt-add-repository

apt-add-repository

  • sudo apt-get update

This will update the package list from the repositories and update them to get the latest versions of the packages and their dependencies. It will update all repositories and PPAs.

apt-get update

apt-get update

  • sudo apt-get install oracle-java8-installer

This command will start the installation process, you will be prompted to accept the license agreement. Run sudo apt-get install oracle-java7-installer if you want to install JDK7 instead. This process will take sometime to finish depending on your connection speed. And if everything runs well you’ll get Java installed at the end of this process.

apt-get install oracle-java8-installer

apt-get install oracle-java8-installer

  • java -version

This command return the version of the installed JDK. In this case it should return something like:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

The JDK8 will be installed in the /usr/lib/jvm/java-8-oracle directory. If you need to define the JAVA_HOME environment variable then it should directed to this directory.

Creating a simple project using Maven

In this post you will learn how to create a simple project, a Hello World project using Maven. If you haven’t install Maven in your machine you can read Introduction to Apache Maven¬†posted earlier in this blog. In this post you will see what the basic configuration for creating a maven project. Such as the basic of pom.xml file and how maven structure the directory of our project files.

At this time we won’t use any special IDE such as Eclipse, Netbeans or IntelliJ to create our project. We’ll just work using a simple text editor and the command prompt. Let’s us begin.

Step 1 – Create a project directory and the pom.xml file.

  • Create a directory where you will place the project files. As an example I’ll create my project in D:\Projects\HelloWorld.
  • Create a file called pom.xml in the HelloWorld directory.¬†POM stands for Project Object Model and it represent a Maven project.
  • Type the following information in the pom.xml file.
<project>
    <groupId>org.kodejava</groupId>
    <artifactId>HelloWorld</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <modelVersion>4.0.0</modelVersion>
</project>
  • At this point we have our pom.xml file created. What you’ve seen above is the simplest example of a pom file. And here is a brief description of the pom file above:
    • groupId: the unique id of a Maven project. Typically it use your company name domain in reverse order just like how you would create a package for your Java project. For example here I use org.kodejava.
    • artifactId: is the name of the project, we’ll be using HelloWorld.
    • version: is the version number of our project.
    • packaging: the project artifact type. In this case we will ask Maven to package our example as a jar file.
    • modelVersion: is the version of the POM file we are using for this project.

Maven works by applying a concept called convention over configuration. This will apply for example on how the directory of a project is structured. All Maven project will use the same directory for organising the files in the project. There is a directory for Java source codes, unit testing codes, configuration files, etc. This will make easier for developer to jump from one Maven project to the other projects. Now let’s us continue to the next step.

Step 2 РCreate the HelloWorld class.

  • Create a directory for Java source code in the project root directory. Actually you’ll create three directories. These directories are src\main\java.
  • Create a file HellWorld.java under the java directory you’ve created above.
  • Type the following code for the HelloWorld class.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
  • Now we have our class created we can start to use maven to build our project. But before we do let see what you should have after finishing these steps. You should see that you have a project structure that similar the the screen capture below:

Maven HelloWorld

Steps 3 – Compiling the Project.

At this time we have our first Maven project created and we are ready to build it. To build this basic project we don’t have to add anything to Maven. It already comes with a predefined sets of build related task such as clean, compile, test, package, etc.

  • Open a¬†Command Prompt and go to your project directory. You should be in the HelloWorld directory where you can see the pom.xml file.
  • To compile your project type¬†mvn compile in the command prompt.
D:\Projects\HelloWorld>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Compiling 1 source file to D:\Projects\HelloWorld\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.405s
[INFO] Finished at: Tue Sep 24 10:18:10 CST 2013
[INFO] Final Memory: 7M/23M
[INFO] ------------------------------------------------------------------------
D:\Projects\HelloWorld>
  • What you see above is the typical result of a success build. You might see longer message such as information about the artifact downloaded by Maven during the compile process.
  • If you list the project directory you’ll see a new directory called targetclasses is created. And inside the classes directory you’ll find your HelloWorld.class file.
  • To run the class cd to targetclasses and type java HelloWorld.

Steps 4 – Clean and Package the Project.

  • Now if you want to clean your previous built project you can use¬†mvn clean. Make sure you are executing this command from the project root directory where the pom.xml file is located.
  • Executing this command will give you the similar output like this.
D:\Projects\HelloWorld>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ HelloWorld ---
[INFO] Deleting D:ProjectsHelloWorldtarget
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.353s
[INFO] Finished at: Tue Sep 24 10:29:16 CST 2013
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
D:ProjectsHelloWorld>
  • As you can see it deleted the previously created target directory.
  • In the pom.xml file we have define the packaging of our project as jar file. So let’s create it now.
  • To package a Maven project type¬†mvn package command.
D:\Projects\HelloWorld>mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Compiling 1 source file to D:\Projects\HelloWorld\target\classes
[INFO] skip non existing resourceDirectory D:\Projects\HelloWorld\src\test\resources
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ HelloWorld ---
[INFO] No sources to compile
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ HelloWorld ---
[INFO] No tests to run.
[INFO] Surefire report directory: D:\Projects\HelloWorld\target\surefire-reports
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ HelloWorld ---
[INFO] Building jar: D:\Projects\HelloWorld\target\HelloWorld-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.040s
[INFO] Finished at: Tue Sep 24 10:32:41 CST 2013
[INFO] Final Memory: 8M/20M
[INFO] ------------------------------------------------------------------------
D:\Projects\HelloWorld>
  • The mvn package gives you a longer console output. ¬†From the output above you can see that executing the package command made Maven to compile the Java source code, unit test source code (we don’t have it at this time). It also run the unit test and finally build the jar file.
  • The jar file is created under the target directory and named HelloWorld-1.0-SNAPSHOT.jar. The name comes from the artifactId, version and packaging information defined in the pom.xml file.

That are all the steps that you need to create and manage a simple project using Maven. We start by creating a pom.xml file and then create a directory structure for storing our classes file. And then we learn how to compile, clean and package our Maven project. In the next Maven post we’ll learn more on Maven dependency management and starting to use an IDE to setup our Maven project.

Thank your for reading and see you on the next Maven post.

Introduction to JUnit

In this post we will start to learn about JUnit. JUnit is a framework for unit testing Java applications. It was developed by Kent Back and Erich Gamma to help developers to create a better applications. JUnit has become the standard tool used by developers when it comes to unit testing.

Everyday, when you create an application from the smallest one, that consist of a single class to a project of a large application, your development workflow will always be the same. You will begin by writing a small code, compile it, run the code and finally test it. And you will mostly find that things doesn’t work as expected at first. So you’ll go back to your favorite IDE, check what the error was and you will repeat the process, code, compile, run and test, until you get the result that you want.

We can do this steps manually. For example when you have a console application you will typically run the code, check the result printed out on the console screen to find out if the program return the correct result. When you find the error you will fix it and re-run the code again and again. This kind of test seems like a time consuming activity, tiresome and even make you bored. And instead of testing the code you are testing your ability to test. Because you have to check whether the output printed in the console is correct or not.

Here is a simple example of a very simple calculator that know how to add two numbers and how you are testing it using a simple main class in a console application.

package org.kodejava.junit;

public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int a = 10;
        int b = 15;
        int c = Calculator.add(a, b);

        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);

        if (c == 25) {
            System.out.println("Test success!");
        } else {
            System.out.println("Test failed!");
        }
    }
}
Testing your ability to test.

Testing your ability to test.

To make life easier JUnit framework comes with great help to overcome these problems. You can tell JUnit framework to test your code by creating a unit tests. You will create a class that test your code, you’ll define your testing criteria in this unit testing class. You can execute these unit testing and it will report whether the tests pass or fail. And you can run it as many time as you’ll like to see if the test still pass after you modified parts of your code.

Now, let see how JUnit can help us testing the previous calculator code. Before creating the unit test class we need to download the JUnit library from the website at JUnit.org, follow the link to download page and download the jars. There are two main jar files that you need to download, the junit.jar and  hamcrest-core.jar. When you are using and IDE, the JUnit usually installed as part of the IDE such as NetBeans, Eclipse or IntelliJ IDEA.

Let’s write the unit testing code.

package org.kodejava.junit;

import org.junit.Test;
import static junit.framework.Assert.*;

public class CalculatorTest {
    @Test
    public void addTwoNumbersTest() {
        int a = 10;
        int b = 15;
        assertEquals(25, Calculator.add(a, b));
    }
}

From this code snippet what you can see is:

  1. We create a class called CalculatorTest. We usually name the unit test class with the same name with the class under test but suffix it with Test.
  2. We create a test method called addTwoNumberTest(). You can name your test method as descriptive as possible. This will have you understand what the method is trying to test.
  3. To make a method a unit test method we add the @Test annotation to it. This annotation will tell the JUnit framework that the annotated method is a part of the unit testing it should execute on our behalf.
  4. In the test method body we use the assertEquals() method to check the test result. In this case we expect 25 is returned when the Calculaor.add() method add two numbers, the a + b.

After you create the unit testing class, let’s compile it and this JUnit test from the command prompt. Remember to have also the class under test, which is the Calculator class beside your unit testing class. To execute JUnit test you can type the following command.

java -cp .;junit-4.10.jar org.junit.runner.JUnitCore org.kodejava.junit.CalculatorTest

I am intentionally place the junit.jar file in the root of my work directory so that I can make the -cp option short. The classpath options tell Java where to look the required class files.

Executing JUnit Test

Executing JUnit Test

That’s is all for the bit of introduction to JUnit. In the coming post I will write more about JUnit and how to use other available annotation so you can write a better test.

Introduction to GenMyModel

After 3 years of research and development, GenMyModel draws the future of software modeling. GenMyModel is a free browser hosted UML tool for developers and software architects. Its main strength: create UML compliant models online and generate code. Unlike the well known desktop alternatives, it allows you to work on any web browser and from any computer with any OS (Windows, Linux, Mac OS).

GenMyModel has been released in beta in 2013. It supports for now class and use case diagrams and works with GitHub to host the generated code. You can try GenMyModel here UML Online Tool.

Online UML Tool

Online UML Tool

 

Using the App

Log in & create an UML project

The application itself is available at this address: http://app.genmymodel.com/. First thing you see is the connection window where you can sign in with your Google account or sign up with another mail address.

GenMyModel Dashboard

GenMyModel Dashboard

Once you are logged in, you discover your dashboard where you have the choice to create a new project or use one of the existing templates below. When you create a new project, you can then set a title and choose between a public or private project. When you open a project, a new tab appears above for you to easily switch between your class and use case
diagrams.

Public UML Online

Public UML Online

 

Creating class and use case diagrams

When you create a new project, it instantly opens a tab for class diagrams, but you can choose in the File menu to make new use case diagrams.

The vertical toolbar between your whiteboard and the project explorer shows you the different tools to create classes, interfaces, add attributes, make associations and more. For example, if you select the class tool or press ‘C’ (the underlined letters being keyboard shortcuts), you can place a class anywhere on your whiteboard. You can also add several elements at a time by holding Ctrl.

Class Diagram Online

Class Diagram Online

You can then select one or more elements and move them on your whiteboard, rearrange links or set a few properties. Same thing goes for use case diagrams.

 

Change the model properties

The bottom left corner of the application groups all the properties you need for the elements you selected. This way, this small window allows you to set names, types, visibility, multiplicity, comments and a few other settings.

UML Online Property

UML Online Property

Those possibilities change according to your selection on your whiteboard or the project explorer.

 

Code generation and push to GitHub

Generate Java and SQL code

GenMyModel provides code generators:

  • Java Beans
  • JPA Beans
  • Spring Data REST application
  • Spring Roo
  • SQL

There are two ways to generate code: with the ‘Tools’ menu or by right clicking on your model. You can then choose between a direct generation creating a ZIP file with Java, Java JPA or SQL code, or configuring your own saved configuration allowing you to push to your GitHub repositories.

UML Code Generators

UML Code Generators

 

Push to GitHub

If you are a GitHub user, you can push your generated code to the hosting service. In the code generation configuration window, you just have to type your repository URL and the branch you would like to send your code to. The first push can take a while but it is quite fast afterwards.

UML Java Code Generator

UML Java Code Generator

 

Report, image and model export

Export to image and XMI

GenMyModel allows you to export you models to image files in JPEG or SVG, or export to XMI. You can choose either format by rightclicking or with the ‘Tools’ menu.

Export documentation to PDF

You can also export the documentation of your models to a PDF file. Resulting in a document with images of your diagrams and the list of every element and its properties.

UML PDF Export

UML PDF Export

 

Share by email

Sharing to social network is planned for the next few months, in the meantime you can share your work by email with the same menu.

Web description for public projects

When creating a project within GenMyModel, you can choose between the public and private options. Private means only you can see and modify the model. Public means you are the only one allowed to modify it but anyone can fork it.

Web pages are automatically created for public projects so that you can share and show what you design. Examples: Class Diagram University Management System

What’s next

The next major release before October 2013 will include:

  • Realtime collaboration
  • Java Reverse engineering
  • Package support for class diagrams and use case diagrams

Technology

GenMyModel is built upon Javascript and HTML5.