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