Mavenizing jar files

These days the standard way to get your java libraries is through Maven. However, sometimes you still need to deal with jar files that aren’t available through Maven at all. Perhaps some software vendor has provided a set of jars,  or you have a custom build that you aren’t allowed to publish at all.

If this is the case, you could just reference the jars on the file system, the old school approach. But you can also mavenize them yourself, and store them in your local Maven repository (which can be found in your user profile folder, in the folder .m2). That makes it possible to reference these libraries in a pom.xml or in a build.gradle file, giving you all the advantages of modern dependency management.

If you are using a Windows PC, you can follow these instructions. It’s quick and dirty, but I hope this will save you some time. If you are on Linux / Mac, you can probably take some inspiration from this but you would need to make a few changes here and there.

Instructions

  • Put all the jars in a folder.
  • ‘Mavenize the files’, i.e. rename them to artifactname-version.jar (e.g. cd_core-8.5.0.1037.jar)
  • Make a dir listing and copy all jar file names
  • Paste this in a new text file in Notepad++
  • Use search and replace (using regular expressions)

Search:
^(.*?)-(\d.*?)\.jar

Replace:
call mvn install:install-file -Dfile=\1-\2.jar -DgroupId=GROUPID -DartifactId=\1 -Dversion=\2 -Dpackaging=jar

Note: you need to replace GROUPID in this regex by a group id that makes sense. Technicaly, it doesn’t matter what you use as long as it a valid group id and you use the same group id in the POM dependency (see further down). Often there will be a logical choice, e.g. the name of the organisation that created the jars, or the shared package name used in the classes contained inside the jars.

  • Save as a .bat file and execute. This will store all the jars in your local Maven repository (see %USERPROFILE%\.m2\repository)

Maven POM

Next, you need to have some XML to insert into your POM. Like before, copy the jar file names into an empty text file, and run this search/replace (again with Regex turned on):

Search:
^(.*?)-(\d.*?)\.jar

Replace:
<dependency>\r\n<groupId>GROUPID</groupId>\r\n<artifactId>\1</artifactId>\r\n<version>\2</version>\r\n</dependency>\r\n

This will give you a list of <dependency>…</dependency> elements, which you can copy into the <dependencies> section of your POM.

Gradle

If you’re using Gradle instead of Maven as a build tool, you can use the following search/replace action instead:

Search:
^(.*?)-(\d.*?)\.jar

Replace:
compile ‘GROUPID:\1:\2’

Copy the output into the dependencies section of your build.gradle file.