Create Swarm Microservices with Forge

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

In this tutorial we will learn how you can create micro services with WildFly Swarm powered by Forge in less than 5 minutes!

So have your timer ready, we will start. Launch forge at first (time to get running the forge shell does not count!)

/bin/forge
    _____                    
   |  ___|__  _ __ __ _  ___ 
   | |_ / _ \| `__/ _` |/ _ \  \\
   |  _| (_) | | | (_| |  __/  //
   |_|  \___/|_|  \__, |\___| 
                   |__/      

JBoss Forge, version [ 3.3.3.Final ] - JBoss, by Red Hat, Inc. [ http://forge.jboss.org ]
Hit '<TAB>' for a list of available commands.
and 'man [cmd]' for help on a specific command.

To quit the shell, type 'exit'.

The first thing we will need is installing the WildFly swarm addon.

What are Forge Add-ons ? Forge addons are simple Maven projects with a special classifier "forge-addon". You can use them to enrich the set of commands which are available on Forge shell.

addon-install-from-git --url https://github.com/forge/wildfly-swarm-addon.git

Now that we have installed the swarm addon, we can create a Java EE 7 project which is based on WildFly swarm

project-new --named demo-swarm --stack JAVA_EE_7 --type wildfly-swarm

We will then create an Entity which will be wrapped with CRUD methods by a REST Service:

jpa-new-entity --named Customer

Let's add some fields to the JPA entity:

jpa-new-field --named firstName
jpa-new-field --named lastName

Done, now it's time to create a REST endpoint for your Entity:

rest-generate-endpoints-from-entities --targets org.demo.swarm.model.Customer 

As a result the following structure will be generated:

demo-swarm/src
├── main
│   ├── java
│   │   └── org
│   │       └── demo
│   │           └── swarm
│   │               ├── Main.java
│   │               ├── model
│   │               │   └── Customer.java
│   │               └── rest
│   │                   ├── CustomerEndpoint.java
│   │                   └── RestApplication.java
│   ├── resources
│   │   └── META-INF
│   │       └── persistence.xml
│   └── webapp

If you have a look at the code, you will see that several defaults have been applied in your project, which can be however overridden by applying additional parameters to the jpa and rest commands. For example, the default application path for the Web services is by default "rest" as you can see from the following class:

package org.demo.swarm.rest;

import javax.ws.rs.core.Application;
import javax.ws.rs.ApplicationPath;

@ApplicationPath("/rest")
public class RestApplication extends Application {
}

In order to build the project, we will need to add the required dependencies to it. Luckily swarm is able to detect the required fractions to build the project. You can execute the following command in order to build the project:

wildfly-swarm-detect-fractions --build  --depend

As you can see from the output, the required fractions for ejb, jpa, jaxrs have been added to the pom.xml:

***INFO*** Detected fractions: [org.wildfly.swarm:ejb:2016.11.0,org.wildfly.swarm:jaxrs-jaxb:2016.11.0, org.wildfly.swarm:jpa:2016.11.0]
***INFO*** Adding missing fractions as project dependencies... 	[3/3] ...
***INFO*** Installing the following dependencies: [org.wildfly.swarm:ejb:2016.11.0, org.wildfly.swarm:jaxrs-jaxb:2016.11.0, org.wildfly.swarm:jpa:2016.11.0]

That's done! We can complete by adding a main class which will let you kickstart your project

wildfly-swarm-new-main-class

We're done! Check your timer: did it take over 5 minutes to create your micro-service ? Probably not. Now start your micro-service with:

wildfly-swarm-run

Now wildfly will start. Let's try kicking some Customers. We will invoke the following POST method which consumes a Client object:

@Stateless
@Path("/customers")
public class CustomerEndpoint {

        @POST
        @Consumes("application/json")
        public Response create(Customer entity) {
                em.persist(entity);
                return Response.created(
                                UriBuilder.fromResource(CustomerEndpoint.class)
                                                .path(String.valueOf(entity.getId())).build()).build();
        }

The following curl command will do the job:

$ curl -H "Content-Type: application/json" -X POST -d '{"firstName":"John","lastName":"Doe"}' http://localhost:8080/rest/customers

And now let's query all Customers with the following GET request:

@GET
@Produces("application/json")
public List<Customer> listAll(@QueryParam("start") Integer startPosition,
                @QueryParam("max") Integer maxResult) {
        TypedQuery<Customer> findAllQuery = em.createQuery(
                        "SELECT DISTINCT c FROM Customer c ORDER BY c.id",
                        Customer.class);
        if (startPosition != null) {
                findAllQuery.setFirstResult(startPosition);
        }
        if (maxResult != null) {
                findAllQuery.setMaxResults(maxResult);
        }
        final List<Customer> results = findAllQuery.getResultList();
        return results;
}

Here we go:

$ curl -H "Content-Type: application/json" -X GET  http://localhost:8080/rest/customers
[{"id":1,"version":0,"firstName":"John","lastName":"Doe"}]

That's it, enjoy Swarm powered by Forge!


Advertisement