Virgo recipe "Accessing Data with MongoDB"

Virgo Homepage

Acknowledgements

This guide is inspired by "Accessing Data with MongoDB" from the Spring Guides.

Accessing Data with MongoDB

The original guide uses Spring Boot to bootstrap the demo application. This guide shows what needs to be done to run Accessing Data with MongoDB with Virgo.

Shopping list

Note

Only Virgo Server for Apache Tomcat and Virgo Jetty Server are supported by the Virgo Tooling.

Ingredients

Preparations

Get the code

Clone the code from the Git repository: Sample Git repository:

$ cd ~/MyAwesomeProjectDirectory/
$ git clone git://git.eclipse.org/gitroot/virgo/org.eclipse.virgo.samples.git
$ cd org.eclipse.virgo.samples
$ cd recipe-accessing-data-mongodb

Once inside the source directory of this recipe - your are good to go.

Create the Custom Virgo Runtime

Create your own Virgo runtime with Gradle and Dockerizor:

$ ./gradlew :recipe-accessing-data-mongodb-runtime dockerize

The custom Virgo Runtime is packaged as tar archive and available from the runtime build directory. Extract the runtime into some directory - let’s say into VIRGO_HOME.

Caution

You’ll need a Docker daemon running in order to create your custom Virgo runtime. For more information please refer to the Dockerizor documentation.

Create Eclipse Project Metadata

Create the Eclipse IDE metadata with:

$ ./gradlew eclipse

Prepare the Virgo Tooling

Download Eclipse IDE for Java EE Developers e.g. Eclipse Mars.2 (4.5.2).

Start your Eclipse IDE and add the Virgo Tooling to your Eclipse IDE.

Optionally add the Docker Tooling to your Eclipse IDE.

Import the code into your Eclipse IDE

Now you can Import ▸ Gradle ▸ Gradle Project into your IDE. The project folder is called recipe-accessing-data-mongodb and lies directly in the "Sample Applications" folder you created previously with the Git clone command. (org.eclipse.virgo.samples).

Note

Before you can drag’n’drop the project onto your freshly created Virgo Server you might have to execute Virgo ▸ Run Generation of META-INF/MANIFEST.MF (via a right click on the project) within your Eclipse IDE.

Create new Virgo Server Runtime

Define a new server

Within the IDE New ▸ Server ▸ EclipseRT ▸ Virgo Runtime and choose the directory of the previously installed Virgo server VIRGO_HOME.

Directions

In the original guide the music plays in the run method of the CommandLineRunner of the Spring Boot application. We are going to transform the @SpringBootApplication into a plain @Component with an init-method.

Spring Boot Application

@SpringBootApplication (1)
public class Application implements CommandLineRunner { (2)

  @Autowired private CustomerRepository repository; (3)

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  public void run(String... args) throws Exception { (4)
    // repository actions...
  }
}
  1. Will be replaced with a plain @Component.

  2. CommandLineRunner will be replaced, too.

  3. @Autowired is the common denominator.

  4. Will be replaced with a @PostConstruct method.

Virgoized Application

After the transformation the component looks something like:

@Component
public class Application {

  @Autowired private CustomerRepository repository;

  @PostConstruct
  public void init() throws Exception {
    // repository actions...
  }
}

Customer

Both: The Customer

Customer
public class Customer {

    @Id
    private String id;

    private String firstName;
    private String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }
}

Customer Repository

and CustomerRepository are unchanged:

CustomerRepository
public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);
}

OSGi Metadata

The OSGi metadata is generated from a template:

template.mf
Bundle-ManifestVersion: 2
Bundle-Version: ${version}
Bundle-Name: Virgo Recipe MongoDB
Bundle-SymbolicName: org.eclipse.virgo.samples.recipe.data.mongodb
Import-Bundle: org.springframework.aop,
 org.springframework.beans,
 org.springframework.data.core,
 org.springframework.data.mongodb
Excluded-Imports: org.springframework.*
Import-Package: com.mongodb;version="[2.14.3,3)",
 javax.annotation;version="0",
 org.aopalliance.aop;version="1"

Dependency management

While the original guide pulls in it’s Spring Data dependencies the Spring Boot way:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-mongodb")
...
}

we create a custom Virgo runtime and add list the required dependencies more explicit:

dependencies {
	repositoryUsr "org.mongodb:mongo-java-driver:${mongoJavaDriverVersion}"
	repositoryUsr "org.springframework.data:spring-data-commons:${springDataCommonsVersion}"
	repositoryUsr "org.springframework.data:spring-data-mongodb:${springDataMongodbVersion}"
}

Spring Boot Demystified

Within the Virgo powered OSGi environment some of the Spring Boot magic becomes visible in XML.

<context:property-placeholder location="classpath:mongodb.properties" />

<mongo:db-factory dbname="recipes" host="${mongodb.host:localhost}:${mongodb.port:27017}" /><!--1 -->
<mongo:template />
<mongo:repositories base-package="org.eclipse.virgo.samples.recipe.data.mongodb" />

<context:component-scan base-package="org.eclipse.virgo.samples.recipe.data.mongodb" /><!--4 -->
  1. Provides a bean MongoDbFactory

  2. Configures and provides a bean MongoTemplate

  3. Scans provide MongoDB backed MongoRepository

  4. Scans the application code for @Component s …​

Let’s taste

When the oven is hot - the Virgo Runtime is up and running - you can insert (drag’n’drop) the fresh OSGi bundle.

A quick glimpse into the oven…​

$ tail -500f ${VIRGO_HOME}/serviceability/logs/log.log

the results

Should show the tasty result of our actions:

log.log
...
System.out Customers found with findAll():
System.out -------------------------------
System.out Customer[id=570fa0b3eec8cfd2c9a99d98, firstName='Alice', lastName='Smith']
System.out Customer[id=570fa0b3eec8cfd2c9a99d99, firstName='Bob', lastName='Smith']
System.out
System.out Customer found with findByFirstName('Alice'):
System.out --------------------------------
System.out Customer[id=570fa0b3eec8cfd2c9a99d98, firstName='Alice', lastName='Smith']
System.out Customers found with findByLastName('Smith'):
System.out --------------------------------
System.out Customer[id=570fa0b3eec8cfd2c9a99d98, firstName='Alice', lastName='Smith']
System.out Customer[id=570fa0b3eec8cfd2c9a99d99, firstName='Bob', lastName='Smith']
...

Dockerise the Application

We use Gradle and Dockerizor to build the application. Instead of running the sample within the Eclipse IDE you can build a Docker image:

$ ./gradlew dockerize
Note

This recipe assumes you have a local MongoDB up and running.

Let’s create an isolated network recipe_nw to test the complete recipe:

docker network create -d bridge --subnet 172.25.0.0/16 recipe_nw

To start a temporary MongoDB container inside this network issue the following command:

$ docker run --rm -it --net=recipe_nw --name mongodb mongo:3.4.3

then run the application with the environment variable mongodb.host set to the container name used in the command above:

$ docker run --rm -it --net=recipe_nw --publish 8080 -e mongodb.host=mongodb virgo-recipe/accessing-data-mongodb-app