User Tools

Site Tools


java:build-java

Build Java

Prepare environment variables

  • add below paths to PATH environment variable in windows
    d:\tools\jdk1.7.0_67\bin;D:\tools\apache-ant-1.8.4\bin;D:\tools\apache-maven-3.2.3\bin;
  • add new environment variable JAVA_HOME(Change Environment Variables in Windows)
    d:\tools\jdk1.7.0_67

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)

  • update code to use log4j2
    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");
        }
    }
  • compile:
    D:\projects\java\externaljar>javac -cp "lib\log4j-core-2.0.jar";"lib\log4j-api-2.0.jar" -sourcepath src -d  build\classes src\oata\helloworld.java
  • run:
    java -cp "lib\log4j-core-2.0.jar";"lib\log4j-api-2.0.jar";"build\classes" oata.helloworld

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)

  • Archive Tasks
  • Audit/Coverage Tasks
  • Compile Tasks
  • Deployment Tasks
  • Documentation Tasks
  • EJB Tasks
  • Execution Tasks
  • File Tasks
  • Java2 Extensions Tasks
  • Logging Tasks
  • Mail Tasks
  • Miscellaneous Tasks
  • Pre-process Tasks
  • Property Tasks
  • Remote Tasks
  • SCM Tasks
  • Testing 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:

  • Making the build process easy
  • Providing a uniform build system
  • Providing quality project information
  • Providing guidelines for best practices development
  • Allowing transparent migration to new features

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:

  • Include directory
    <project>
    ...
      <build>
       ...
        <resources>
          <resource>
            <directory>[your folder here]</directory>
          </resource>
        </resources>
       ...
      </build>
    ...
    </project>
  • Include files
    <project>
      ...
      <name>My Resources Plugin Practice Project</name>
      ...
      <build>
        ...
        <resources>
          <resource>
            <directory>[your directory]</directory>
            <includes>
              <include>[resource file #1]</include>
              <include>[resource file #2]</include>
              <include>[resource file #3]</include>
              ...
              <include>[resource file #n]</include>
            </includes>
          </resource>
          ...
        </resources>
        ...
      </build>
      ...
    </project>

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/

  • Without arguments:
    mvn exec:java -Dexec.mainClass="com.mycompany.App"
  • With arguments:
    mvn exec:java -Dexec.mainClass="com.mycompany.App" -Dexec.args="arg0 arg1 arg2"
  • With runtime dependencies in the CLASSPATH
    mvn exec:java -Dexec.mainClass="com.mycompany.App" -Dexec.classpathScope=runtime

Maven Phases(Or targets)

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

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

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

  • clean: cleans up artifacts created by prior builds
  • site: generates site documentation for this project

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:

  • Launching Maven builds from within Eclipse
  • Dependency management for Eclipse build path based on Maven’s pom.xml
  • Resolving Maven dependencies from the Eclipse workspace without installing to local Maven repository
  • Automatic downloading of the required dependencies and sources from the remote Maven repositories
  • Wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects
  • Quick search for dependencies in remote Maven repositories
  • Quick fixes in the Java editor for looking up required dependencies/jars by the class or package name
  • Integration with other Eclipse tools, such as WTP, AJDT, Mylyn, Subclipse and others.
  • M2E dynamically integrates with your Maven projects with Eclipse while you make changes in the IDE. As you change dependencies, or configurations of Maven plugins in your POMs M2E, will synchronize the Eclipse workspace with those changes.

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

Introduce about Gradle

Introduce about Gradle:

  • A very flexible general purpose build tool like Ant.
  • Switchable, build-by-convention frameworks like Maven. But we never lock you in!
  • Very powerful support for multi-project builds.
  • Very powerful dependency management (based on Apache Ivy).
  • Full support for your existing Maven or Ivy repository infrastructure.
  • Support for transitive dependency management without the need for remote repositories or pom.xml and ivy.xml files.
  • Ant tasks and builds as first class citizens.
  • Groovy build scripts.
  • A rich domain model for describing your build.

Gradle supports the following repository formats:

  • Ivy repositories
  • Maven repositories
  • Flat directory repositories

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

java/build-java.txt · Last modified: 2024/04/19 03:24 by admin