Editing pass for new content (#570)

 Editing pass for new content (#570)

Olga Maciaszek-Sharma added very nice content, in the form of a three-second and a three-minute introduction for the verifier. I edited her additions to conform to our usual standards and corporate voice.

== Spring Cloud Contract Verifier Introduction

TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski
(http://codearte.io[codearte.io])

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of
JVM-based applications. It moves TDD to the level of software architecture.

Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract
definitions are used to produce the following resources:

* JSON stub definitions to be used by WireMock when doing integration testing on the
client code (_client tests_). Test code must still be written by hand, and test data is
produced by Spring Cloud Contract Verifier.
* Messaging routes, if you're using a messaging service. We integrate with Spring
Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your
own integrations.
* Acceptance tests (in JUnit or Spock) are used to verify if server-side implementation
of the API is compliant with the contract (__server tests__). A full test is generated by
Spring Cloud Contract Verifier.

=== Why a Contract Verifier?

Assume that we have a system consisting of multiple microservices:

image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture]

==== Testing issues

If we wanted to test the application in top left corner to determine whether it can
communicate with other services, we could do one of two things:

- Deploy all microservices and perform end-to-end tests.
- Mock other microservices in unit/integration tests.

Both have their advantages but also a lot of disadvantages.

*Deploy all microservices and perform end to end tests*

Advantages:

- Simulates production.
- Tests real communication between services.

Disadvantages:

- To test one microservice, we have to deploy 6 microservices, a couple of databases,
etc.
- The environment where the tests run is locked for a single suite of tests (nobody else
would be able to run the tests in the meantime).
- They take a long time to run.
- The feedback comes very late in the process.
- They are extremely hard to debug.

*Mock other microservices in unit/integration tests*

Advantages:

- They provide very fast feedback.
- They have no infrastructure requirements.

Disadvantages:

- The implementor of the service creates stubs that might have nothing to do with
reality.
- You can go to production with passing tests and failing production.

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was
created. The main idea is to give you very fast feedback, without the need to set up the
whole world of microservices. If you work on stubs, then the only applications you need
are those that your application directly uses.

image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services]

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were
created by the service that you're calling. Also, if you can use them, it means that they
were tested against the producer's side. In short, you can trust those stubs.

=== Purposes

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly
what the actual server-side implementation does.
- To promote ATDD method and Microservices architectural style.
- To provide a way to publish changes in contracts that are immediately visible on both
sides.
- To generate boilerplate test code to be used on the server side.

IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business
features in the contracts. Assume that we have a business use case of fraud check. If a
user can be a fraud for 100 different reasons, we would assume that you would create 2
contracts, one for the positive case and one for the negative case. Contract tests are
used to test contracts between applications and not to simulate full behavior.

=== How It Works

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

[[spring-cloud-contract-verifier-intro-three-second-tour]]
==== A Three-second Tour

This very brief tour walks through using Spring Cloud Contract:

* <<spring-cloud-contract-verifier-intro-three-second-tour-producer>>
* <<spring-cloud-contract-verifier-intro-three-second-tour-consumer>>

You can find a somewhat longer tour
<<spring-cloud-contract-verifier-intro-three-minute-tour,here>>.

[[spring-cloud-contract-verifier-intro-three-second-tour-producer]]
===== On the Producer Side

To start working with Spring Cloud Contract, add files with `REST/` messaging contracts
expressed in either Groovy DSL or YAML to the contracts directory, which is set by the
`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`.

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as
shown in the following example:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

The following listing shows how to add the plugin, which should go in the build/plugins
portion of the file:

[source,xml,indent=0]
----
<plugin>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
	<version>${spring-cloud-contract.version}</version>
	<extensions>true</extensions>
</plugin>
----

Running `./mvnw clean install` automatically generates tests that verify the application
compliance with the added contracts. By default, the tests get generated under
`org.springframework.cloud.contract.verifier.tests.`.

As the implementation of the functionalities described by the contracts is not yet
present, the tests fail.

To make them pass, you must add the correct implementation of either handling HTTP
requests or messages. Also, you must add a correct base test class for auto-generated
tests to the project. This class is extended by all the auto-generated tests, and it
should contain all the setup necessary to run them (for example `RestAssuredMockMvc`
controller setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the
application and the stub artifacts are built and installed in the local Maven repository.
The changes can now be merged, and both the application and the stub artifacts may be
published in an online repository.

[[spring-cloud-contract-verifier-intro-three-second-tour-consumer]]
===== On the Consumer Side

`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running
WireMock instance or messaging route that simulates the actual service.

To do so, add the dependency to `Spring Cloud Contract Stub Runner`, as shown in the
following example:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

You can get the Producer-side stubs installed in your Maven repository in either of two
ways:

* By checking out the Producer side repository and adding contracts and generating the stubs
by running the following commands:
+
[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----
TIP: The tests are being skipped because the Producer-side contract implementation is not
in place yet, so the automatically-generated contract tests fail.
* By getting already-existing producer service stubs from a remote repository. To do so,
pass the stub artifact IDs and artifact repository URL as `Spring Cloud Contract
Stub Runner` properties, as shown in the following example:
+
[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation,
provide the `group-id` and `artifact-id` values for `Spring Cloud Contract Stub Runner` to
run the collaborators' stubs for you, as shown in the following example:

[source,java, indent=0]
----
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@DirtiesContext
public class LoanApplicationServiceTests {
----

TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and
`LOCAL` for offline work.

Now, in your integration test, you can receive stubbed versions of HTTP responses or
messages that are expected to be emitted by the collaborator service.

[[spring-cloud-contract-verifier-intro-three-minute-tour]]
==== A Three-minute Tour

This brief tour walks through using Spring Cloud Contract:

* <<spring-cloud-contract-verifier-intro-three-minute-tour-producer>>
* <<spring-cloud-contract-verifier-intro-three-minute-tour-consumer>>

You can find an even more brief tour
<<spring-cloud-contract-verifier-intro-three-second-tour,here>>.

[[spring-cloud-contract-verifier-intro-three-minute-tour-producer]]
===== On the Producer Side

To start working with `Spring Cloud Contract`, add files with `REST/` messaging contracts
expressed in either Groovy DSL or YAML to the contracts directory, which is set by the
`contractsDslDir` property. By default, it is `$rootDir/src/test/resources/contracts`.

For the HTTP stubs, a contract defines what kind of response should be returned for a
given request (taking into account the HTTP methods, URLs, headers, status codes, and so
on). The following example shows how an HTTP stub contract in Groovy DSL:

[source,groovy,indent=0]
----
package contracts

org.springframework.cloud.contract.spec.Contract.make {
	request {
		method 'PUT'
		url '/fraudcheck'
		body([
			   "client.id": $(regex('[0-9]{10}')),
			   loanAmount: 99999
		])
		headers {
			contentType('application/json')
		}
	}
	response {
		status 200
		body([
			   fraudCheckStatus: "FRAUD",
			   "rejection.reason": "Amount too high"
		])
		headers {
			contentType('application/json')
		}
	}
}
----

The same contract expressed in YAML would look like the following example:

[source,yaml,indent=0]
----
request:
  method: PUT
  url: /fraudcheck
  body:
    "client.id": 1234567890
    loanAmount: 99999
  headers:
    Content-Type: application/json
  matchers:
    body:
      - path: $.['client.id']
        type: by_regex
        value: "[0-9]{10}"
response:
  status: 200
  body:
    fraudCheckStatus: "FRAUD"
    "rejection.reason": "Amount too high"
  headers:
    Content-Type: application/json;charset=UTF-8
----

In the case of messaging, you can define:

* The input and the output messages can be defined (taking into account from and where it
was sent, the message body, and the header).
* The methods that should be called after the message is received.
* The methods that, when called, should trigger a message.

The following example shows a Camel messaging contract expressed in Groovy DSL:

[source,groovy]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl]
----

The following example shows the same contract expressed in YAML:

[source,yml,indent=0]
----
include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0]
----

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file,
as shown in the following example:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

The following listing shows how to add the plugin, which should go in the build/plugins
portion of the file:

[source,xml,indent=0]
----
<plugin>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
	<version>${spring-cloud-contract.version}</version>
	<extensions>true</extensions>
</plugin>
----

Running `./mvnw clean install` automatically generates tests that verify the application
compliance with the added contracts. By default, the generated tests are under
`org.springframework.cloud.contract.verifier.tests.`.

The following example shows a sample auto-generated test for an HTTP contract:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

The preceding example uses Spring's `MockMvc` to run the tests. This is the default test
mode for HTTP contracts. However, JAX-RX client and explicit HTTP invocations can also be
used. (To do so, change the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`,
respectively.)

Apart from the default JUnit, you can instead use Spock tests, by setting the plugin
`testFramework` property to `Spock`.

TIP: You can now also generate WireMock scenarios based on the contracts, by including an
order number followed by an underscore at the beginning of the contract file names.

The following example shows an auto-generated test in Spock for a messaging stub contract:

 [source,groovy,indent=0]
----
given:
	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
		\'\'\'{"bookName":"foo"}\'\'\',
		['sample': 'header']
	)

when:
	 contractVerifierMessaging.send(inputMessage, 'jms:delete')

then:
	 noExceptionThrown()
	 bookWasDeleted()
----

As the implementation of the functionalities described by the contracts is not yet
present, the tests fail.

To make them pass, you must add the correct implementation of handling either HTTP
requests or messages. Also, you must add a correct base test class for auto-generated
tests to the project. This class is extended by all the auto-generated tests and should
contain all the setup necessary to run them (for example, `RestAssuredMockMvc` controller
setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the
application and the stub artifacts are built and installed in the local Maven repository.
Information about installing the stubs jar to the local repository appears in the logs, as
shown in the following example:

[source,bash,indent=0]
----
 [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
 [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
 [INFO]
 [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
 [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
 [INFO]
 [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
 [INFO]
 [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
 [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
 [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
 [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

You can now merge the changes and publish both the application and the stub artifacts
in an online repository.

*Docker Project*

In order to enable working with contracts while creating applications in non-JVM
technologies, the `springcloud/spring-cloud-contract` Docker image has been created. It
contains a project that automatically generates tests for HTTP contracts and executes them
in  `EXPLICIT` test mode. Then, if the tests pass, it generates Wiremock stubs and,
optionally, publishes them to an artifact manager. In order to use the image, you can
mount the contracts into the `/contracts` directory and set a few environment variables.
// TODO: We should answer the obvious question: Which environment variables?

[[spring-cloud-contract-verifier-intro-three-minute-tour-consumer]]
===== On the Consumer Side

`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running
WireMock instance or messaging route that simulates the actual service.

To get started, add the dependency to `Spring Cloud Contract Stub Runner`:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

You can get the Producer-side stubs installed in your Maven repository in either of two
ways:

* By checking out the Producer side repository and adding contracts and generating the
stubs by running the following commands:
+
[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----
NOTE: The tests are skipped because the Producer-side contract implementation is not yet
in place, so the automatically-generated contract tests fail.
* Getting already existing producer service stubs from a remote repository. To do so,
pass the stub artifact IDs and artifact repository URl as `Spring Cloud Contract Stub
Runner` properties, as shown in the following example:
+
[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

Now you can annotate your test class with `@AutoConfigureStubRunner`. In the annotation,
provide the `group-id` and `artifact-id` for `Spring Cloud Contract Stub Runner` to run
the collaborators' stubs for you, as shown in the following example:

[source,java, indent=0]
----
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@DirtiesContext
public class LoanApplicationServiceTests {
----

TIP: Use the `REMOTE` `stubsMode` when downloading stubs from an online repository and
`LOCAL` for offline work.

In your integration test, you can receive stubbed versions of HTTP responses or messages
that are expected to be emitted by the collaborator service. You can see entries similar
to the following in the build logs:

[source,bash,indent=0]
----
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
----

==== Defining the Contract

As consumers of services, we need to define what exactly we want to achieve. We need to
formulate our expectations. That is why we write contracts.

Assume that you want to send a request containing the ID of a client company and the
amount it wants to borrow from us. You also want to send it to the /fraudcheck url via
the PUT method.

.Groovy DSL
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
----

.YAML
[source,yml,indent=0]
----
include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[]
----

==== Client Side

Spring Cloud Contract generates stubs, which you can use during client-side testing.
You get a running WireMock instance/Messaging route that simulates the service.
You would like to feed that instance with a proper stub definition.

At some point in time, you need to send a request to the Fraud Detection service.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]
----

Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----

After that, during the tests, Spring Cloud Contract automatically finds the stubs
(simulating the real service) in the Maven repository and exposes them on a configured
(or random) port.

==== Server Side

Since you are developing your stub, you need to be sure that it actually resembles your
concrete implementation. You cannot have a situation where your stub acts in one way and
your application behaves in a different way, especially in production.

To ensure that your application behaves the way you define in your stub, tests are
generated from the stub you provide.

The autogenerated test looks, more or less, like this:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

=== Step-by-step Guide to Consumer Driven Contracts (CDC)

Consider an example of Fraud Detection and the Loan Issuance process. The business
scenario is such that we want to issue loans to people but do not want them to steal from
us. The current implementation of our system grants loans to everybody.

Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current
sprint, we must develop a new feature: if a client wants to borrow too much money, then
we mark the client as a fraud.

Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan
Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`.

Social remark - both client and server development teams need to communicate directly and
discuss changes while going through the process. CDC is all about communication.

The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server
side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the
client code here].

TIP: In this case, the producer owns the contracts. Physically, all the contract are
in the producer's repository.

==== Technical note

If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the
following section to your build:

[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0]
----

[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
.Gradle
----
include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0]
----

==== Consumer side (Loan Issuance)

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

. Start doing TDD by writing a test for your feature.
. Write the missing implementation.
. Clone the Fraud Detection service repository locally.
. Define the contract locally in the repo of Fraud Detection service.
. Add the Spring Cloud Contract Verifier plugin.
. Run the integration tests.
. File a pull request.
. Create an initial implementation.
. Take over the pull request.
. Write the missing implementation.
. Deploy your app.
. Work online.

*Start doing TDD by writing a test for your feature.*

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0]
----

Assume that you have written a test of your new feature. If a loan application for a big
amount is received, the system should reject that loan application with some description.

*Write the missing implementation.*

At some point in time, you need to send a request to the Fraud Detection service. Assume
that you need to send the request containing the ID of the client and the amount the
client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]
----

For simplicity, the port of the Fraud Detection service is set to `8080`, and the
application runs on `8090`.

If you start the test at this point, it breaks, because no service currently runs on port
`8080`.

*Clone the Fraud Detection service repository locally.*

You can start by playing around with the server side contract. To do so, you must first
clone it.

[source,bash,indent=0]
----
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
----

*Define the contract locally in the repo of Fraud Detection service.*

As a consumer, you need to define what exactly you want to achieve. You need to formulate
your expectations. To do so, write the following contract:

IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder
is important because the producer's test base class name references that folder.

.Groovy DSL
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
----

.YAML
[source,yml,indent=0]
----
include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[]
----

The YML contract is quite straight-forward. However when you take a look at the Contract
written using a statically typed Groovy DSL - you might wonder what the
`value(client(...), server(...))` parts are. By using this notation, Spring Cloud
Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case
of an identifier or a timestamp, you need not hardcode a value. You want to allow some
different ranges of values. To enable ranges of values, you can set regular expressions
matching those values for the consumer side. You can provide the body by means of either
a map notation or String with interpolations.
https://cloud.spring.io/spring-cloud-contract/single/spring-cloud-contract.html#_contract_dsl[Consult the docs
for more information.] We highly recommend using the map notation!

TIP: You must understand the map notation in order to set up contracts. Please read the
http://groovy-lang.org/json.html[Groovy docs regarding JSON].

The previously shown contract is an agreement between two sides that:

- if an HTTP request is sent with all of
** a `PUT` method on the `/fraudcheck` endpoint,
** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and
`loanAmount` equal to `99999`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`,
- then an HTTP response is sent to the consumer that
** has status `200`,
** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and
the `rejectionReason` field having value `Amount too high`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`.

Once you are ready to check the API in practice in the integration tests, you need to
install the stubs locally.

*Add the Spring Cloud Contract Verifier plugin.*

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven.
First, add the `Spring Cloud Contract` BOM.

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0]
----

Next, add the `Spring Cloud Contract Verifier` Maven plugin

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----

Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which,
from the provided contracts:

- generate and run tests
- produce and install stubs

You do not want to generate tests since you, as the consumer, want only to play with the
stubs. You need to skip the test generation and execution. When you execute:

[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----

In the logs, you see something like this:

[source,bash,indent=0]
----
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

The following line is extremely important:

[source,bash,indent=0]
----
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

It confirms that the stubs of the `http-server` have been installed in the local
repository.

*Run the integration tests.*

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic
stub downloading, you must do the following in your consumer side project (`Loan
Application service`):

Add the `Spring Cloud Contract` BOM:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0]
----

Add the dependency to `Spring Cloud Contract Stub Runner`:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the
`group-id` and `artifact-id` for the Stub Runner to download the stubs of your
collaborators. (Optional step) Because you're playing with the collaborators offline, you
can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`).

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----

Now, when you run your tests, you see something like this:

[source,bash,indent=0]
----
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
----

This output means that Stub Runner has found your stubs and started a server for your app
with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of
the stubs and with `stubs` classifier on port `8080`.

*File a pull request.*

What you have done until now is an iterative process. You can play around with the
contract, install it locally, and work on the consumer side until the contract works as
you wish.

Once you are satisfied with the results and the test passes, publish a pull request to
the server side. Currently, the consumer side work is done.

==== Producer side (Fraud Detection server)

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

*Create an initial implementation.*

As a reminder, you can see the initial implementation here:

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0]
}
----

*Take over the pull request.*

[source,bash,indent=0]
----
$ git checkout -b contract-change-pr master
$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
----

You must add the dependencies needed by the autogenerated tests:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----

IMPORTANT: This example uses "convention based" naming by setting the
`packageWithBaseClasses` property. Doing so means that the two last packages combine to
make the name of the base test class. In our case, the contracts were placed under
`src/test/resources/contracts/fraud`. Since you do not have two packages starting from
the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and
capitalize `fraud`. That gives you the `FraudBase` test class name.

All the generated tests extend that class. Over there, you can set up your Spring Context
or whatever is necessary. In this case, use http://rest-assured.io/[Rest Assured MVC] to
start the server side `FraudDetectionController`.

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[]
----

Now, if you run the `./mvnw clean install`, you get something like this:

[source,bash,indent=0]
----
Results :

Tests in error:
  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
----

This error occurs because you have a new contract from which a test was generated and it
failed since you have not implemented the feature. The auto-generated test would look
like this:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the
`value(consumer(...), producer(...))` blocks got injected into the test.
In case of using YAML, the same applied for the `matchers` sections of the `response`.

Note that, on the producer side, you are also doing TDD. The expectations are expressed
in the form of a test. This test sends a request to our own application with the URL,
headers, and body defined in the contract. It also is expecting precisely defined values
in the response. In other words, you have the `red` part of `red`, `green`, and
`refactor`. It is time to convert the `red` into the `green`.

*Write the missing implementation.*

Because you know the expected input and expected output, you can write the missing
implementation:

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0]
}
----

When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud
Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can
actually run those tests from your IDE.

*Deploy your app.*

Once you finish your work, you can deploy your change. First, merge the branch:

[source,bash,indent=0]
----
$ git checkout master
$ git merge --no-ff contract-change-pr
$ git push origin master
----

Your CI might run something like `./mvnw clean deploy`, which would publish both the
application and the stub artifacts.

==== Consumer Side (Loan Issuance) Final Step

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

*Merge branch to master.*

[source,bash,indent=0]
----
$ git checkout master
$ git merge --no-ff contract-change-pr
----

*Work online.*

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate
where the repository with your stubs is located. At this moment the stubs of the server
side are automatically downloaded from Nexus/Artifactory. You can set the value of
`stubsMode` to `REMOTE`. The following code shows an example of
achieving the same thing by changing the properties.

[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

That's it!

=== Dependencies

The best way to add dependencies is to use the proper `starter` dependency.

For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add
`spring-cloud-starter-contract-verifier`.

=== Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note
that some may be outdated, because the Spring Cloud Contract Verifier project is under
constant development.

==== Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

video::sAAklvxmPmk[youtube,start=538,width=640,height=480]

==== Readings

- http://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest]
- http://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog]
- http://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog]
- http://groovy-lang.org/json.html[Groovy docs regarding JSON]

=== Samples

You can find some samples at
https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples].

== Spring Cloud Contract Verifier Introduction

TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski
(http://codearte.io[codearte.io])

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of
JVM-based applications. It moves TDD to the level of software architecture.

Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract
definitions are used to produce the following resources:

* JSON stub definitions to be used by WireMock when doing integration testing on the
client code (_client tests_). Test code must still be written by hand, and test data is
produced by Spring Cloud Contract Verifier.
* Messaging routes, if you're using a messaging service. We integrate with Spring
Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your
own integrations.
* Acceptance tests (in JUnit or Spock) are used to verify if server-side implementation
of the API is compliant with the contract (__server tests__). A full test is generated by
Spring Cloud Contract Verifier.

=== Why a Contract Verifier?

Assume that we have a system consisting of multiple microservices:

image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture]

==== Testing issues

If we wanted to test the application in top left corner to determine whether it can
communicate with other services, we could do one of two things:

- Deploy all microservices and perform end-to-end tests.
- Mock other microservices in unit/integration tests.

Both have their advantages but also a lot of disadvantages.

*Deploy all microservices and perform end to end tests*

Advantages:

- Simulates production.
- Tests real communication between services.

Disadvantages:

- To test one microservice, we have to deploy 6 microservices, a couple of databases,
etc.
- The environment where the tests run is locked for a single suite of tests (nobody else
would be able to run the tests in the meantime).
- They take a long time to run.
- The feedback comes very late in the process.
- They are extremely hard to debug.

*Mock other microservices in unit/integration tests*

Advantages:

- They provide very fast feedback.
- They have no infrastructure requirements.

Disadvantages:

- The implementor of the service creates stubs that might have nothing to do with
reality.
- You can go to production with passing tests and failing production.

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was
created. The main idea is to give you very fast feedback, without the need to set up the
whole world of microservices. If you work on stubs, then the only applications you need
are those that your application directly uses.

image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services]

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were
created by the service that you're calling. Also, if you can use them, it means that they
were tested against the producer's side. In short, you can trust those stubs.

=== Purposes

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly
what the actual server-side implementation does.
- To promote ATDD method and Microservices architectural style.
- To provide a way to publish changes in contracts that are immediately visible on both
sides.
- To generate boilerplate test code to be used on the server side.

IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business
features in the contracts. Assume that we have a business use case of fraud check. If a
user can be a fraud for 100 different reasons, we would assume that you would create 2
contracts, one for the positive case and one for the negative case. Contract tests are
used to test contracts between applications and not to simulate full behavior.

=== How It Works

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

==== A three second tour

===== On the Producer Side

In order to start working with `Spring Cloud Contract`, add files with REST/ messaging contracts expressed in either
Groovy DSL or YAML to the contracts directory set by the
`contractsDslDir` property, by default `$rootDir/src/test/resources/contracts`.

Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

[source,xml,indent=0]
----
<plugin>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
	<version>${spring-cloud-contract.version}</version>
	<extensions>true</extensions>
</plugin>
----

Now, running `./mvnw clean install` will cause tests that verify the application
compliance with the added contracts to be automatically generated, by default under `org.springframework.cloud.contract.verifier.tests.`.

As the implementation of the functionalities described by the contracts is not  yet present,
 the tests will fail.

To make them pass, the correct implementation of either handling HTTP requests or messages
will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project.
This class will be extended by all the auto-generated tests and it should contain all the setup
necessary to run them (for example `RestAssuredMockMvc` controller setup or messaging test setup).

Once the implementation and the test base class are in place, the tests will pass, and both the application
 and the stub artifacts will be built and installed in the local Maven repository. The changes can now be merged
 and both the application and the stub artifacts may be published in an online repository.

===== On the Consumer Side

`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running WireMock instance/
messaging route that simulates the actual service.

Add the dependency to `Spring Cloud Contract Stub Runner`:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

Get the Producer-side stubs installed in your Maven repository by either:

- checking out the Producer side repository, adding contracts and generating the stubs by running:

[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----
TIP: The tests are being skipped because the Producer-side contract implementation is not in place yet,
so the automatically-generated contract tests would fail;

or:

- getting already existing producer service stubs from a remote repository; to do this, simply pass the
 stub artifact ids and artifact repository url as `Spring Cloud Contract Stub Runner` properties:

[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

Now just annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide
the group-id and artifact-id for `Spring Cloud Contract Stub Runner` to run the collaborators' stubs for you.

TIP: Use the `REMOTE` stubsMode when downloading stubs from an online repository and `LOCAL` for offline work.

[source,java, indent=0]
----
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@DirtiesContext
public class LoanApplicationServiceTests {
----

Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are
expected to be emitted by the collaborator service.

==== A three minute tour

===== On the Producer Side

In order to start working with `Spring Cloud Contract`, add files with REST/ messaging contracts expressed in either
Groovy DSL or YAML to the contracts directory set by the
`contractsDslDir` property, by default `$rootDir/src/test/resources/contracts`.

For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP
methods, urls, headers, status codes, etc.). A sample HTTP stub contract in Groovy DSL would look like this:

[source,groovy,indent=0]
----
package contracts

org.springframework.cloud.contract.spec.Contract.make {
	request {
		method 'PUT'
		url '/fraudcheck'
		body([
			   "client.id": $(regex('[0-9]{10}')),
			   loanAmount: 99999
		])
		headers {
			contentType('application/json')
		}
	}
	response {
		status 200
		body([
			   fraudCheckStatus: "FRAUD",
			   "rejection.reason": "Amount too high"
		])
		headers {
			contentType('application/json')
		}
	}
}
----

While the same contract expressed in YAML would look the following way:

[source,yaml,indent=0]
----
request:
  method: PUT
  url: /fraudcheck
  body:
    "client.id": 1234567890
    loanAmount: 99999
  headers:
    Content-Type: application/json
  matchers:
    body:
      - path: $.['client.id']
        type: by_regex
        value: "[0-9]{10}"
response:
  status: 200
  body:
    fraudCheckStatus: "FRAUD"
    "rejection.reason": "Amount too high"
  headers:
    Content-Type: application/json;charset=UTF-8
----

In the case of messaging, the input and the output messages can be defined (taking into account from and
where to it was sent, the message body and header), as well as the methods that should be called after the message
 is received or the methods that, when called, should trigger a message.
An example of a Camel messaging contract expressed in Groovy DSL whould look like this:

[source,groovy]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl]
----

While, the same contract expressed in YAML would look as in the code below:

[source,yml,indent=0]
----
include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0]
----

Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

[source,xml,indent=0]
----
<plugin>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
	<version>${spring-cloud-contract.version}</version>
	<extensions>true</extensions>
</plugin>
----

Now, running `./mvnw clean install` will cause tests that verify the application
compliance with the added contracts to be automatically generated, by default under `org.springframework.cloud.contract.verifier.tests.`.

A sample auto-generated test for an HTTP contract would look the following way:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

The sample above uses Spring's `MockMvc` to run the tests. This is the default test mode for HTTP
contracts, however also JAX-RX client and explicit HTTP invocations can be used as well (just change
the `testMode` property of the plugin to `JAX-RS` or `EXPLICIT`.

Apart from the default JUnit, you can also use Spock tests, instead, by setting the plugin `testFramework`
property to `Spock`.

TIP: You can now also generate WireMock scenarios based on the contracts, by including an order number followed by
 an underscore at the beginning of the contract file names.

A sample auto-generated test in Spock for a messaging stub contract would look similar to this:

 [source,groovy,indent=0]
----
given:
	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
		\'\'\'{"bookName":"foo"}\'\'\',
		['sample': 'header']
	)

when:
	 contractVerifierMessaging.send(inputMessage, 'jms:delete')

then:
	 noExceptionThrown()
	 bookWasDeleted()
----

As the implementation of the functionalities described by the contracts is not  yet present,
 the tests will fail.

To make them pass, the correct implementation of handling either HTTP requests or messages
will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project.
This class will be extended by all the auto-generated tests and it should contain all the setup
necessary to run them (for example `RestAssuredMockMvc` controller setup or messaging test setup).

Once the implementation and the test base class are in place, the tests will pass, and both the application
 and the stub artifacts will be built and installed in the local Maven repository. Information about
 installing the stubs jar to the local repository will appear in the logs:

[source,bash,indent=0]
----
 [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
 [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
 [INFO]
 [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
 [INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
 [INFO]
 [INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
 [INFO]
 [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
 [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
 [INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
 [INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

The changes can now be merged and both the application and the stub artifacts may be published in an online repository.

*Docker Project*

In order to enable working with contracts while creating applications in non-JVM technologies,
the `springcloud/spring-cloud-contract`  Docker image has been created. It contains a project that will
automatically generate tests for HTTP contracts and execute them in  `EXPLICIT` test mode, then, if
the tests pass, generate Wiremock stubs and -optionally- publish them to an artifact manager. In order to use the
image, it's sufficient to mount the contracts into the `/contracts` directory and set a few environment variables.

===== On the Consumer Side

`Spring Cloud Contract Stub Runner` can be used in the integration tests to get a running WireMock instance/
messaging route that simulates the actual service.

Add the dependency to `Spring Cloud Contract Stub Runner`:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

Get the Producer-side stubs installed in your Maven repository by either:

- checking out the Producer side repository, adding contracts and generating the stubs by running:

[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----
TIP: The tests are being skipped because the Producer-side contract implementation is not in place yet,
so the automatically-generated contract tests would fail;

or:

- getting already existing producer service stubs from a remote repository; to do this, simply pass the
 stub artifact ids and artifact repository url as `Spring Cloud Contract Stub Runner` properties:

[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

Now just annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide
the group-id and artifact-id for `Spring Cloud Contract Stub Runner` to run the collaborators' stubs for you.

TIP: Use the `REMOTE` stubsMode when downloading stubs from an online repository and `LOCAL` for offline work.

[source,java, indent=0]
----
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@DirtiesContext
public class LoanApplicationServiceTests {
----

Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are
expected to be emitted by the collaborator service. You will see entries similar to theses in the build logs:

[source,bash,indent=0]
----
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
----

==== Defining the contract

As consumers of services, we need to define what exactly we want to achieve. We need to
formulate our expectations. That is why we write contracts.

Assume that you want to send a request containing the ID of a client company and the
amount it wants to borrow from us. You also want to send it to the /fraudcheck url via
the PUT method.

.Groovy DSL
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
----

.YAML
[source,yml,indent=0]
----
include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[]
----

==== Client Side

Spring Cloud Contract generates stubs, which you can use during client-side testing.
You get a running WireMock instance/Messaging route that simulates the service.
You would like to feed that instance with a proper stub definition.

At some point in time, you need to send a request to the Fraud Detection service.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]
----

Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----

After that, during the tests, Spring Cloud Contract automatically finds the stubs
(simulating the real service) in the Maven repository and exposes them on a configured
(or random) port.

==== Server Side

Since you are developing your stub, you need to be sure that it actually resembles your
concrete implementation. You cannot have a situation where your stub acts in one way and
your application behaves in a different way, especially in production.

To ensure that your application behaves the way you define in your stub, tests are
generated from the stub you provide.

The autogenerated test looks, more or less, like this:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

=== Step-by-step Guide to Consumer Driven Contracts (CDC)

Consider an example of Fraud Detection and the Loan Issuance process. The business
scenario is such that we want to issue loans to people but do not want them to steal from
us. The current implementation of our system grants loans to everybody.

Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current
sprint, we must develop a new feature: if a client wants to borrow too much money, then
we mark the client as a fraud.

Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan
Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`.

Social remark - both client and server development teams need to communicate directly and
discuss changes while going through the process. CDC is all about communication.

The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server
side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the
client code here].

TIP: In this case, the producer owns the contracts. Physically, all the contract are
in the producer's repository.

==== Technical note

If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the
following section to your build:

[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0]
----

[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
.Gradle
----
include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0]
----

==== Consumer side (Loan Issuance)

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

. Start doing TDD by writing a test for your feature.
. Write the missing implementation.
. Clone the Fraud Detection service repository locally.
. Define the contract locally in the repo of Fraud Detection service.
. Add the Spring Cloud Contract Verifier plugin.
. Run the integration tests.
. File a pull request.
. Create an initial implementation.
. Take over the pull request.
. Write the missing implementation.
. Deploy your app.
. Work online.

*Start doing TDD by writing a test for your feature.*

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0]
----

Assume that you have written a test of your new feature. If a loan application for a big
amount is received, the system should reject that loan application with some description.

*Write the missing implementation.*

At some point in time, you need to send a request to the Fraud Detection service. Assume
that you need to send the request containing the ID of the client and the amount the
client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method.

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]
----

For simplicity, the port of the Fraud Detection service is set to `8080`, and the
application runs on `8090`.

If you start the test at this point, it breaks, because no service currently runs on port
`8080`.

*Clone the Fraud Detection service repository locally.*

You can start by playing around with the server side contract. To do so, you must first
clone it.

[source,bash,indent=0]
----
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
----

*Define the contract locally in the repo of Fraud Detection service.*

As a consumer, you need to define what exactly you want to achieve. You need to formulate
your expectations. To do so, write the following contract:

IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder
is important because the producer's test base class name references that folder.

.Groovy DSL
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
----

.YAML
[source,yml,indent=0]
----
include::{introduction_url}/samples/standalone/yml/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.yml[]
----

The YML contract is quite straight-forward. However when you take a look at the Contract
written using a statically typed Groovy DSL - you might wonder what the
`value(client(...), server(...))` parts are. By using this notation, Spring Cloud
Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case
of an identifier or a timestamp, you need not hardcode a value. You want to allow some
different ranges of values. To enable ranges of values, you can set regular expressions
matching those values for the consumer side. You can provide the body by means of either
a map notation or String with interpolations.
https://cloud.spring.io/spring-cloud-contract/single/spring-cloud-contract.html#_contract_dsl[Consult the docs
for more information.] We highly recommend using the map notation!

TIP: You must understand the map notation in order to set up contracts. Please read the
http://groovy-lang.org/json.html[Groovy docs regarding JSON].

The previously shown contract is an agreement between two sides that:

- if an HTTP request is sent with all of
** a `PUT` method on the `/fraudcheck` endpoint,
** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and
`loanAmount` equal to `99999`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`,
- then an HTTP response is sent to the consumer that
** has status `200`,
** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and
the `rejectionReason` field having value `Amount too high`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`.

Once you are ready to check the API in practice in the integration tests, you need to
install the stubs locally.

*Add the Spring Cloud Contract Verifier plugin.*

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven.
First, add the `Spring Cloud Contract` BOM.

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0]
----

Next, add the `Spring Cloud Contract Verifier` Maven plugin

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----

Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which,
from the provided contracts:

- generate and run tests
- produce and install stubs

You do not want to generate tests since you, as the consumer, want only to play with the
stubs. You need to skip the test generation and execution. When you execute:

[source,bash,indent=0]
----
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
----

In the logs, you see something like this:

[source,bash,indent=0]
----
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

The following line is extremely important:

[source,bash,indent=0]
----
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----

It confirms that the stubs of the `http-server` have been installed in the local
repository.

*Run the integration tests.*

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic
stub downloading, you must do the following in your consumer side project (`Loan
Application service`):

Add the `Spring Cloud Contract` BOM:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0]
----

Add the dependency to `Spring Cloud Contract Stub Runner`:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----

Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the
`group-id` and `artifact-id` for the Stub Runner to download the stubs of your
collaborators. (Optional step) Because you're playing with the collaborators offline, you
can also provide the offline work switch (`StubRunnerProperties.StubsMode.LOCAL`).

[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----

Now, when you run your tests, you see something like this:

[source,bash,indent=0]
----
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
----

This output means that Stub Runner has found your stubs and started a server for your app
with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of
the stubs and with `stubs` classifier on port `8080`.

*File a pull request.*

What you have done until now is an iterative process. You can play around with the
contract, install it locally, and work on the consumer side until the contract works as
you wish.

Once you are satisfied with the results and the test passes, publish a pull request to
the server side. Currently, the consumer side work is done.

==== Producer side (Fraud Detection server)

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

*Create an initial implementation.*

As a reminder, you can see the initial implementation here:

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0]
}
----

*Take over the pull request.*

[source,bash,indent=0]
----
$ git checkout -b contract-change-pr master
$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
----

You must add the dependencies needed by the autogenerated tests:

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----

In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property

[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----

IMPORTANT: This example uses "convention based" naming by setting the
`packageWithBaseClasses` property. Doing so means that the two last packages combine to
make the name of the base test class. In our case, the contracts were placed under
`src/test/resources/contracts/fraud`. Since you do not have two packages starting from
the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and
capitalize `fraud`. That gives you the `FraudBase` test class name.

All the generated tests extend that class. Over there, you can set up your Spring Context
or whatever is necessary. In this case, use http://rest-assured.io/[Rest Assured MVC] to
start the server side `FraudDetectionController`.

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[]
----

Now, if you run the `./mvnw clean install`, you get something like this:

[source,bash,indent=0]
----
Results :

Tests in error:
  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
----

This error occurs because you have a new contract from which a test was generated and it
failed since you have not implemented the feature. The auto-generated test would look
like this:

[source,java,indent=0]
----
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/vnd.fraud.v1+json")
                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    // when:
        ResponseOptions response = given().spec(request)
                .put("/fraudcheck");

    // then:
        assertThat(response.statusCode()).isEqualTo(200);
        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
    // and:
        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
----

If you used the Groovy DSL, you can see, all the `producer()` parts of the Contract that were present in the
`value(consumer(...), producer(...))` blocks got injected into the test.
In case of using YAML, the same applied for the `matchers` sections of the `response`.

Note that, on the producer side, you are also doing TDD. The expectations are expressed
in the form of a test. This test sends a request to our own application with the URL,
headers, and body defined in the contract. It also is expecting precisely defined values
in the response. In other words, you have the `red` part of `red`, `green`, and
`refactor`. It is time to convert the `red` into the `green`.

*Write the missing implementation.*

Because you know the expected input and expected output, you can write the missing
implementation:

[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0]
include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0]
}
----

When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud
Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can
actually run those tests from your IDE.

*Deploy your app.*

Once you finish your work, you can deploy your change. First, merge the branch:

[source,bash,indent=0]
----
$ git checkout master
$ git merge --no-ff contract-change-pr
$ git push origin master
----

Your CI might run something like `./mvnw clean deploy`, which would publish both the
application and the stub artifacts.

==== Consumer Side (Loan Issuance) Final Step

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

*Merge branch to master.*

[source,bash,indent=0]
----
$ git checkout master
$ git merge --no-ff contract-change-pr
----

*Work online.*

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate
where the repository with your stubs is located. At this moment the stubs of the server
side are automatically downloaded from Nexus/Artifactory. You can set the value of
`stubsMode` to `REMOTE`. The following code shows an example of
achieving the same thing by changing the properties.

[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----

That's it!

=== Dependencies

The best way to add dependencies is to use the proper `starter` dependency.

For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add
`spring-cloud-starter-contract-verifier`.

=== Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note
that some may be outdated, because the Spring Cloud Contract Verifier project is under
constant development.

==== Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

video::sAAklvxmPmk[youtube,start=538,width=640,height=480]

==== Readings

- http://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura[Slides from Marcin Grzejszczak's talk about Accurest]
- http://toomuchcoding.com/blog/categories/accurest/[Accurest related articles from Marcin Grzejszczak's blog]
- http://toomuchcoding.com/blog/categories/spring-cloud-contract/[Spring Cloud Contract related articles from Marcin Grzejszczak's blog]
- http://groovy-lang.org/json.html[Groovy docs regarding JSON]

=== Samples

You can find some samples at
https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples].


Cleanup example to get haproxy statistics via oc exec.

= Monitoring Routers
{product-author}
{product-version]
:data-uri:
:icons:
:experimental:
:toc: macro
:toc-title:
:prewrap!:

toc::[]

== Overview
Depending on the underlying implementation, you can monitor a running
link:../architecture/core_concepts/routes.html[router] in multiple ways. This
topic discusses the HAProxy template router and the components to check to
ensure its health.

== Viewing Statistics
The HAProxy router exposes a web listener for the HAProxy statistics. Enter the
router's public IP address and the correctly configured port (*1936* by default)
to view the statistics page, and enter the administrator password when prompted.
This password and port are configured during the router installation, but they
can be found by viewing the *_haproxy.conf_* file on the container.

== Disabling Statistics View
By default the HAProxy statistics are exposed on port *1936* (with a
password protected account). To disable exposing the HAProxy statistics,
specify *0* as the stats port number.

ifdef::openshift-enterprise[]
====
----
$ oadm router hap --service-account=router --stats-port=0  \
    --credentials='/etc/openshift/master/openshift-router.kubeconfig'
----
====
endif::[]
ifdef::openshift-origin[]
====
----
$ oadm router hap --service-account=router --stats-port=0  \
    --credentials="$KUBECONFIG"
----
====
endif::[]

Note: HAProxy will still collect and store statistics, it would just _not_
      expose them via a web listener. You can still get access to the
      statistics by sending a request to the HAProxy AF_UNIX socket inside
      the HAProxy Router container.

====
----
$ cmd="echo 'show stat' | socat - UNIX-CONNECT:/var/lib/haproxy/run/haproxy.sock"
$ routerPod=$(oc get pods --selector="router=router"  \
    --template="{{with index .items 0}}{{.metadata.name}}{{end}}")
$ oc exec $routerPod -- bash -c "$cmd"
----
====

== Viewing Logs
To view a router log, run the `oc log` command on the pod. Since the router is
running as a plug-in process that manages the underlying implementation, the log
is for the plug-in, not the actual HAProxy log.

== Viewing the Router Internals
*routes.json*

Routes are processed by the HAProxy router, and are stored both in memory, on
disk, and in the HAProxy configuration file. The internal route representation,
which is passed to the template to generate the HAProxy configuration file, is
found in the *_/var/lib/containers/router/routes.json_* file. When
troubleshooting a routing issue, view this file to see the data being used to
drive configuration.

*HAProxy configuration*

You can find the HAProxy configuration and the backends that have been created
for specific routes in the *_/var/lib/haproxy/conf/haproxy.conf_* file. The
mapping files are found in the same directory. The helper frontend and
backends use mapping files when mapping incoming requests to a backend.

*Certificates*

Certificates are stored in two places:

- Certificates for edge terminated and re-encrypt terminated routes are stored
in the *_/var/lib/containers/router/certs_* directory.
- Certificates that are used for connecting to backends for re-encrypt
terminated routes are stored in the *_/var/lib/containers/router/cacerts_*
directory.

The files are keyed by the namespace and name of the route. The key,
certificate, and CA certificate are concatenated into a single file. You can use
link:https://www.openssl.org/[OpenSSL] to view the contents of these files.

= Monitoring Routers
{product-author}
{product-version]
:data-uri:
:icons:
:experimental:
:toc: macro
:toc-title:
:prewrap!:

toc::[]

== Overview
Depending on the underlying implementation, you can monitor a running
link:../architecture/core_concepts/routes.html[router] in multiple ways. This
topic discusses the HAProxy template router and the components to check to
ensure its health.

== Viewing Statistics
The HAProxy router exposes a web listener for the HAProxy statistics. Enter the
router's public IP address and the correctly configured port (*1936* by default)
to view the statistics page, and enter the administrator password when prompted.
This password and port are configured during the router installation, but they
can be found by viewing the *_haproxy.conf_* file on the container.

== Disabling Statistics View
By default the HAProxy statistics are exposed on port *1936* (with a
password protected account). To disable exposing the HAProxy statistics,
specify *0* as the stats port number.

ifdef::openshift-enterprise[]
====
----
$ oadm router hap --service-account=router --stats-port=0  \
    --credentials='/etc/openshift/master/openshift-router.kubeconfig'
----
====
endif::[]
ifdef::openshift-origin[]
====
----
$ oadm router hap --service-account=router --stats-port=0  \
    --credentials="$KUBECONFIG"
----
====
endif::[]

Note: HAProxy will still collect and store statistics, it would just _not_
      expose them via a web listener. You can still get access to the
      statistics by sending a request to the HAProxy AF_UNIX socket inside
      the HAProxy Router container.

====
----
$ cmd="echo 'show stat' | socat - UNIX-CONNECT:/var/lib/haproxy/run/haproxy.sock"
$ oc exec $(oc get pods --selector="router=router"  \
    --template="{{with index .items 0}}{{.metadata.name}}{{end}}") -- \
    bash -c "$cmd"
----
====

== Viewing Logs
To view a router log, run the `oc log` command on the pod. Since the router is
running as a plug-in process that manages the underlying implementation, the log
is for the plug-in, not the actual HAProxy log.

== Viewing the Router Internals
*routes.json*

Routes are processed by the HAProxy router, and are stored both in memory, on
disk, and in the HAProxy configuration file. The internal route representation,
which is passed to the template to generate the HAProxy configuration file, is
found in the *_/var/lib/containers/router/routes.json_* file. When
troubleshooting a routing issue, view this file to see the data being used to
drive configuration.

*HAProxy configuration*

You can find the HAProxy configuration and the backends that have been created
for specific routes in the *_/var/lib/haproxy/conf/haproxy.conf_* file. The
mapping files are found in the same directory. The helper frontend and
backends use mapping files when mapping incoming requests to a backend.

*Certificates*

Certificates are stored in two places:

- Certificates for edge terminated and re-encrypt terminated routes are stored
in the *_/var/lib/containers/router/certs_* directory.
- Certificates that are used for connecting to backends for re-encrypt
terminated routes are stored in the *_/var/lib/containers/router/cacerts_*
directory.

The files are keyed by the namespace and name of the route. The key,
certificate, and CA certificate are concatenated into a single file. You can use
link:https://www.openssl.org/[OpenSSL] to view the contents of these files.


edits after peer review

edits after peer review

= Routers
{product-author}
{product-version]
:data-uri:
:icons:
:experimental:
:toc: macro
:toc-title:

toc::[]

== Overview
Depending on the underlying implementation, you can monitor a running
link:../architecture/core_objects/routing.html[router] in multiple ways. This
topic discusses the HAProxy template router, and the components to check to
ensure its health.

== Viewing Statistics
The HAProxy router exposes a web listener for the HAProxy statistics. Enter the
router's public IP address and the correctly configured port (1936 by default)
to view the statistics page, and enter the admin password when prompted. This
password and port were configured during the router installation, but can be
found by viewing the *_haproxy.conf_* file on the container.

== Viewing Logs
To view a router log, run the `oc log` command on the pod. Since the router is
running as a plug-in process that manages the underlying implementation, the log
is for the plug-in, not the actual HAProxy log.

== Router Internals
.Routes.json

Routes are processed by the HAProxy router, and are stored both in memory, on
disk, and in the HAProxy configuration file. The internal route representation,
which is passed to the template to generate the HAProxy configuration file, is
found in the *_/var/lib/containers/router/routes.json_* file. When
troubleshooting a routing issue, view this file to see the data being used to
drive configuration.

.HAProxy Config

You can find the HAProxy configuration and the back-ends that have been created
for specific routes in the *_/var/lib/haproxy/conf/haproxy.conf_* file. The
mapping files are found in the same directory. The helper front-end and
back-ends use mapping files when mapping incoming requests to a back-end.

.Certificates

Certificates are stored in two places. Certificates for edge terminated and
re-encrypt terminated routes are stored in the
*_/var/lib/containers/router/certs_* directory. Certificates that are used for
connecting to back-ends for re-encrypt terminated routes are stored in the
*_/var/lib/containers/router/cacerts_* directory. The files are keyed by the
namespace and name of the route. The key, certificate, and CA certificate are
concatenated into a single file. You can use
link:https://www.openssl.org/[OpenSSL] to view the contents of these files.

= Routers
{product-author}
{product-version]
:data-uri:
:icons:
:experimental:
:toc: macro
:toc-title:

toc::[]

== Overview
Once you have a running link:../architecture/core_objects/routing.html[Router] you are ready
to monitor it.  Depending on the underlying router implementation this may be accomplished
multiple ways.  This document will discuss the HAProxy template router and the different
components that can be checked to ensure its health.

== Viewing Statistics
The HAProxy router exposes a web listener for the HAProxy statistics.  You can enter the public
IP address of the router with the correctly configured port to view the statistics page.  You
will be prompted for the admin password.  This password and port were configured during the
router installation.

== Viewing Logs
To view a router log, simply run the `oc log` command for the pod.  Keep in mind that since
the router is running as a plugin process that manages the underlying implementation the log
that you will see is the log for the plugin, not the actual HAProxy log.

== Router Internals
.Routes.json

As routes are processed by the HAProxy router they are stored both in memory, on disk, and in
the HAProxy configuration file.  In `/var/lib/containers/router/routes.json` you can find the
internal representation of the routes that is passed to the template to generate the HAProxy
configuration file.  When troubleshooting a route issue it may help to look at this file to
see the data that is being used to drive configuration.

.HAProxy Config

In `/var/lib/haproxy/conf/haproxy.conf` you can find the configuration that is being used
by HAProxy.  Here is where you can view the backends that have been created for specific routes.
Also, in the same directory you can find the mapping files that are used by the helper
frontend and backends when mapping an incoming request to a backend.

.Certificates

Certificates are stored in two places. Certificates that are presented at the edge for edge
terminated and re-encrypt terminated routes are stored in `/var/lib/containers/router/certs/`.
Certificates that are used when connecting to backends for re-encrypt terminated routes are
stored in `/var/lib/containers/router/cacerts/`.  The files are keyed by the namespace and
name of the route.  You will find that the key, certificate, and CA certificate are
concatenated into a single file.  You may use openssl to view the contents of these files.


Add readme reference to license.

Add readme reference to license.

:libVersion: 0.1.7

# ADAL

image:https://api.bintray.com/packages/jmspt/maven/adal/images/download.svg[Build Status,link=https://bintray.com/jmspt/maven/adal/_latestVersion]

Android Development Accelaration Library

Add the dependency in the form:
[source, groovy, subs='attributes']
dependencies {
  /* Include all modules */
  compile 'com.massivedisaster.adal:adal:{libVersion}'
  /* Specific modules*/
  compile 'com.massivedisaster.adal:adal-accounts:{libVersion}'
  compile 'com.massivedisaster.adal:adal-adapters:{libVersion}'
  compile 'com.massivedisaster.adal:adal-analytics:{libVersion}'
  compile 'com.massivedisaster.adal:adal-bus:{libVersion}'
  compile 'com.massivedisaster.adal:adal-fragments:{libVersion}'
  compile 'com.massivedisaster.adal:adal-managers:{libVersion}'
  compile 'com.massivedisaster.adal:adal-network:{libVersion}'
  compile 'com.massivedisaster.adal:adal-utils:{libVersion}'
  compile 'com.massivedisaster.adal:adal-location:{libVersion}'
}

### License
[GNU LESSER GENERAL PUBLIC LICENSE](LICENSE.md)