Tag : mahendra-tonape

Developing custom maven plugin using Java5 annotations

Maven provides lots of built-in plugins for developers but at some point you may find need of custom maven plugin. Developing custom maven plugin using java5 annotations is very simple and straightforward.

 

d

 

You just need to follow below steps to develop custom maven plugin using Java 5 annotations:

 

Steps:

 

1. Create a new project with pom packaging set to “maven-pom”

 

2. Add below dependencies to your plugin pom:

 

i.Maven-plugin-api dependency helps for developing mojos required by custom maven plugin.

<dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
</dependency>

 

ii. Since Maven 3.0 version we can use java 5 annotations to develop custom plugin.with annotations it is not necessasry that mojo super class should be in the same project if your super class also uses annotations. To use annotations in mojos add below dependency to your plugin pom file.

<dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
</dependency>

 

iii.Below dependency is used to not only read Maven project object model files, but to assemble inheritence and to retrieve remote models as required.

<dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-project</artifactId>
            <version>2.0.6</version>
</dependency>

 

iv. If you want to add any test cases or any other 3rd party dependencies add them.

 

3.Maven plugin tools looks classes with @Mojo annotation any class annotated with @Mojo will be added to plugin configuration file.

 

Eg:

 

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
@Mojo(name="simplePlugin")
public class CustomMojo extends AbstractMojo{
            @override
            public void execute() throws MojoExecutionException, MojoFailureException {
            getLog().info("Successfully created custom maven plugin");
                        /*
                        * your businees logic goes here
                        */
            }
}

 

The “name” parameter of mojo annotation is your plugins name,your plugin will be recognised with this name.You mojo class extends AbstractMojo class.AbstractMojo class implements mojo interface and set logging for your plugin.AbstractMojo sets log4j based logging getLog() method provides info,error,debug,warn levels of logging.

 

Mojo interface is having execute method which will contain business logic of plugin.execute method throws 2 kinds of execptions:

 

i. MojoFailureException : If expected probelm occurs throwing this exception causes Build Failure message to be displayed.Throwing this exception causes build failure.

 

ii. MojoExecutionException : If unexcepted probelm occurs throwing this exception causes Build error message to be displayed.

 

4.You can execute your plugin from command line by providing following command:

 

mvn pluginGroupId:artifactID:version:mojoName

to shorten the command to be executed for plugin add below lines to maven’s settings.xml file in pluginGroups section. This will tell maven to search repository for this groupID:

<pluginGroups><pluginGroup>plugin group id</pluginGroup></pluginGroups>

After this you can run your plugin simply by providing goal prefix and mojo name command to run plugin will be like this:

mvn goalPrefix:mojoName

 

5. configuring goalPrefix:

To Create goalPrefix add plugin maven-plugin-plugin to maven plugin pom.It is used to create plugin descriptor for any mojo’s found in source tree to include in jar.it can be used for generating report files for mojo’s updating plugin registry.

Eg:

<build>
                        <plugins>
                                    <plugin>
                                                <groupId>org.apache.maven.plugins</groupId>
                                                <artifactId>maven-plugin-plugin</artifactId>
                                                <version>3.4</version>
                                                <configuration>
                                                            <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                                                            <goalPrefix>your goalPrefix</goalPrefix>
                                                            <parameter1>custom param1</parameter1>
                                                            <parameter2>custom param2</parameter2>
                                                </configuration>
                                                <executions>
                                                            <execution>
                                                                        <id>mojo-descriptor</id>
                                                                        <phase>process-classes</phase>
                                                                        <goals>
                                                                                    <goal>descriptor</goal>
                                                                        </goals>
                                                            </execution>
                                                </executions>
                                    </plugin>
</build>

 

6. You can pass external parameters to your plugin from command line and also you can set default values for you parameters if they are not send from command line.

 

Eg:

@Parameter(property = "param1", defaultValue = "abc")
            private String type;

 

command to run plugin by passing parameter is :

mvn goalPrefix:mojoName -Dparam1='acd';

 

if you set required parameter of property to false then there is no compulsion of passing parameter from command line.

As we all know that maven has default structure of scanning source files in src/main/java structure and test files in src/test folded,similarly if you want your plugin to scan files in particular folder in your project structure then you can do this by adding org.apache.maven.project.MavenProject property

to your project.

Eg:

            @Parameter(defaultValue = "${project}", readonly = true, required = true)
            private MavenProject project;

 

you can also set default values to your parameters by setting parameter property name tag in maven-plugin-plugin plugin’s configuration section.if you don’t want to set default property then keep these custom property fields blank.these property fields are the property values you mentioned in mojo.

 

9. Using your plugin in main project: for using your plugin in another project add plugins dependency in build section of your project.

Eg:

 

        <build>
       <plugins>
         <plugin>
           <groupId>plugin's group id</groupId>
           <artifactId>>plugin's artifact id</artifactId>
           <version>versin of plugin</version>
         </plugin>
       </plugins>
     </build>

 

10. To release plugin copy plugin’s jar and other dependent jars from your m2 repository and release it to client or qa.

 

Here we are done with developing custom maven plugin with java 5 annotations.please let me know if you have any doubts or suggestions.The sample project is present on github you can download it from below link:

 

https://github.com/omtonape/CustomPlugin-MavenJava5Annotations.git

 

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Writing Custom Gradle Plugin using Java

What is Gradle ?

Gradle is build automation tool based on Apache ant and Maven. Gradle avoids traditional .xml file based configuration by introducing groovy based domain specific language. In gradle project have .gradle files instead of .pom files. Gradle was designed for multi-project builds and supports incremental build.

Gradle plugin groups together reusable pieces of build logic which can be then used across many different projects and builds. We can use any language whose compiled code gets converted to byte code for  developing custom gradle plugin. As gradle is mainly designed using groovy language its very easy to develop gradle plugin using groovy but  lets see how to develop custom gradle plugin using Java language:

d

Here are the steps :

 

1. Create new Java project using eclipse or any other IDE.

 

2. Create plugin folder in your project which will have source code of your custom gradle plugin.

 

3. create your package structure in this plugin folder.

    Eg: com.sample.gradle

This package structure will have your custom plugins source code.

 

4. Create Plugin class which will implement Plugin<Project> interface.Plugin is represents extension to gradle.This interface is having apply method which applies configuration to gradle Project object.

Eg :

package com.sample.gradle;
import org.gradle.api.Project;
import org.gradle.api.Plugin;
import com.sample.gradle.SamplePluginExtension;
public class SampleGradlePlugin implements Plugin<Project> {
                @Override
    public void apply(Project target) {
                                target.getExtensions().create("samplePlugin",
                                                                SamplePluginExtension.class);    }
}

 

5. All the user defined values to custom plugin are provided through extension object so creaete extension class and register it with plugin as shown above to receive inputs from user.If user doesnot provided input then default values will be assumed.

 

6. Create extension class which is similar to java pojo class it will contain user defined properties and their getter setter methods.If user provides values for these properties during run time then these values will be accepted otherwise default values will be considered.

 

Eg :

public class SamplePluginExtension {
                private String sampleFilePath="/home/mahendra/abc”;
                public void setSampleFilePath(String sampleFilePath){
                  this.sampleFilePath=sampleFilePath;
                }
                public String getSampleFilePath(){
                                return sampleFilePath;
                }
}

 

7. Create task class which will have your plugin logic this task class contains your main plugin logic.This task class extends org.gradle.api.DefaultTask class and defines method with @TaskAction annotation.This method will have actual logic.

Eg:

package com.sample.gradle;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SampleTask extends DefaultTask {
                private final Logger log = LoggerFactory.getLogger(this.getClass());
                @TaskAction
                public void samplePluginTasks() throws TaskExecutionException {
                                log.info("Starting  sample task");
                                try {
                                                SamplePluginExtension extension = getProject().getExtensions()
                                                                                .findByType(
amplePluginExtension.class);
                                                String filePath = extension.getSampleFilePat
();
                                                log.debug("Sample file path is: {}",filePath
;
                                                /* Here comes
                                                 *
                                                 * your main logic
                                                 *
                                                 */
                                                log.info("Successfully completed sample Task
);
                                }catch(Exception e){
                                                log.error("",e);
                                                throw new TaskExecutionException(this,new Ex
eption("Exception occured while processing sampleTask",e));
                                }
                }
}

 

For logging into your custom plugin use slf4j or any other logging framework of your choice.If you want to fail the build on exception in your task then throw TaskExecutionException which will cause BuildFailures other exceptions will not cause build failure.TaskExecutionException accepts task object and Throwable object as input.

 

Here DefaultTask is standard gradle task implementation class and we need to extend it while implementing custom tasks.@TaskAction annotation makes method action method and whenever task executes this method will be executed.

 

8. Registering plugin class : create resources folder in plugin/src/main folder.Inside resources create META-INF/gradle-plugin folder, in this gradle-plugin folder create properties file.Name of this property file is used for registering plugin in build.gradle build file.

 

eg: sample-plugin.properties:

In sample-plugin.properties file add following line:

implementation-class=com.sample.gradle.SampleGradlePlugin

value of implementation-class if path of plugin class.

 

9. Create settings.gradle file in your plugin folder which will have below line:

rootProject.name = 'customGradlePlugin'

value of rootProject.name is name of your root project.

 

10. Create build.gradle build file for you plugin in plugin folder as follows:

apply plugin: 'java'
dependencies {
    compile gradleApi()
}
apply plugin: 'maven-publish'
repositories {
    mavenCentral()
    mavenLocal()
    jcenter()
}
dependencies {
    compile 'org.slf4j:slf4j-simple:1.6.1'
    testCompile 'junit:junit:4.11'
}
group = 'com.sample.gradle'
version = '1.0.0'
publishing {
                publications {
                                maven(MavenPublication) {
                                                groupId "$group"
                                                artifactId 'CustomGradlePlugin'
                                                version "$version"
                                                from components.java
                                }
                }
}
uploadArchives {
    repositories {
            mavenLocal()
    }
}

as we are developing gradle plugin using java add apply plugin:’java’ line.whatever external dependencies your plugin is dependent upon add these dependencies in dependencies section.the repositories in which your plugin should look for should be mentioned in repositories section.mentioned group id,version of plugin in group and version tag.

For making plugin available to other projects gradle plugin should be published to repository or its archives should be uploaded for this purpose either use publishing or uploadArchives functionality.

 

for publishing plugin use following command if you are publishing plugin to local maven repository:

“gradle clean build publishToMavenLocal”

 

If you are uploading plugin to local maven repository then use below command:

“gradle clean build uploadToArchives”

 

11. For using plugin in another projects make following changes in build.gradle file of your project.

apply plugin: 'java'
buildscript {
repositories {
         mavenLocal()
         mavenCentral()
    }
    dependencies {
                                classpath "com.sample.gradle:CustomGradlePlugin:1.0.0"
    }
}
apply plugin: 'sample-plugin'
 task sampleTask(type: com.sample.gradle.SampleTask) {
 samplePlugin.sampleFilePath = "$sampleFilePath"
}

 

here plugin dependency must be defined in buildscript section and  to tell gradle which repositories to scan for getting plugin dependencies  add repositories section in buildscript section this repository section must come ahead of dependencies section.Afer this add apply plugin line.

Sample task provided will be used for executing our plugin logic in task value of type is path of our custom task.whatever custom arguments we want to provide to plugin that we need to define in task section .if we want to run with default parameters then comment samplePlugin.sampleFilePath line in task section.

To run plugin with custom parameter use below command:

gradle clean build sampleTask -PsampleFilePath='/home/mahendra/abc.sample'

 

To run plugin without custom parameter use below command:

gradle clean build sampleTask

 

Sample plugin project structure is as follows:

 

m

 

Here we are done with developing gradle custom plugin with java.

 

please let me know if you have any issues or suggestions.The sample project is present on github you can download it from below link:

https://github.com/omtonape/CustomPlugin-GradleJava.git

 

Please do not forget to comment your feedback on this Article! :-)

 

 

 

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

About US

crazyadmins.com is developed by hadoop lovers to share knowledge about open source technologies, latest hadoop technologies and much more, if you think you are crazy for sharing your knowledge, please email your articles on any opensource technology on crazyadmins.com

email ID –  info@crazyadmins.com

Like Our Facebook page – https://www.facebook.com/crazyhadoopers

 

Screen Shot 2016-04-08 at 3.38.58 PM   Kuldeep Kulkarni: Website founder and Contributor

     LinkedIn : https://in.linkedin.com/pub/kuldeep-kulkarni/23/167/707
     Facebook: https://www.facebook.com/cools1990
     HDP Certified Administrator
     Cloudera Certified Hadoop Administrator [ License number – 100-014-213 ]

 

 

In Kuldeep’s words…
Having a great passion for technologies and interest in knowing all that is possible and achievable. At the same time I also believe in sharing the same knowledge and experiences with everyone. This is one such initiative to do so!
Crazy for Hadoop and I have started learning it since the beginning of my career. With 4+ years of experience, currently working on exploring all Big Data Technologies Administration.
Also good at good shell scripting, I strongly support automation of every possible task to make things easier for implementation and management. Lets Hadoop everyone! :)

 


 

  Arti Wadhwani: Contributor

   LinkedIn : https://in.linkedin.com/in/artiwadhwani
   Facebook: https://www.facebook.com/WadhwaniArti
   HDP Certified Administrator
   Cloudera Certified Hadoop Administrator [ License number – 100-014-210 ]

 

 

In Arti’s words…
Started as a fresher by being a part of Technical Operations team. Got great opportunities to grow and then started exploring more of Hadoop. It has been more than 4+ years now and my love for Hadoop is only increasing! :) Currently working on core BigData Technologies and enjoying being a Hadooper! :-)

 


 

mayur   Mayur Bhokase: Contributor

   LinkedIn : https://in.linkedin.com/pub/mayur-bhokase/76/14b/56
   Facebook: https://www.facebook.com/bhokasemayur

 

 

In Mayur’s words…
I’m professional java developer since last 3 years in well known multinational IT industry and famous for my jasper, spring, angular JS and hibernate skills,  I’m always enthusiastic about sharing my domain knowledge with techies

 


 

tussi

 

   Tushar Bodhale: Contributor

   LinkedIn : https://in.linkedin.com/pub/tushar-bodhale/24/4b3/665
   Facebook: https://www.facebook.com/tusharbodhale

 

In Tushar’s words…
” Having 4+ years of experience in Application Design, Development and Maintenance but still there is lot to learn.
Technology is always the integral part of my life and hence love to share my experience through such blogs.
I like experimenting new technologies by working as a freelancer “

Believe ” When we know it, you’ll know it…”

 


 

MyPhoto

 

  Mahendra Tonape: Contributor

   LinkedIn : https://www.linkedin.com/pub/mahendra-tonape/22/28b/641 
   Facebook: https://www.facebook.com/mahendra.tonape.9

 

In Mahendra’s words…
“I am working as java developer since more than 3 years.I really feels java is base platform to so many latest technologies and new software developments thanks to great open source community of java I would really love to be part of java’s large open source community.”

 


 

hajime

  Hajime Osako: Contributor

   LinkedIn : https://www.linkedin.com/in/hajime-osako-a3280048 
   HDP Certified Administrator

 

 

In Hajime’s words…
“Started as a graphic designer including 3d animation in Japan. More than 10 years of experience as Web application developer with PHP, Python and Java. Also worked as MySQL, SQL Server, PostgreSQL DBA and also FreeBSD, Ubuntu Server system administrator, but new to Hadoop and enjoying learning new things everyday”