Showing posts with label BUILD TOOL. Show all posts
Showing posts with label BUILD TOOL. Show all posts

Thursday, 3 June 2021

Gradle Build : Project API Inbuilt properties

 One can use these properties given by gradle project api, within build.gradle file.

------------------------------Start of the File--------------------------

build.gradle

//project api properties
logger.info("Name of the project: ${project.name}")
logger.info(
"absolute path of the project: ${project.path}")
logger.info(
"description for the project: ${project.description}")
logger.info(
"directory containing the build script: ${project.projectDir}")
logger.info(
"build directory: ${project.buildDir}")
logger.info(
"${project.group}")
logger.info(
"${project.version}")

//The above properties - print same as below
//project api properties without project. prefix - implied by default
logger.info("Name of the project: ${name}")
logger.info("absolute path of the project: ${path}")
logger.info("description for the project: ${description}")
logger.info("directory containing the build script: ${projectDir}")
logger.info("build directory: ${buildDir}")
logger.info("${group}")
logger.info("${version}")
------------------------------End of the File--------------------------
Execution:
gradle -i build

-i for enabling logging for info level.
Output:
Name of the project: gradle-demo
absolute path of the project: :
description for the project: null
directory containing the build script: /Users/dinesh/IdeaProjects/gradle-demo
build directory: /Users/dinesh/IdeaProjects/gradle-demo/build

unspecified
Name of the project: gradle-demo
absolute path of the project: :
description for the project: null
directory containing the build script: /Users/dinesh/IdeaProjects/gradle-demo
build directory: /Users/dinesh/IdeaProjects/gradle-demo/build

unspecified

Gradle Logging Options: How to use logger in gradle build files?

 By default, there are no logs printed, because logging is disabled by default.

OptionOutputs Log Levels

no logging options

LIFECYCLE and higher

-q or --quiet

QUIET and higher

-w or --warn

WARN and higher

-i or --info

INFO and higher

-d or --debug

DEBUG and higher (that is, all log messages)


Note: reference official docs

Friday, 5 February 2021

How to force the maven to redownload all the packages ?

First Way: 

You can use mvn option -U : which forces the maven to download the dependency into local repository (.m2 folder)

Eg:

mvn clean package -U

Second Way:

Use purge-local-repository

Eg:

mvn dependency:purge-local-repository clean package


Third Way:

You can manually directly delete the .m2 folder in computers home directory (like in linux - mac, ~)





Wednesday, 8 February 2017

GRADLE BASICS - EXAMPLE GRADLE PROJECT FROM TERMINAL - COMPARISON WITH MAVEN

Gradle is a build tool just like Maven.(if you are not familiar with maven check this link)

A build tool generally does provide features like dependency management, compilation, packaging & running the unit test cases during its build phases.

Build Tool Features: 

Dependency Management: Provides all the project dependencies (eg: some external jars)

Compilation: Compiles the source code

Packaging: packages the project in jar / war as you configure in build file

Test Cases Execution: once after successful compilation & before packaging it executes the test cases.
 
Maven uses pom.xml as its build file, where all dependencies of the project & packaging of the project (either jar/war) are declared. Whereas, Gradle uses build.gradle file to declare all the dependencies & plugins required for the project. Maven uses XML as its file format, while gradle uses Groovy code.

Note: But to start a gradle project, we don't need to be an expert in Groovy.

Gradle Installation:

you download the latest Gradle distribution here : Download Gradle

Note: Gradle require JDK / JRE 7 or higher versions (mandatory)

Once after downloading the distribution, add the bin folder path to environment variable "PATH". This makes the binary gradle commands to work any where in the command-line.

In Ubuntu: you can also install using this command

dinesh@dinesh:~$ sudo apt-get install gradle

(by using this above command, you do not need any extra configuration like maintaining PATH environment variable. The binary shell script gradle.sh directly placed under /usr/bin/ path, which is already by default added to PATH environment variable).

In Mac: you can also install using this command

dinesh@dinesh:~$ brew install gradle

I recommend to get the binary distribution directly from gradle site.

Now, you can test the installation using the following gradle command(in command-line)

dinesh@dinesh:~$ gradle -v 

for the successful installation, you will see the following output

------------------------------------------------------------
Gradle 3.3
------------------------------------------------------------

Build time:   2017-01-03 15:31:04 UTC
Revision:     075893a3d0798c0c1f322899b41ceca82e4e134b

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_92 (Oracle Corporation 25.92-b14)
OS:           Linux 3.5.0-61-generic amd64


A Sample Gradle Project:

To create gradle project, you must first need to create build.gradle file

> Create a directory for the project

dinesh@dinesh:~$mkdir gradle_proj

> Switch to project

dinesh@dinesh:~$  cd gradle_proj

> Create a build.gradle file

dinesh@dinesh:~/gradle_proj$ gedit build.gradle

Note: gedit is an editor in ubuntu os, you can use any editor you are comfortable with, like sublime text, notepad++
 


Now, apply a java gradle plugin in the script: 

apply plugin: 'java' 

Note: This is important plugin inorder to resolve the project dependencies. Now, you can check the importance of the above line added in build.gradle file, you execute a gradle command

dinesh@dinesh:~/gradle_proj$ gradle tasks

This command "gradle tasks" shows all the project tasks.

A task is small atomic unit of work which performs our build (a task can be compilation, running tests. For that matter, any build tool feature).

when it is executed, it first search for the build.gradle, it shows all the tasks that are related to java plugin. For example, build & test are some of the tasks added. Some of the important tasks are assemble, build, test & dependencies

I can relate the tasks in gradle to Maven goals. 

when you run "gradle tasks", you may see these:


I recommend, once you execute the same command with empty build.gradle file to notice the tasks added especially by java gradle plugin.

Now, you can add a dependency, all the dependencies are added to dependencies block

dependencies{
    compile("org.springframework.boot:spring-boot-starter-web:1.5.1.RELEASE")
}


To resolve, these dependencies you must also add a repository, where all dependencies are downloaded from.

Add a repository block

repositories{
    mavenCentral()
}


The added dependencies are successfully resolved by just executing this

dinesh@dinesh:~/gradle_proj$ gradle build



Now, this commands downloads all the dependencies from maven central. You can also use other repositories like jcenter().

Create a directory for adding java files:

dinesh@dinesh:~/gradle_proj$ mkdir -p src/main/java/sample

Add Some Source Code: Spring Boot Application

package sample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
@RestController
public class SampleApp{ 

 public static void main(String[] args) throws Exception {
  SpringApplication.run(SampleApp.class, args);
 }

 @RequestMapping("/home")
 public String getHome(){
  return "I am Home";
 } 
 
}

To execute the spring boot application, I am adding the spring boot gradle plugin to classpath using buildscript block

buildscript{

    repositories{
        mavenCentral()
    }

    dependencies{
        classpath("org.springframework.boot:spring-boot-gradle-plugin

                                                            :1.5.1.RELEASE")
    }


}


To get the dependency to classpath, we need to separately define repositories block in buildscript block also.

And also apply the plugin

apply plugin: 'org.springframework.boot'

Now, execute the command 

dinesh@dinesh:~/gradle_proj$ gradle clean build

This once again builds. Once execute the ls command to see the files & directories (dir for windows). It creates build directory as maven creates a target directory.

dinesh@dinesh:~/gradle_proj$ gradle tasks

you will find a gradle task related to spring boot gradle plugin, bootRun:

 
 Now, you can start the spring boot application by running this gradle task: bootRun

dinesh@dinesh:~/gradle_proj$ gradle bootRun

This starts the spring boot application by searching the java file having main method:

 
  Now, type localhost:8080/home in your browser & it returns "I am Home".

                        Hope it helps :) Please share :)

Tuesday, 16 September 2014

WHAT IS MAVEN ? A PROJECT MANAGEMENT TOOL (UPDATED)

MAVEN is a Java Dependency Management tool. You wonder what is a dependency management tool.

Its Simple...

For instance, if your working on a project which uses many external jar files, which you generally download from the web and then you configure them in the classpath- which is a conventional way of doing.

But if you use maven tool which is basically command line tool(can also be integrated with popular IDEs like NET BEANS & ECLIPSE), you can create a project without this overhead 
How?

Behind the scenes, maven actually works for us a lot to get the required jars from a central repository(collections of jars),  but as a developer only need to do is to supply it the information specifically related to the project you want to create.

We can supply our project information(required jars-simply called as dependencies) through a simple XML file which is called pom.xml

Let us take an example, consider I am developing a JMS application which uses JMS
(Java Messaging Service) API jar file, here for your application this is a dependency, without which you can't create your app. 

And also consider, you are using logging API(requires log4j jar file) in your project for logging purposes, so this is also considered as another dependency.

so we need JMS jar and log4j jar for my project to be completed,so specify them in pom.xml file

Example:

<?xml version="1.0" encoding="UTF-8"?>

<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">

        <groupId>....your groupid or your company name..</groupId>
       <artifactId>..your project name...</artifactId>
    <version>..your project build version number---</version>
       <modelVersion>4.0.0</modelVersion>

<!-- Here are your project dependencies-->

    <dependencies>
        <dependency>
                       <groupId>javax.jms</groupId>
                      <artifactId>javax.jms-api</artifactId>
                      <version>2.0</version>
        </dependency>
        <dependency>
                      <groupId>log4j</groupId>
                      <artifactId>log4j</artifactId>
                      <version>1.2.17</version>
        </dependency>
  </dependencies>
  <build>
           <!-- I can use various maven plugins for different use cases- like reporting
                 ,  mailing, packaging(such jar, war) -->
          <!-- Here I am using a reporting plugin - Maven-Surefire-Report-Plugin
            .This plugin generates a html report showing all my test case failures  
           passed cases & skipped test cases--> 
         <!-- you have use plugins & dependencies according to your project needs--> 
      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                    </dependency>
 
          </plugin> 
      </plugins>    
  </build>
</project>


JMS jar details are

                   <groupId>javax.jms</groupId>
                  <artifactId>javax.jms-api</artifactId>      
                    <version>2.0</version>

log4j jar details are

                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                 <version>1.2.17</version>


Terminology :

groupId
artifactId
version

are tags that maven generally uses to specify the project structure.

groupId is generally a name which represents a company the project belongs to.

artifactId is name of your project

version is the build release version

Plugins are placed under build tag. As aforementioned, you can use any plugins such as war plugin creates a war file for a web application, jar plugin creates a jar file. In the above example, I have defined a surefire-report plug-in , this creates an HTML report for your tests if there are any tests in your project.

Sample Surefire Report 

You can configure your plugins using a <configuration> tag under <plugin> tag.

Let us, you want your surefire-reports, i.e HTML file, you this file to be stored in an outtput directory called newsite. you can configure like this


      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                              <configuration>                                      
                     <outputDirectory>${basedir}/target/newsite</outputDirectory>
                              </configuration>
          
          </dependency>
 
          </plugin> 
      </plugins>    

${basedir}  is the default variable represents the path of your project.

say your project is at c:/documents/MyProject  

so ${basedir} points to this path.

By default, Surefire-report plugin stores its reports in site folder under target.


Maven  has build life cycle phases. During this life cycle phases, it performs various operations. Mostly the build phase names are self-explanatory.

Maven's default build life cycle phases : validate, compile, test, package, integration-test-process, verify, install and deploy.

  • 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.


Complete list of Build Phases

<scope> represents this plugin is going to be used in only test phase of the build life cycle.

One of Maven plug in's : maven-compiler-plugin. Its scope is only up to compile build phase. Because it is going to be used only in compiling the classes of your project. so you can specify the <scope>compile</scope> for compiler-plugin.
  

Important Note: Once maven builds a project - you are able to see a new target folder, where all distributions(war, jar) , surefire reports , and compiled classes are placed in that target folder.

 Until you have pom.xml file in your project folder, you cannot execute your maven goals.

Oh! what are Maven goals? How to execute maven using command line?

Each and every maven build phases binds to some goals:

say:

assume this format for explanation - Build Phase: Goals

>>>>>>>>>>>>>>>>
compile phase : compiler:compile
>>>>>>>>>>>>>>>

During compile phase, a compiler plugin uses these goals to perform its executions.

For example, Maven-compiler-plugin as another goa

compiler: testCompile (here, compiler represents plugin & testCompile is the goal)

Whats the difference between two goals?

Here, the plugin used is same - maven-compiler-plugin. But these two goals: compile & testCompile are executed in two different build phases

Execute maven compile goal  like this
(on command line)


< proj path>$ mvn compiler:compile 

Note: In proj path - you must have pom.xml file.

This only compiles your main source files. (Exclusdes test source files)

Whereas, testCompile goal is bound to test-compile phase 

As I mentioned, test is also a build phase. test-compile is executed just before test build phase. These test classes are excluded during compilation of normal source files.

>>>>>>>>>
test phase: surefire-report:report
 >>>>>>>>>

Here, Build phase is test.  Plugin used here is maven-surefire-report-plugin.

surefire-report:report

surefire-report represents plugin

report represents goal

Note: This is one of the reporting plugin I have used in test phase. There can be n number of maven reporting plugins. you have decide which to one to choose.
This post will be updated in future also. 
An Updated on 25-Feb-2015