[
  {
    "path": ".gitignore",
    "content": "*.sw[op]\n.idea\ntarget\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.adoc",
    "content": "= head-first-reactive-with-spring-and-reactor is no longer actively maintained by VMware, Inc.\n\n= Head-First Reactive Workshop\n\nThis repository hosts a complete workshop on Spring + Reactor.\nYou can follow the script\nhttps://reactor.github.io/head-first-reactive-with-spring-and-reactor/[follow the script]\n(the source document is in the \"docs\" folder) to create your first\nWebFlux applications!\nEach step of this workshop has its companion commit in the git history with a detailed commit message.\n"
  },
  {
    "path": "docs/README.adoc",
    "content": "= Head-First Reactive Workshop\nStephane Maldini, Ben Hale, Madhura Bhave - Pivotal\n:sectanchors: true\n:source-highlighter: prettify\n:icons: font\n:toc:\n:spring-boot-version: 2.0.4.RELEASE\n:spring-framework-version: 5.0.8.RELEASE\n:reactor-version: BISMUTH-SR10\n:spring-framework-doc-base: https://docs.spring.io/spring-framework/docs/{spring-framework-version}\n\nThis repository hosts a complete workshop on Spring + Reactor.\nJust follow this README and create your first reactive Spring applications!\nEach step of this workshop has its companion commit in the git history with a detailed commit message.\n\nAt the end of the workshop, we will have created three applications:\n\n* `stock-quotes` is a functional WebFlux app which streams stock quotes\n* `stock-details` is an annotation-based WebFlux app using a reactive datastore\n* `trading-service` is an annotation-based WebFlux app that consumes data from `stock-quotes` and `stock-details`\n\nReference documentations can be useful while working on those apps:\n\n* https://projectreactor.io/docs[Reactor Core documentation]\n* https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html[API documentation for Flux]\n* https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html[API documentation for Mono]\n* Spring WebFlux\n{spring-framework-doc-base}/spring-framework-reference/web.html#web-reactive[reference documentation]\nand {spring-framework-doc-base}/javadoc-api/[javadoc]\n\nClone the repository:\n\ngit clone https://github.com/reactor/head-first-reactive-with-spring-and-reactor.git\n\nWe will start off by creating the Trading Service application which gets data from a pre-existing Stock Quotes application.\n\n== Trading Service application\n\n=== Create this application\n\nGo to `https://start.spring.io` and create a Maven project with Spring Boot {spring-boot-version},\nwith groupId `io.spring.workshop` and artifactId `trading-service`. Select the `Reactive Web` and `Devtools` dependencies.\nUnzip the given file into a directory and import that application into your IDE.\n\nIf generated right, you should have a main `Application` class that looks like this:\n\n[source,java]\n.stock-quotes/src/main/java/io/spring/workshop/tradingservice/TradingServiceApplication.java\n----\ninclude::../trading-service/src/main/java/io/spring/workshop/tradingservice/TradingServiceApplication.java[]\n----\n\nNote that, by default, `spring-boot-starter-webflux` transitively brings `spring-boot-starter-reactor-netty`\nand Spring Boot auto-configures Reactor Netty as a web server.\n\nSpring Boot supports Tomcat, Undertow and Jetty as well.\n\n=== Use the WebClient to stream JSON to the browser\n\nIn this section, we'll call our remote `stock-quotes` service to get Quotes from it, so we first need to:\n\n* copy over the `Quote` class to this application\n* add the Jackson JSR310 module dependency\n\nCreate a `QuotesClient` annotated with `@Component` and inject a `WebClient.Builder`. Now, create a method in the `QuotesClient` called\n`quotesFeed` which will use the `webClient` to consume the stream of quotes via Server Sent Events (SSE).\n\nNOTE: There are two ways to use a `WebClient`, directly via the static factory or by injecting the `WebClient.Builder`.\nThe latter is used by libraries such as Spring Cloud Sleuth that enrich `WebClient` with extra features.\n\nNow create a `QuotesController` annotated with `@Controller` and inject it with the `QuotesClient`.\nAdd a method that responds to `\"GET /quotes/feed\"` requests with the `\"text/event-stream\"` content-type,\nwith a `Flux<Quote>` as the response body. The data can be retrieved from the `quotesFeed` method on `QuotesClient`.\n\nYou can test it by starting both applications. First, start the Stock Quotes application.\nIt can be started from your IDE or with `mvn spring-boot:run` and it should run a Netty server on port 8081.\nYou should see in the logs something like:\n\n[source,bash]\n----\nINFO 2208 --- [  restartedMain] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8081\nINFO 2208 --- [  restartedMain] i.s.w.s.StockQuotesApplication           : Started StockQuotesApplication in 1.905 seconds (JVM running for 3.075)\n----\n\nStart the Trading Service application from your IDE or with `mvn spring-boot:run`. This should run a Netty server on port 8080.\n\n[source,bash]\n----\nINFO 2208 --- [  restartedMain] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080\nINFO 2208 --- [  restartedMain] i.s.w.t.TradingServiceApplication           : Started TradingServiceApplication in 1.905 seconds (JVM running for 3.075)\n----\n\nYou can hit http://localhost:8080/quotes/feed to consume the stream of quotes.\n\nNow, let's create another application that can provide the details for a trading company.\n\n== Stock Details application\n\n=== Create this application\n\nGo to `https://start.spring.io` and create a Maven project with Spring Boot {spring-boot-version},\nwith groupId `io.spring.workshop` and artifactId `stock-details`. Select the `Reactive Web`, `Devtools`\nand `Reactive Mongo` dependencies.\n\nUnzip the given file into a directory and import that application into your IDE.\n\nIf generated right, you should have a main `Application` class that looks like this:\n\n[source,java]\n.stock-details/src/main/java/io/spring/workshop/stockdetails/StockDetailsApplication.java\n----\ninclude::../stock-details/src/main/java/io/spring/workshop/stockdetails/StockDetailsApplication.java[]\n----\n\nEdit your `application.properties` file to start the server on port 8082.\n\n[source,properties]\n.stock-details/src/main/resources/application.properties\n----\ninclude::../stock-details/src/main/resources/application.properties[]\n----\n\n=== Use a reactive datastore\n\nIn this application, we’ll use a MongoDB datastore with its reactive driver; for this workshop, we’ll use an in-memory instance of MongoDB. So add the following:\n\n[source,xml]\n.stock-details/pom.xml\n----\ninclude::../stock-details/pom.xml[tags=inMemMongo]\n----\n\nWe'd like to manage `TradingCompany` with our datastore.\n\n[source,java]\n.stock-details/src/main/java/io/spring/workshop/stockdetails/TradingCompany.java\n----\ninclude::../stock-details/src/main/java/io/spring/workshop/stockdetails/TradingCompany.java[]\n----\n\nNow create a `TradingCompanyRepository` interface that extends `ReactiveMongoRepository`.\nAdd a `findByTicker(String ticker)` method that returns a single `TradingCompany` in a reactive fashion.\n\nWe'd like to insert trading companies in our datastore when the application starts up. For that, create a `TradingCompanyCommandLineRunner`\ncomponent that implements Spring Boot's `CommandLineRunner`. In the `run` method, use the reactive repository\nto insert `TradingCompany` instances in the datastore.\n\nNOTE: Since the `run` method returns void, it expects a blocking implementation. This is why you should use the\n`blockLast(Duration)` operator on the `Flux` returned by the repository when inserting data.\nYou can also `then().block(Duration)` to turn that `Flux` into a `Mono<Void>` that waits for completion.\n\n=== Create a JSON web service\n\nWe're now going to expose `TradingCompany` through a Controller.\nFirst, create a `TradingCompanyController` annotated with `@RestController` and inject the `TradingCompanyRepository`.\nThen add two new Controller methods in order to handle:\n\n* GET requests to  `\"/details\"`, returning all `TradingCompany` instances, serializing them with content-type `\"application/json\"`\n* GET requests to  `\"/details/{ticker}\"`, returning a single `TradingCompany` instance, serializing it with content-type `\"application/json\"`\n\nIt can be started from your IDE or with `mvn spring-boot:run` and it should run a Netty server on port 8082.\nYou should see in the logs something like:\n\n[source,bash]\n----\nINFO 2208 --- [  restartedMain] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8082\nINFO 2208 --- [  restartedMain] i.s.w.s.StockDetailsApplication           : Started StockDetailsApplication in 1.905 seconds (JVM running for 3.075)\n----\n\nNow that we have an application that can return the details for a company with a given ticker, we can update the Trading Service application\nto use those details and return a combination of the latest quote for that ticker along with the company's details.\n\n== Update Trading Service application\n\nWe will first create a service that will use a `WebClient` to get data from the Stock Details application.\nCreate a `TradingCompanyClient` annotated with `@Component`.\nThen add two methods:\n\n* `findAllCompanies` will return a `Flux<TradingCompany>` by using the webClient to get data from the `/details` endpoint from the Stock details application\n* `getTradingCompany` will return a `Mono<TradingCompany>` by using the webClient to get data from the `/details/{ticker}` endpoint from the Stock details application\n  - If no trading company is found for the given ticker, the `Mono` will complete without any data. Instead, we will emit a `TickerNotFoundException` error using the `switchIfEmpty` operator.\n\nLet's expose the two `TradingCompanyClient` methods with a local `TradingCompanyController`.\n\nYou might have updated an already running `TradingServiceApplication`. Since DevTools is present, you can just recompile to automatically restart the application.\n\nYou can test the new endpoints by hitting:\n\n* http://localhost:8080/details to list all trading companies\n* http://localhost:8080/details/MSFT to get details for a particular ticker\n* http://localhost:8080/details/PIZZA to see what happens for an unknown ticker\n\nLet's add a method called `getLatestQuote(String ticker)` on the `QuotesClient` which will get the latest quote for a given ticker from the quotes feed.\n\n* Reuse `quotesFeed` to get the actual feed\n* Filter the stream of quotes with quotes matching the given ticker\n* Take the next matching quote\n* If no matching quote is found within 15 seconds, then return a fallback `Quote` for the ticker.\n\nNow, we want to combine data produced by `stock-quotes` and `stock-details` as a `TradingCompanySummary`.\n\nCopy the following class to your project.\n\n[source,java]\n.trading-service/src/main/java/io/spring/workshop/tradingservice/TradingCompanySummary.java\n----\ninclude::../trading-service/src/main/java/io/spring/workshop/tradingservice/TradingCompanySummary.java[]\n----\n\nNow, add another method to the `QuotesController` which can handle requests to `/quotes/summary/{ticker}`.\n\n* Use the `TradingCompanyClient` to get the details for the company with the given ticker\n* Create a `TradingCompanySummary` by composing the details with the latest quote from the `QuotesClient`\n\nTIP: You can compose two reactive results using `Mono.zip(monoA, monoB, biFunction)` or `monoA.zipWith(monoB, biFunction)`.\n\nWe need to handle the `TickerNotFoundException` emitted by the `TradingCompanyClient` as an HTTP 404.\nYou will need to create a method annotated with `@ExceptionHandler`.\n\nAgain, because of DevTools we can just recompile and test by hitting:\n\n* http://localhost:8080/quotes/summary/MSFT to get the summary for a particular ticker\n* http://localhost:8080/quotes/summary/PIZZA to test the 404 NOT FOUND an unknown ticker\n\nNow, we will look at creating a functional-style WebFlux application by re-creating the Stock Quotes Application.\nFasten your seatbelt and remove the stock-quotes directory!\n\n== Stock Quotes application\n\n=== Create this application\n\nGo to `https://start.spring.io` and create a Maven project with Spring Boot {spring-boot-version},\nwith groupId `io.spring.workshop` and artifactId `stock-quotes`. Select the `Reactive Web` and `Devtools`\ndependencies.\nUnzip the given file into a directory and import that application into your IDE.\n\nIf generated right, you should have a main `Application` class that looks like this:\n\n[source,java]\n.stock-quotes/src/main/java/io/spring/workshop/stockquotes/StockQuotesApplication.java\n----\ninclude::../stock-quotes/src/main/java/io/spring/workshop/stockquotes/StockQuotesApplication.java[]\n----\n\nEdit your `application.properties` file to start the server on port 8081.\n\n[source,properties]\n.stock-quotes/src/main/resources/application.properties\n----\ninclude::../stock-quotes/src/main/resources/application.properties[]\n----\n\nLaunching it from your IDE or with `mvn spring-boot:run` should start a Netty server on port 8081.\nYou should see in the logs something like:\n\n[source,bash]\n----\nINFO 2208 --- [  restartedMain] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8081\nINFO 2208 --- [  restartedMain] i.s.w.s.StockQuotesApplication           : Started StockQuotesApplication in 1.905 seconds (JVM running for 3.075)\n----\n\n=== Create a Quote Generator\n\nTo simulate real stock values, we'll create a generator that emits such values at a specific interval.\nCopy the following classes to your project.\n\n[source,java]\n.stock-quotes/src/main/java/io/spring/workshop/stockquotes/Quote.java\n----\ninclude::../stock-quotes/src/main/java/io/spring/workshop/stockquotes/Quote.java[]\n----\n\n[source,java]\n.stock-quotes/src/main/java/io/spring/workshop/stockquotes/QuoteGenerator.java\n----\ninclude::../stock-quotes/src/main/java/io/spring/workshop/stockquotes/QuoteGenerator.java[]\n----\n\nBecause we're working with `java.time.Instant` and Jackson, we should import the dedicated module in our app.\n\nNOTE: The `QuoteGenerator` instantiates a `Flux<Quote>` that emits a `Quote` every 200 msec and can be **shared** between\nmultiple subscribers (look at the `Flux` operators for that). This instance is kept as an attribute for reusability.\n\n[source,xml]\n.stock-quotes/pom.xml\n----\ninclude::../stock-quotes/pom.xml[tags=jacksonJSR310]\n----\n\n=== Functional web applications with \"WebFlux.fn\"\n\nSpring WebFlux comes in two flavors of web applications: annotation based and functional.\nFor this first application, we'll use the functional variant.\n\nIncoming HTTP requests are handled by a `HandlerFunction`, which is essentially a function\nthat takes a ServerRequest and returns a `Mono<ServerResponse>`. The annotation counterpart\nto a handler function would be a Controller method.\n\nBut how those incoming requests are routed to the right handler?\n\nWe're using a `RouterFunction`, which is a function that takes a `ServerRequest`, and returns\na `Mono<HandlerFunction>`. If a request matches a particular route, a handler function is returned;\notherwise it returns an empty `Mono`. The `RouterFunction` has a similar purpose as the `@RequestMapping`\nannotation in `@Controller` classes.\n\nTake a look at the code samples in\n{spring-framework-doc-base}/spring-framework-reference/web.html#web-reactive-server-functional[the Spring WebFlux.fn reference documentation]\n\n=== Create your first HandlerFunction + RouterFunction\n\nFirst, create a `QuoteHandler` class and mark is as a `@Component`;this class will have all our handler functions as methods.\nLet's inject our `QuoteGenerator` instance in our `QuoteHandler`.\n\nNow create a `streamQuotes` handler that streams the generated quotes with the `\"application/stream+json\"` content type.\n\nTo route requests to that handler, you need to expose a `RouterFunction` to Spring Boot.\nCreate a `QuoteRouter` configuration class (i.e. annotated with `@Configuration`)\nthat creates a bean of type `RouterFunction<ServerResponse>`.\n\nModify that class so that GET requests to `\"/quotes\"` are routed to the handler you just implemented.\n\nTIP: Since `QuoteHandler` is a component, you can inject it in `@Bean` methods as a method parameter.\n\nYour application should now behave like this:\n\n[source,bash]\n----\n$ curl http://localhost:8081/quotes -i -H \"Accept: application/stream+json\"\nHTTP/1.1 200 OK\ntransfer-encoding: chunked\nContent-Type: application/stream+json\n\n{\"ticker\":\"CTXS\",\"price\":84.0,\"instant\":1494841666.633000000}\n{\"ticker\":\"DELL\",\"price\":67.1,\"instant\":1494841666.834000000}\n{\"ticker\":\"GOOG\",\"price\":869,\"instant\":1494841667.034000000}\n{\"ticker\":\"MSFT\",\"price\":66.5,\"instant\":1494841667.231000000}\n{\"ticker\":\"ORCL\",\"price\":46.13,\"instant\":1494841667.433000000}\n{\"ticker\":\"RHT\",\"price\":86.9,\"instant\":1494841667.634000000}\n{\"ticker\":\"VMW\",\"price\":93.7,\"instant\":1494841667.833000000}\n----\n\n=== Integration tests with WebTestClient\n\nSpring WebFlux (actually the `spring-test` module) includes a `WebTestClient`\nthat can be used to test WebFlux server endpoints with or without a running server.\nTests without a running server are comparable to MockMvc from Spring MVC where mock request\nand response are used instead of connecting over the network using a socket.\nThe WebTestClient however can also perform tests against a running server.\n\nYou can check that your last endpoint is working properly with the following\nintegration test:\n\n[source,java]\n.stock-quotes/src/test/java/io/spring/workshop/stockquotes/StockQuotesApplicationTests.java\n----\ninclude::../stock-quotes/src/test/java/io/spring/workshop/stockquotes/StockQuotesApplicationTests.java[]\n----\n\n== Additional Resources\n\nTalks on Spring Reactive:\n\n* https://content.pivotal.io/springone-platform-2017/designing-implementing-and-using-reactive-apis-ben-hale-paul-harris[Designing, Implementing, and Using Reactive APIs (Ben Hale, Paul Harris)]\n* https://content.pivotal.io/springone-platform-2017/reactive-spring-josh-long-mark-heckler[Reactive Spring (Josh Long, Mark Heckler)]\n\nHands-on Reactor:\n\n* https://github.com/reactor/lite-rx-api-hands-on[Reactor Hands-on]\n"
  },
  {
    "path": "stock-quotes/.gitignore",
    "content": "target/\n!.mvn/wrapper/maven-wrapper.jar\n\n### STS ###\n.apt_generated\n.classpath\n.factorypath\n.project\n.settings\n.springBeans\n\n### IntelliJ IDEA ###\n.idea\n*.iws\n*.iml\n*.ipr\n\n### NetBeans ###\nnbproject/private/\nbuild/\nnbbuild/\ndist/\nnbdist/\n.nb-gradle/"
  },
  {
    "path": "stock-quotes/.mvn/wrapper/maven-wrapper.properties",
    "content": "distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip\n"
  },
  {
    "path": "stock-quotes/mvnw",
    "content": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#    https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# ----------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n# Maven2 Start Up Batch script\n#\n# Required ENV vars:\n# ------------------\n#   JAVA_HOME - location of a JDK home dir\n#\n# Optional ENV vars\n# -----------------\n#   M2_HOME - location of maven2's installed home dir\n#   MAVEN_OPTS - parameters passed to the Java VM when running Maven\n#     e.g. to debug Maven itself, use\n#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\n#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files\n# ----------------------------------------------------------------------------\n\nif [ -z \"$MAVEN_SKIP_RC\" ] ; then\n\n  if [ -f /etc/mavenrc ] ; then\n    . /etc/mavenrc\n  fi\n\n  if [ -f \"$HOME/.mavenrc\" ] ; then\n    . \"$HOME/.mavenrc\"\n  fi\n\nfi\n\n# OS specific support.  $var _must_ be set to either true or false.\ncygwin=false;\ndarwin=false;\nmingw=false\ncase \"`uname`\" in\n  CYGWIN*) cygwin=true ;;\n  MINGW*) mingw=true;;\n  Darwin*) darwin=true\n    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home\n    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html\n    if [ -z \"$JAVA_HOME\" ]; then\n      if [ -x \"/usr/libexec/java_home\" ]; then\n        export JAVA_HOME=\"`/usr/libexec/java_home`\"\n      else\n        export JAVA_HOME=\"/Library/Java/Home\"\n      fi\n    fi\n    ;;\nesac\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  if [ -r /etc/gentoo-release ] ; then\n    JAVA_HOME=`java-config --jre-home`\n  fi\nfi\n\nif [ -z \"$M2_HOME\" ] ; then\n  ## resolve links - $0 may be a link to maven's home\n  PRG=\"$0\"\n\n  # need this for relative symlinks\n  while [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n      PRG=\"$link\"\n    else\n      PRG=\"`dirname \"$PRG\"`/$link\"\n    fi\n  done\n\n  saveddir=`pwd`\n\n  M2_HOME=`dirname \"$PRG\"`/..\n\n  # make it fully qualified\n  M2_HOME=`cd \"$M2_HOME\" && pwd`\n\n  cd \"$saveddir\"\n  # echo Using m2 at $M2_HOME\nfi\n\n# For Cygwin, ensure paths are in UNIX format before anything is touched\nif $cygwin ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --unix \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --unix \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --unix \"$CLASSPATH\"`\nfi\n\n# For Migwn, ensure paths are in UNIX format before anything is touched\nif $mingw ; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=\"`(cd \"$M2_HOME\"; pwd)`\"\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=\"`(cd \"$JAVA_HOME\"; pwd)`\"\n  # TODO classpath?\nfi\n\nif [ -z \"$JAVA_HOME\" ]; then\n  javaExecutable=\"`which javac`\"\n  if [ -n \"$javaExecutable\" ] && ! [ \"`expr \\\"$javaExecutable\\\" : '\\([^ ]*\\)'`\" = \"no\" ]; then\n    # readlink(1) is not available as standard on Solaris 10.\n    readLink=`which readlink`\n    if [ ! `expr \"$readLink\" : '\\([^ ]*\\)'` = \"no\" ]; then\n      if $darwin ; then\n        javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n        javaExecutable=\"`cd \\\"$javaHome\\\" && pwd -P`/javac\"\n      else\n        javaExecutable=\"`readlink -f \\\"$javaExecutable\\\"`\"\n      fi\n      javaHome=\"`dirname \\\"$javaExecutable\\\"`\"\n      javaHome=`expr \"$javaHome\" : '\\(.*\\)/bin'`\n      JAVA_HOME=\"$javaHome\"\n      export JAVA_HOME\n    fi\n  fi\nfi\n\nif [ -z \"$JAVACMD\" ] ; then\n  if [ -n \"$JAVA_HOME\"  ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n      # IBM's JDK on AIX uses strange locations for the executables\n      JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n      JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n  else\n    JAVACMD=\"`which java`\"\n  fi\nfi\n\nif [ ! -x \"$JAVACMD\" ] ; then\n  echo \"Error: JAVA_HOME is not defined correctly.\" >&2\n  echo \"  We cannot execute $JAVACMD\" >&2\n  exit 1\nfi\n\nif [ -z \"$JAVA_HOME\" ] ; then\n  echo \"Warning: JAVA_HOME environment variable is not set.\"\nfi\n\nCLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher\n\n# traverses directory structure from process work directory to filesystem root\n# first directory with .mvn subdirectory is considered project base directory\nfind_maven_basedir() {\n\n  if [ -z \"$1\" ]\n  then\n    echo \"Path not specified to find_maven_basedir\"\n    return 1\n  fi\n\n  basedir=\"$1\"\n  wdir=\"$1\"\n  while [ \"$wdir\" != '/' ] ; do\n    if [ -d \"$wdir\"/.mvn ] ; then\n      basedir=$wdir\n      break\n    fi\n    # workaround for JBEAP-8937 (on Solaris 10/Sparc)\n    if [ -d \"${wdir}\" ]; then\n      wdir=`cd \"$wdir/..\"; pwd`\n    fi\n    # end of workaround\n  done\n  echo \"${basedir}\"\n}\n\n# concatenates all lines of a file\nconcat_lines() {\n  if [ -f \"$1\" ]; then\n    echo \"$(tr -s '\\n' ' ' < \"$1\")\"\n  fi\n}\n\nBASE_DIR=`find_maven_basedir \"$(pwd)\"`\nif [ -z \"$BASE_DIR\" ]; then\n  exit 1;\nfi\n\nexport MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-\"$BASE_DIR\"}\necho $MAVEN_PROJECTBASEDIR\nMAVEN_OPTS=\"$(concat_lines \"$MAVEN_PROJECTBASEDIR/.mvn/jvm.config\") $MAVEN_OPTS\"\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin; then\n  [ -n \"$M2_HOME\" ] &&\n    M2_HOME=`cygpath --path --windows \"$M2_HOME\"`\n  [ -n \"$JAVA_HOME\" ] &&\n    JAVA_HOME=`cygpath --path --windows \"$JAVA_HOME\"`\n  [ -n \"$CLASSPATH\" ] &&\n    CLASSPATH=`cygpath --path --windows \"$CLASSPATH\"`\n  [ -n \"$MAVEN_PROJECTBASEDIR\" ] &&\n    MAVEN_PROJECTBASEDIR=`cygpath --path --windows \"$MAVEN_PROJECTBASEDIR\"`\nfi\n\nWRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\n\nexec \"$JAVACMD\" \\\n  $MAVEN_OPTS \\\n  -classpath \"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar\" \\\n  \"-Dmaven.home=${M2_HOME}\" \"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}\" \\\n  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG \"$@\"\n"
  },
  {
    "path": "stock-quotes/mvnw.cmd",
    "content": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software Foundation (ASF) under one\n@REM or more contributor license agreements.  See the NOTICE file\n@REM distributed with this work for additional information\n@REM regarding copyright ownership.  The ASF licenses this file\n@REM to you under the Apache License, Version 2.0 (the\n@REM \"License\"); you may not use this file except in compliance\n@REM with the License.  You may obtain a copy of the License at\n@REM\n@REM    https://www.apache.org/licenses/LICENSE-2.0\n@REM\n@REM Unless required by applicable law or agreed to in writing,\n@REM software distributed under the License is distributed on an\n@REM \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n@REM KIND, either express or implied.  See the License for the\n@REM specific language governing permissions and limitations\n@REM under the License.\n@REM ----------------------------------------------------------------------------\n\n@REM ----------------------------------------------------------------------------\n@REM Maven2 Start Up Batch script\n@REM\n@REM Required ENV vars:\n@REM JAVA_HOME - location of a JDK home dir\n@REM\n@REM Optional ENV vars\n@REM M2_HOME - location of maven2's installed home dir\n@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands\n@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending\n@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven\n@REM     e.g. to debug Maven itself, use\n@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000\n@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files\n@REM ----------------------------------------------------------------------------\n\n@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'\n@echo off\n@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'\n@if \"%MAVEN_BATCH_ECHO%\" == \"on\"  echo %MAVEN_BATCH_ECHO%\n\n@REM set %HOME% to equivalent of $HOME\nif \"%HOME%\" == \"\" (set \"HOME=%HOMEDRIVE%%HOMEPATH%\")\n\n@REM Execute a user defined script before this one\nif not \"%MAVEN_SKIP_RC%\" == \"\" goto skipRcPre\n@REM check for pre script, once with legacy .bat ending and once with .cmd ending\nif exist \"%HOME%\\mavenrc_pre.bat\" call \"%HOME%\\mavenrc_pre.bat\"\nif exist \"%HOME%\\mavenrc_pre.cmd\" call \"%HOME%\\mavenrc_pre.cmd\"\n:skipRcPre\n\n@setlocal\n\nset ERROR_CODE=0\n\n@REM To isolate internal variables from possible post scripts, we use another setlocal\n@setlocal\n\n@REM ==== START VALIDATION ====\nif not \"%JAVA_HOME%\" == \"\" goto OkJHome\n\necho.\necho Error: JAVA_HOME not found in your environment. >&2\necho Please set the JAVA_HOME variable in your environment to match the >&2\necho location of your Java installation. >&2\necho.\ngoto error\n\n:OkJHome\nif exist \"%JAVA_HOME%\\bin\\java.exe\" goto init\n\necho.\necho Error: JAVA_HOME is set to an invalid directory. >&2\necho JAVA_HOME = \"%JAVA_HOME%\" >&2\necho Please set the JAVA_HOME variable in your environment to match the >&2\necho location of your Java installation. >&2\necho.\ngoto error\n\n@REM ==== END VALIDATION ====\n\n:init\n\n@REM Find the project base dir, i.e. the directory that contains the folder \".mvn\".\n@REM Fallback to current working directory if not found.\n\nset MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%\nIF NOT \"%MAVEN_PROJECTBASEDIR%\"==\"\" goto endDetectBaseDir\n\nset EXEC_DIR=%CD%\nset WDIR=%EXEC_DIR%\n:findBaseDir\nIF EXIST \"%WDIR%\"\\.mvn goto baseDirFound\ncd ..\nIF \"%WDIR%\"==\"%CD%\" goto baseDirNotFound\nset WDIR=%CD%\ngoto findBaseDir\n\n:baseDirFound\nset MAVEN_PROJECTBASEDIR=%WDIR%\ncd \"%EXEC_DIR%\"\ngoto endDetectBaseDir\n\n:baseDirNotFound\nset MAVEN_PROJECTBASEDIR=%EXEC_DIR%\ncd \"%EXEC_DIR%\"\n\n:endDetectBaseDir\n\nIF NOT EXIST \"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\" goto endReadAdditionalConfig\n\n@setlocal EnableExtensions EnableDelayedExpansion\nfor /F \"usebackq delims=\" %%a in (\"%MAVEN_PROJECTBASEDIR%\\.mvn\\jvm.config\") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a\n@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%\n\n:endReadAdditionalConfig\n\nSET MAVEN_JAVA_EXE=\"%JAVA_HOME%\\bin\\java.exe\"\n\nset WRAPPER_JAR=\"%MAVEN_PROJECTBASEDIR%\\.mvn\\wrapper\\maven-wrapper.jar\"\nset WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain\n\n%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% \"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%\" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*\nif ERRORLEVEL 1 goto error\ngoto end\n\n:error\nset ERROR_CODE=1\n\n:end\n@endlocal & set ERROR_CODE=%ERROR_CODE%\n\nif not \"%MAVEN_SKIP_RC%\" == \"\" goto skipRcPost\n@REM check for post script, once with legacy .bat ending and once with .cmd ending\nif exist \"%HOME%\\mavenrc_post.bat\" call \"%HOME%\\mavenrc_post.bat\"\nif exist \"%HOME%\\mavenrc_post.cmd\" call \"%HOME%\\mavenrc_post.cmd\"\n:skipRcPost\n\n@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'\nif \"%MAVEN_BATCH_PAUSE%\" == \"on\" pause\n\nif \"%MAVEN_TERMINATE_CMD%\" == \"on\" exit %ERROR_CODE%\n\nexit /B %ERROR_CODE%\n"
  },
  {
    "path": "stock-quotes/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>io.spring.workshop</groupId>\n\t<artifactId>stock-quotes</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>stock-quotes</name>\n\t<description>Demo project for Spring Boot</description>\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>2.0.0.BUILD-SNAPSHOT</version>\n\t\t<relativePath/> <!-- lookup parent from repository -->\n\t</parent>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<java.version>1.8</java.version>\n\t\t<reactor-bom.version>Bismuth-BUILD-SNAPSHOT</reactor-bom.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-webflux</artifactId>\n\t\t</dependency>\n\t\t<!-- tag::jacksonJSR310[] -->\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.datatype</groupId>\n\t\t\t<artifactId>jackson-datatype-jsr310</artifactId>\n\t\t</dependency>\n\t\t<!-- end::jacksonJSR310[] -->\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\n\t<pluginRepositories>\n\t\t<pluginRepository>\n\t\t\t<id>spring-snapshots</id>\n\t\t\t<name>Spring Snapshots</name>\n\t\t\t<url>https://repo.spring.io/snapshot</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t\t<pluginRepository>\n\t\t\t<id>spring-milestones</id>\n\t\t\t<name>Spring Milestones</name>\n\t\t\t<url>https://repo.spring.io/milestone</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</pluginRepository>\n\t</pluginRepositories>\n\n\n</project>\n"
  },
  {
    "path": "stock-quotes/src/main/java/io/spring/workshop/stockquotes/Quote.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.time.Instant;\n\npublic class Quote {\n\n\tprivate static final MathContext MATH_CONTEXT = new MathContext(2);\n\n\tprivate String ticker;\n\n\tprivate BigDecimal price;\n\n\tprivate Instant instant = Instant.now();\n\n\tpublic Quote() {\n\t}\n\n\tpublic Quote(String ticker, BigDecimal price) {\n\t\tthis.ticker = ticker;\n\t\tthis.price = price;\n\t}\n\n\tpublic Quote(String ticker, Double price) {\n\t\tthis(ticker, new BigDecimal(price, MATH_CONTEXT));\n\t}\n\n\tpublic String getTicker() {\n\t\treturn ticker;\n\t}\n\n\tpublic void setTicker(String ticker) {\n\t\tthis.ticker = ticker;\n\t}\n\n\tpublic BigDecimal getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(BigDecimal price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Instant getInstant() {\n\t\treturn instant;\n\t}\n\n\tpublic void setInstant(Instant instant) {\n\t\tthis.instant = instant;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Quote{\" +\n\t\t\t\t\"ticker='\" + ticker + '\\'' +\n\t\t\t\t\", price=\" + price +\n\t\t\t\t\", instant=\" + instant +\n\t\t\t\t'}';\n\t}\n}"
  },
  {
    "path": "stock-quotes/src/main/java/io/spring/workshop/stockquotes/QuoteGenerator.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.stream.Collectors;\n\nimport reactor.core.publisher.Flux;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class QuoteGenerator {\n\n\tprivate final MathContext mathContext = new MathContext(2);\n\n\tprivate final Random random = new Random();\n\n\tprivate final List<Quote> prices = new ArrayList<>();\n\n\tprivate final Flux<Quote> quoteStream;\n\n\t/**\n\t * Bootstraps the generator with tickers and initial prices\n\t */\n\tpublic QuoteGenerator() {\n\t\tinitializeQuotes();\n\t\tthis.quoteStream = getQuoteStream();\n\t}\n\n\tpublic Flux<Quote> fetchQuoteStream() {\n\t\treturn quoteStream;\n\t}\n\n\tprivate void initializeQuotes() {\n\t\tthis.prices.add(new Quote(\"CTXS\", 82.26));\n\t\tthis.prices.add(new Quote(\"DELL\", 63.74));\n\t\tthis.prices.add(new Quote(\"GOOG\", 847.24));\n\t\tthis.prices.add(new Quote(\"MSFT\", 65.11));\n\t\tthis.prices.add(new Quote(\"ORCL\", 45.71));\n\t\tthis.prices.add(new Quote(\"RHT\", 84.29));\n\t\tthis.prices.add(new Quote(\"VMW\", 92.21));\n\t}\n\n\n\tprivate Flux<Quote> getQuoteStream() {\n\t\treturn Flux.interval(Duration.ofMillis(200))\n\t\t\t\t.onBackpressureDrop()\n\t\t\t\t.map(this::generateQuotes)\n\t\t\t\t.flatMapIterable(quotes -> quotes)\n\t\t\t\t.share();\n\t}\n\n\tprivate List<Quote> generateQuotes(long i) {\n\t\tInstant instant = Instant.now();\n\t\treturn prices.stream()\n\t\t\t\t.map(baseQuote -> {\n\t\t\t\t\tBigDecimal priceChange = baseQuote.getPrice()\n\t\t\t\t\t\t\t.multiply(new BigDecimal(0.05 * this.random.nextDouble()), this.mathContext);\n\n\t\t\t\t\tQuote result = new Quote(baseQuote.getTicker(), baseQuote.getPrice().add(priceChange));\n\t\t\t\t\tresult.setInstant(instant);\n\t\t\t\t\treturn result;\n\t\t\t\t})\n\t\t\t\t.collect(Collectors.toList());\n\t}\n}\n"
  },
  {
    "path": "stock-quotes/src/main/java/io/spring/workshop/stockquotes/QuoteHandler.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport reactor.core.publisher.Mono;\n\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.reactive.function.server.ServerRequest;\nimport org.springframework.web.reactive.function.server.ServerResponse;\n\nimport static org.springframework.http.MediaType.APPLICATION_STREAM_JSON;\nimport static org.springframework.web.reactive.function.server.ServerResponse.ok;\n\n@Component\npublic class QuoteHandler {\n\n\tprivate final QuoteGenerator quoteGenerator;\n\n\tpublic QuoteHandler(QuoteGenerator quoteGenerator) {\n\t\tthis.quoteGenerator = quoteGenerator;\n\t}\n\n\tpublic Mono<ServerResponse> streamQuotes(ServerRequest request) {\n\t\treturn ok()\n\t\t\t\t.contentType(APPLICATION_STREAM_JSON)\n\t\t\t\t.body(this.quoteGenerator.fetchQuoteStream(), Quote.class);\n\t}\n}\n"
  },
  {
    "path": "stock-quotes/src/main/java/io/spring/workshop/stockquotes/QuoteRouter.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.reactive.function.server.RouterFunction;\nimport org.springframework.web.reactive.function.server.RouterFunctions;\nimport org.springframework.web.reactive.function.server.ServerResponse;\n\nimport static org.springframework.http.MediaType.APPLICATION_JSON;\nimport static org.springframework.http.MediaType.APPLICATION_STREAM_JSON;\nimport static org.springframework.http.MediaType.TEXT_PLAIN;\nimport static org.springframework.web.reactive.function.server.RequestPredicates.GET;\nimport static org.springframework.web.reactive.function.server.RequestPredicates.POST;\nimport static org.springframework.web.reactive.function.server.RequestPredicates.accept;\nimport static org.springframework.web.reactive.function.server.RequestPredicates.contentType;\n\n@Configuration\npublic class QuoteRouter {\n\n\t@Bean\n\tpublic RouterFunction<ServerResponse> route(QuoteHandler quoteHandler) {\n\t\treturn RouterFunctions\n\t\t\t\t.route(GET(\"/quotes\").and(accept(APPLICATION_STREAM_JSON)), quoteHandler::streamQuotes) ;\n\t}\n}"
  },
  {
    "path": "stock-quotes/src/main/java/io/spring/workshop/stockquotes/StockQuotesApplication.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class StockQuotesApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(StockQuotesApplication.class, args);\n\t}\n}\n"
  },
  {
    "path": "stock-quotes/src/main/resources/application.properties",
    "content": "server.port=8081"
  },
  {
    "path": "stock-quotes/src/test/java/io/spring/workshop/stockquotes/StockQuotesApplicationTests.java",
    "content": "package io.spring.workshop.stockquotes;\n\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.test.web.reactive.server.WebTestClient;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\n@RunWith(SpringRunner.class)\n//  We create a `@SpringBootTest`, starting an actual server on a `RANDOM_PORT`\n@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\npublic class StockQuotesApplicationTests {\n\n\t// Spring Boot will create a `WebTestClient` for you,\n\t// already configure and ready to issue requests against \"localhost:RANDOM_PORT\"\n\t@Autowired\n\tprivate WebTestClient webTestClient;\n\n\t@Test\n\tpublic void fetchQuotes() {\n\t\tList<Quote> result =\n\t\t\t\twebTestClient\n\t\t\t\t// We then create a GET request to test an endpoint\n\t\t\t\t.get().uri(\"/quotes\")\n\t\t\t\t.accept(MediaType.APPLICATION_STREAM_JSON)\n\t\t\t\t.exchange()\n\t\t\t\t// and use the dedicated DSL to test assertions against the response\n\t\t\t\t.expectStatus().isOk()\n\t\t\t\t.expectHeader().contentType(MediaType.APPLICATION_STREAM_JSON)\n\t\t\t\t.returnResult(Quote.class)\n\t\t\t\t.getResponseBody()\n\t\t\t\t.take(20)\n\t\t\t\t.collectList()\n\t\t\t\t.block();\n\n\t\tassertThat(result).allSatisfy(quote -> assertThat(quote.getPrice()).isPositive());\n\t}\n\n}"
  }
]