Showing posts with label Maven. Show all posts
Showing posts with label Maven. Show all posts

Thursday 23 November 2017

How to enforce specific JDK for a Maven build

As you maybe aware, the Maven enforcer plugin provides the option to enforce specific rules while building a project. For instance we could enforce a specific version of JDK to be used for a build.

For instance, let us enforce the usage of JDK 1.8.0. In that case, check the configuration of maven-enforcer-plugin in your main parent POM

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
<phase>validate</phase>
</execution>
</executions>
<configuration>
<rules>
<requireJavaVersion>
                  <version>1.8.0</version>
                </requireJavaVersion>
</rules>
</configuration>
</plugin>

Note the <requireJavaVersion> tag used for the same. For more information, check the following link as well.

How to configure Jacoco plugin in Maven

Guys, for getting the unit test coverage report in SonarQube for code quality and analysis, let us look into how to use the Jacoco plugin for the same. In this post we'll see how to configure Maven with the Jacoco plugin. FYI Jacoco is a free code coverage tool for Java


In your main parent POM, let us enter the Sonar properties firstly, as follows :

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.jacoco.reportPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
<drools.version>5.5.0.Final</drools.version> 
</properties> 

Now in the <pluginManagement> section, let us enter the configuration for the Jacoco plugin.

<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.2.201409121644</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>

Hope it helps guys. Until next time, ciao!

Change default javadoc output directory in Maven

When using the Maven javadoc plugin for generating javadoc for your project, we also have the option of changing the default output directory. As you know, by default the javadoc gets created within the project-folder/target/apidocs directory.

So, when updating the location of javadoc's output directory, use the <reportOutputDirectory> tag. Consider the illustration below :

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<reportOutputDirectory>E:\\Javadoc\${project.name}</reportOutputDirectory>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>

As you see in this case we have updated the javadoc output directory to a different drive itself i.e. E:\\Javadoc\${project.name}. Kindly check this link as well for additional reference.

Tuesday 31 October 2017

How to skip tests for specific module in a Maven build

In a Maven build of a multi module project, sometimes we may want to skip tests for only a specific module. For illustration, let's consider a multi module project with 10 modules and we want to skip tests only for 1 or 2 modules.

In such a scenario, enter the following in that module's pom whose tests we want to skip. We simply set the skipTests tag to true in the maven surefire plugin configuration.

<build>
        <plugins>
            <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
        </plugins>
    </build>

Until next time, Ciao.

Wednesday 4 October 2017

How to generate report to list unused dependencies in Maven

In this post, we will see how to generate a report to list the unused dependencies of a Java project built using Maven.

We will use the dependency plugin to do so. Let's use the dependency:analyze-report goal as below

mvn dependency:analyze-report -DignoreNonCompile=true

This will basically generate an HTML report containing the list of dependencies with the following classification :

  • used and declared.
  • used and undeclared.
  • unused and declared.

Ideally, it's always a good idea to cleanup the pom's by removing and/or commenting the unused but declared dependencies.

Tuesday 3 October 2017

How to deploy specific file to Artifactory using Maven from Jenkins

This post will be helpful in a scenario where you are required to deploy i.e upload just a specific individual file (eg: xyz.zip or abc.jar) to Artifactory using Maven from Jenkins.

For illustration, configure a deploy-file job in Jenkins and add the following Maven goal.

clean deploy:deploy-file
-DgroupId=com.company.abc.message -DartifactId=message -Dversion=${version}
-DgeneratePom=false
-Dpackaging=jar
-DrepositoryId=artifactory
-Durl=http://17.16.18.12:8080/artifactory/simple/libs-release-local/
-Dusername=admin -Dpassword=admin-password
-Dfile=C:\Users\ironcladzone\Desktop\messageTest\message-${version}.jar

This will basically upload the message jar with a dynamically passed version parameter. Assuming the ${version} parameter value is defined 5.3.2 in Jenkins, the above command will essentially deploy message-5.3.2.jar to the libs-release-local repository.

Ciao!

Version increment and/or update using Maven

In today's fresh post, we will look into how to increment and/or update version numbers in pom.xml of your project using Maven.

Let's assume your project has a multi-module/multi-component setup. Each of the module/component has its own pom.xml with a list of dependencies and the overall bill of materials in general.

As a good practice, it's always a good idea to have about 2 pom's on the topmost levels. 1st pom should have all the project dependencies, which will be the parent pom of all modules. The 2nd pom should contain all third party non-project dependencies. This 2nd toplevel pom should be the parent of the 1st toplevel pom. These 2 toplevel pom's collectively define the project and 3rd party dependencies. Note that the versions of all dependencies should be defined in these 2 pom's. The individual module pom's should not carry the version number of dependencies. It will fetch them from the above 2 toplevel pom's.

Also, the module's own version should not be explicitly defined within it's own pom. It should only carry the version of it's parent pom. The below diagram should you help you visualize the ideal structure.

Let's say for instance the current version in current sprint is 5.3.3-7 and you want to update the version to 5.3.4-1 for going on to the next sprint. The following command can get that job done.

  • mvn versions:set -DnewVersion=5.3.4-1


Note however, that if your source code is under version control (for eg: IBM Clearcase), you may want to check out the files first, then update the versions in pom.xml and then check them in. In such a scenario, use the following sequence of commands to do so :

  • cleartool find . -name pom.xml -exec "cleartool co -nc %CLEARCASE_PN%"


This will recursively checkout all pom.xml files within your Clearcase view.
  • mvn versions:set -DnewVersion=5.3.4-1
This will increment all pom versions to 5.3.4-1
  • cleartool find . -name pom.xml -exec "cleartool ci -nc %CLEARCASE_PN%"
Once the versions are updated, all you have to do is recursively checkin all the pom.xml's. The above command will do that. 

Please note that the above cleartool commands will only work if you're using IBM Clearcase for source control.

For any questions, queries or discussion's kindly drop a comment or two. Peace. Cheers!

Friday 13 May 2016

Extract pom.xml version number using Shell script - Scenario 1

Guys, in todays post we'll look into an example where we want to extract version number from pom.xml of a Maven based project. In other words, all we have to do is extract text between 2 strings from a file. Quite obviously we would use sed for that. But let's look into a scenario where you have to pipe sed to other unix commands.

FYI this will work universally on Linux/Unix/Mac OS X flavors.

Let's say I have a pom.xml file of a Maven based project and I want to display only the version number from it. As you may be aware, we define the version number within the <version> </version> tags.

For e.g. my pom.xml looks something like this :


Here we want to extract only the version number from the file. i.e in this case I only want to display 1.0-SNAPSHOT.

Did you notice that in our file we have two lines of the <version></version> tags. One for our main project version and the other is for the dependency version. Now if we use sed to extract text between the "version" words, it will give output like this below.

sed -n '/version/,/version/p' pom.xml
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>

      <version>3.8.1</version>

So let's display only the topmost line with head -1. That should help narrow down our output.

sed -n '/version/,/version/p' pom.xml | head -1
  <version>1.0-SNAPSHOT</version>

Now all we need is to extract the version number. Let's cut the output characters as follows :

sed -n '/version/,/version/p' pom.xml | head -1 | cut -c 12-23
1.0-SNAPSHOT

Cheers guys! That's what we wanted right? Now we could perhaps develop a script around this. Maybe have a variable which stores this version number. Perhaps we could use this variable for some conditional checks. Something like this :

#!/bin/bash
# Program to extract version number from the pom.xml

i=`sed -n '/version/,/version/p' /Users/ironcladzone/workspace/MavenTest/testapp/pom.xml | head -1 | cut -c 12-23`

echo $i

if [ $i = "1.0-SNAPSHOT" ]; then

echo "Version 1.0 Development copy. Team A is working on it."
else

echo "That's not a Version 1.0 Dev copy"

fi

Output :

./ExtractVersionFromPom.sh
1.0-SNAPSHOT

Version 1.0 Development copy. Team A is working on it.

The possibilities are limitless! Until next time, ciao!

Saturday 30 April 2016

How to setup Jenkins with custom Maven Home

Guys I earlier posted a quick short article on how to setup Jenkins with custom Ant Home. In today's post you'll learn how to similarly setup Jenkins with your custom Maven Home.

As usual go to Manage Jenkins -> Configure System

Scroll down to the Maven installations and untick Install Automatically. Now simply enter details about your custom MAVEN_HOME. Refer the screenshot below for reference please.


Cheers guys! Hope you are having a good time reading my blog. Make sure to dig in to discover more interesting posts.

Saturday 5 March 2016

Maven : mvn package in Eclipse

Guys, as you maybe aware the command "mvn package" creates a package and stores it in the target directory. On the other side if you run "mvn install" it will create a package and then store it in your local repository.

I assume you have created a project from the archetypes from command line and then converted it to a Maven project after importing it in Eclipse.

Make sure the pom.xml has packaging set to jar by default. You could also change the package to war if needed.

Now simple right click the project to choose Run as -> Run Configurations.


Here you can specify the goals. In this case, we just want to create a simple package. So do this :


As you see, we also get various options for e.g. to build offline, skip tests, debug output etc. Now just enter the goals "clean package" and click Run.

You'll see that after a while a jar package gets created in the target directory of the project. Similarly if you run "clean install", it will install the jar to your local repository location. Make sure to double check the timestamp of the package from Terminal.

Friday 5 February 2016

Maven - Install vs Deploy

In Maven, the difference between mvn install and mvn deploy is the following :

  • mvn install is used to install the artifact/dependency on your local repository.


  • mvn deploy is used to upload/install the artifact/dependency on the remote repository like nexus or artifactory.

Check this link for detailed reference.

Also let me refresh your memory about repositories. As you may be aware, your local repository is usually a local cache of the remote repository and may also contain unreleased artifacts.

Tuesday 2 February 2016

Maven - Offline Build

In order to execute a Maven build in offline mode, run the following command :

mvn -o install  OR  mvn --offline install.

In offline mode, Maven will not connect to the remote repository to check for the artifacts/dependencies. It will just check for the artifacts currently present in your local repository.

Saturday 26 April 2014

Invoke Ant build from Maven

The jar created by the Ant build can be then attached to the project using the Build Helper Maven plugin.

Consider the following example snippet of the pom.xml

<plugins>
   <plugin>
        <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-antrun-plugin</artifactId>
         <version>1.7</version>
            <executions>
              <execution>
                <tasks>
                      Place any Ant task here
                </tasks>
             </execution>
           <executions>
   </plugin>
 </plugins>

If required, you can then attach the jar created by the Ant build to this Maven project using another plugin named "build-helper-maven-plugin".

This plugin has various goals like build-helper:add-resource and build-helper:attach-artifact

Thursday 20 March 2014

Show hidden .classpath .project files in Eclipse

If you're using Eclipse IDE for any Java based projects, you might want to make .classpath or .project files visible.

In order to do so, click the small triangle on the right top side of Project Explorer and select Customize View.

Just deselect / un-tick the .* resources option and refresh your project.

Now you will be able to see the .classpath & .project files, which are hidden by default. Note that the .classpath file will contain information about the classpath and build info while the .project file will contain the project metadata.

This is useful while working with Maven. When you use the command mvn eclipse:eclipse, it creates .classpath & .project files, which are not visible in the project explorer by default. You can make them visible in Eclipse Project Explorer like this.


Wednesday 19 March 2014

Unsupported IClasspathentry kind=4 error in Maven

While importing a Maven project into eclipse, you may sometimes get an error like "Unsupported IClasspathentry kind=4".

The best solution was found on this StackOverflow page. The 2nd solution provided by Sagar worked for me and fixed the issue.

Quick Fix : 

In Eclipse, Right click the project -> Maven -> Disable Maven Nature

Open Terminal, go to the project directory and type mvn eclipse:clean

Now, again right click the project in Eclipse -> Configure -> Convert to Maven Project

Note that when you type mvn eclipse:clean in terminal, it deletes the old .classpath, .project files

[INFO] Deleting file: .project
[INFO] Deleting file: .classpath
[INFO] Deleting file: .wtpmodules

Maven Environment Variables

In order to make Maven work perfectly, we need to define 2 distinct environment variables. They are M2_HOME and M2_REPO. Let's see the basic difference between the two.

M2_HOME is the variable which defines the Maven installation directory.

M2_REPO is the variable which defines the location of your local repository.

Eg : 

So, for instance, if you installed Maven in /usr/local directory, then M2_HOME should be set to /usr/local/apache-maven-3.x.x

If you want to use some local directory (at any location) as your local repository, the M2_REPO should point to it.

Let's say for example, you created a directory /Users/IronCladZone/Maven/Repos which you intend to use as your local repository, M2_REPO should point to this location.

Also, If you use Eclipse IDE to work on, you should define the same in the preferences as well.

Go to Preferences -> Java -> Build Path -> Classpath Variables and create a New entry for M2_REPO, which points to your local repository and a new entry for M2_HOME which points to Maven installation directory.

Go to Preferences -> Maven -> User Settings and check if the Local Repository is set to the desired location.

Also check if the settings.xml location is rightly pointed. Sometimes, the settings.xml is not located in the ~/.m2/repository location. If not, then it must be located at your M2_HOME/conf location. ( Eg : /usr/local/apache-maven-3.x.x/conf ).

Thursday 6 March 2014

Import a Maven project in Eclipse

In order to import a Maven project into Eclipse, go to the project directory and type the following in Terminal.

mvn eclipse:eclipse

This command creates the following configuration files :

.classpath - Detailed information can be read here about it.

.project - Detailed information can be read here.

Describe a plugin in Maven

If you're using Maven for building projects, occasionally you might come across situation where you wonder what version of a certain plugin you're using. You might also wonder what goals are available.

In order to identify the plugin's version and goals, type the following in terminal.

Eg : 

mvn -Dplugin=install help:describe

This will describe the details of the "install" plugin. Note that this will also describe the plugin's available goals.

Wednesday 5 March 2014

Artifactory on Mac OS X

Recently, while trying to install Artifactory on my Mac OS X machine, I encountered a weird error. Finding a solution was a bit tricky and took some time to figure it out.

Artifactory is basically an open source repository manager. I downloaded the latest current version v3.1.1.1. In this tutorial, we'll cover the easy method using hot deployment on servlet container.

Note that Artifactory comes pre-bundled with it's war file which we can deploy onto Tomcat. Although it does come pre-loaded with it's own container, I wanted to deploy the war using Tomcat 7. Since I already have Tomcat 7 installed on my machine.

When I logged on to Tomcat manager and tried to deploy the Artifactory war, I got the generic looking error : FAIL - application at context path could not be started.

So I fired up the terminal and looked into the Tomcat Catalina logs and here's what I came across :




The error "Setting property 'disableURLRewriting' to 'true' did not find a matching property." was looking really strange. So I googled a bit and realised that Artifactory needs JDK 1.7 to run. Refer this forum for some insights.

Now since Mac machines come pre-loaded with Apple supplied Java 6, I was in a kind of a fix. I wondered what to do. Should I download and install Java 7 & uninstall Java 6?

However I was skeptical of uninstalling Java 6. Also, I was not quite sure about what overall impact it would have by uninstalling Java 6 altogether. Since I mentioned previously that Google Chrome does not work with 64-bit Java 7. I spent some time doing impact analysis but didn't quite reach a conclusive decision. A little bit of coffee did the trick :)

Now, here's the workaround. Download the JDK 1.7 for Mac from this link. Now luckily I had the Eclipse IDE with Tomcat plugin ready. If you don't have this setup yet, I highly recommend working with the Eclipse IDE. Lots of customizations are possible.

Open Tomcat Preferences and and expand Java > Installed JRE from the left menu. Click Add. Now browse to /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home. Describe it with some name like Jdk 1.7. Apply settings and don't exit the preferences as yet.

Make sure you only mention the path till Home. If you mention path further like .../Contents/Home/bin/java, you will see an error like "Target is not a JDK root. Java executable not found."

Check the screenshot for reference.




Now, scroll down the preferences' left pane and expand Tomcat > JVM Settings. From the drop down, select Jdk 1.7 that just defined above. So henceforth, Tomcat container will only be invoked using Jdk 1.7. If for any reasons, you have to invoke using Java 6, you can always choose Apple supplied Java 6 from this list. Check the screenshot for reference.




Now simply hit the Start Tomcat button. Bingo. Wait and watch the console till you see that Artifactory has started. Something like this : 

###########################################################
### Artifactory successfully started (29.031 seconds)   ###
###########################################################

Now, all you have to do is open browser to localhost:<listener-port-no>/artifactory. By default, tomcat's listener port is 8080. You can modify it if you want to.




In my next tutorial, I'll post about working with Artifactory & Maven repositories. Stay tuned folks.

Tuesday 4 March 2014

Manual Installation of 3rd party jars in Maven

Occasionally, while using Apache Maven, we may come across scenarios when we would have to manually install 3rd party dependency jars. This might occur when a certain dependency jar does not exist on your local repository or Maven Central. Let's discuss how to manually install such jars.

The first obvious step would be to download the 3rd party jar. For instance Kaptcha or Gin. Now our next job would be to install this jar into our local repository, so that Maven detects it. Open terminal and browse to your local Maven repository.

For installing the jar, we provide a goal to the maven-install-plugin. Use the goal install:install-file and pass parameters as shown in the below example :

mvn install:install-file -Dfile=path-to-3rd-party.jar -DgroupId=com.example-plugin.code -DartifactId=example-plugin-name -Dversion=version-of-the-jar -Dpackaging=jar

The Output would start with something like this. You'll see the Build Success message once the plugin is installed successfully.



The entire list of paramaters that can be passed to the goal install:install-file can be found here.

Note that once such 3rd party jars are installed, you may have to use the sha1 or md5 utility to create MD5 checksums of the jar and pom that got created within the repository. Refer my previous post on using the MD5 utility.

Also, correct me if am wrong, in older Maven 1 versions, once the plugin is installed, you had to manually edit the generated pom to include details like groupId, artifactId and version. However in Maven 2+ versions, the pom gets auto-populated with these details.
Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker