Maven is a well known software project management and comprehension tool with a great package management solution. in this post, we’ll discuss a simple solution to acquire latest version number of a Maven package.
Any maven package could be a candidate for this tutorial, we chose Google’s Libphonenumber because its a regularly updated package with important changes.
A Maven package is the compiled code and package it in its distributable format, such as a JAR. each Maven package comes with a maven-metadata.xml file where Maven stores basic information about artifacts such as versioning information, release time etc.
a. Choose a package: To choose a package you can visit https://mvnrepository.com/ and search for the package you need. our choice is: https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber
b. Find maven-metadata.xml URL: you can click on one of the versions like: https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber/8.12.53
then copy link from jar file download button, which will be like:
https://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.12.53/libphonenumber-8.12.53.jar
then remove version and file name and append “maven-metadata.xml” to it. your url will be sth like:
https://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/maven-metadata.xml
c. Bash scripting:
We will use bash for automating the process:
# get latest version number from maven metadata, you can replace "latest" with "release" to get latest release version. latest_version=`curl https://repo.maven.apache.org/maven2/com/googlecode/libphonenumber/libphonenumber/maven-metadata.xml 2>/dev/null | grep latest | grep -o -P '(?<=\>).*(?=\<)'` # update file modification timestamp, and craete it if it doesn't exist. touch /var/tmp/libphone_version # read latest saved version ver=`cat /var/tmp/libphone_version` # use default value: "5.12.50" if file is empty. previous_version=${ver:=5.12.50} # function to compare semantic version # From: https://stackoverflow.com/a/4025065/4134048 by Dennis Williamson vercomp () { if [[ $1 == $2 ]] then return 0 fi local IFS=. local i ver1=($1) ver2=($2) # fill empty fields in ver1 with zeros for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)) do ver1[i]=0 done for ((i=0; i<${#ver1[@]}; i++)) do if [[ -z ${ver2[i]} ]] then # fill empty fields in ver2 with zeros ver2[i]=0 fi if ((10#${ver1[i]} > 10#${ver2[i]})) then return 1 fi if ((10#${ver1[i]} < 10#${ver2[i]})) then return 2 fi done return 0 } # Compare two versions vercomp $previous_version $latest_version # Fail if versions are not the same if [ $? != 0 ]; then echo "Oops!" # Print Jar download url echo "https://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.12.53/libphonenumber-$latest_version.jar" # Save version number echo "latest_version" > /var/tmp/libphone_version exit 1; else echo "Ok!" exit 0; fi
you can use the output and exit code to sent alerts and notification.