Eddú Meléndez

Java 9: JShell

JDK 9 Build b90 have been released few days ago and in this build JShell REPL has been integrated. Officially this is the Kulla Project.

REPL - Read- Eval- Print- Loop has been in other languages and now has arrived to Java. Now, we can write code in our terminal and it read, evaluate them, print the output and

Provide an interactive tool to evaluate declarations, statements, and expressions of the Java programming language, together with an API so that other applications can leverage this functionality. - JEP 222

If you want to know more about REPL check JEP 222.

To install the JDK 9 download from here. Make sure you have the right version and remember that build 1.9.0-ea-b90 is integrated with jshell.

1
java -version

Terminal will display the java version and the build number.

1
2
3
java version "1.9.0-ea"
Java(TM) SE Runtime Environment (build 1.9.0-ea-b90)
Java HotSpot(TM) 64-Bit Server VM (build 1.9.0-ea-b90, mixed mode)

Now, that you have installed the right version you just need to execute the following command:

1
jshell

Terminal will display something like this:

1
2
3
4
|  Welcome to JShell -- Version 1.9.0-ea
|  Type /help for help

->

In the example below, start typing "Hello World" and the value will be stored in $1. Then, assign $1 to saludo which is a String. Finally, print saludo.

1
2
3
4
5
6
7
8
9
10
11
12
-> "Hello World"
|  Expression value is: "Hello World"
|    assigned to temporary variable $1 of type String

-> String saludo = $1
|  Added variable saludo of type String with initial value "Hello World"

-> System.out.print
print(     printf(    println(   

-> System.out.println(saludo)
Hello World

Good, you have started playing around jshell. As you can see, jshell provides autocompletion with tab key.

If you want test the last successful build from Kulla Project click here. Download the jar and execute it.

1
java -jar kulla--20151104010121.jar

Check the REPL tutorial and play with java in your terminal.

If you want to start in java this is a good place to start and if you are an experienced developer then jshell is for you too!

Spring Boot Endpoints for Data Migration

Database Change Management has been one of the practices which I have not seen much in action but there is a first time for everything. When I started a new project time ago, I was aware of lack of this practice and the risks around. In order to avoid risks in the database and wasting time between team members with backups and restores, I started with the research. During the research, I met Flyway and Liquibase. Both are powerful but liquibase was chosen because meet the needs. You can read my post about Database Change Management and Database Change Management with Liquibase.

Currently, Flyway and Liquibase are supported by spring-boot. Both help to manage the scripts execution over the database and you can configure using flyway.* and liquibase.* property namespaces. Since version 1.3.0, endpoints for both technologies has been added, their purpose is display data in schema_version, databasechangelog or any table you have customized. Previous to this change, credentials are required to access to the database in order to know this status. Now, everything is exposed via spring-boot and can be accessed to this information through the following endpoints /flyway, /liquibase.

These new endpoints have arrived thanks to actuator which provide several useful endpoints in spring-boot.

If you are currently using one of these technologies integrated with spring-boot you just need to add the actuator in your dependencies and voilá you can see through the inside.

For maven users:

1
2
3
4
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-actuator</artifactId>
</dependency>

For gradle users:

1
org.springframework.boot:spring-boot-actuator

/flyway endpoint

Once you have everything configure, point to the endpoint. E.g: http://localhost:8080/flyway

1
2
3
4
5
6
7
8
9
10
11
12
[
   {
      "type":"SQL",
      "checksum":710039845,
      "version":"1",
      "description":"init",
      "script":"V1__init.sql",
      "state":"SUCCESS",
      "installedOn":1441826719448,
      "executionTime":3
   }
]

/liquibase endpoint

Once you have everything configure, point to the endpoint. E.g: http://localhost:8080/liquibase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[
   {
      "ID":"1",
      "AUTHOR":"marceloverdijk",
      "FILENAME":"classpath:/db/changelog/db.changelog-master.yaml",
      "DATEEXECUTED":1441826872659,
      "ORDEREXECUTED":1,
      "EXECTYPE":"EXECUTED",
      "MD5SUM":"7:b8f2ae9c88deabd32666dff9bc5d7f5d",
      "DESCRIPTION":"createTable",
      "COMMENTS":"",
      "TAG":null,
      "LIQUIBASE":"3.4.1",
      "CONTEXTS":null,
      "LABELS":null
   },
   {
      "ID":"2",
      "AUTHOR":"marceloverdijk",
      "FILENAME":"classpath:/db/changelog/db.changelog-master.yaml",
      "DATEEXECUTED":1441826872663,
      "ORDEREXECUTED":2,
      "EXECTYPE":"EXECUTED",
      "MD5SUM":"7:a8006415097ebb8b3334a23347847322",
      "DESCRIPTION":"insert",
      "COMMENTS":"",
      "TAG":null,
      "LIQUIBASE":"3.4.1",
      "CONTEXTS":null,
      "LABELS":null
   }
]

Dockerizing Mule ESB

Creating a Dockerfile for MuleESB

Let’s create our Dockerfile

1
vim Dockerfile

We will build our Mule ESB Standalone Server image based on java version 8 from Docker Hub Java repository. More info about FROM

1
FROM java:8

We will use two environment variables MULE_HOME and MULE_VERSION, which will be used in our Dockerfile. More info about ENV

1
2
3
ENV MULE_HOME /opt/mule

ENV MULE_VERSION 3.7.0

Now, we need to download the latest version of Mule Standalone Server from Mulesoft’s repository in /opt folder, unzip it and rename the folder to mule. Additionally, zip file will be deleted. Since, we are running over Linux (Ubuntu) we can use some useful commands. More info about RUN

1
2
3
4
5
6
RUN set -x \
        && cd /opt \
        && curl -o mule.zip https://repository.mulesoft.org/nexus/content/repositories/releases/org/mule/distributions/mule-standalone/$MULE_VERSION/mule-standalone-$MULE_VERSION.zip \
        && unzip mule.zip \
        && mv mule-standalone-$MULE_VERSION mule \
        && rm mule.zip*

Then, we will locate at $MULE_HOME folder. More info about WORKDIR

1
WORKDIR $MULE_HOME

Now, we will expose some folder inside of mule in order to have access from outside of docker container. More info about VOLUME

1
2
3
4
VOLUME $MULE_HOME/apps
VOLUME $MULE_HOME/conf
VOLUME $MULE_HOME/domains
VOLUME $MULE_HOME/logs

Finally, we need to start the server. More info about ENTRYPOINT

1
ENTRYPOINT ["./bin/mule"]

Our final Dockerfile looks like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
FROM java:8

MAINTAINER Eddú Meléndez <eddu.melendez@gmail.com>

ENV MULE_HOME /opt/mule

ENV MULE_VERSION 3.7.0

RUN set -x \
        && cd /opt \
        && curl -o mule.zip https://repository.mulesoft.org/nexus/content/repositories/releases/org/mule/distributions/mule-standalone/$MULE_VERSION/mule-standalone-$MULE_VERSION.zip \
        && unzip mule.zip \
        && mv mule-standalone-$MULE_VERSION mule \
        && rm mule.zip*

WORKDIR $MULE_HOME

VOLUME $MULE_HOME/apps
VOLUME $MULE_HOME/conf
VOLUME $MULE_HOME/domains
VOLUME $MULE_HOME/logs

ENTRYPOINT ["./bin/mule"]

Building the MuleESB Docker image

In order to have the image available in your local machine we just need to execute the command below:

1
docker build --tag eddumelendez/mule  .

Running the MuleESB Docker image

1
docker run -ti eddumelendez/mule

You can find the final example on my github repository docker-mule

Spring 4.2.0: SpringClassRule and SpringMethodRule

Spring Framework 4.2.0.RELEASE has arrived and two new rules have been added to spring-framework project SpringClassRule and SpringMethodRule.

In spring applications we have used SpringJUnit4ClassRunner for a long time in our tests but JUnit only support one Runner at the time, in order to allow integration between spring with other Runners like org.junit.runners.Parameterized we can use these new classes instead of @RunWith(SpringJUnit4ClassRunner.class)

  • SpringClassRule enable the following annotations @BeforeClass, @AfterClass, @ProfileValueSourceConfiguration, @IfProfileValue.

  • SpringMethodRule enable the following annotations @Before, @After, @Repeat, @Timeout, @ProfileValueSourceConfiguration, @IfProfileValue.

Test using classic SpringJUnit4ClassRunner.

1
2
3
4
5
6
7
8
9
package io.eddumelendez;

import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTest {

}

Test using new rules SpringClassRule and SpringMethodRule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package io.eddumelendez;

import org.junit.ClassRule;
import org.junit.Rule;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;

public class SpringTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

}

Both have the same effect in your test and you can use them in different context.

Java EE: MVC 1.0

Java EE is evolving and there are a lot of news coming in Java EE 8. Java EE is constantly adopting standards and now is time to the new spec MVC 1.0 (JSR-371) is part of Java EE 8 which will be released in 2016.

If you are thinking on a new concept, let me tell that you are wrong MVC is Model, View, Controller the pattern for web frameworks and you already knew it.

Now, UI frameworks has been categorized in:

  • Action-based, like MVC.
  • Component-based, like JSF.

But, I am pretty sure that you have the following question Why another MVC framework?.

Complete integration with Jersey (JAX-RS) and obviously with all Java EE ecosystem.

You can see in ozark github repository the RI (Reference Implementation) to the frameworks below:

  • Freemaker
  • Handlebars
  • Mustache
  • Thymeleaf
  • Velocity

Note: Glassfish 4.1, is the only Server Application which support this specification at the time I am writing this post.

To use it in your projects add the this dependency in your pom.xml (if you are using maven)

1
2
3
4
5
<dependency>
  <groupId>javax.mvc</groupId>
  <artifactId>javax.mvc-api</artifactId>
  <version>1.0-edr1</version>
</dependency>

JSP’s are located at src/main/webapp/WEB-INF/views folder.

There are 4 ways to return a view:

  1. Void method with @View and the jsp name.
  2. Return String with the jsp name.
  3. Return Viewable class with the jsp name.
  4. Return Response class from JAX-RS to return the jsp name as a entity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Controller
@Path("book")
@Produces("text/html")
public class BookController {

  @GET
  @View("books.jsp")
  public void viewBooks() {

  }

  @GET
  public String viewBookInfo() {
      return "book.jsp";
  }

  @GET
  public Viewable viewBookDetail() {
      return new Viewable("bookDetail.jsp");
  }

  @GET
  public Response viewBook() {
      return Response.status(Response.Status.OK).entity("book.jsp").build();
  }

}

If you can check the code of this API take a look the github repository MVC 1.0

Git: Useful Commands

Git is the most popular Version Control System at this time. There are several benefits like Distributed Version Control System, manage commits by references, save space and so on. And to be honest make my job easy in the software development.

In this post I will share some git useful commands.

View cool log

Sometimes we don’t need to much detail in our log and it is enough reading the commit’s title. Also we would like to know ref names of commits. Additionally, we would like to display branching graph.

1
git log --oneline --decorate --graph

As a result, you can see the commit hash towards to the commit’s title. Also, you can see branches graph.

View pending commits to push

Sometimes, I thought that have been sent my commits to the central repository. An easy way to know how many commits are in your local repository and ready to push them is with the command below.

1
git log --oneline origin/master.. master

Rebase

Put your local commits to the top and pull all the changes in the repository avoiding conflicts with the central repository.

1
git pull --rebase origin master

You can also rebase in interactive mode, which allow to choose actions like pick, reword, edit, squash, fixup, exec. To know about this command check this link.

1
git rebase -i origin/master

Push specific commit

If you have one pending commit and start in a new feature you maybe wondering how to push your commit without revert all the changes you started. You just need the commit hash and execute the command below.

1
git push origin hash:master

Get commit from another branch

Imagine you are working in a new feature with your team in a different branch than master. Then, a team member add a cool functionality which will be util in production right now. You can not wait and want to deploy this functionality in production tonight.

Using the command below you just need to know the commit hash and all changes in that commit will be copy in your current branch. Awesome, isn’t it?

1
git cherry-pick hash

Amend

Every day, as a developers we are introducing new code. After few changes we can save our work, but, wait!!! It’s not the end we need to do more changes to finish the feature. Git add amend which allow us to override the last commit. NOTE: which has not been pushed to the central repository.

1
git commit --amend --reuse-message=HEAD

Building git command alias

All commands mentioned above can be too large or complex to remember them but you can use alias to give a easy name for you.

Command below will store log --oneline --decorate --graph in the alias logd

1
git config --global alias.lodg `log --oneline --decorate --graph`

After setup your new alias. You can use git lodg instead git log --oneline --decorate --graph and the result will be the same.

Code Analysis With JArchitect

Code Analysis is a really important stage in our projects, we need to take a look the software healthy every day. In this blog, JArchitect is the Code Analysis tool for Java projects that we are going to talk about.

Months ago I have the chance to get a JArchitect’s license- thanks to the CodeGears team for this license. Then, I started taking a look how it works.

  • Code Quality Metrics
  • Graph Dependency
  • Dependency Cycle

Features

A really nice feature is that you can use CQLinq to build query over Java code. To learn more about CQLinq syntax check here. Also, allow you to create your own rules.

Modern projects use build tools to package their artifacts (jar, war, etc) So the integration with modern build tools such as gradle and maven is possible, you can follow the online documentation to set up.

Also, Continuous Integration process is real using JArchitect.

About Code Coverage, cobertura is the only technology supported by JArchitect at this moment. These metrics can be getting from xml files, but we need to generate reports previous to the code analysis.

Another great integration is that we can enrich our analysis with existing tools in the market like CheckStyle, FindBugs, PMD.

Languages that already run in the JVM can be analyze by JArchitect like scala, groovy, clojure.

For Open Source contributor there are good news. You can get your own free copy of JArchitect. How to apply? Check this link for more information.

Analysis Bar

Graph Dependency

Report- Metrics

Report- Rules Violated

CQLinq sentence

Improving Maven Projects

During long time maven has been the defacto build tool and dependency management for java projects. Since previous version some cool things has been added by plugins but now maven has been enriched with new features learning from the others.

All these new stuff is thanks to Takiri which is lead by Jason van Zyl (@jvanzyl) the maven’s father.

Requirements:

  • Maven 3.3.1
  • Java 7

Maven Lifecycle

Avoid the re-compilation if there are no changes in the source code. Just is needed two simple steps to enable this awesome feature. Save your time!!!

1. Add plugin below:

1
2
3
4
5
6
7
8
9
<build>
  <plugins>
    <plugin>
      <groupId>io.takari.maven.plugins</groupId>
      <artifactId>takari-lifecycle-plugin</artifactId>
      <extensions>true</extensions>
    </plugin>
  </plugins>
</build>

2. Switch your current packaging from jar to takari-jar.

You can see the log to see if the plugin take effect. If you have compiled previously and you do again with after these configuration then no compilation will be done but if there are any change in your source code then it will compile again.

Maven Polyglot

Build pom file in xml format is verbose. Now, you can build your pom in different languages: atom, clojure, groovy, ruby, scala, yaml. And take advantage of each one.

Pre-requisite:

  1. Inside the project create .mvn/extensions.xml file, where language dependency will take place:

Atom

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-atom</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Clojure:

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-clojure</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Groovy

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-groovy</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Ruby

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-ruby</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Scala

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-scala</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Yaml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
  <extension>
      <groupId>io.takari.polyglot</groupId>
      <artifactId>polyglot-yaml</artifactId>
      <version>0.1.6</version>
  </extension>
</extensions>

Would you like to migrate your xml to any other language? You can do it running the command below:

1
mvn io.takari.polyglot:polyglot-translate-plugin:translate -Dinput=pom.xml -Doutput=pom.{format}

Where format could be atom, clj, groovy, rb, scala and yml.

Maven Wrapper

Share projects is common and sometimes we have specific version from our build tool. Now, you don’t need to ask to your friend which maven version you need if the maven project use maven-wrapper. To do that, you just need to run:

1
mvn -N io.takari:maven:wrapper

Now you can make a build mvnw clean install. If you like to see which maven version you will download take a look at .mvn/wrapper/maven-wrapper.properties inside your project.

My Advice to (Junior) Developers About Their Career

Mi consejo a desarrolladores (juniors) sobre su carrera

“Los últimos meses he conocido jóvenes desarrolladores que están buscando su primer trabajo o están todavia tratando de obtener su grado de bachiller. Muchos de ellos pidieron darles un consejo sobre cuales serian sus primeros pasos en la carrera de desarrollo de software. Se ve bien ver jóvenes preocuparse sobre sus carreras. No recuerdo que los chicos de mi edad tuvieran esa mentalidad. Asumo que fue la crisis económica la que hizo que todos estos jóvenes actúen con bastante madurez, pero me gusta.

En este post resumo mi consejo a todos estos jóvenes y desarrolladores ambiciosos. No se deje engañar por la palabra jóven. Incluso si ustedes tienen 10 años, son todavía jóvenes. Al menos yo me siento así.

Lo primero que ellos me preguntaron fue que lenguaje o framework deberían aprender primero. Pude dar miles de diferentes respuestas pero la clave no está en saber qué lenguaje ya conoces sino la rapidez con la que se puede aprender uno nuevo. Piensas que a Google, Ebay ó Amazon les importa si eres un experto en Java ó JEE ó JavaScript? Envía tu CV y ten una entrevista con algunos chicos techie.

Las compañías de IT deben contratar personajes y entrenar sus habilidades. Ok, sé que este no siempre es el caso pero tarde o temprano, alguien te preguntará por la lista de lenguajes de programación o frameworks que conoces. Si eres el personaje de “Lucky Luke” nadie te va a querer en su equipo. La era de los desarrolladores super héroes ha pasado y no veo que regrese nunca. El trabajo en equipo es la clave del éxito y debes estar preparado para eso. Que hay sobre las habilidades? Si no puedes aprender una nueva herramienta, un nuevo lenguaje de programación o un framework, tu todavía tienes tiempo de ir a otra carrera. Las compañías invertirán en tí para enseñarte nuevas habilidades pero tu debes ser un rápido aprendiz y ser capaz de adoptar nuevas habilidades técnicas en tu trabajo diario. Piensa por un minuto sobre la definición de inversión. Sí, estas en lo correcto. Las compañías no están regalando esas habilidades. Ellos esperan de ti devolver el nuevo conocimiento mediante el aumento de habilidades, productividad y eventualmente el valor de la empresa.

Otra gran idea es ser amigo del OpenSource. Coge una herramienta OpenSource que te guste, que conozcas bien o sólo la encuentres interesante, y unite a la comunidad. Trata de ser activo, y por que no, contribuir al proyecto. No hay nada mejor que mostrarle a los futuros empleadores sobre su trabajo en un proyecto real de código abierto. Por otra parte, abre una cuenta en github, si no lo ha hecho ya. Sube tus proyectos personales. Deje ver a otros que eres un apasionado del desarrollo de software y no solo están considerandolo como un camino para obtener dinero. Y desde que tienes tu cuenta de github lee el código de otros. Es una gran camino para abrir tu mente y aprender nuevas cosas de lenguajes que tu nunca has visto.

Sé ágil! aprende a escribir código limpio, no importa cual es el lenguaje en el que tu escribes tu código. Aprende a respetarte a ti mismo y a los demás desarrolladores de tu equipo. Tu código refleja tu personalidad. Un código desordenado probablemente hara a tus colegas pensar que eres lo mismo en tu vida personal. No querrás escuchar de tus colegas wtf is this? cuando ellos lean o revisen tu último commit. Aprende patrones de diseño y refactoring. Puedes aplicarlos en todos los lenguajes populares y seguramente te haran escribir código limpio.

Unete a un Grupo Local y ve a algunas conferencias. Es increíble cuantas cosas aprendes cuando conoces gente de diferentes culturas, orígenes y conocimiento. No tienes nada que perder. Al contrario, puedo asegurarte que estas en una situación ganadora. Sin mencionar que incrementaras tu círculo social y quizás mejorar las opciones de obtener un nuevo trabajo.

Finalmente construye tu marca. Quizás suene como un chico de marketing, pero no lo soy. Haga publicidad de si mismo con sus logros, incluso si es el millonésimo que lo hizo. No importa. Haga saber a los demás sus intereses y que estas activo en el desarrollo de software. Linkedin, Twitter y otras redes profesionales pueden ayudar bastante. Empieza tu blog y publica pequeños artículos sobre tu experiencia y conocimiento, incluso si son para principiantes. Otra vez, no importa!!! Te encontraras publicando mas y mas material avanzado muy pronto.

Y unas cosa mas… Nunca pares de aprender nuevas cosas. Tu decidiste ser un Ingeniero de Software. Este es tu destino. Aprender nuevas cosas constantemente."

Source: My Advice to (Junior) Developers About Their Career 

How to Start With Mule ESB

What is an ESB?

It’s a software architecture. ESB or Enterprise Service Bus is a Enterprise Integration Pattern (EIP) solves the spaghetti integration pattern.

What is Mule ESB?

It is a Open Source Enterprise Service Bus (ESB), which allow to integrate lot of technologies.

Mule main parts:

  • Component
  • Transport
  • Transformers
  • Inbound/Outbound Routers

Mule also provide rich set of:

  • Routers
  • Transformers
  • Filters

Using Maven

Make sure you have set the Mulesoft’s repository in settings.xml

1
2
3
4
5
6
7
<repositories>
  <repository>
    <id>mulesoft-release</id>
    <name>Mulesoft Release Repository</name>
    <url>https://repository.mulesoft.org/nexus/content/repositories/public/</url>
  </repository>
</repositories>

Also, check you have the pluginGroup org.mule.tools.

Now, you are able to run the following command your terminal:

1
mvn mule-project-archetype:create -DartifactId=helloWorld -DmuleVersion=3.5.0

Using Gradle

Make sure you have a build.gradle file inside the folder with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
buildscript {
    dependencies {
        classpath group: 'org.mulesoft.build', name: 'mule-gradle-plugin', version: '1.1.0'
    }

    repositories {
        maven {
            url 'http://repository.mulesoft.org/releases'
        }
    }
}

apply plugin: 'mule'

mule.version = '3.5.0'

mule.muleEnterprise = false

After that you can execute:

1
gradle initMuleProject

By default, mule.muleEnterprise is set to true.

For more information you can visit mule-gradle-plguin documentation.

Using maven or gradle you will be able to see the project like this

Differences between maven and gradle plugin

Maven Gradle
Provide mule packaging Provide mule plugin
Allow to deploy in local mule standalone Allow to deploy in local mule standalone, Mule Management Console and Cloudhub
- Allow to run application with a simple command

Testing

mule-config.xml is placed inside of src/main/app. Here you will find a http service which will return Hello World! message.

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!-- created by the gradle mule plugin -->

<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
  http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
  http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
  <flow name="mule-configFlow1" doc:name="mule-configFlow1">
    <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP"/>
    <set-payload doc:name="Set Payload" value="Hello World!"/>
  </flow>
</mule>

Then, proceed to write a test for the existing flow. As you can see response will be validated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.mule.api.MuleMessage;
import org.mule.api.client.MuleClient;
import org.mule.tck.junit4.FunctionalTestCase;

public class MuleTest extends FunctionalTestCase {

  @Override
  protected String getConfigFile() {
    return "src/main/app/mule-config.xml";
  }

  @Test
  public void testMuleConfigFlow1() throws Exception {
    MuleClient client = muleContext.getClient();
    MuleMessage message = client.request("http://localhost:8081", 3000L);
    String payload = message.getPayloadAsString();
    Assert.assertThat(payload, Is.is("Hello World!"));
  }
}