Table of Contents

Build Java

Prepare environment variables

Build simple application with command line

Basic steps to build application

  1. step1: create simple application with below directory structure:
    md src
    md build\classes
    md build\jar
  2. step2: create simple application src\oata\helloworld.java:
    package oata;
     
    public class helloworld {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }
  3. step3:build and run
    set PATH=%PATH%;d:\tools\jdk1.7.0_67\bin
    javac -sourcepath src -d build\classes src\oata\helloworld.java
    java -cp build\classes oata.helloworld
  4. step4: create manifest and jar file
    echo Main-Class: oata.helloworld>myManifest
    md build\jar
    jar cfm build\jar\helloworld.jar myManifest -C build\classes .
    java -jar build\jar\helloworld.jar

compile and run with external libraries(log4j)

Ant

refer:

Apache Ant is a Java-based build tool. In theory, it is kind of like make, without make's wrinkles.

Instead of writing shell commands, the configuration files are XML-based, calling out a target tree where various tasks get executed. Each task is run by an object that implements a particular Task interface. Below are list ant tasks:(refer http://ant.apache.org/manual/index.html at toc Ant Tasks)

create simple xml for building above simple application with ant

  1. step1: create build.xml(the same structure of makefile in linux)
    <project>
        <target name="clean">
            <delete dir="build"/>
        </target>
        <target name="compile">
            <mkdir dir="build/classes"/>
            <javac srcdir="src" destdir="build/classes"/>
        </target>
        <target name="jar">
            <mkdir dir="build/jar"/>
            <jar destfile="build/jar/helloworld.jar" basedir="build/classes">
                <manifest>
                    <attribute name="Main-Class" value="oata.helloworld"/>
                </manifest>
            </jar>
        </target>
        <target name="run">
            <java jar="build/jar/helloworld.jar" fork="true"/>
        </target>
    </project>

    ⇒ list targets in build.xml:

    clean, compile, jar, run

    ⇒ and list tasks in build.xml:

    delete, mkdir, javac, jar, java
  2. step2: build with ant and run
    set PATH=%PATH%;D:\tools\apache-ant-1.8.4\bin;d:\tools\jdk1.7.0_67\bin
    ant compile
    ant jar
    ant run

Enhance the build file

  1. Step1: custom enhance-build.xml with content below:
    <project name="helloworld" basedir="." default="main">
        <property name="src.dir"     value="src"/>
        <property name="build.dir"   value="build"/>
        <property name="classes.dir" value="${build.dir}/classes"/>
        <property name="jar.dir"     value="${build.dir}/jar"/>
        <property name="main-class"  value="oata.helloworld"/>
        <target name="clean">
            <delete dir="${build.dir}"/>
        </target>
        <target name="compile">
            <mkdir dir="${classes.dir}"/>
            <javac srcdir="${src.dir}" destdir="${classes.dir}"/>
        </target>
        <target name="jar" depends="compile">
            <mkdir dir="${jar.dir}"/>
            <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
                <manifest>
                    <attribute name="Main-Class" value="${main-class}"/>
                </manifest>
            </jar>
        </target>
        <target name="run" depends="jar">
            <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
        </target>
        <target name="clean-build" depends="clean,jar"/>
        <target name="main" depends="clean,run"/>
    </project>
  2. Step2: to build and run, we only run command below:
    ant -buildfile enhance-build.xml

    Output:

    Buildfile: D:\projects\java\simpleapplication\enhance-build.xml
    
    clean:
       [delete] Deleting directory D:\projects\java\simpleapplication\build
    
    compile:
        [mkdir] Created dir: D:\projects\java\simpleapplication\build\classes
        [javac] D:\projects\java\simpleapplication\enhance-build.xml:12: warning: 'includeantruntime' was not set, defaultin
    g to build.sysclasspath=last; set to false for repeatable builds
        [javac] Compiling 1 source file to D:\projects\java\simpleapplication\build\classes
    
    jar:
        [mkdir] Created dir: D:\projects\java\simpleapplication\build\jar
          [jar] Building jar: D:\projects\java\simpleapplication\build\jar\helloworld.jar
    
    run:
         [java] Hello World
    
    main:
    
    BUILD SUCCESSFUL
    Total time: 1 second

External libraries with ant

Update helloworld.java for using log4j external library:

package oata;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
public class helloworld {
    static Logger logger = LogManager.getLogger(helloworld.class);
    public static void main(String[] args) {
        System.out.println("Hello World");
        logger.error("Hello World");
    }
}

to use external lib log4j, we update the build.xml follow changes below: And full content of build.xml ater change:

<project name="helloworld" basedir="." default="main">
    <property name="lib.dir"     value="lib"/>
    <path id="classpath">
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>
    <property name="src.dir"     value="src"/>
    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>
    <property name="main-class"  value="oata.helloworld"/>    
    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>
    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}"  classpathref="classpath"/>
    </target>
    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>
    <target name="run" depends="jar">
        <java fork="true" classname="${main-class}">
            <classpath>
                <path refid="classpath"/>
                <path location="${jar.dir}/${ant.project.name}.jar"/>
            </classpath>
        </java>
    </target>
    <target name="clean-build" depends="clean,jar"/>
    <target name="main" depends="clean,run"/>
</project>

External libraries with eclipse

Go to properties → Java Build Path

Using Eclipse to import Ant build

maven

refer:

Maven, a Yiddish word meaning accumulator of knowledge, was originally started as an attempt to simplify the build processes in the Jakarta Turbine project

Maven’s primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with:

Maven will build all java classes in the src, and don't care the class names in src

Simple project

Create simple project with maven

Create basic simple maven:

  1. Step1: prepare environment
    set PATH=%PATH%;D:\tools\apache-maven-3.2.3\bin;D:\tools\jdk1.7.0_67\bin
    set JAVA_HOME=D:\tools\jdk1.7.0_67\
    mvn --version
  2. Step2: create simple project
    mvn archetype:generate -DgroupId=com.mycompany -DartifactId=simplemaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

    And the maven will create the directory tree below:

    simplemaven
    |-- pom.xml
    `-- src
        |-- main
        |   `-- java
        |       `-- com
        |           `-- mycompany
        |               `-- App.java
        `-- test
            `-- java
                `-- com
                    `-- mycompany
                        `-- AppTest.java
  3. Step3: Build
    cd simplemaven
    mvn compile

    ⇒ maven will download all dependency packages to ~/.m2

  4. Step4: Run
    java -cp target\simplemaven-1.0-SNAPSHOT.jar com.mycompany.App

    Output:

    Hello World!

Add new class to simple project and run

Create new class and run it in simple maven:

  1. Step1: Create new class Helloworld.java in simplemaven\src\main\java\com\mycompany\
    package com.mycompany;
     
    /**
     * Hello world!
     *
     */
    public class Helloworld
    {
        public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
        }
    }
  2. Step2: Rebuild the simplemaven:
    mvn compile
  3. Step3: Run Helloworld:
    java -cp target\simplemaven-1.0-SNAPSHOT.jar com.mycompany.Helloworld

    Output:

    Hello World!

Some basic commands with mvn

Set main class for packaging jar file

  1. Step1: Add build config for pom.xml which set main class is com.mycompany.Helloworld:
    <project>
    ........
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>        
            <configuration>
              <archive>
                <manifest>
                  <addClasspath>true</addClasspath>
                  <mainClass>com.mycompany.Helloworld</mainClass>
                </manifest>
              </archive>
            </configuration>
          </plugin>
        </plugins>
      </build>
    ........
    </project>  
  2. Step2: Build and Run:
    mvn compile
    java -jar target\simplemaven-1.0-SNAPSHOT.jar

Include resource for package jar file

refer:

Below are methods to include resources:

Using external library(dependency) log4j

  1. Step1: edit config to use log4j in pom.xml
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-api</artifactId>
          <version>2.0</version>
        </dependency>
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-core</artifactId>
          <version>2.0</version>
        </dependency>
      </dependencies>

And below are full 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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany</groupId>
  <artifactId>mavenexternaljar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>mavenexternaljar</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.0</version>
    </dependency>
  </dependencies>
</project>
  1. Step2: Edit App.java to use logger:
    package com.mycompany;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    /**
     * Hello world!
     *
     */
    public class App 
    {
        static Logger logger = LogManager.getLogger(App.class);
        public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
            logger.error("Hello World");
        }
    }
  2. Step3: Compile
    mvn compile
  3. Step4: Run with external library logger:
    mvn exec:java -Dexec.mainClass="com.mycompany.App"

Run java Main with Maven command

refer: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/

Maven Phases(Or targets)

Although hardly a comprehensive list, these are the most common default lifecycle phases executed:

There are two other Maven lifecycles of note beyond the default list above. They are:

Base on mavent phases, we can run command below to clean all files which are generated by maven by prior builds:

mvn clean

Maven 2.x Integration for Eclipse

refer: http://maven.apache.org/eclipse-plugin.html
Go to help→Install New Software: http://download.eclipse.org/technology/m2e/releases

M2E: The Maven Integration for Eclipse is the official Eclipse project aimed at integrating Maven within the Eclipse IDE. It is released under the EPL 1.0 license. Features include:

maven attach source and javadoc artifacts

config maven source plugin in pom.xml

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-source-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-sources</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

config maven javadoc plugin in pom.xml

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-javadocs</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

wrap maven with full jar files

run command below:

mvn wrap

Build Java with Gradle

refer: https://gradle.org/docs/

Introduce about Gradle

Introduce about Gradle:

Gradle supports the following repository formats:

Install Gradle Plugin in Eclipse

Below are steps to install Gradle Plugin in Eclipse

  1. Step1: Go to Help → Eclipse Marketplace
  2. Step2: Enter text below to search textbox
    gradle
  3. Step3: Click Install Buildship Gradle Integration 2.0 or Install Gradle IDE Pack

Add Depedency Package

refer: https://docs.gradle.org/3.3/userguide/dependency_management.html

  1. Step1: Goto pages below to search maven packages:
  2. Step2: search depedency package, for example “libgdx”, we will see info of package below:
    <dependency>
        <groupId>com.badlogicgames.gdx</groupId>
        <artifactId>gdx</artifactId>
        <version>1.9.6</version>
    </dependency>
  3. Step3: Configure depedency in build.gradle
    project(":core") {
        apply plugin: "java"
     
     
        dependencies {
            compile "com.badlogicgames.gdx:gdx:1.9.6"
    ...............................
        }
    }

Clear Gradle caches

Go to C:\Users\anhvc\.gradle and delete all files and directories in this directory ⇒ Fix error run gradle when you change java version from 1.8 to 1.7. When you change java version, you must reload new jar packages of gradle in new version 1.7

Fix error build with gradle when change default java form 1.8 to 1.7

I 've tried installing Java 8, and setting my project to use Java 8. If I change my JAVA_HOME to 1.8 on the command line and compile with gradle it works. If I try to use JAVA_HOME set to 1.7 and gradle it fails with the same error.

java.lang.UnsupportedClassVersionError: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0

⇒ Fix: set JAVA_HOME and PATH to java8

Build Java with eclipse

Add jars or class build path

Add required project

Proguard

refer: https://www.guardsquare.com/en/proguard