From ab9f547657c38eb006e15b875989a77d0ad183f8 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Sat, 18 Mar 2017 22:52:57 +0530 Subject: [PATCH] changes for BAEL_711 --- lagom-cargotracker/.gitignore | 104 +++ lagom-cargotracker/LICENSE | 201 +++++ lagom-cargotracker/README.md | 22 + lagom-cargotracker/build.sbt | 67 ++ .../front-end/app/assets/main.css | 845 ++++++++++++++++++ .../front-end/app/assets/main.jsx | 253 ++++++ .../app/controllers/Application.java | 15 + .../front-end/app/views/index.scala.html | 18 + .../front-end/conf/application.conf | 10 + lagom-cargotracker/front-end/conf/routes | 3 + lagom-cargotracker/project/build.properties | 1 + lagom-cargotracker/project/plugins.sbt | 3 + .../registration/api/AbstractCargo.java | 26 + .../registration/api/RegistrationService.java | 53 ++ .../registration/impl/AbstractCargoState.java | 27 + .../registration/impl/CargoEntity.java | 86 ++ .../impl/CargoEventProcessor.java | 150 ++++ .../impl/RegistrationCommand.java | 36 + .../registration/impl/RegistrationEvent.java | 40 + .../impl/RegistrationEventTag.java | 13 + .../impl/RegistrationServiceImpl.java | 138 +++ .../impl/RegistrationServiceModule.java | 15 + .../src/main/resources/application.conf | 1 + .../test/java/RegistrationServiceTest.java | 22 + .../cargotracker/shipping/ErrorHandler.java | 69 ++ .../shipping/api/AbstractItinerary.java | 32 + .../shipping/api/AbstractLeg.java | 29 + .../shipping/api/ShippingService.java | 73 ++ .../src/main/resources/application.conf | 1 + .../shipping/impl/AbstractItineraryState.java | 56 ++ .../shipping/impl/ItineraryEntity.java | 107 +++ .../shipping/impl/ShippingCommand.java | 49 + .../shipping/impl/ShippingEvent.java | 63 ++ .../shipping/impl/ShippingServiceImpl.java | 53 ++ .../shipping/impl/ShippingServiceModule.java | 17 + .../src/main/resources/application.conf | 1 + 36 files changed, 2699 insertions(+) create mode 100644 lagom-cargotracker/.gitignore create mode 100644 lagom-cargotracker/LICENSE create mode 100644 lagom-cargotracker/README.md create mode 100644 lagom-cargotracker/build.sbt create mode 100644 lagom-cargotracker/front-end/app/assets/main.css create mode 100644 lagom-cargotracker/front-end/app/assets/main.jsx create mode 100644 lagom-cargotracker/front-end/app/controllers/Application.java create mode 100644 lagom-cargotracker/front-end/app/views/index.scala.html create mode 100644 lagom-cargotracker/front-end/conf/application.conf create mode 100644 lagom-cargotracker/front-end/conf/routes create mode 100644 lagom-cargotracker/project/build.properties create mode 100644 lagom-cargotracker/project/plugins.sbt create mode 100644 lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/AbstractCargo.java create mode 100644 lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/RegistrationService.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/AbstractCargoState.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEntity.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEventProcessor.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationCommand.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEvent.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEventTag.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceImpl.java create mode 100644 lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceModule.java create mode 100644 lagom-cargotracker/registration-impl/src/main/resources/application.conf create mode 100644 lagom-cargotracker/registration-impl/src/test/java/RegistrationServiceTest.java create mode 100644 lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/ErrorHandler.java create mode 100644 lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractItinerary.java create mode 100644 lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractLeg.java create mode 100644 lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/ShippingService.java create mode 100644 lagom-cargotracker/shipping-api/src/main/resources/application.conf create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/AbstractItineraryState.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ItineraryEntity.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingCommand.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingEvent.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceImpl.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceModule.java create mode 100644 lagom-cargotracker/shipping-impl/src/main/resources/application.conf diff --git a/lagom-cargotracker/.gitignore b/lagom-cargotracker/.gitignore new file mode 100644 index 000000000000..80faf7805b42 --- /dev/null +++ b/lagom-cargotracker/.gitignore @@ -0,0 +1,104 @@ +### Eclipse template +*.pydevproject +.metadata +.gradle +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +logs + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ +.cache-main + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Java annotation processor (APT) +.factorypath + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse +### SBT template +# Simple Build Tool +# http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control + +target/ +lib_managed/ +src_managed/ +project/boot/ +.history +.cache +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + +# mac folder +.DS_Store + +# Created by .ignore support plugin (hsz.mobi) diff --git a/lagom-cargotracker/LICENSE b/lagom-cargotracker/LICENSE new file mode 100644 index 000000000000..8dada3edaf50 --- /dev/null +++ b/lagom-cargotracker/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/lagom-cargotracker/README.md b/lagom-cargotracker/README.md new file mode 100644 index 000000000000..2884f82f2aa5 --- /dev/null +++ b/lagom-cargotracker/README.md @@ -0,0 +1,22 @@ + +# lagom-cargotracker +A cargo tracker application built with Lagom. + +The core concepts of reactive microservices have been introduced by Jonas Bonér in his report [Reactive Microservices Architecture](https://www.lightbend.com/reactive-microservices-architecture). [Lagom](http://lightbend.com/lagom) is the implementation of the described concepts. To find a good example to implement a Microservices based system with Lagom, we just needed to look into Eric Evans' book [Domain-Driven Design: Tackling Complexity in the Heart of Software](http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215) and use the discussed example, the [Cargo Tracker](http://dddsample.sourceforge.net/). The example in this repository follows this idea and is meant to be a starting point to build a full blown Lagom based cargo tracker. + +### Further Readings +* [How to make "Just right easier with Microservices"](https://www.oreilly.com/ideas/how-to-make-just-right-easier-with-microservices) +* [Developing Reactive Microservices](http://www.oreilly.com/programming/free/developing-reactive-microservices-signup.html) +* [Reactive Microservices Architecture](https://www.lightbend.com/reactive-microservices-architecture) + +### Community Contributions +Contributions welcome! Feel free to fork the example and help to build it out. + +### License +This software is licensed under the Apache 2 license, quoted below. + +Copyright (C) 2016 Lightbend Inc. (https://www.lightbend.com). + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project 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. diff --git a/lagom-cargotracker/build.sbt b/lagom-cargotracker/build.sbt new file mode 100644 index 000000000000..f944522ec4ea --- /dev/null +++ b/lagom-cargotracker/build.sbt @@ -0,0 +1,67 @@ +organization in ThisBuild := "org.lightbend.lagom" + +// the Scala version that will be used for cross-compiled libraries +scalaVersion in ThisBuild := "2.11.7" + +lazy val registrationApi = project("registration-api") + .settings( + version := "1.0-SNAPSHOT", + libraryDependencies ++= Seq( + lagomJavadslApi, + lagomJavadslImmutables + ) + ) + +lazy val registrationImpl = project("registration-impl") + .enablePlugins(LagomJava) + .settings( + version := "1.0-SNAPSHOT", + libraryDependencies ++= Seq( + lagomJavadslPersistence, + lagomJavadslPubSub, + lagomJavadslImmutables, + lagomJavadslTestKit + ) + ) + .settings(lagomForkedTestSettings: _*) + .dependsOn(registrationApi) + + +lazy val shippingApi = project("shipping-api") + .settings( + version := "1.0-SNAPSHOT", + libraryDependencies ++= Seq( + lagomJavadslApi, + lagomJavadslImmutables + ) + ) + +lazy val shippingImpl = project("shipping-impl") + .enablePlugins(LagomJava) +.dependsOn(registrationApi) + .settings( + version := "1.0-SNAPSHOT", + libraryDependencies ++= Seq( + lagomJavadslPersistence, + lagomJavadslImmutables, + lagomJavadslTestKit + ) + ) + .settings(lagomForkedTestSettings: _*) + .dependsOn(shippingApi) + +lazy val frontEnd = project("front-end") + .enablePlugins(PlayJava, LagomPlay) + .settings( + version := "1.0-SNAPSHOT", + routesGenerator := InjectedRoutesGenerator, + libraryDependencies ++= Seq( + "org.webjars" % "react" % "0.14.3", + "org.webjars" % "react-router" % "1.0.3", + "org.webjars" % "jquery" % "2.2.0", + "org.webjars" % "foundation" % "5.3.0" + ), + ReactJsKeys.sourceMapInline := true + ) + +def project(id: String) = Project(id, base = file(id)) diff --git a/lagom-cargotracker/front-end/app/assets/main.css b/lagom-cargotracker/front-end/app/assets/main.css new file mode 100644 index 000000000000..d794918a8ba2 --- /dev/null +++ b/lagom-cargotracker/front-end/app/assets/main.css @@ -0,0 +1,845 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} +html, +body { + margin: 0; + padding: 0; + height: 100%; +} +body { + background: #fff; + padding: 0; + margin: 0; + font-weight: 400; + font-style: normal; + line-height: 1; + position: relative; + cursor: default; + font: 16px "Source Sans Pro", "Helvetica Neue", Arial, sans-serif !important; + color: #1c3b47; + font-smoothing: antialiased; + -webkit-font-size-adjust: none; + text-rendering: optimizeLegibility; +} +body.clipped #clipped { + overflow-x: hidden; +} +body.versal #clipped { + height: 100%; +} +#site-header { + background: #1c3b47; + width: 100%; + height: 95px; + padding: 0px 0px; + position: relative; + z-index: 9999; + box-shadow: 0 0 8px rgba(0,0,0,0.5); +} +@media only screen and (min-width: 40.063em) { + #site-header { + position: fixed; + } +} +#site-header #logo { + display: block; + float: left; + margin-top: 25px; + width: 220px; + height: 45px; + color: #fff; + font-size: 32pt; +} +#site-header .aside-nav-button { + opacity: 0; + visibility: hidden; + -webkit-transition: visibility 0.2s linear, opacity 0.2s linear; + -moz-transition: visibility 0.2s linear, opacity 0.2s linear; + -o-transition: visibility 0.2s linear, opacity 0.2s linear; + position: absolute; + top: 10px; + left: 10px; + padding: 0px; + height: 70px; + width: 40px; + background-color: #ff931e; + border-radius: 2px; + border-bottom: 2px solid #f48122; + z-index: 1000; + padding-top: 15px; + padding-bottom: 15px; +} +#site-header .aside-nav-button .menu-icon { + fill: #fff; +} +#site-header .aside-nav-button:hover { + background-color: #f48122; +} +#site-header .aside-nav-button.visible { + visibility: visible; + opacity: 1; +} +#site-header a.logo { + z-index: 500; +} +#site-header a.logo img { + height: 40px; + margin: 25px 0; +} +#site-header .row > div { + height: 75px; +} +#site-header nav { + float: right; +} +#site-header nav .tertiary-nav { + text-align: right; + background-color: rgba(255,255,255,0); + padding-top: 6px; + height: 45px; +} +#site-header nav .tertiary-nav a { + margin-left: 10px; + font-size: 0.85em; + font-weight: 700; + color: #489dbd; +} +#site-header nav .tertiary-nav .btn { + margin: 0; + margin-left: 10px; + font-size: 0.65em; + border: none; + background-color: #489dbd; + color: #fff !important; +} +#site-header nav .primary-nav { + padding: 0; + clear: both; + color: #fff; + margin: 0; + font-size: 14px; + height: 45px; + float: right; +} +#site-header nav .primary-nav .footer-only { + display: none; +} +#site-header nav .primary-nav > a.btn { + margin: 5px 0 0 10px; + padding: 0.6em 1em; + font-size: 1em; +} +#site-header nav .primary-nav dl { + margin: 0px; + font-weight: 400; + display: block; + float: left; + padding: 0px; + line-height: 0.8em; + font-size: 14px; + position: relative; + transition: all 200ms ease-in-out; +} +#site-header nav .primary-nav dl hr { + padding: 0; + margin: 0; + height: 1px; + background: #3e515e; + border-top: 1px solid #000; +} +#site-header nav .primary-nav dl dt { + padding: 10px 15px; + position: relative; + z-index: 500; + text-transform: uppercase; + margin-bottom: 0; + height: 50px; + line-height: 25px; + transition: all 200ms ease-in-out; +} +#site-header nav .primary-nav dl dt a { + color: #fff; + font-weight: 700; + font-size: 15px; +} +#site-header nav .primary-nav dl dt a:hover { + text-decoration: none; + color: #1a84ad; +} +#site-header nav .primary-nav dl dd { + display: block; + opacity: 0; + height: 0; + overflow: hidden; + position: absolute; + width: 240px; + border-radius: 2px; + border-top-left-radius: 0; + font-weight: 400; + background-color: #0c323b; + box-shadow: 0px 0px 0px 3px rgba(255,147,30,0.1); + transition: all 200ms ease-in-out; +} +#site-header nav .primary-nav dl dd h2, +#site-header nav .primary-nav dl dd h2 a { + color: #ff931e; + margin: 1.2em 0 0.7em 0; + padding-top: 0.5em; + font-size: 13px; + font-weight: 700; + border-top: 0px solid rgba(255,255,255,0.1); + text-transform: uppercase; +} +#site-header nav .primary-nav dl dd h2:first-child, +#site-header nav .primary-nav dl dd h2 a:first-child { + margin-top: 0; + padding-top: 0; +} +#site-header nav .primary-nav dl dd h2 a { + margin-top: 0; + padding-top: 0; +} +#site-header nav .primary-nav dl dd a { + display: block; + line-height: 0.8em; + margin-bottom: 0.8em; + color: #fff; + font-size: 15px; +} +#site-header nav .primary-nav dl dd a > span { + padding-left: 14px; + padding-right: 6px; + color: #ff931e; +} +#site-header nav .primary-nav dl dd a:hover { + color: #ff931e; + text-decoration: none; +} +#site-header nav .primary-nav dl dd a.ib { + display: inline-block; + margin-right: 5px; +} +#site-header nav .primary-nav dl dd a .svg-icon { + width: 15px; + height: 15px; +} +#site-header nav .primary-nav dl dd a.rss-icon { + margin: 0; +} +#site-header nav .primary-nav dl:hover { + transition: all 200ms ease-in-out; +} +#site-header nav .primary-nav dl:hover dt { + box-shadow: inset 0 2px 0 #ff931e; + background-color: #0c323b; + transition: all 200ms ease-in-out; +} +#site-header nav .primary-nav dl:hover dt a { + color: #ff931e; +} +#site-header nav .primary-nav dl:hover dd { + opacity: 1; + height: auto; + background-color: #0c323b; + transition: all 200ms ease-in-out; + padding: 25px 15px 15px 15px; +} +#page-content { + padding: 0; + margin: 0; +} +#page-content #top { + width: 100%; + background: #1a84ad; + color: #fff; + padding: 30px 0 30px 0; + position: relative; + overflow: hidden; + box-shadow: inset 0 -3px 0 rgba(137,156,169,0.1); +} +@media only screen and (min-width: 40.063em) { + #page-content #top { + padding: 130px 0 30px 0; + } +} +#page-content #top p { + color: #fff; +} +#page-content #top header { + white-space: nowrap; +} +#page-content #top header h1 { + overflow: hidden; + display: inline-block; + text-transform: uppercase; + font-size: 35px; + line-height: 40px; + color: #fff; + margin: 0; + font-weight: 300; +} +#page-content #top nav h1 { + max-width: 62.5em; + width: 100%; + height: 60px; + overflow: hidden; + padding: 10px; + text-overflow: ellipsis; + white-space: nowrap; + color: #fff; + margin: 0; +} +#page-content #top nav h1 a { + color: #fff; + text-transform: uppercase; + font-size: 30px; + font-weight: 300; +} +#page-content #top nav h1 a:hover { + text-decoration: none; +} +#page-content #top nav h1 a:after { + content: "/"; + margin-left: 5px; + margin-right: 5px; + font-weight: 400; +} +#page-content #top nav h1 a:last-child { + font-weight: 300; +} +#page-content #top nav h1 a:last-child:after { + content: ""; +} +#page-content #top nav h1 strong { + text-transform: uppercase; +} +#page-content #top .banner { + position: relative; + min-height: 500px; +} +#page-content #top .banner .illustration { + content: " "; + display: block; + position: absolute; + width: 700px; + left: 0; + top: 50px; + height: 400px; + margin-left: -150px; + background-size: 80%; +} +#page-content #top .banner .details { + position: relative; + margin: 150px 0 10px 0; + float: right; + width: 50%; + text-align: right; +} +#page-content #top .banner .details.video { + margin: 40px 0 0 0; + width: 65%; +} +#page-content #top .banner .details h1 { + font-size: 33px; + font-weight: 400; + color: #fff; +} +#page-content #top.short-top { + height: initial; +} +.fw-wrapper { + padding: 60px 0px; + min-width: 62.5em; +} +.fw-wrapper.flush { + padding: 0; +} +.fw-wrapper.flush-top { + padding: 0 0 60px 0; +} +.fw-wrapper.flush-bottom { + padding: 60px 0 0 0; +} +.fw-wrapper.grey { + background-color: #c5d0d4; +} +.fw-wrapper.slate { + background-color: #364550; +} +.fw-wrapper.slate h1, +.fw-wrapper.slate h2, +.fw-wrapper.slate h3, +.fw-wrapper.slate h4, +.fw-wrapper.slate p, +.fw-wrapper.slate a { + color: #fff; +} +.fw-wrapper.slate-dkr { + background-color: #2a363e; +} +.fw-wrapper.slate-dkr h1, +.fw-wrapper.slate-dkr h2, +.fw-wrapper.slate-dkr h3, +.fw-wrapper.slate-dkr h4, +.fw-wrapper.slate-dkr p, +.fw-wrapper.slate-dkr a { + color: #fff; +} +.fw-wrapper.slate-ltr { + background-color: #3e515e; +} +.fw-wrapper.slate-ltr h1, +.fw-wrapper.slate-ltr h2, +.fw-wrapper.slate-ltr h3, +.fw-wrapper.slate-ltr h4, +.fw-wrapper.slate-ltr p, +.fw-wrapper.slate-ltr a { + color: #fff; +} +.fw-wrapper.slate-tt { + background-color: #1c3b47; +} +.fw-wrapper.slate-tt h1, +.fw-wrapper.slate-tt h2, +.fw-wrapper.slate-tt h3, +.fw-wrapper.slate-tt h4, +.fw-wrapper.slate-tt p, +.fw-wrapper.slate-tt a { + color: #fff; +} +.fw-wrapper.white-ltr, +.fw-wrapper.lb-light-grey-ltr { + background-color: #f3f6f6; +} +.fw-wrapper.white-dkr, +.fw-wrapper.lb-light-grey { + background-color: #c5d0d4; +} +.fw-wrapper.teal-blue { + background-color: #1c3b47; +} +.fw-wrapper.teal-blue h1, +.fw-wrapper.teal-blue h2, +.fw-wrapper.teal-blue h3, +.fw-wrapper.teal-blue h4, +.fw-wrapper.teal-blue p, +.fw-wrapper.teal-blue a { + color: #fff; +} +.fw-wrapper.lb-dark-teal { + background-color: #1c3b47; +} +.fw-wrapper.lb-dark-teal h1, +.fw-wrapper.lb-dark-teal h2, +.fw-wrapper.lb-dark-teal h3, +.fw-wrapper.lb-dark-teal h4, +.fw-wrapper.lb-dark-teal p, +.fw-wrapper.lb-dark-teal a { + color: #fff; +} +.fw-wrapper.blue, +.fw-wrapper.lb-blue { + background-color: #1a84ad; +} +.fw-wrapper.blue h1, +.fw-wrapper.lb-blue h1, +.fw-wrapper.blue h2, +.fw-wrapper.lb-blue h2, +.fw-wrapper.blue h3, +.fw-wrapper.lb-blue h3, +.fw-wrapper.blue h4, +.fw-wrapper.lb-blue h4, +.fw-wrapper.blue p, +.fw-wrapper.lb-blue p, +.fw-wrapper.blue a, +.fw-wrapper.lb-blue a { + color: #fff; +} +.fw-wrapper.blue-dkr, +.fw-wrapper.lb-blue-dkr { + background-color: #127796; +} +.fw-wrapper.blue-dkr h1, +.fw-wrapper.lb-blue-dkr h1, +.fw-wrapper.blue-dkr h2, +.fw-wrapper.lb-blue-dkr h2, +.fw-wrapper.blue-dkr h3, +.fw-wrapper.lb-blue-dkr h3, +.fw-wrapper.blue-dkr h4, +.fw-wrapper.lb-blue-dkr h4, +.fw-wrapper.blue-dkr p, +.fw-wrapper.lb-blue-dkr p, +.fw-wrapper.blue-dkr a, +.fw-wrapper.lb-blue-dkr a { + color: #fff; +} +.fw-wrapper.red { + background-color: #ff931e; +} +.fw-wrapper.red h1, +.fw-wrapper.red h2, +.fw-wrapper.red h3, +.fw-wrapper.red h4, +.fw-wrapper.red p, +.fw-wrapper.red a { + color: #fff; +} +.fw-wrapper.lb-orange { + background-color: #ff931e; +} +.fw-wrapper.lb-orange h1, +.fw-wrapper.lb-orange h2, +.fw-wrapper.lb-orange h3, +.fw-wrapper.lb-orange h4, +.fw-wrapper.lb-orange p, +.fw-wrapper.lb-orange a { + color: #fff; +} +.fw-wrapper.lb-dark-teal { + background-color: #1c3b47; +} +.fw-wrapper.lb-dark-teal h1, +.fw-wrapper.lb-dark-teal h2, +.fw-wrapper.lb-dark-teal h3, +.fw-wrapper.lb-dark-teal h4, +.fw-wrapper.lb-dark-teal p, +.fw-wrapper.lb-dark-teal a { + color: #fff; +} +.fw-wrapper.lb-dark-teal-dkr { + background-color: #0c323b; +} +.fw-wrapper.lb-dark-teal-dkr h1, +.fw-wrapper.lb-dark-teal-dkr h2, +.fw-wrapper.lb-dark-teal-dkr h3, +.fw-wrapper.lb-dark-teal-dkr h4, +.fw-wrapper.lb-dark-teal-dkr p, +.fw-wrapper.lb-dark-teal-dkr a { + color: #fff; +} +.fw-wrapper.lb-dark-teal-ltr { + background-color: #406972; +} +.fw-wrapper.lb-dark-teal-ltr h1, +.fw-wrapper.lb-dark-teal-ltr h2, +.fw-wrapper.lb-dark-teal-ltr h3, +.fw-wrapper.lb-dark-teal-ltr h4, +.fw-wrapper.lb-dark-teal-ltr p, +.fw-wrapper.lb-dark-teal-ltr a { + color: #fff; +} +.fw-wrapper.navy { + background-color: #1c3b47; + box-shadow: inset 0 -3px 0 rgba(0,0,0,0.1); +} +.fw-wrapper.navy h1, +.fw-wrapper.navy h2, +.fw-wrapper.navy h3, +.fw-wrapper.navy h4, +.fw-wrapper.navy p, +.fw-wrapper.navy a { + color: #fff; +} +.fw-wrapper.shadow { + box-shadow: inset 0 -3px 0 rgba(0,0,0,0.1); +} +.fw-wrapper.shadow-dark { + box-shadow: inset 0 -3px 0 rgba(0,0,0,0.2); +} +.fw-wrapper.play { + background-color: play-green; +} +.fw-wrapper.play h1, +.fw-wrapper.play h2, +.fw-wrapper.play h3, +.fw-wrapper.play h4, +.fw-wrapper.play p, +.fw-wrapper.play a { + color: #fff; +} +.fw-wrapper.playday { + border-top: 6px play-dkr solid; +} +.fw-wrapper.akka { + background-color: akka-blue; +} +.fw-wrapper.akka h1, +.fw-wrapper.akka h2, +.fw-wrapper.akka h3, +.fw-wrapper.akka h4, +.fw-wrapper.akka p, +.fw-wrapper.akka a { + color: #fff; +} +.fw-wrapper.scala { + background-color: scala-red; +} +.fw-wrapper.scala h1, +.fw-wrapper.scala h2, +.fw-wrapper.scala h3, +.fw-wrapper.scala h4, +.fw-wrapper.scala p, +.fw-wrapper.scala a { + color: #fff; +} +aside { + color: #fff; +} +aside h3, +aside a, +aside a:link, +aside a:visited { + color: #fff; + font-weight: 700; +} +aside h3 { + background-color: #1c3b47; + border-bottom: 2px solid #406972; + margin: 0 0 10px 0; + padding: 10px 0 8px 0; + text-transform: uppercase; + font-weight: 700; + font-size: 14px; + color: #ff931e; +} +aside h3 a:link { + font-weight: 700; +} +aside ul { + background-color: #1c3b47; + border-radius: 2px; + margin: 0; + list-style-type: none; + padding: 0px 0px 20px 0px; + background-image: none; + text-align: center; +} +aside ul li { + padding: 0; + margin: 0; + line-height: 30px; + background-image: none; +} +aside ul li h3:first-child { + margin-top: 20px; +} +aside ul li:before { + content: ""; +} +aside ul li:first-child h3 { + border-radius: 2px 2px 0 0; + margin-top: 0px; +} +aside ul li a { + margin-bottom: 5px; + display: inline-block; + width: 90%; + border-radius: 2px; + transition: all 200ms ease-in-out; +} +aside ul li a:hover { + background-color: #fff; + text-decoration: none; + color: #f48122; +} +.responsive .fw-wrapper, +.responsive .row { + min-width: 0; +} +.invisible-table { + border: 0; +} +a.btn, +.btn { + transition: all 200ms ease-in-out; + display: inline-block; + line-height: 1em; + padding: 0.625em 0.875em; + margin: 5px 0; + background-color: #ff931e; + border: 2px solid #ff931e; + color: #fff; + text-transform: uppercase; + font-size: 1em; + font-weight: 700; + text-align: center; +} +a.btn:link, +.btn:link { + color: #fff; +} +a.btn:visited, +.btn:visited { + color: #fff; +} +a.btn:hover, +.btn:hover { + text-decoration: none; + background-color: #f48122; + border: 2px solid #f48122; + color: #fff; +} +a.btn:active, +.btn:active { + color: #fff; +} +a.btn.glass, +.btn.glass { + border: 2px solid #fff; + background-color: transparent; + color: #fff; +} +a.btn.glass:hover, +.btn.glass:hover { + background-color: rgba(255,255,255,0.5); + color: #1c3b47; +} +a.btn.blue, +.btn.blue { + background-color: #1a84ad; + border: 2px solid #1a84ad; +} +a.btn.blue:hover, +.btn.blue:hover { + background-color: #127796; + border: 2px solid #127796; +} +a.btn.blue.glass, +.btn.blue.glass { + border: 2px solid #1a84ad; + background-color: transparent; + color: #1a84ad; +} +a.btn.blue.glass:hover, +.btn.blue.glass:hover { + background-color: #1a84ad; + color: #fff; +} +a.btn.red, +.btn.red { + background-color: #ff931e; + border: 2px solid #ff931e; +} +a.btn.red:hover, +.btn.red:hover { + background-color: #f48122; + border: 2px solid #f48122; +} +a.btn.red.glass, +.btn.red.glass { + border: 2px solid #ff931e; + background-color: transparent; + color: #ff931e; +} +a.btn.red.glass:hover, +.btn.red.glass:hover { + background-color: #ff931e; + color: #fff; +} +a.btn.red-dkr, +.btn.red-dkr { + background-color: #f48122; + border: 2px solid #f48122; +} +a.btn.red-dkr:hover, +.btn.red-dkr:hover { + background-color: #f48122; +} +a.btn.teal-blue, +.btn.teal-blue { + background-color: #1c3b47; + border: 2px solid #1c3b47; +} +a.btn.teal-blue:hover, +.btn.teal-blue:hover { + background-color: #0c323b; + border: 2px solid #0c323b; +} +a.btn.teal-blue.glass, +.btn.teal-blue.glass { + border: 2px solid #1c3b47; + background-color: transparent; + color: #1c3b47; +} +a.btn.teal-blue.glass:hover, +.btn.teal-blue.glass:hover { + background-color: #1c3b47; + color: #fff; +} +a.btn.blue-dkr, +.btn.blue-dkr { + background-color: #127796; + border: 2px solid #127796; +} +a.btn.blue-dkr:hover, +.btn.blue-dkr:hover { + background-color: #19aacf; + border: 2px solid #19aacf; +} +a.btn.navy, +.btn.navy { + background-color: #1c3b47; + border: 2px solid #1c3b47; +} +a.btn.navy:hover, +.btn.navy:hover { + background-color: #1c3b47; + border: 2px solid #1c3b47; +} +a.btn.navy.glass, +.btn.navy.glass { + border: 2px solid #1c3b47; + background-color: transparent; + color: #1c3b47; +} +a.btn.navy.glass:hover, +.btn.navy.glass:hover { + background-color: #1c3b47; + color: #fff; +} +a.btn.small, +.btn.small { + font-size: 0.8em; + padding: 0.5em 1em; + line-height: 1.3em; +} +a.btn.full-width, +.btn.full-width { + display: block; +} +@media only screen and (min-width: 40.063em) { + a.btn, + .btn { + display: inline-block; + } +} +button, +input[type=submit] { + border: 0; + background: #1a84ad; + border-bottom: 2px solid #127796; + border-radius: 2px; + color: #fff; + margin: 10px 0; + padding: 10px; + text-align: center; + font: 18px "Source Sans Pro", "Helvetica Neue", Arial, sans-serif; + font-weight: 900; + text-transform: uppercase; + display: inline-block; + width: 200px; +} +button:hover, +input[type=submit]:hover { + background: #127796; + text-decoration: none; +} + +.cargoForm input { + width: 140px; + display: inline-block; + margin:10px; +} diff --git a/lagom-cargotracker/front-end/app/assets/main.jsx b/lagom-cargotracker/front-end/app/assets/main.jsx new file mode 100644 index 000000000000..59cca2012db1 --- /dev/null +++ b/lagom-cargotracker/front-end/app/assets/main.jsx @@ -0,0 +1,253 @@ +var Route = ReactRouter.Route; +var IndexRoute = ReactRouter.IndexRoute; +var Link = ReactRouter.Link; + +function sendJson(params) { + params.data = JSON.stringify(params.data); + params.contentType = "application/json"; + return $.ajax(params); +} + +function createStream(path, onopen) { + return { + connect: function(onData) { + var stream = new WebSocket("ws://" + location.host + path); + if (onopen) { + stream.onopen = function(event) { + onopen(stream, event); + }.bind(this); + } + stream.onmessage = function(event) { + var data = JSON.parse(event.data); + onData(data); + }.bind(this); + return { + close: function() { + stream.close(); + } + } + } + }; +} + +function createCargoStream() { + return createStream("/api/registration/live"); +} + +var Cargo = React.createClass({ + render: function() { + return ( +
+ {this.props.children} +
+
+ ); + } +}); + +var CargoForm = React.createClass({ + getInitialState: function() { + return {name: "", description: "", owner: "", destination: ""}; + }, + handleChange: function(field) { + var outerThis = this; + return function(e) { + var s = outerThis.state; + s[field] = e.target.value; + outerThis.setState(s); + } + }, + handleSubmit: function(e) { + e.preventDefault(); + var dataToSend = this.state; + dataToSend["id"] = Math.floor(Math.random() * 1000000); + sendJson({ + url: "/api/registration", + type: 'POST', + data: dataToSend, + success: function() { + this.setState({name: "", description: "", owner: "", destination: ""}); + }.bind(this), + error: function(xhr, status, err) { + console.error(this.props.url, status, err.toString()); + }.bind(this) + }); + }, + render: function() { + return ( +
+
+ + + + +
+ +
+ ); + } +}); + +var Section = React.createClass({ + render: function() { + return ( +
+
+ {this.props.children} +
+
+ ); + } +}); + +var CargoStream = React.createClass({ + getInitialState: function() { + return {cargos: []}; + }, + componentDidMount: function() { + this.stream = this.props.stream.connect(function(cargo) { + var newCargo = [cargo].concat(this.state.cargos); + this.setState({cargos: newCargo}); + }.bind(this)); + }, + componentWillUnmount: function() { + this.stream.close(); + }, + render: function() { + var cargoNodes = this.state.cargos.map(function(cargo) { + return ( + + + + + + + + + + + + + + + + + + +
Cargo IDCargo nameDescriptionOwnerDestination
{cargo.id}{cargo.name}{cargo.description}{cargo.owner}{cargo.destination}
+
+ ); + }.bind(this)); + return ( +
+
+ {cargoNodes} +
+ + ); + } +}); + +var RegistrationStream = React.createClass({ + getInitialState: function() { + return {cargos: {}}; + }, + render: function() { + return ( + +
+
+ + +
+
+
+ ); + } +}); + +var PageLayout = React.createClass({ + render: function() { + + var links =
; + + return ( +
+ + {this.props.children} +
+ ); + } +}); + +var ContentLayout = React.createClass({ + render: function() { + return ( +
+
+
+
+

{this.props.subtitle}

+
+
+
+ {this.props.children} +
+ ); + } +}); + +var App = React.createClass({ + getInitialState: function() { + return {}; + }, + render: function() { + return ( + + {this.props.children} + + ); + } +}); + +ReactDOM.render( + + + + + , + document.getElementById("content") +); diff --git a/lagom-cargotracker/front-end/app/controllers/Application.java b/lagom-cargotracker/front-end/app/controllers/Application.java new file mode 100644 index 000000000000..ae5b4a517581 --- /dev/null +++ b/lagom-cargotracker/front-end/app/controllers/Application.java @@ -0,0 +1,15 @@ +package controllers; + +import play.mvc.*; + +public class Application extends Controller { + + public Result index() { + return ok(views.html.index.render()); + } + + public Result userStream(String userId) { + return ok(views.html.index.render()); + } + +} diff --git a/lagom-cargotracker/front-end/app/views/index.scala.html b/lagom-cargotracker/front-end/app/views/index.scala.html new file mode 100644 index 000000000000..8cb6e5e01b17 --- /dev/null +++ b/lagom-cargotracker/front-end/app/views/index.scala.html @@ -0,0 +1,18 @@ + + + Cargotracker + + + + + + +
+ + + + + + + + diff --git a/lagom-cargotracker/front-end/conf/application.conf b/lagom-cargotracker/front-end/conf/application.conf new file mode 100644 index 000000000000..df2964514229 --- /dev/null +++ b/lagom-cargotracker/front-end/conf/application.conf @@ -0,0 +1,10 @@ +play.crypto.secret = "changeme" + +lagom.play { + service-name = "lagom-cargotracker-front-end" + acls = [ + { + path-regex = "(?!/api/).*" + } + ] +} diff --git a/lagom-cargotracker/front-end/conf/routes b/lagom-cargotracker/front-end/conf/routes new file mode 100644 index 000000000000..9e36edba5472 --- /dev/null +++ b/lagom-cargotracker/front-end/conf/routes @@ -0,0 +1,3 @@ +GET / controllers.Application.index() +GET /addCargo controllers.Application.index() +GET /assets/*file controllers.Assets.versioned(path = "/public", file) diff --git a/lagom-cargotracker/project/build.properties b/lagom-cargotracker/project/build.properties new file mode 100644 index 000000000000..43b8278c68cf --- /dev/null +++ b/lagom-cargotracker/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.11 diff --git a/lagom-cargotracker/project/plugins.sbt b/lagom-cargotracker/project/plugins.sbt new file mode 100644 index 000000000000..1708db150ebc --- /dev/null +++ b/lagom-cargotracker/project/plugins.sbt @@ -0,0 +1,3 @@ +addSbtPlugin("com.lightbend.lagom" % "lagom-sbt-plugin" % "1.0.0-M1") +addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "3.0.0") +addSbtPlugin("com.github.ddispaltro" % "sbt-reactjs" % "0.5.2") diff --git a/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/AbstractCargo.java b/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/AbstractCargo.java new file mode 100644 index 000000000000..3c2e712f11c2 --- /dev/null +++ b/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/AbstractCargo.java @@ -0,0 +1,26 @@ +package sample.cargotracker.registration.api; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import org.immutables.value.Value; + +@Value.Immutable +@ImmutableStyle +@JsonDeserialize(as = Cargo.class) +public interface AbstractCargo { + + @Value.Parameter + String getId(); + + @Value.Parameter + String getName(); + + @Value.Parameter + String getDescription(); + + @Value.Parameter + String getOwner(); + + @Value.Parameter + String getDestination(); +} diff --git a/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/RegistrationService.java b/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/RegistrationService.java new file mode 100644 index 000000000000..423d9cca03c6 --- /dev/null +++ b/lagom-cargotracker/registration-api/src/main/java/sample/cargotracker/registration/api/RegistrationService.java @@ -0,0 +1,53 @@ +package sample.cargotracker.registration.api; + +import static com.lightbend.lagom.javadsl.api.Service.*; + +import akka.Done; +import akka.NotUsed; +import akka.stream.javadsl.Source; + +import com.lightbend.lagom.javadsl.api.Descriptor; +import com.lightbend.lagom.javadsl.api.Service; +import com.lightbend.lagom.javadsl.api.ServiceCall; +import com.lightbend.lagom.javadsl.api.transport.Method; +import org.pcollections.PSequence; + +/** + * The registration service interface. + *

+ * This describes everything that Lagom needs to know about how to serve and consume the RegistrationService. + */ +public interface RegistrationService extends Service { + + /** + * Example: curl -H "Content-Type: application/json" -X POST -d + * '{ + * "cargo": { + * "id": 1, + * "name": "laptop", + * "description": "macbook", + * "owner": "Clark Kent", + * "destination": "Metropolis" + * } + * }' http://localhost:9000/api/registration + */ + ServiceCall register(); + + ServiceCall> getLiveRegistrations(); + + ServiceCall> getAllRegistrations(); + + ServiceCall getRegistration(); + + @Override + default Descriptor descriptor() { + // @formatter:off + return named("registrationService").with( + restCall(Method.POST, "/api/registration", register()), + pathCall("/api/registration/live", getLiveRegistrations()), + restCall(Method.GET, "/api/registration/all", getAllRegistrations()), + restCall(Method.GET, "/api/registration/:id", getRegistration()) + ).withAutoAcl(true); + // @formatter:on + } +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/AbstractCargoState.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/AbstractCargoState.java new file mode 100644 index 000000000000..497d1c5ae6c7 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/AbstractCargoState.java @@ -0,0 +1,27 @@ +package sample.cargotracker.registration.impl; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.common.base.Preconditions; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.serialization.CompressedJsonable; +import java.time.LocalDateTime; +import java.util.Optional; + +import org.immutables.value.Value; +import sample.cargotracker.registration.api.Cargo; + +/** + * The state for the cargo entity. + */ +@Value.Immutable +@ImmutableStyle +@JsonDeserialize(as = CargoState.class) +public interface AbstractCargoState { + + + @Value.Parameter + Cargo getCargo(); + + @Value.Parameter + LocalDateTime getTimestamp(); +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEntity.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEntity.java new file mode 100644 index 000000000000..fa9455b8c80a --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEntity.java @@ -0,0 +1,86 @@ +package sample.cargotracker.registration.impl; + +import com.lightbend.lagom.javadsl.persistence.PersistentEntity; + +import java.time.LocalDateTime; +import java.util.Optional; + +import akka.Done; +import sample.cargotracker.registration.api.Cargo; + +/** + * This is an event sourced entity. It has a state, {@link CargoState}, which stores what the registered cargo caries. + *

+ * Event sourced entities are interacted with by sending them commands. This entity supports one command, + * a {@link RegisterCargo} command, which is used for cargo registration. + *

+ * Commands get translated to events, and it's the events that get persisted by the entity. Each event + * will have an event handler registered for it, and an event handler simply applies an event to the + * current state. This will be done when the event is first created, and it will also be done when the + * entity is loaded from the database - each event will be replayed to recreate the state of the entity. + *

+ * This entity defines one event, the {@link CargoRegistered} event, which is emitted when a + * {@link RegisterCargo} command is received. + */ +public class CargoEntity extends PersistentEntity { + + /** + * An entity can define different behaviours for different states, but it will always start with an + * initial behaviour. This entity only has one behaviour. + */ + @Override + public Behavior initialBehavior(Optional snapshotState) { + + /** + * Behaviour is defined using a behaviour builder. The behaviour builder starts with a state, if this + * entity supports snapshotting (an optimisation that allows the state itself to be persisted to combine + * many events into one), then the passed in snapshotState may have a value that can be used. + * + * Otherwise, the default state is to use a dummy Cargo with an id of empty string. + */ + BehaviorBuilder b = newBehaviorBuilder(snapshotState.orElse( + CargoState.builder().cargo( + Cargo.builder() + .id("") + .description("") + .destination("") + .name("") + .owner("").build()) + .timestamp(LocalDateTime.now() + ).build())); + + + // Command handlers are invoked for incoming messages (commands). + // A command handler must "return" the events to be persisted (if any). + b.setCommandHandler(RegisterCargo.class, (cmd, ctx) -> { + if (cmd.getCargo().getName() == null || cmd.getCargo().getName().equals("")) { + ctx.invalidCommand("Name must be defined"); + return ctx.done(); + } + + final CargoRegistered cargoRegistered = + CargoRegistered.builder().cargo(cmd.getCargo()).id(entityId()).build(); + + return ctx.thenPersist(cargoRegistered, evt -> ctx.reply(Done.getInstance())); + + }); + /** + * Event handler for the CargoRegistered event. + */ + b.setEventHandler(CargoRegistered.class, + // We simply update the current state to use the new cargo payload and update the timestamp + evt -> state() + .withCargo(evt.getCargo()) + .withTimestamp(LocalDateTime.now()) + ); + + + // b.setReadOnlyCommandHandler() + + /** + * We've defined all our behaviour, so build and return it. + */ + return b.build(); + } +} + diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEventProcessor.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEventProcessor.java new file mode 100644 index 000000000000..470b182d6ad8 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/CargoEventProcessor.java @@ -0,0 +1,150 @@ +package sample.cargotracker.registration.impl; + +import akka.Done; +import com.datastax.driver.core.BoundStatement; +import com.lightbend.lagom.javadsl.persistence.AggregateEventTag; +import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSideProcessor; +import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraSession; + +import com.datastax.driver.core.PreparedStatement; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletionStage; + +/** + * Transform the Persistent Entity events into Cassandra database + * tables and records that can be queried from a service. + */ +public class CargoEventProcessor extends CassandraReadSideProcessor { + + private final Logger log = LoggerFactory.getLogger(CargoEventProcessor.class); + + @Override + public AggregateEventTag aggregateTag() { + return RegistrationEventTag.INSTANCE; + } + + + private PreparedStatement writeCargo = null; // initialized in prepare + private PreparedStatement writeOffset = null; // initialized in prepare + + private void setWriteCargo(PreparedStatement writeCargo) { + this.writeCargo = writeCargo; + } + + private void setWriteOffset(PreparedStatement writeOffset) { + this.writeOffset = writeOffset; + } + + /** + * Prepare read-side table and statements + * + * @param session + * @return + */ + @Override + public CompletionStage> prepare(CassandraSession session) { + // @formatter:off + return + prepareCreateTables(session).thenCompose(a -> + prepareWriteCargo(session).thenCompose(b -> + prepareWriteOffset(session).thenCompose(c -> + selectOffset(session)))); + // @formatter:on + } + + /** + * prepare read-side tables + * + * @param session + * @return + */ + private CompletionStage prepareCreateTables(CassandraSession session) { + // @formatter:off + return session.executeCreateTable( + "CREATE TABLE IF NOT EXISTS cargo (" + + "cargoId text, name text, description text, owner text, destination text," + + "PRIMARY KEY (cargoId, destination))") + .thenCompose(a -> session.executeCreateTable( + "CREATE TABLE IF NOT EXISTS cargo_offset (" + + "partition int, offset timeuuid, " + + "PRIMARY KEY (partition))")); + // @formatter:on + } + + /** + * prepared statement for writing a Cargo object + * + * @param session + * @return + */ + private CompletionStage prepareWriteCargo(CassandraSession session) { + return session.prepare("INSERT INTO cargo (cargoId, name, description, owner,destination) VALUES (?, ?,?,?,?)").thenApply(ps -> { + setWriteCargo(ps); + return Done.getInstance(); + }); + } + + /** + * Prepared statement for the persistence offset + * + * @param session + * @return + */ + private CompletionStage prepareWriteOffset(CassandraSession session) { + return session.prepare("INSERT INTO cargo_offset (partition, offset) VALUES (1, ?)").thenApply(ps -> { + setWriteOffset(ps); + return Done.getInstance(); + }); + } + + /** + * Find persistence offset + * + * @param session + * @return + */ + private CompletionStage> selectOffset(CassandraSession session) { + return session.selectOne("SELECT offset FROM cargo_offset") + .thenApply( + optionalRow -> optionalRow.map(r -> r.getUUID("offset"))); + } + + /** + * Bind the read side persistence to the CargoRegistered event + * + * @param builder + * @return + */ + @Override + public EventHandlers defineEventHandlers(EventHandlersBuilder builder) { + builder.setEventHandler(CargoRegistered.class, this::processCargoRegistered); + return builder.build(); + } + + /** + * Write a persistent event into the read-side optimized database. + * + * @param @link{CargoRegistered} + * @param offset + * @return + */ + private CompletionStage> processCargoRegistered(CargoRegistered event, UUID offset) { + BoundStatement bindWriteCargo = writeCargo.bind(); + bindWriteCargo.setString("cargoId", event.getCargo().getId()); + bindWriteCargo.setString("name", event.getCargo().getName()); + bindWriteCargo.setString("description", event.getCargo().getDescription()); + bindWriteCargo.setString("owner", event.getCargo().getOwner()); + bindWriteCargo.setString("destination", event.getCargo().getDestination()); + BoundStatement bindWriteOffset = writeOffset.bind(offset); + log.info("Persisted {}", event.getCargo().getId()); + return completedStatements(Arrays.asList(bindWriteCargo, bindWriteOffset)); + } + +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationCommand.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationCommand.java new file mode 100644 index 000000000000..8abdf955f61d --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationCommand.java @@ -0,0 +1,36 @@ +package sample.cargotracker.registration.impl; + +import akka.Done; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.javadsl.persistence.PersistentEntity; +import com.lightbend.lagom.serialization.CompressedJsonable; +import com.lightbend.lagom.serialization.Jsonable; +import org.immutables.value.Value; +import sample.cargotracker.registration.api.Cargo; + +/** + * This interface defines all the commands that the Cargo entity supports. + *

+ * By convention, the commands should be inner classes of the interface, which makes it simple to get a + * complete picture of what commands an entity supports. + */ +public interface RegistrationCommand extends Jsonable { + + /** + * A command to register cargo. + *

+ * It has a reply type of {@link akka.Done}, which is sent back to the caller when all the events + * emitted by this command are successfully persisted. + */ + @Value.Immutable + @ImmutableStyle + @JsonDeserialize(as = RegisterCargo.class) + public interface AbstractRegisterCargo extends RegistrationCommand, CompressedJsonable, + PersistentEntity.ReplyType { + + @Value.Parameter + Cargo getCargo(); + } + +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEvent.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEvent.java new file mode 100644 index 000000000000..f0c01d4eabad --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEvent.java @@ -0,0 +1,40 @@ +package sample.cargotracker.registration.impl; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.javadsl.persistence.AggregateEvent; +import com.lightbend.lagom.javadsl.persistence.AggregateEventTag; +import com.lightbend.lagom.serialization.Jsonable; +import org.immutables.value.Value; +import org.immutables.value.Value.Immutable; +import sample.cargotracker.registration.api.Cargo; + +/** + * This interface defines all the events that the Cargo entity supports. + * + * By convention, the events should be inner classes of the interface, which makes it simple to get a + * complete picture of what events an entity has. + */ +public interface RegistrationEvent extends Jsonable , AggregateEvent { + + /** + * An event that represents a new cargo registration . + */ + @Immutable + @ImmutableStyle + @JsonDeserialize(as = CargoRegistered.class) + interface AbstractCargoRegistered extends RegistrationEvent { + + @Override + default public AggregateEventTag aggregateTag() { + return RegistrationEventTag.INSTANCE; + } + + + @Value.Parameter + String getId(); + + @Value.Parameter + Cargo getCargo(); + } +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEventTag.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEventTag.java new file mode 100644 index 000000000000..85504cc9c911 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationEventTag.java @@ -0,0 +1,13 @@ +package sample.cargotracker.registration.impl; + +import com.lightbend.lagom.javadsl.persistence.AggregateEventTag; + +/** + * Register a common event tag + */ +public class RegistrationEventTag { + + public static final AggregateEventTag INSTANCE = + AggregateEventTag.of(RegistrationEvent.class); + +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceImpl.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceImpl.java new file mode 100644 index 000000000000..77cb0db9fa82 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceImpl.java @@ -0,0 +1,138 @@ +package sample.cargotracker.registration.impl; + +import akka.Done; +import akka.NotUsed; +import akka.stream.javadsl.Source; +import com.google.inject.Inject; +import com.lightbend.lagom.javadsl.api.ServiceCall; +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef; +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry; +import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSide; +import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraSession; +import com.lightbend.lagom.javadsl.pubsub.PubSubRef; +import com.lightbend.lagom.javadsl.pubsub.PubSubRegistry; +import com.lightbend.lagom.javadsl.pubsub.TopicId; +import org.pcollections.PSequence; +import org.pcollections.TreePVector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sample.cargotracker.registration.api.Cargo; +import sample.cargotracker.registration.api.RegistrationService; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.stream.Collectors; + +/** + * Implementation of the RegistrationService. + * Look at circuit breaker information: http://localhost:25003/_status/circuit-breaker/current + */ +public class RegistrationServiceImpl implements RegistrationService { + + private final PersistentEntityRegistry persistentEntityRegistry; + private final PubSubRegistry topics; + private final CassandraSession db; + private final Logger log = LoggerFactory.getLogger(RegistrationServiceImpl.class); + + /** + * Constructor with the relevant infrastructure elements injected. + * + * @param topics + * @param persistentEntityRegistry + * @param readSide + * @param db + */ + @Inject + public RegistrationServiceImpl(PubSubRegistry topics, PersistentEntityRegistry persistentEntityRegistry, CassandraReadSide readSide, + CassandraSession db) { + this.persistentEntityRegistry = persistentEntityRegistry; + this.topics = topics; + this.db = db; + persistentEntityRegistry.register(CargoEntity.class); + readSide.register(CargoEventProcessor.class); + } + + /** + * Register Cargo service call + * + * @return + */ + @Override + public ServiceCall register() { + return (id, request) -> { + /* Publish received entity into topic named "Topic" */ + PubSubRef topic = topics.refFor(TopicId.of(Cargo.class, "topic")); + topic.publish(request); + log.info("Cargo ID: {}.", request.getId()); + /* Look up the Cargo entity for the given ID. */ + PersistentEntityRef ref = + persistentEntityRegistry.refFor(CargoEntity.class, request.getId()); + /* Tell the entity to use the Cargo information in the request. */ + return ref.ask(RegisterCargo.of(request)); + }; + } + + /** + * Get live registrations service call + * + * @return + */ + @Override + public ServiceCall> getLiveRegistrations() { + return (id, req) -> { + PubSubRef topic = topics.refFor(TopicId.of(Cargo.class, "topic")); + return CompletableFuture.completedFuture(topic.subscriber()); + }; + } + + + /** + * Get all persisted Cargo services call + * Websockets capable + * + * @return + * @deprecated + */ + public ServiceCall> getAllRegistrationsOld() { + log.info("Select all cargo ."); + return (id, req) -> { + Source result = db.select( + "SELECT cargoId, name, description, owner, destination FROM cargo;").map(row -> + Cargo.of(row.getString("cargoId"), + row.getString("name"), + row.getString("description"), + row.getString("owner"), + row.getString("destination"))); + return CompletableFuture.completedFuture(result); + + }; + } + + /** + * Get all registered Cargo + * + * @return + */ + @Override + public ServiceCall> getAllRegistrations() { + return (userId, req) -> { + CompletionStage> result = db.selectAll("SELECT cargoid, name, description, owner, destination FROM cargo") + .thenApply(rows -> { + List cargos = rows.stream().map(row -> Cargo.of(row.getString("cargoid"), + row.getString("name"), + row.getString("description"), + row.getString("owner"), + row.getString("destination"))).collect(Collectors.toList()); + return TreePVector.from(cargos); + }); + return result; + }; + } + + public ServiceCall getRegistration() { + + //TODO Implement meaningful + return null; + } +} diff --git a/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceModule.java b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceModule.java new file mode 100644 index 000000000000..bebc97db4cdd --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/java/sample/cargotracker/registration/impl/RegistrationServiceModule.java @@ -0,0 +1,15 @@ +package sample.cargotracker.registration.impl; + +import com.google.inject.AbstractModule; +import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; +import sample.cargotracker.registration.api.RegistrationService; + +/** + * The module that binds the RegistrationService so that it can be served. + */ +public class RegistrationServiceModule extends AbstractModule implements ServiceGuiceSupport { + @Override + protected void configure() { + bindServices(serviceBinding(RegistrationService.class, RegistrationServiceImpl.class)); + } +} diff --git a/lagom-cargotracker/registration-impl/src/main/resources/application.conf b/lagom-cargotracker/registration-impl/src/main/resources/application.conf new file mode 100644 index 000000000000..96cfb8673531 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/main/resources/application.conf @@ -0,0 +1 @@ +play.modules.enabled += sample.cargotracker.registration.impl.RegistrationServiceModule diff --git a/lagom-cargotracker/registration-impl/src/test/java/RegistrationServiceTest.java b/lagom-cargotracker/registration-impl/src/test/java/RegistrationServiceTest.java new file mode 100644 index 000000000000..90b6b0340fb4 --- /dev/null +++ b/lagom-cargotracker/registration-impl/src/test/java/RegistrationServiceTest.java @@ -0,0 +1,22 @@ + +import static com.lightbend.lagom.javadsl.testkit.ServiceTest.*; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import sample.cargotracker.registration.api.RegistrationService; + +/** + * Created by myfear on 03/04/16. + */ +public class RegistrationServiceTest { + + @Test + public void shouldSayHello() throws Exception { + withServer(defaultSetup(), server -> { + RegistrationService service = server.client(RegistrationService.class); + + //TODO add meaningfull test + }); + } + +} diff --git a/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/ErrorHandler.java b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/ErrorHandler.java new file mode 100644 index 000000000000..6a3bcfe4cce4 --- /dev/null +++ b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/ErrorHandler.java @@ -0,0 +1,69 @@ +package sample.cargotracker.shipping; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import play.Configuration; +import play.Environment; +import play.api.OptionalSourceMapper; +import play.api.UsefulException; +import play.api.routing.Router; +import play.http.DefaultHttpErrorHandler; +import play.libs.Json; +import play.mvc.Http; +import play.mvc.Result; +import play.mvc.Results; + +import javax.inject.Inject; +import javax.inject.Provider; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; + +/** + * Overrides the default HTTP error handler to return JSON + */ +public class ErrorHandler extends DefaultHttpErrorHandler { + + @Inject + public ErrorHandler(Configuration configuration, Environment environment, OptionalSourceMapper sourceMapper, Provider routes) { + super(configuration, environment, sourceMapper, routes); + } + + /** + * Invoked in dev mode when a server error occurs. + * + * @param request The request that triggered the error. + * @param exception The exception. + */ + protected CompletionStage onDevServerError(Http.RequestHeader request, UsefulException exception) { + + ObjectNode jsonError = Json.newObject(); + + final Throwable cause = exception.cause; + final String description = exception.description; + final String id = exception.id; + final String title = exception.title; + + jsonError.put("description", description); + jsonError.put("title", title); + jsonError.put("id", id); + jsonError.put("message", exception.getMessage()); + jsonError.set("cause", causesToJson(cause)); + + return CompletableFuture.completedFuture(Results.internalServerError(jsonError)); + } + + private ArrayNode causesToJson(Throwable throwable) { + ArrayNode causesNode = JsonNodeFactory.instance.arrayNode(); + + while (throwable != null) { + ObjectNode causeNode = causesNode.addObject(); + causeNode.put("message", throwable.getMessage()); + causeNode.put("type", throwable.getClass().getName()); + + throwable = throwable.getCause(); + } + + return causesNode; + } +} diff --git a/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractItinerary.java b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractItinerary.java new file mode 100644 index 000000000000..17bd377bc935 --- /dev/null +++ b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractItinerary.java @@ -0,0 +1,32 @@ +package sample.cargotracker.shipping.api; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; + +import java.util.List; + +import org.immutables.value.Value; + +import org.pcollections.PSequence; +import sample.cargotracker.shipping.api.Leg; + +@Value.Immutable +@ImmutableStyle +@JsonDeserialize(as = Itinerary.class) +public interface AbstractItinerary { + + @Value.Parameter + String getId(); + + @Value.Parameter + String getCargoId(); + + @Value.Parameter + String getOrigin(); + + @Value.Parameter + String getDestination(); + + @Value.Parameter + PSequence getLegs(); +} diff --git a/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractLeg.java b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractLeg.java new file mode 100644 index 000000000000..1ed653e17cb4 --- /dev/null +++ b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/AbstractLeg.java @@ -0,0 +1,29 @@ +package sample.cargotracker.shipping.api; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; + +import java.util.Date; + +import org.immutables.value.Value; + +@Value.Immutable +@ImmutableStyle +@JsonDeserialize(as = Leg.class) +public interface AbstractLeg { + + @Value.Parameter + String getId(); + + @Value.Parameter + String getCargoId(); + + @Value.Parameter + String getLocation(); + + @Value.Parameter + Date getArrivalTime(); + + @Value.Parameter + Date getDepartureTime(); +} diff --git a/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/ShippingService.java b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/ShippingService.java new file mode 100644 index 000000000000..73cabf2b5a5d --- /dev/null +++ b/lagom-cargotracker/shipping-api/src/main/java/sample/cargotracker/shipping/api/ShippingService.java @@ -0,0 +1,73 @@ +package sample.cargotracker.shipping.api; + +import static com.lightbend.lagom.javadsl.api.Service.named; +import static com.lightbend.lagom.javadsl.api.Service.restCall; + +import akka.Done; +import akka.NotUsed; +import com.lightbend.lagom.javadsl.api.Descriptor; +import com.lightbend.lagom.javadsl.api.Service; +import com.lightbend.lagom.javadsl.api.ServiceCall; +import com.lightbend.lagom.javadsl.api.transport.Method; + +/** + * The shipping service interface. + *

+ * This describes everything that Lagom needs to know about how to serve and consume the ShippingService. + */ +public interface ShippingService extends Service { + + /** + * Example: curl -H "Content-Type: application/json" -X POST -d + * '{ + * "itinerary": { + * "id": "1", + * "cargoId": "1", + * "origin": "Gothom City", + * "destination": "Metropolis", + * } + * }' http://localhost:9000/api/itinerary + */ + ServiceCall createItinerary(); + + /** + * Adds a leg to an existing itinerary. + * + * The String here is the itinerary id. + * + *

{@code curl -H "Content-Type: application/json" -X POST -d
+     * '{
+     *      "leg": {
+     *          "id": "1",
+     *          "cargoId": "cargoId",
+     *          "location": "derp",
+     *          "arrivalTime": arrivalTime,
+     *          "departureTime": departureTime
+     *      }
+     * }' http://localhost:9000/api/itinerary/1/leg
+     * }
+ */ + ServiceCall addLeg(); + + @Override + default Descriptor descriptor() { + // @formatter:off + return named("shippingService").with( + restCall(Method.POST, "/api/itinerary", createItinerary()).withAutoAcl(true), + restCall(Method.POST, "/api/itinerary/:itinerary/leg", addLeg()).withAutoAcl(true) + ); + // @formatter:on + + /* + { + "leg": { + "id": "1", + "cargoId": "cargoId", + "location": "derp", + "arrivalTime": "2002-05-30T09:30:10Z", + "departureTime": "2002-05-30T010:30:10Z" + } + } + */ + } +} diff --git a/lagom-cargotracker/shipping-api/src/main/resources/application.conf b/lagom-cargotracker/shipping-api/src/main/resources/application.conf new file mode 100644 index 000000000000..e0f7afc396bc --- /dev/null +++ b/lagom-cargotracker/shipping-api/src/main/resources/application.conf @@ -0,0 +1 @@ +play.http.errorHandler=sample.cargotracker.shipping.ErrorHandler diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/AbstractItineraryState.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/AbstractItineraryState.java new file mode 100644 index 000000000000..db06a44dee6b --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/AbstractItineraryState.java @@ -0,0 +1,56 @@ +package sample.cargotracker.shipping.impl; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.serialization.CompressedJsonable; +import java.util.List; +import java.time.LocalDateTime; +import org.immutables.value.Value; +import org.pcollections.PCollection; +import org.pcollections.PSequence; +import sample.cargotracker.shipping.api.Leg; + +/** + * The state for the itinerary entity. + */ +@Value.Immutable +@ImmutableStyle +@JsonDeserialize(as = ItineraryState.class) +public abstract class AbstractItineraryState implements CompressedJsonable { + + /** + * The itinerary id. + */ + @Value.Parameter + public abstract String getId(); + + /** + * The cargo id. + */ + @Value.Parameter + public abstract String getCargoId(); + + /** + * The cargo origin. + */ + @Value.Parameter + public abstract String getOrigin(); + + /** + * The cargo destination. + */ + @Value.Parameter + public abstract String getDestination(); + + /** + * The legs for the itinerary. + */ + @Value.Parameter + public abstract PSequence getLegs(); + + /** + * When the greeting last changed. + */ + @Value.Parameter + public abstract LocalDateTime getTimestamp(); +} diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ItineraryEntity.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ItineraryEntity.java new file mode 100644 index 000000000000..8e372bfe393e --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ItineraryEntity.java @@ -0,0 +1,107 @@ +package sample.cargotracker.shipping.impl; + +import com.lightbend.lagom.javadsl.persistence.PersistentEntity; +import java.time.LocalDateTime; +import java.util.Optional; + +import akka.Done; +import org.pcollections.PSequence; +import org.pcollections.TreePVector; +import sample.cargotracker.shipping.api.Leg; + +public class ItineraryEntity extends PersistentEntity { + /** + * An entity can define different behaviours for different states, but it will always start with an + * initial behaviour. This entity only has one behaviour. + */ + @Override + public Behavior initialBehavior(Optional snapshotState) { + + /* + * Behaviour is defined using a behaviour builder. The behaviour builder starts with a state, if this + * entity supports snapshotting (an optimisation that allows the state itself to be persisted to combine + * many events into one), then the passed in snapshotState may have a value that can be used. + * + * Otherwise, the default state is to use a dummy Cargo with and id of 0L.. + */ + BehaviorBuilder b = newBehaviorBuilder(snapshotState.orElse( + ItineraryState.builder() + .id("") + .cargoId("") + .origin("") + .destination("") + .legs(TreePVector.empty()) + .timestamp(LocalDateTime.now()).build())); + + /* + * Command handler for the create itinerary command. + */ + b.setCommandHandler(CreateItinerary.class, + (cmd, ctx) -> + // In response to this command, we want to first persist it as a itinerary created event + ctx.thenPersist( + ItineraryCreated.of( + cmd.getItinerary().getId(), + cmd.getItinerary().getCargoId(), + cmd.getItinerary().getOrigin(), + cmd.getItinerary().getDestination()), + // Then once the event is successfully persisted, we respond with done. + evt -> ctx.reply(Done.getInstance()) + ) + ); + + /* + * Command handler for the create itinerary command. + */ + b.setCommandHandler(AddLeg.class, + (cmd, ctx) -> + // In response to this command, we want to first persist it as a itinerary created event + ctx.thenPersist( + LegAdded.of( + cmd.getLeg().getId(), + cmd.getLeg().getCargoId(), + cmd.getLeg().getLocation(), + cmd.getLeg().getArrivalTime(), + cmd.getLeg().getDepartureTime()), + // Then once the event is successfully persisted, we respond with done. + evt -> ctx.reply(Done.getInstance()) + ) + ); + + /* + * Event handler for the itinerary created event. + */ + b.setEventHandler(LegAdded.class, + evt -> { + final Leg leg = Leg.builder() + .id(evt.getId()) + .cargoId(evt.getCargoId()) + .location(evt.getLocation()) + .arrivalTime(evt.getArrivalTime()) + .departureTime(evt.getDepartureTime()) + .build(); + return state().withLegs(state().getLegs().plus(leg)); + } + ); + + /* + * Event handler for the itinerary created event. + */ + b.setEventHandler(ItineraryCreated.class, + // We simply update the current state to use the greeting message from the event. + evt -> state() + .withId(evt.getId()) + .withCargoId(evt.getCargoId()) + .withOrigin(evt.getOrigin()) + .withDestination(evt.getDestination()) + .withTimestamp(LocalDateTime.now()) + ); + + /* + * We've defined all our behaviour, so build and return it. + */ + return b.build(); + } + + +} diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingCommand.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingCommand.java new file mode 100644 index 000000000000..579f21d35e48 --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingCommand.java @@ -0,0 +1,49 @@ +package sample.cargotracker.shipping.impl; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.javadsl.persistence.PersistentEntity; +import com.lightbend.lagom.serialization.CompressedJsonable; +import com.lightbend.lagom.serialization.Jsonable; +import java.util.Optional; +import org.immutables.value.Value; + +import sample.cargotracker.shipping.api.Itinerary; + +import akka.Done; +import sample.cargotracker.shipping.api.Leg; + +/** + * This interface defines all the commands that the Itinerary entity supports. + * + * By convention, the commands should be inner classes of the interface, which makes it simple to get a + * complete picture of what commands an entity supports. + */ +public interface ShippingCommand extends Jsonable { + + /** + * A command to create an itinerary. + * + * It has a reply type of {@link akka.Done}, which is sent back to the caller when all the events + * emitted by this command are successfully persisted. + */ + @Value.Immutable + @ImmutableStyle + @JsonDeserialize(as = CreateItinerary.class) + public interface AbstractCreateItinerary extends ShippingCommand, CompressedJsonable, + PersistentEntity.ReplyType { + + @Value.Parameter + Itinerary getItinerary(); + } + + @Value.Immutable + @ImmutableStyle + @JsonDeserialize(as = AddLeg.class) + public interface AbstractAddLeg extends ShippingCommand, CompressedJsonable, + PersistentEntity.ReplyType { + + @Value.Parameter + Leg getLeg(); + } +} diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingEvent.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingEvent.java new file mode 100644 index 000000000000..75e12b3aa29b --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingEvent.java @@ -0,0 +1,63 @@ +package sample.cargotracker.shipping.impl; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.lightbend.lagom.javadsl.immutable.ImmutableStyle; +import com.lightbend.lagom.serialization.Jsonable; +import org.immutables.value.Value; +import org.immutables.value.Value.Immutable; + +import java.util.Date; + +/** + * This interface defines all the events that the Shipping entity supports. + * + * By convention, the events should be inner classes of the interface, which makes it simple to get a + * complete picture of what events an entity has. + */ +public interface ShippingEvent extends Jsonable { + + /** + * An event that represents a new shipping itinerary. + */ + @Immutable + @ImmutableStyle + @JsonDeserialize(as = ItineraryCreated.class) + interface AbstractItineraryCreated extends ShippingEvent { + + @Value.Parameter + String getId(); + + @Value.Parameter + String getCargoId(); + + @Value.Parameter + String getOrigin(); + + @Value.Parameter + String getDestination(); + } + + /** + * An event that represents a leg being added. + */ + @Immutable + @ImmutableStyle + @JsonDeserialize(as = LegAdded.class) + interface AbstractLegAdded extends ShippingEvent { + + @Value.Parameter + String getId(); + + @Value.Parameter + String getCargoId(); + + @Value.Parameter + String getLocation(); + + @Value.Parameter + Date getArrivalTime(); + + @Value.Parameter + Date getDepartureTime(); + } +} diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceImpl.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceImpl.java new file mode 100644 index 000000000000..4bf53ba3433f --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceImpl.java @@ -0,0 +1,53 @@ +package sample.cargotracker.shipping.impl; + +import akka.Done; +import akka.NotUsed; +import com.lightbend.lagom.javadsl.api.ServiceCall; +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef; +import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry; +import javax.inject.Inject; + +import sample.cargotracker.registration.api.Cargo; +import sample.cargotracker.registration.api.RegistrationService; +import sample.cargotracker.shipping.api.Itinerary; +import sample.cargotracker.shipping.api.Leg; +import sample.cargotracker.shipping.api.ShippingService; + +import java.util.concurrent.CompletionStage; + +/** + * Implementation of the ShippingService. + */ +public class ShippingServiceImpl implements ShippingService { + + private final PersistentEntityRegistry persistentEntityRegistry; + private final RegistrationService registrationService; + + @Inject + public ShippingServiceImpl(PersistentEntityRegistry persistentEntityRegistry, RegistrationService registrationService) { + this.persistentEntityRegistry = persistentEntityRegistry; + this.registrationService = registrationService; + persistentEntityRegistry.register(ItineraryEntity.class); + } + + @Override + public ServiceCall addLeg() { + return (id, request) -> { + CompletionStage response = registrationService.getRegistration().invoke(request.getCargoId(), NotUsed.getInstance()); + PersistentEntityRef itinerary = persistentEntityRegistry.refFor(ItineraryEntity.class, id); + return itinerary.ask(AddLeg.of(request)); + }; + } + + @Override + public ServiceCall createItinerary() { + return (id, request) -> { + // Look up the itinerary for the given ID. + PersistentEntityRef itinerary = + persistentEntityRegistry.refFor(ItineraryEntity.class, request.getId()); + // Tell the entity to use the greeting message specified. + return itinerary.ask(CreateItinerary.of(request)); + }; + } + +} diff --git a/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceModule.java b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceModule.java new file mode 100644 index 000000000000..0de7ae842472 --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/java/sample/cargotracker/shipping/impl/ShippingServiceModule.java @@ -0,0 +1,17 @@ +package sample.cargotracker.shipping.impl; + +import com.google.inject.AbstractModule; +import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; +import sample.cargotracker.registration.api.RegistrationService; +import sample.cargotracker.shipping.api.ShippingService; + +/** + * The module that binds the ShippingService so that it can be served. + */ +public class ShippingServiceModule extends AbstractModule implements ServiceGuiceSupport { + @Override + protected void configure() { + bindServices(serviceBinding(ShippingService.class, ShippingServiceImpl.class)); + bindClient(RegistrationService.class); + } +} diff --git a/lagom-cargotracker/shipping-impl/src/main/resources/application.conf b/lagom-cargotracker/shipping-impl/src/main/resources/application.conf new file mode 100644 index 000000000000..c6154749372c --- /dev/null +++ b/lagom-cargotracker/shipping-impl/src/main/resources/application.conf @@ -0,0 +1 @@ +play.modules.enabled += sample.cargotracker.shipping.impl.ShippingServiceModule