How do I set up a private Maven repository for internal Android library distribution

Yesterday I received a question: “Eventually, the Android project will have a lot of library modules. What is the best and sustainable way to organize these libraries for current and future use?” .

Well, I think this is a very good question, and I’m sure many of you may have the same question, so I decided to write this blog post to show you how to ** “set up your own private Maven repository” ** for internal use.

Let’s get started.

Why would we want to set up a private Maven repository?

Obviously, an Android library module is really just a bunch of source code grouped in the same directory. If you want other developers to use your libraries, you can simply send them the entire catalog and have them include it in their projects.

It sounds easy, but that doesn’t mean it’s good. The question is, “If the company starts to grow and the number of projects starts to grow, can we still pass the library as source code like this?”

The answer is a firm no. ** Don’t do that! Here are some important reasons to pay attention:

  1. Let’s imagine. If you have about 10 projects sharing the same library module. Finally, you will find that these projects are littered with copies of source code, which is not conducive to code control at all.

  2. Updating libraries to new versions is inconvenient. The process is as follows: download the source code, copy it, replace the old with the new, check for problems, and so on…… You have to do each step manually.

  3. If you are out of shape at times, newer versions of the library may cause applications you previously worked on to become unusable. In this case, you need to roll back the library to a previous version. Wow, that means we need to keep the source code for each version as a backup in case we might run into trouble one day.

  4. On the usage side, we need to distribute the library for other developers to “use” it. So there’s no need for them to see the source code. A clear document on how to use the library is sufficient.

  5. Libraries distributed to other developers should not be modifiable. If problems occur, they should be reported to the relevant developers for resolution. Giving other developers direct access to the source code can cause them to accidentally make quick fixes themselves, which can lead to big problems later.

This is why we should not distribute libraries as source code. In this case, it is better to distribute a built-in version of the library in the form of a.jar or.aar file.

While it looks better, it’s not perfect. Most of the problems listed above have been resolved, except for one: updating and rolling back versions is still difficult. We still need to download, copy, replace, backup, and so on. Developer time is precious and should not be wasted on these things.

Wouldn’t it be nice if we could build. Gradle and add a line of code to the dependencies area as if it were a third-party library, for example,

compile 'my.com pany: library: 1.1.0'
Copy the code

If you have any problems with the new version of the library, just change the version number back to the available version number within a second.

compile 'my.com pany: library: 1.0.0'
Copy the code

I found it a perfect choice. Distributing libraries is easy, and if you want to use them, you only need to add one line of code to do it! It’s also easy to update and roll back to whatever version you want. And the source code is not modifiable.

So I encourage every company to have a Maven repository for internal use. Because we use it internally, these libraries should be private, so a public repository is not an option. We had to use a private Maven repository with a full access control system so that no one but team members could access it.

To this end, we have two options:

  1. Use private repository hosting services – there are many such services. The most popular are Bintray Premium and JitPack Private Repositories. In any case, it was very expensive (at least for me). In addition, you will be charged more for the number of library artifacts you need to host there. It seems to me that the number of library artifacts could grow to 10 in a year, which is not a good choice for long-term use.

  2. Set up your own dedicated server – there are plenty of open source software available to give you the perfect solution, such as Artifactory and Nexus. You can place as many library artifacts as you need. The only fees you will have to pay are custodial fees, which are no longer a big issue. With DigitalOcean, you pay $10 a month. That’s all. Sounds pretty cool, right?

Ok, I’ll show you how to set up our own private Maven repository as a dedicated server. The open source software I chose was Artifactory because it was very easy to install, despite its myriad promising features and stability.

Artifactory installation

I know you all have to have your favorite operating system, but for the sake of convenience, let me control the hosting environment a little bit. In this blog post, I’ll guide you through how to set up Artifactory on Ubuntu 14.04 LTS on DigitalOcean. If you don’t want to pay anything, you can also choose your favorite VM on VirtualBox.

Create the Ubuntu 14.04 LTS Droplet

First, let’s create a Droplet on DigitalOcean with the following specifications:

OS: Ubuntu 14.04 LTS

Specifications: $10 / month

Region: Any region, but I recommend you choose the server closest to you.

Once Droplet is created, send the root user name and password to your email and then SSH into the created server.

Install Java 8

Java 8 does not ship with the default repository of Ubuntu 14.04 LTS. We need to install it from the PPA repository. You can do this using the following command line:

# add-apt-repository ppa:webupd8team/java
# apt-get update
# apt-get install oracle-java8-installer
Copy the code

You can verify the installation by entering this command.

# java -version
java version "1.8.0 comes with _72"
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)
Copy the code

To complete.

Install Artifactory

Installation is easy. First you need to download Artifactory’s Debian package from Bintray:

$ wget https://bintray.com/artifact/download/jfrog/artifactory-debs/pool/main/j/jfrog-artifactory-oss-deb/jfrog-artifactory-oss - 4.5.1. DebCopy the code

The version used in this tutorial is 4.5.1 because it is the latest version as I write this blog post. Feel free to use any other version you like. A list of Artifactory versions is provided in the Bintray site.

Now it’s time to install it with these four lines of code. Of course, if you are using a version other than 4.5.1, don’t forget to change the number of DEB packages to the one you are using.

$ gpg --keyserver pgpkeys.mit.edu --recv-key 6B219DCCD7639232 
$ gpg -a --export6 b219dccd7639232 | sudo apt - key add - $apt - get the update $DPKG -i jfrog artifactory - oss - 4.5.1. DebCopy the code

It was installed in about a minute. You can use this command to start the service immediately.

# service artifactory start
Copy the code

Tomcat is embedded in the Artifactory package, so you don’t need to install anything else. It can now stand alone.

Configuration Artifactory

Open your preferred web browser and browse to this website: http://IPADDRESS:8081/artifactory/ will IPADDRESS to replace the IP address of the server) for you. You should see the login screen as follows:

Log in with user name admin and password ** : ** password

The first thing I recommend you do immediately after logging in is to change your administrator password to prevent further security issues. To do this, go to Admin -> Security -> Users -> Admin to change the password to what you want.

In any case, we should not use the warehouse as an administrator. Therefore, we will keep the account like this and create a new one. Here’s how to do it step by step.

Create a group

Browse to Admin -> Security -> Groups and click +New in the upper right corner.

We will create a group of users who can upload and download any library from the system. Therefore, I named this group ** “contributors” and described it as “repository contributor group” **. For the user pane, leave it unchanged.

Click Save to create the group.

Create permissions

The next step is to assign permissions to the users in the contributor group. Browse to Admin -> Security -> Permissions and click +New in the upper right corner.

Name the permission Contribute to Anything and select the Any Local Repository and Any Remote Repository boxes to give the contributor access to Any Repository in the system. Click Next.

In the Groups TAB, add the contributor to the right area and assign the following permissions. Click Save and finish.

Permissions are now assigned to the contributor group.

Create a new user account

The final step is to create a new user account that has been assigned contributor rights. Click +New in the upper right corner of the Admin -> Security -> Users page.

Enter a user name, password, and email address. In the Related Groups area, add only contributor groups to the right pane.

Click Save and… Done! We now have an account with the appropriate permissions.

If you want to create more user accounts with the same access rights after this point, you can do so by creating a new user and adding it to the contributor group.

However, if you want to create a user account with read-only access. In this case, the reader is the group that you need to assign to the account.

Obtain encrypted password

The next step is to use the password in the Gradle script, preferably not the plain text version of the password. Fortunately, Artifactory provides a way to use an encrypted password, and to get this information, you need to log out from admin and log in using the account you created in the previous step.

After login, click the user name in the upper right corner of the page.

Enter your password and click Unlock.

Some data will be presented.

Copy the text in the encrypted password box and save it somewhere. We will use it in the near future.

Switch the Artifactory to private mode

By default, repositories hosted in Artifactory are publicly accessible. We need to switch to private mode and allow only permitted users to access the repository.

To turn on private mode, simply uncheck allow anonymous access on the Administration -> Security -> General page.

The server is now configured and ready to use!

How do I upload Android libraries to Artifactory from Android Studio

Now it’s time to start working on Android Studio. To upload the library to Artifactory, we need to modify some Gradle scripts. The first step is to define the username and encrypted password for the account on the Artifactory set up in the previous step. Since this information will be visible in gradle scripts, it is best to put it in a file that will not be uploaded to version control. Let’s put them into HOME_DIR /. Gradle/gradle. Properties

For those not familiar with this file, it is a global Gradle script that is used for each gradle project compilation step. So if we declare anything in this file, this data can also be accessed in the Android project gradle script.

I’m sure you, the developer, must already know what HOME_DIR is for each operating system. For Mac OS X and Linux, it is ~ in Windows, it is C:\Users\USERNAME in general. Try browsing to the folder where you will. Gradle see the directory. If not, you’re in the wrong directory.

Gradle. properties creates a file in HOME_DIR/.gradle/ if the directory does not exist, and modifies it if it does. Add the following two lines of script, and replace YOUR_USERNAME and YOUR_ENCRYPTED_PASSWORD with the username and encrypted password you obtained in the previous step.

# HOME_DIR/.gradle/gradle.properties

artifactory_username=YOUR_USERNAME
artifactory_password=YOUR_ENCRYPTED_PASSWORD
Copy the code

Now open the build.gradle file placed at the top of your Android project. Add the following line of classpath.

buildscript {
    dependencies {
        // Add this line
        classpath "Org. Jfrog. Buildinfo: build - info - extractor - gradle: 4.0.1." "}}Copy the code

Open build.gradle and place it in the library module that you need to upload to Artifactory. Insert the two lines of code shown below in the first line of the file.

apply plugin: 'com.jfrog.artifactory'
apply plugin: 'maven-publish'
Copy the code

Add these lines to the end of the same working file.

def libraryGroupId = 'my.group.package'
def libraryArtifactId = 'thelibrary'
def libraryVersion = '1.0.0'
Copy the code

The code shown above will lead to rely on the form of, because the compile ‘my. Group. Package: thelibrary: 1.0.0’ it is available in the repository. Please feel free to change libraryGroupId, libraryArtifactId, and libraryVersion to whatever you want.

In the same working file, add these lines at the end of the file.

publishing {
    publications {
        aar(MavenPublication) {
            groupId libraryGroupId
            version libraryVersion
            artifactId libraryArtifactId

            artifact("$buildDir/outputs/aar/${artifactId}-release.aar")
        }
    }
}

artifactory {
    contextUrl = 'http://IPADDRESS:8081/artifactory'
    publish {
        repository {
            repoKey = 'libs-release-local'

            username = artifactory_username
            password = artifactory_password
        }
        defaults {
            publications('aar')
            publishArtifacts = true

            properties = ['qa.level': 'basic'.'q.os': 'android'.'dev.team': 'core']
            publishPom = true}}}Copy the code

And don’t forget to change IPADDRESS to your server’s IP address.

Ok. Now the script is ready!

Upload library

Uploading libraries is very easy. Just open the terminal in Android Studio.

Enter the following command.

Windows:

gradlew.bat assembleRelease artifactoryPublish
Copy the code

Mac OS X & Linux:

./gradlew assembleRelease artifactoryPublish
Copy the code

Let it do its job and wait for BUILD SUCCESSFUL to appear on the screen.

At this step, your library has now been successfully uploaded to your private Maven repository. A: congratulations!

Verify the uploaded binary file

Browse to your http://IPADDRESS:8081/artifactory Artifactory control panel, and then click the Artifacts – > libs – release – local. You will see the uploaded library displayed, which contains some metadata, such as the user name of the deployer.

Can through the browser to access the repository at http://IPADDRESS:8081/artifactory/libs-release-local/. Please feel free to give me a check.

Use of warehouse

The warehouse is now ready for use. To use it in your project, you need to declare the Maven URL to the repository address and the credential build.gradle within the project level.

Add **maven {… }** part of the code, as shown below :(of course, don’t forget to change IPADDRESS to your server’s IP address)

allprojects {
    repositories {
        jcenter()
        // Add these lines
        maven {
            url "http://IPADDRESS:8081/artifactory/libs-release-local"
            credentials {
                username = "${artifactory_username}"
                password = "${artifactory_password}"}}}}Copy the code

Open build.gradle for the internal modules you want to use with the library, and then simply add a dependency in a very familiar form.

dependencies {
    compile ' 'my.group.package:thelibrary:1.0. 0"}Copy the code

Now it’s all done. You can now:

  • Set up your own Maven repository (private or public)
  • Upload the library to a repository with full user access control.
  • Download libraries from a repository with full user access control.

Distribution of repositories is more systematic than any other distribution method, and it now doesn’t matter how many libraries or library versions you have. Everything is in order now. =)

Hope you find this blog useful!

If you’re interested in this blog post, the article “How to distribute your own Android libraries from Android Studio via jCenter and Maven Central” may also be available. If you want to upload your own libraries to a common standard Maven repository such as JCenter or Maven Central, this blog will show you how. Again, hopefully you found it useful =)

Cheers.