====== 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 ==== - step1: create simple application with below directory structure: md src md build\classes md build\jar - step2: create simple application **src\oata\helloworld.java**: package oata; public class helloworld { public static void main(String[] args) { System.out.println("Hello World"); } } - 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 - 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: * http://ant.apache.org/manual/index.html * http://ant.apache.org/manual/Tasks/javac.html * refer: https://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html 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 ==== - step1: create build.xml(the same structure of makefile in linux) => list targets in build.xml: clean, compile, jar, run => and list tasks in build.xml: delete, mkdir, javac, jar, java - 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 ==== - Step1: custom enhance-build.xml with content below: - 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: {{:java:external-jar.png|}} And full content of build.xml ater change: ==== External libraries with eclipse ==== Go to **properties -> Java Build Path** ==== Using Eclipse to import Ant build ==== {{:java:ant-eclipse.png|}} ===== maven ===== refer: * http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html 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: - 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 - 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 - Step3: Build cd simplemaven mvn compile => maven will download all **dependency packages** to **~/.m2** - 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: - 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!" ); } } - Step2: Rebuild the simplemaven: mvn compile - Step3: Run Helloworld: java -cp target\simplemaven-1.0-SNAPSHOT.jar com.mycompany.Helloworld Output: Hello World! ==== Some basic commands with mvn ==== * Show **all options** of mvn mvn -h * compile code in project mvn compile * maven **search** packages: http://search.maven.org/ or https://mvnrepository.com/ ==== Set main class for packaging jar file ==== - Step1: Add build config for pom.xml which set** main class** is **com.mycompany.Helloworld**: ........ org.apache.maven.plugins maven-jar-plugin true com.mycompany.Helloworld ........ - Step2: Build and Run: mvn compile java -jar target\simplemaven-1.0-SNAPSHOT.jar ==== Include resource for package jar file ==== refer: * https://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html * https://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html Below are methods to include resources: * Include directory ... ... [your folder here] ... ... * Include files ... My Resources Plugin Practice Project ... ... [your directory] [resource file #1] [resource file #2] [resource file #3] ... [resource file #n] ... ... ... ==== Using external library(dependency) log4j ==== - Step1: edit config to use log4j in pom.xml org.apache.logging.log4j log4j-api 2.0 org.apache.logging.log4j log4j-core 2.0 And below are full pom.xml: 4.0.0 com.mycompany mavenexternaljar jar 1.0-SNAPSHOT mavenexternaljar http://maven.apache.org junit junit 3.8.1 test org.apache.logging.log4j log4j-api 2.0 org.apache.logging.log4j log4j-core 2.0 - 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"); } } - Step3: Compile mvn compile - 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 org.apache.maven.plugins maven-source-plugin attach-sources jar config maven javadoc plugin in pom.xml org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar ==== 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: * 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 - Step1: Go to **Help -> Eclipse Marketplace** - Step2: Enter text below to **search** textbox gradle - 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 - Step1: Goto pages below to search maven packages: * http://search.maven.org/ * or https://mvnrepository.com/ - Step2: search depedency package, for example "libgdx", we will see info of package below: com.badlogicgames.gdx gdx 1.9.6 - 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 ==== {{:java:eclipse-jar-libraries.png|}} ==== Add required project ==== {{:java:eclipse-project-depedency.png|}} ===== Proguard ===== refer: https://www.guardsquare.com/en/proguard