├── .env ├── .gitignore ├── LICENSE ├── README.md ├── auth-service ├── Dockerfile ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── authservice │ │ │ └── AuthServiceApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── authservice │ ├── AuthServiceApplicationTests.java │ └── IntegrationTests.java ├── docker-compose.local.yml ├── docker-compose.yml ├── docker-entrypoint-initdb.d └── init.cql ├── eureka-server ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ └── EurekaServerApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── EurekaServerApplicationTests.java ├── favorite-service ├── Dockerfile ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── favoriteservice │ │ │ └── FavoriteServiceApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── favoriteservice │ └── FavoriteServiceApplicationTests.java ├── gateway-kotlin ├── pom.xml └── src │ ├── main │ ├── kotlin │ │ └── com │ │ │ └── example │ │ │ └── gateway │ │ │ └── GatewayApplication.kt │ └── resources │ │ └── application.properties │ └── test │ └── kotlin │ └── com │ └── example │ └── gateway │ └── GatewayApplicationTests.kt ├── gateway ├── Dockerfile ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── gateway │ │ │ └── GatewayApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── gateway │ └── GatewayApplicationTests.java ├── pom.xml ├── post-service ├── Dockerfile ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── Comment.java │ │ │ ├── CommentHandler.java │ │ │ ├── CommentRepository.java │ │ │ ├── DataInitializer.java │ │ │ ├── Post.java │ │ │ ├── PostHandler.java │ │ │ ├── PostRepository.java │ │ │ ├── PostServiceApplication.java │ │ │ ├── Slug.java │ │ │ ├── Username.java │ │ │ └── Utils.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── demo │ ├── PostServiceApplicationTests.java │ └── SlugifyTest.java └── vbox-ports-forward.sh /.env: -------------------------------------------------------------------------------- 1 | # env for docker compose, https://docs.docker.com/compose/env-file/ 2 | COMPOSE_CONVERT_WINDOWS_PATHS=1 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | nbproject/private/ 21 | build/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ 26 | 27 | # Compiled class file 28 | *.class 29 | 30 | # Log file 31 | *.log 32 | 33 | # BlueJ files 34 | *.ctxt 35 | 36 | # Mobile Tools for Java (J2ME) 37 | .mtj.tmp/ 38 | 39 | # Package Files # 40 | *.jar 41 | *.war 42 | *.ear 43 | *.zip 44 | *.tar.gz 45 | *.rar 46 | 47 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 48 | hs_err_pid* 49 | 50 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-reactive-microservice-sample 2 | Spring Microservice Demo built with Spring 5 Reactive features 3 | -------------------------------------------------------------------------------- /auth-service/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM frolvlad/alpine-oraclejdk8:slim 2 | VOLUME /tmp 3 | ADD ./target/auth-service-0.0.1-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] 7 | -------------------------------------------------------------------------------- /auth-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | auth-service 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | auth-service 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | Finchley.SR1 25 | 1.8 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-cassandra-reactive 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-redis-reactive 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | org.springframework.session 43 | spring-session-data-redis 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-webflux 48 | 49 | 50 | 51 | org.springframework.cloud 52 | spring-cloud-starter-netflix-eureka-client 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.projectlombok 63 | lombok 64 | true 65 | 66 | 67 | org.slf4j 68 | slf4j-api 69 | 70 | 71 | org.slf4j 72 | jcl-over-slf4j 73 | 74 | 75 | ch.qos.logback 76 | logback-core 77 | 78 | 79 | ch.qos.logback 80 | logback-classic 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-starter-test 85 | test 86 | 87 | 88 | io.projectreactor 89 | reactor-test 90 | test 91 | 92 | 93 | org.springframework.security 94 | spring-security-test 95 | test 96 | 97 | 98 | 99 | 100 | 101 | org.springframework.cloud 102 | spring-cloud-dependencies 103 | ${spring-cloud.version} 104 | pom 105 | import 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | org.springframework.boot 114 | spring-boot-maven-plugin 115 | 116 | 117 | 118 | 119 | 120 | docker 121 | 122 | 123 | 124 | io.netty 125 | netty-transport-native-epoll 126 | 4.1.17.Final 127 | linux-x86_64 128 | 129 | 130 | 131 | 132 | 133 | 134 | spring-snapshots 135 | Spring Snapshots 136 | https://repo.spring.io/snapshot 137 | 138 | true 139 | 140 | 141 | 142 | spring-milestones 143 | Spring Milestones 144 | https://repo.spring.io/milestone 145 | 146 | false 147 | 148 | 149 | 150 | 151 | 152 | 153 | spring-snapshots 154 | Spring Snapshots 155 | https://repo.spring.io/snapshot 156 | 157 | true 158 | 159 | 160 | 161 | spring-milestones 162 | Spring Milestones 163 | https://repo.spring.io/milestone 164 | 165 | false 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /auth-service/src/main/java/com/example/authservice/AuthServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.authservice; 2 | 3 | import lombok.*; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.boot.context.event.ApplicationReadyEvent; 9 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.event.EventListener; 13 | import org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration; 14 | import org.springframework.data.cassandra.config.SchemaAction; 15 | import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification; 16 | import org.springframework.data.cassandra.core.cql.keyspace.DropKeyspaceSpecification; 17 | import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption; 18 | import org.springframework.data.cassandra.core.mapping.PrimaryKey; 19 | import org.springframework.data.cassandra.core.mapping.Table; 20 | import org.springframework.data.cassandra.repository.Query; 21 | import org.springframework.data.cassandra.repository.ReactiveCassandraRepository; 22 | import org.springframework.http.HttpMethod; 23 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 24 | import org.springframework.security.authorization.AuthorizationDecision; 25 | import org.springframework.security.config.web.server.ServerHttpSecurity; 26 | import org.springframework.security.core.Authentication; 27 | import org.springframework.security.core.authority.AuthorityUtils; 28 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 29 | import org.springframework.security.core.userdetails.ReactiveUserDetailsService; 30 | import org.springframework.security.core.userdetails.UserDetails; 31 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 32 | import org.springframework.security.crypto.factory.PasswordEncoderFactories; 33 | import org.springframework.security.crypto.password.PasswordEncoder; 34 | import org.springframework.security.web.server.SecurityWebFilterChain; 35 | import org.springframework.security.web.server.authorization.AuthorizationContext; 36 | import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; 37 | import org.springframework.stereotype.Component; 38 | import org.springframework.web.reactive.function.BodyInserters; 39 | import org.springframework.web.reactive.function.server.RouterFunction; 40 | import org.springframework.web.reactive.function.server.ServerRequest; 41 | import org.springframework.web.reactive.function.server.ServerResponse; 42 | import org.springframework.web.server.WebSession; 43 | import org.springframework.web.server.session.HeaderWebSessionIdResolver; 44 | import org.springframework.web.server.session.WebSessionIdResolver; 45 | import reactor.core.publisher.Flux; 46 | import reactor.core.publisher.Mono; 47 | 48 | import java.util.*; 49 | 50 | import static java.util.stream.Collectors.toList; 51 | import static org.springframework.web.reactive.function.server.RequestPredicates.DELETE; 52 | import static org.springframework.web.reactive.function.server.RequestPredicates.GET; 53 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 54 | import static org.springframework.web.reactive.function.server.ServerResponse.badRequest; 55 | import static org.springframework.web.reactive.function.server.ServerResponse.noContent; 56 | import static org.springframework.web.reactive.function.server.ServerResponse.ok; 57 | 58 | 59 | @SpringBootApplication 60 | @EnableDiscoveryClient 61 | public class AuthServiceApplication { 62 | 63 | public static void main(String[] args) { 64 | SpringApplication.run(AuthServiceApplication.class, args); 65 | } 66 | 67 | @Bean 68 | public PasswordEncoder passwordEncoder() { 69 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 70 | } 71 | 72 | @Bean 73 | WebSessionIdResolver webSessionIdResolver() { 74 | HeaderWebSessionIdResolver webSessionIdResolver = new HeaderWebSessionIdResolver(); 75 | webSessionIdResolver.setHeaderName("X-AUTH-TOKEN"); 76 | return webSessionIdResolver; 77 | } 78 | 79 | @Bean 80 | SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { 81 | return http 82 | .csrf().disable() 83 | .httpBasic().securityContextRepository(new WebSessionServerSecurityContextRepository()) 84 | .and() 85 | .authorizeExchange() 86 | .pathMatchers(HttpMethod.GET, "/users/exists").permitAll() 87 | .pathMatchers("/session").authenticated() 88 | .pathMatchers("/users/{user}/**").access(this::currentUserMatchesPath) 89 | .anyExchange().authenticated() 90 | .and() 91 | .build(); 92 | } 93 | 94 | private Mono currentUserMatchesPath(Mono authentication, AuthorizationContext context) { 95 | return authentication 96 | .map((a) -> context.getVariables().get("user").equals(a.getName())) 97 | .map(AuthorizationDecision::new); 98 | } 99 | 100 | @Bean 101 | public ReactiveUserDetailsService userDetailsRepository(UserRepository users) { 102 | return (username) -> users 103 | .findByUsername(username) 104 | .map(user -> org.springframework.security.core.userdetails.User 105 | .withUsername(user.getUsername()) 106 | .password(user.getPassword()) 107 | .roles(user.getRoles().toArray(new String[0])) 108 | .disabled(!user.isActive()) 109 | .accountLocked(!user.isActive()) 110 | .credentialsExpired(!user.isActive()) 111 | .accountExpired(!user.isActive()) 112 | .build() 113 | 114 | ); 115 | } 116 | 117 | @Bean 118 | public RouterFunction routes( 119 | UserHandler userHandler) { 120 | return route(GET("/session"), userHandler::current) 121 | .andRoute(DELETE("/session"), userHandler::logout) 122 | .andRoute(GET("/users/exists"), userHandler::exists); 123 | } 124 | } 125 | 126 | 127 | @Component 128 | class UserHandler { 129 | 130 | private final UserRepository users; 131 | 132 | public UserHandler(UserRepository users) { 133 | this.users = users; 134 | } 135 | 136 | public Mono current(ServerRequest req) { 137 | return req.principal() 138 | .cast(UsernamePasswordAuthenticationToken.class) 139 | .map(u -> u.getPrincipal()) 140 | .cast(UserDetails.class) 141 | .map( 142 | user -> { 143 | Map map = new HashMap<>(); 144 | map.put("username", user.getUsername()); 145 | map.put("roles", AuthorityUtils.authorityListToSet(user.getAuthorities())); 146 | return map; 147 | } 148 | ) 149 | .flatMap((user) -> ok().body(BodyInserters.fromObject(user))); 150 | } 151 | 152 | public Mono logout(ServerRequest req) { 153 | return req.session() 154 | .flatMap(WebSession::invalidate) 155 | .flatMap(v-> noContent().build()); 156 | } 157 | 158 | public Mono exists(ServerRequest req) { 159 | 160 | Mono emailExists = Mono.justOrEmpty(req.queryParam("email")) 161 | .flatMap(email -> this.users.findByEmail(email) 162 | .flatMap(user -> ok().syncBody(Collections.singletonMap("exists", true))) 163 | .switchIfEmpty(ok().syncBody(Collections.singletonMap("exists", false))) 164 | ) 165 | .switchIfEmpty(badRequest().syncBody(Collections.singletonMap("error", "request param username or email is required."))); 166 | 167 | return Mono.justOrEmpty(req.queryParam("username")) 168 | .flatMap(name -> this.users.findByUsername(name) 169 | .flatMap(user -> ok().syncBody(Collections.singletonMap("exists", true))) 170 | .switchIfEmpty(ok().syncBody(Collections.singletonMap("exists", false))) 171 | ) 172 | .switchIfEmpty(emailExists); 173 | } 174 | } 175 | 176 | @Component 177 | @Slf4j 178 | class DataInitializer { 179 | 180 | private final UserRepository users; 181 | private final PasswordEncoder passwordEncoder; 182 | 183 | public DataInitializer(UserRepository users, PasswordEncoder passwordEncoder) { 184 | this.users = users; 185 | this.passwordEncoder = passwordEncoder; 186 | } 187 | 188 | @EventListener(value = ApplicationReadyEvent.class) 189 | private void init() { 190 | log.info("start users initialization ..."); 191 | this.users 192 | .deleteAll() 193 | .thenMany( 194 | Flux 195 | .just("user", "admin") 196 | .flatMap( 197 | username -> { 198 | List roles = "user".equals(username) 199 | ? Arrays.asList("USER") 200 | : Arrays.asList("USER", "ADMIN"); 201 | 202 | User user = User.builder().roles(roles).email(username + "@example.com").username(username).password(this.passwordEncoder.encode("password")).build(); 203 | return this.users.save(user); 204 | } 205 | ) 206 | ) 207 | .log() 208 | .subscribe( 209 | null, 210 | null, 211 | () -> log.info("done users initialization...") 212 | ); 213 | } 214 | 215 | } 216 | 217 | 218 | interface UserRepository extends ReactiveCassandraRepository { 219 | Mono findByUsername(String username); 220 | 221 | // NOTE, be very careful about ALLOW FILTERING in real world apps, this 222 | // may affect scalability quite a lot. Filtering is efficient over primary 223 | // keys, not on all generic columns 224 | @Query("SELECT * FROM users WHERE email = ?0 ALLOW FILTERING") 225 | Mono findByEmail(String email); 226 | } 227 | // @Component 228 | // class UserRepository{ 229 | // private final ReactiveCassandraTemplate template; 230 | // 231 | // public UserRepository(ReactiveCassandraTemplate template) { 232 | // this.template = template; 233 | // } 234 | // 235 | // public Mono findByUsername(String username) { 236 | // return this.template 237 | // .selectOne( 238 | // query(where("username").is(username)), 239 | // User.class 240 | // ); 241 | // } 242 | // 243 | // public Mono findByEmail(String email) { 244 | // return this.template 245 | // .selectOne( 246 | // query(where("email").is(email)), 247 | // User.class 248 | // ); 249 | // } 250 | // 251 | // public Mono save(User user) { 252 | // return this.template.insert(user); 253 | // } 254 | // 255 | // public Mono deleteAll() { 256 | // return this.template.delete(Query.empty(), User.class); 257 | // } 258 | //} 259 | 260 | @Data 261 | @ToString 262 | @Builder 263 | @NoArgsConstructor 264 | @AllArgsConstructor 265 | @Table("users") 266 | class User { 267 | 268 | @PrimaryKey 269 | private String username; 270 | private String password; 271 | 272 | private String email; 273 | 274 | @Builder.Default 275 | private boolean active = true; 276 | @Builder.Default 277 | private List roles = new ArrayList<>(); 278 | 279 | } 280 | 281 | -------------------------------------------------------------------------------- /auth-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | spring.application.name=auth-service 3 | spring.data.cassandra.keyspace-name=demo 4 | spring.data.cassandra.schema-action=RECREATE 5 | 6 | logging.level.org.springframework.web=DEBUG 7 | logging.level.org.springframework.security=DEBUG 8 | -------------------------------------------------------------------------------- /auth-service/src/test/java/com/example/authservice/AuthServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.authservice; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.security.test.context.support.WithMockUser; 10 | import org.springframework.security.web.server.WebFilterChainProxy; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.test.web.reactive.server.WebTestClient; 13 | import org.springframework.web.reactive.function.server.RouterFunction; 14 | 15 | import java.util.Map; 16 | import java.util.function.Consumer; 17 | 18 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser; 19 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; 20 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.Credentials.basicAuthenticationCredentials; 21 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 25 | public class AuthServiceApplicationTests { 26 | 27 | @Autowired 28 | RouterFunction routerFunction; 29 | @Autowired 30 | WebFilterChainProxy springSecurityFilterChain; 31 | 32 | WebTestClient client; 33 | 34 | @Before 35 | public void setup() { 36 | this.client = WebTestClient 37 | .bindToRouterFunction(this.routerFunction) 38 | .webFilter(this.springSecurityFilterChain) 39 | .apply(springSecurity()) 40 | .configureClient() 41 | .filter(basicAuthentication()) 42 | .build(); 43 | } 44 | 45 | @Test 46 | public void getUserInfoWithoutAuthWillReturn401(){ 47 | client 48 | .get() 49 | .uri("/user") 50 | .exchange() 51 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 52 | } 53 | 54 | @Test 55 | public void getUserInfoWithInvalidAuthWillReturn401(){ 56 | client 57 | .get() 58 | .uri("/user") 59 | .attributes(invalidCredentials()) 60 | .exchange() 61 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 62 | } 63 | 64 | 65 | @Test 66 | @WithMockUser 67 | public void getUserInfoWithAuthWillBeOk(){ 68 | client 69 | .get() 70 | .uri("/user") 71 | .exchange() 72 | .expectStatus().isEqualTo(HttpStatus.OK); 73 | } 74 | 75 | @Test 76 | public void getUserInfoWithAuthWillBeOk2(){ 77 | client 78 | .mutateWith(mockUser()) 79 | .get() 80 | .uri("/user") 81 | .exchange() 82 | .expectStatus().isEqualTo(HttpStatus.OK); 83 | } 84 | 85 | @Test 86 | public void getUserInfoWithAuthWillBeOk3(){ 87 | client 88 | .get() 89 | .uri("/user") 90 | .attributes(userCredentials()) 91 | .exchange() 92 | .expectStatus().isEqualTo(HttpStatus.OK); 93 | } 94 | 95 | private Consumer> userCredentials() { 96 | return basicAuthenticationCredentials("user", "password"); 97 | } 98 | 99 | private Consumer> invalidCredentials() { 100 | return basicAuthenticationCredentials("user", "INVALID"); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /auth-service/src/test/java/com/example/authservice/IntegrationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.authservice; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.web.server.LocalServerPort; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | import org.springframework.test.web.reactive.server.WebTestClient; 11 | 12 | import java.time.Duration; 13 | import java.util.Map; 14 | import java.util.function.Consumer; 15 | 16 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.Credentials.basicAuthenticationCredentials; 17 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication; 18 | 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 21 | public class IntegrationTests { 22 | 23 | @LocalServerPort 24 | int port; 25 | 26 | WebTestClient client; 27 | 28 | @Before 29 | public void setup() { 30 | this.client = WebTestClient.bindToServer() 31 | .responseTimeout(Duration.ofDays(1)) 32 | .baseUrl("http://localhost:" + this.port) 33 | .filter(basicAuthentication()) 34 | .build(); 35 | } 36 | 37 | @Test 38 | public void getUserInfoWithoutAuthWillReturn401() { 39 | client 40 | .get() 41 | .uri("/user") 42 | .exchange() 43 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 44 | } 45 | 46 | @Test 47 | public void getUserInfoWithInvalidCredentialsWillReturn401() { 48 | client 49 | .get() 50 | .uri("/user") 51 | .attributes(invalidCredentials()) 52 | .exchange() 53 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 54 | } 55 | 56 | @Test 57 | public void getUserInfoWithValidBasicAuthWillBeOk() { 58 | client 59 | .mutate().filter(basicAuthentication("user", "password")).build() 60 | .get() 61 | .uri("/user") 62 | .exchange() 63 | .expectStatus().isEqualTo(HttpStatus.OK); 64 | } 65 | 66 | 67 | @Test 68 | public void getUserInfoWithUserCredentialsWillBeOk() { 69 | client 70 | .get() 71 | .uri("/user") 72 | .attributes(userCredentials()) 73 | .exchange() 74 | .expectStatus().isEqualTo(HttpStatus.OK); 75 | } 76 | 77 | private Consumer> userCredentials() { 78 | return basicAuthenticationCredentials("user", "password"); 79 | } 80 | 81 | private Consumer> invalidCredentials() { 82 | return basicAuthenticationCredentials("user", "INVALID"); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /docker-compose.local.yml: -------------------------------------------------------------------------------- 1 | version: '3.3' # specify docker-compose version 2 | 3 | services: 4 | 5 | gateway: 6 | image: hantsy/gateway 7 | container_name: gateway 8 | build: 9 | context: ./gateway 10 | dockerfile: Dockerfile 11 | environment: 12 | AUTH_SERVICE_URL: http://auth-service:8081 13 | POST_SERVICE_URL: http://post-service:8082 14 | FAVORITE_SERVICE_URL: http://favorite-service:8083 15 | depends_on: 16 | - auth-service 17 | - post-service 18 | - favorite-service 19 | ports: 20 | - "8000:8000" 21 | 22 | auth-service: 23 | image: hantsy/auth-service 24 | container_name: auth-service 25 | build: 26 | context: ./auth-service # specify the directory of the Dockerfile 27 | dockerfile: Dockerfile 28 | environment: 29 | SPRING_DATA_CASSANDRA_CONTACT_POINTS: cassandra # Comma-separated list of cluster node addresses. 30 | SPRING_DATA_CASSANDRA_KEYSPACE_NAME: demo # Keyspace name to use. 31 | SPRING_REDIS_URL: redis://redis:6379 32 | ports: 33 | - "8081:8081" #specify ports forewarding 34 | depends_on: 35 | - cassandra 36 | - redis 37 | 38 | post-service: 39 | image: hantsy/post-service 40 | container_name: post-service 41 | build: 42 | context: ./post-service 43 | dockerfile: Dockerfile 44 | environment: 45 | SPRING_DATA_MONGODB_URI: mongodb://mongodb:27017/posts 46 | SPRING_REDIS_URL: redis://redis:6379 47 | ports: 48 | - "8082:8082" #specify ports forewarding 49 | depends_on: 50 | - mongodb 51 | - redis 52 | 53 | favorite-service: 54 | image: hantsy/favorite-service 55 | container_name: favorite-service 56 | build: 57 | context: ./favorite-service # specify the directory of the Dockerfile 58 | dockerfile: Dockerfile 59 | environment: 60 | SPRING_REDIS_URL: redis://redis:6379 61 | ports: 62 | - "8083:8083" #specify ports forewarding 63 | depends_on: 64 | - redis 65 | 66 | 67 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.3' # specify docker-compose version 2 | 3 | # Define the services/containers to be run 4 | services: 5 | rabbitmq: 6 | image: rabbitmq:management 7 | ports: 8 | - "5672:5672" 9 | - "15672:15672" 10 | # https://github.com/docker-library/cassandra/issues/104#issuecomment-383211480 11 | cassandra: 12 | image: cassandra 13 | ports: 14 | # 7000: intra-node communication 15 | # 7001: TLS intra-node communication 16 | # 7199: JMX 17 | # 9042: CQL 18 | # 9160: thrift service 19 | - "9042:9042" 20 | # environment: 21 | # CASSANDRA_KEYSPACE: demo 22 | volumes: 23 | - cassandradata:/var/lib/cassandra 24 | #- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d 25 | # command: /cassandra-init.sh 26 | 27 | redis: 28 | image: redis 29 | ports: 30 | - "6379:6379" 31 | 32 | mongodb: 33 | image: mongo 34 | volumes: 35 | - mongodata:/data/db 36 | ports: 37 | - "27017:27017" 38 | command: --smallfiles #--rest 39 | # command: --smallfiles --rest --auth // if there is a password set in mongo. 40 | 41 | volumes: 42 | mongodata: 43 | # driver: local-persist 44 | # driver_opts: 45 | # mountpoint: ./data/mongodb 46 | cassandradata: 47 | -------------------------------------------------------------------------------- /docker-entrypoint-initdb.d/init.cql: -------------------------------------------------------------------------------- 1 | CREATE KEYSPACE IF NOT EXISTS demo WITH replication = {'class':'SimpleStrategy','replication_factor':'1'}; 2 | -------------------------------------------------------------------------------- /eureka-server/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /eureka-server/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hantsy/spring-reactive-microservice-sample/154f9412d530bb966ad956734a32c49d8da161d2/eureka-server/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /eureka-server/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /eureka-server/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /eureka-server/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /eureka-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | eureka-server 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | eureka-server 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.SR1 26 | 27 | 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-starter-netflix-eureka-server 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-test 37 | test 38 | 39 | 40 | 41 | 42 | 43 | 44 | org.springframework.cloud 45 | spring-cloud-dependencies 46 | ${spring-cloud.version} 47 | pom 48 | import 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /eureka-server/src/main/java/com/example/demo/EurekaServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | @SpringBootApplication 8 | @EnableEurekaServer 9 | public class EurekaServerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(EurekaServerApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /eureka-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8761 3 | spring: 4 | application: 5 | name: eureka 6 | eureka: 7 | client: 8 | register-with-eureka: false 9 | -------------------------------------------------------------------------------- /eureka-server/src/test/java/com/example/demo/EurekaServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.cloud.client.discovery.DiscoveryClient; 8 | import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; 9 | import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.test.context.web.WebAppConfiguration; 12 | 13 | import static org.junit.Assert.assertTrue; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | @WebAppConfiguration 18 | public class EurekaServerApplicationTests { 19 | 20 | @Autowired 21 | DiscoveryClient discoveryClient; 22 | 23 | @Test 24 | public void contextLoads() { 25 | } 26 | 27 | @Test 28 | public void discoveryClientIsEureka() { 29 | assertTrue("discoveryClient is wrong type " + discoveryClient.getClass(), discoveryClient instanceof CompositeDiscoveryClient); 30 | CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) discoveryClient; 31 | assertTrue("composite discovery client should be composed of Eureka and Simple Discovery client's" 32 | , compositeDiscoveryClient.getDiscoveryClients().size() == 2); 33 | 34 | assertTrue("the composed discovery client should have a EurekaDiscoveryClient with a higher precedence ", 35 | compositeDiscoveryClient.getDiscoveryClients().get(0) instanceof EurekaDiscoveryClient); 36 | } 37 | 38 | 39 | } -------------------------------------------------------------------------------- /favorite-service/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM frolvlad/alpine-oraclejdk8:slim 2 | VOLUME /tmp 3 | ADD ./target/favorite-service-0.0.1-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] -------------------------------------------------------------------------------- /favorite-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | favorite-service 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | favorite-service 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | Finchley.SR1 25 | 1.8 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-webflux 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-data-redis-reactive 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-security 41 | 42 | 43 | org.springframework.session 44 | spring-session-data-redis 45 | 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-starter-netflix-eureka-client 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.slf4j 60 | slf4j-api 61 | 62 | 63 | org.slf4j 64 | jcl-over-slf4j 65 | 66 | 67 | ch.qos.logback 68 | logback-core 69 | 70 | 71 | ch.qos.logback 72 | logback-classic 73 | 74 | 75 | org.springframework.boot 76 | spring-boot-starter-test 77 | test 78 | 79 | 80 | io.projectreactor 81 | reactor-test 82 | test 83 | 84 | 85 | org.springframework.security 86 | spring-security-test 87 | test 88 | 89 | 90 | 91 | 92 | 93 | org.springframework.cloud 94 | spring-cloud-dependencies 95 | ${spring-cloud.version} 96 | pom 97 | import 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | org.springframework.boot 106 | spring-boot-maven-plugin 107 | 108 | 109 | 110 | 111 | 112 | 113 | spring-snapshots 114 | Spring Snapshots 115 | https://repo.spring.io/snapshot 116 | 117 | true 118 | 119 | 120 | 121 | spring-milestones 122 | Spring Milestones 123 | https://repo.spring.io/milestone 124 | 125 | false 126 | 127 | 128 | 129 | 130 | 131 | 132 | spring-snapshots 133 | Spring Snapshots 134 | https://repo.spring.io/snapshot 135 | 136 | true 137 | 138 | 139 | 140 | spring-milestones 141 | Spring Milestones 142 | https://repo.spring.io/milestone 143 | 144 | false 145 | 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /favorite-service/src/main/java/com/example/favoriteservice/FavoriteServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.favoriteservice; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.data.domain.Range; 9 | import org.springframework.data.redis.connection.ReactiveRedisConnection; 10 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.security.config.web.server.ServerHttpSecurity; 13 | import org.springframework.security.web.server.SecurityWebFilterChain; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.reactive.function.BodyInserters; 16 | import org.springframework.web.reactive.function.server.RouterFunction; 17 | import org.springframework.web.reactive.function.server.ServerRequest; 18 | import org.springframework.web.reactive.function.server.ServerResponse; 19 | import org.springframework.web.server.session.HeaderWebSessionIdResolver; 20 | import org.springframework.web.server.session.WebSessionIdResolver; 21 | import reactor.core.publisher.Mono; 22 | 23 | import java.nio.ByteBuffer; 24 | import java.util.Collections; 25 | 26 | import static org.springframework.web.reactive.function.server.RequestPredicates.*; 27 | import static org.springframework.web.reactive.function.server.RouterFunctions.nest; 28 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 29 | import static org.springframework.web.reactive.function.server.ServerResponse.noContent; 30 | import static org.springframework.web.reactive.function.server.ServerResponse.ok; 31 | 32 | @SpringBootApplication 33 | @EnableDiscoveryClient 34 | public class FavoriteServiceApplication { 35 | 36 | public static void main(String[] args) { 37 | SpringApplication.run(FavoriteServiceApplication.class, args); 38 | } 39 | 40 | @Bean 41 | WebSessionIdResolver webSessionIdResolver() { 42 | HeaderWebSessionIdResolver webSessionIdResolver = new HeaderWebSessionIdResolver(); 43 | webSessionIdResolver.setHeaderName("X-AUTH-TOKEN"); 44 | return webSessionIdResolver; 45 | } 46 | 47 | @Bean 48 | SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { 49 | return http 50 | .csrf().disable() 51 | .authorizeExchange() 52 | .anyExchange().authenticated() 53 | .and() 54 | .build(); 55 | } 56 | 57 | @Bean 58 | public RouterFunction routes(FavoriteHandler favoriteHandler) { 59 | RouterFunction usersRoutes = route(GET("/{username}/favorites"), favoriteHandler::favoritedPosts); 60 | RouterFunction postsRoutes = route(GET("/{slug}/favorited"), favoriteHandler::favorited) 61 | .andRoute(GET("/{slug}/favorites"), favoriteHandler::all) 62 | .andRoute(POST("/{slug}/favorites"), favoriteHandler::favorite) 63 | .andRoute(DELETE("/{slug}/favorites"), favoriteHandler::unfavorite); 64 | 65 | return nest(path("/posts"), postsRoutes) 66 | .andNest(path("/users"), usersRoutes); 67 | } 68 | } 69 | 70 | @Component 71 | class FavoriteHandler { 72 | 73 | private ReactiveRedisConnection conn; 74 | 75 | public FavoriteHandler(ReactiveRedisConnectionFactory factory) { 76 | this.conn = factory.getReactiveConnection(); 77 | } 78 | 79 | public Mono favorited(ServerRequest req) { 80 | 81 | String slug = req.pathVariable("slug"); 82 | return req.principal() 83 | .map(p -> p.getName()) 84 | .flatMap( 85 | name -> this.conn.zSetCommands() 86 | .zRange( 87 | ByteBuffer.wrap(("posts:" + slug + ":favorites").getBytes()), 88 | Range.of(Range.Bound.inclusive(0L), Range.Bound.inclusive(-1L)) 89 | ) 90 | .map(this::toString) 91 | .collectList() 92 | .map(f -> Collections.singletonMap("favorited", f.contains(name))) 93 | ) 94 | .flatMap(f -> ok().body(BodyInserters.fromObject(f))); 95 | 96 | } 97 | 98 | public Mono all(ServerRequest req) { 99 | 100 | String slug = req.pathVariable("slug"); 101 | return this.conn.zSetCommands() 102 | .zRange( 103 | ByteBuffer.wrap(("posts:" + slug + ":favorites").getBytes()), 104 | Range.of(Range.Bound.inclusive(0L), Range.Bound.inclusive(-1L)) 105 | ) 106 | .map(this::toString) 107 | .collectList() 108 | .flatMap(f -> ok().body(BodyInserters.fromObject(f))); 109 | } 110 | 111 | public Mono favoritedPosts(ServerRequest req) { 112 | 113 | return req.principal() 114 | .map(p -> p.getName()) 115 | .flatMap( 116 | name -> this.conn.zSetCommands() 117 | .zRange( 118 | ByteBuffer.wrap(("users:" + name + ":favorites").getBytes()), 119 | Range.of(Range.Bound.inclusive(0L), Range.Bound.inclusive(-1L)) 120 | ) 121 | .map(this::toString) 122 | .collectList() 123 | ) 124 | .flatMap(f -> ok().body(BodyInserters.fromObject(f))); 125 | } 126 | 127 | public Mono favorite(ServerRequest req) { 128 | 129 | String slug = req.pathVariable("slug"); 130 | return req.principal() 131 | .map(p -> p.getName()) 132 | .flatMap( 133 | name -> this.conn.zSetCommands() 134 | .zAdd(ByteBuffer.wrap(("posts:" + slug + ":favorites").getBytes()), 1.0D, ByteBuffer.wrap(name.getBytes())) 135 | .then(this.conn.zSetCommands().zAdd(ByteBuffer.wrap(("users:" + name + ":favorites").getBytes()), 1.0D, ByteBuffer.wrap(slug.getBytes()))) 136 | ) 137 | .flatMap(f -> ok().build()); 138 | } 139 | 140 | 141 | public Mono unfavorite(ServerRequest req) { 142 | String slug = req.pathVariable("slug"); 143 | return req.principal() 144 | .map(p -> p.getName()) 145 | .flatMap( 146 | name -> this.conn.zSetCommands() 147 | .zRem(ByteBuffer.wrap(("posts:" + slug + ":favorites").getBytes()), ByteBuffer.wrap(name.getBytes())) 148 | .then(this.conn.zSetCommands().zRem(ByteBuffer.wrap(("users:" + name + ":favorites").getBytes()), ByteBuffer.wrap(slug.getBytes()))) 149 | ) 150 | .flatMap(f -> noContent().build()); 151 | 152 | } 153 | 154 | private String toString(ByteBuffer byteBuffer) { 155 | byte[] bytes = new byte[byteBuffer.remaining()]; 156 | byteBuffer.get(bytes); 157 | return new String(bytes); 158 | } 159 | } 160 | 161 | -------------------------------------------------------------------------------- /favorite-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8083 2 | spring.application.name=favorite-service 3 | -------------------------------------------------------------------------------- /favorite-service/src/test/java/com/example/favoriteservice/FavoriteServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.favoriteservice; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.web.server.LocalServerPort; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.security.test.context.support.WithMockUser; 12 | import org.springframework.security.web.server.WebFilterChainProxy; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | import org.springframework.test.web.reactive.server.FluxExchangeResult; 15 | import org.springframework.test.web.reactive.server.WebTestClient; 16 | import org.springframework.web.reactive.function.server.RouterFunction; 17 | 18 | import static org.junit.Assert.assertNotNull; 19 | import static org.junit.Assert.assertTrue; 20 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; 21 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 25 | public class FavoriteServiceApplicationTests { 26 | 27 | 28 | @Autowired 29 | RouterFunction routerFunction; 30 | @Autowired 31 | WebFilterChainProxy springSecurityFilterChain; 32 | 33 | WebTestClient client; 34 | 35 | @Before 36 | public void setup() { 37 | this.client = WebTestClient 38 | .bindToRouterFunction(this.routerFunction) 39 | .webFilter(this.springSecurityFilterChain) 40 | .apply(springSecurity()) 41 | .configureClient() 42 | .filter(basicAuthentication()) 43 | .build(); 44 | } 45 | 46 | @Test 47 | public void getFavoritedWithoutAuthWillReturn401(){ 48 | String slug = "testslug"; 49 | client 50 | .get() 51 | .uri("/posts/" + slug + "/favorited") 52 | .exchange() 53 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 54 | } 55 | 56 | @Test 57 | @WithMockUser 58 | public void postCrudOperations() { 59 | String slug = "testslug"; 60 | client 61 | .post() 62 | .uri("/posts/" + slug + "/favorites") 63 | .exchange() 64 | .expectStatus().isEqualTo(HttpStatus.OK); 65 | 66 | client 67 | .get() 68 | .uri("/posts/" + slug + "/favorited") 69 | .exchange() 70 | .expectStatus().isEqualTo(HttpStatus.OK) 71 | .expectBody().jsonPath("$.favorited").isEqualTo(true); 72 | 73 | client 74 | .get() 75 | .uri("/posts/" + slug + "/favorites") 76 | .exchange() 77 | .expectStatus().isEqualTo(HttpStatus.OK) 78 | .expectBody().jsonPath("$[0]").isEqualTo("user"); 79 | 80 | client 81 | .get() 82 | .uri("/users/user/favorites") 83 | .exchange() 84 | .expectStatus().isEqualTo(HttpStatus.OK) 85 | .expectBody().jsonPath("$[0]").isEqualTo("testslug"); 86 | 87 | client 88 | .delete() 89 | .uri("/posts/" + slug + "/favorites") 90 | .exchange() 91 | .expectStatus().isEqualTo(HttpStatus.NO_CONTENT); 92 | 93 | client 94 | .get() 95 | .uri("/posts/" + slug + "/favorited") 96 | .exchange() 97 | .expectStatus().isEqualTo(HttpStatus.OK) 98 | .expectBody().jsonPath("$.favorited").isEqualTo(false); 99 | } 100 | 101 | 102 | } 103 | -------------------------------------------------------------------------------- /gateway-kotlin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | gateway 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | gateway 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | true 23 | UTF-8 24 | UTF-8 25 | 1.8 26 | Finchley.SR1 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-webflux 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | org.springframework.session 43 | spring-session-data-redis 44 | 45 | 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-starter-gateway 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-data-redis-reactive 56 | 57 | 58 | 59 | 60 | org.springframework.cloud 61 | spring-cloud-starter-netflix-hystrix 62 | 63 | 64 | 65 | 66 | org.springframework.cloud 67 | spring-cloud-starter-netflix-eureka-client 68 | 69 | 70 | 71 | 72 | org.springframework.cloud 73 | spring-cloud-starter-config 74 | 75 | 76 | 77 | 78 | org.jetbrains.kotlin 79 | kotlin-stdlib-jre8 80 | 81 | 82 | org.jetbrains.kotlin 83 | kotlin-reflect 84 | 85 | 86 | 87 | org.projectlombok 88 | lombok 89 | true 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-starter-test 94 | test 95 | 96 | 97 | 98 | 99 | 100 | 101 | org.springframework.cloud 102 | spring-cloud-dependencies 103 | ${spring-cloud.version} 104 | pom 105 | import 106 | 107 | 108 | 109 | 110 | 111 | ${project.basedir}/src/main/kotlin 112 | ${project.basedir}/src/test/kotlin 113 | 114 | 115 | org.springframework.boot 116 | spring-boot-maven-plugin 117 | 118 | 119 | kotlin-maven-plugin 120 | org.jetbrains.kotlin 121 | 122 | 123 | spring 124 | 125 | 126 | 127 | 128 | org.jetbrains.kotlin 129 | kotlin-maven-allopen 130 | ${kotlin.version} 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | spring-snapshots 140 | Spring Snapshots 141 | https://repo.spring.io/snapshot 142 | 143 | true 144 | 145 | 146 | 147 | spring-milestones 148 | Spring Milestones 149 | https://repo.spring.io/milestone 150 | 151 | false 152 | 153 | 154 | 155 | 156 | 157 | 158 | spring-snapshots 159 | Spring Snapshots 160 | https://repo.spring.io/snapshot 161 | 162 | true 163 | 164 | 165 | 166 | spring-milestones 167 | Spring Milestones 168 | https://repo.spring.io/milestone 169 | 170 | false 171 | 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /gateway-kotlin/src/main/kotlin/com/example/gateway/GatewayApplication.kt: -------------------------------------------------------------------------------- 1 | package com.example.gateway 2 | 3 | import org.reactivestreams.Publisher 4 | import org.springframework.boot.autoconfigure.SpringBootApplication 5 | import org.springframework.boot.runApplication 6 | import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction 7 | import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator 8 | import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory 9 | import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter 10 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder 11 | import org.springframework.cloud.gateway.route.builder.filters 12 | import org.springframework.cloud.gateway.route.builder.routes 13 | import org.springframework.cloud.netflix.hystrix.HystrixCommands 14 | import org.springframework.context.support.beans 15 | import org.springframework.core.ParameterizedTypeReference 16 | import org.springframework.core.env.get 17 | import org.springframework.web.reactive.function.client.WebClient 18 | import org.springframework.web.reactive.function.server.ServerResponse 19 | import org.springframework.web.reactive.function.server.body 20 | import org.springframework.web.reactive.function.server.router 21 | import reactor.core.publisher.Flux 22 | import java.time.LocalDateTime 23 | 24 | @SpringBootApplication 25 | class GatewayApplication 26 | 27 | fun main(args: Array) { 28 | runApplication(*args) { 29 | beans { 30 | bean { 31 | DiscoveryClientRouteDefinitionLocator(ref()) 32 | } 33 | // bean { 34 | // MapReactiveUserDetailsService( 35 | // User.withDefaultPasswordEncoder() 36 | // .username("user") 37 | // .roles("USER") 38 | // .password("pw") 39 | // .build()) 40 | // } 41 | // bean { 42 | // //@formatter:off 43 | // val http = ref() 44 | // http 45 | // .csrf().disable() 46 | // .httpBasic() 47 | // .and() 48 | // .authorizeExchange() 49 | // .pathMatchers("/proxy").authenticated() 50 | // .anyExchange().permitAll() 51 | // .and() 52 | // .build() 53 | // //@formatter:on 54 | // } 55 | bean { 56 | val builder = ref() 57 | builder 58 | .routes { 59 | val authServiceUrl = env["services.auth-service.url"] 60 | val postServiceUrl = env["services.post-service.url"] 61 | 62 | route { 63 | path("/user") 64 | uri(authServiceUrl + "/user") 65 | } 66 | 67 | route { 68 | val rl = ref() 69 | .apply(RedisRateLimiter.args(2, 4)) 70 | path("/posts") 71 | filters { 72 | filter(rl) 73 | } 74 | uri(postServiceUrl + "/posts") 75 | } 76 | } 77 | } 78 | bean { 79 | WebClient.builder().filter(ref()).build() 80 | } 81 | bean { 82 | router { 83 | val client = ref() 84 | 85 | val favoriteServiceUrl = env["services.favorite-service.url"] 86 | val postServiceUrl = env["services.post-service.url"] 87 | GET("/posts/{slug}/favorites") { 88 | 89 | val favorites: Publisher = client 90 | .get() 91 | .uri(favoriteServiceUrl + "/posts/{slug}/favorites", it.pathVariable("slug")) 92 | .retrieve() 93 | .bodyToFlux(ParameterizedTypeReference.forType(String::class.java)) 94 | 95 | 96 | val cb = HystrixCommands 97 | .from(favorites) 98 | .commandName("posts-favorites") 99 | .fallback(Flux.just("favorited users!!")) 100 | .eager() 101 | .build() 102 | 103 | ServerResponse.ok().body(cb) 104 | } 105 | 106 | 107 | GET("/user/favorites") { 108 | 109 | val favorites: Publisher = client 110 | .get() 111 | .uri(favoriteServiceUrl +"/users/{username}/favorites", it.principal().block()?.name) 112 | .retrieve() 113 | .bodyToFlux(String::class.java) 114 | .flatMap { 115 | slug -> client 116 | .get() 117 | .uri(postServiceUrl +"/posts/{slug}/", it) 118 | .retrieve() 119 | .bodyToFlux(Post::class.java) 120 | .map { (_, title, slug, _, createdDate) -> 121 | FavoritedPost(title, slug, createdDate) 122 | } 123 | } 124 | 125 | 126 | val cb = HystrixCommands 127 | .from(favorites) 128 | .commandName("posts-favorites") 129 | .fallback(Flux.just(FavoritedPost("Loading error", "not_loaded", LocalDateTime.now()))) 130 | .eager() 131 | .build() 132 | 133 | ServerResponse.ok().body(cb) 134 | } 135 | } 136 | } 137 | } 138 | } 139 | } 140 | 141 | data class Post(var id: Long, var title: String, var slug: String, var content: String, var createdData: LocalDateTime) 142 | data class FavoritedPost(var title: String, var slug: String, var createdDate: LocalDateTime) -------------------------------------------------------------------------------- /gateway-kotlin/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8000 2 | services.auth-service.url=${AUTH_SERVICE_URL:http://localhost:8081} 3 | services.post-service.url=${POST_SERVICE_URL:http://localhost:8082} 4 | services.favorite-service.url=${FAVORITE_SERVICE_URL:http://localhost://8083} 5 | -------------------------------------------------------------------------------- /gateway-kotlin/src/test/kotlin/com/example/gateway/GatewayApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.example.gateway 2 | 3 | import org.junit.Test 4 | import org.junit.runner.RunWith 5 | import org.springframework.boot.test.context.SpringBootTest 6 | import org.springframework.test.context.junit4.SpringRunner 7 | 8 | @RunWith(SpringRunner::class) 9 | @SpringBootTest 10 | class GatewayApplicationTests { 11 | 12 | @Test 13 | fun contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /gateway/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM frolvlad/alpine-oraclejdk8:slim 2 | VOLUME /tmp 3 | ADD ./target/gateway-0.0.1-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] -------------------------------------------------------------------------------- /gateway/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | gateway 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | gateway 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | Finchley.SR1 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-webflux 33 | 34 | 35 | 36 | 37 | org.springframework.cloud 38 | spring-cloud-starter-gateway 39 | 40 | 41 | 42 | org.isomorphism 43 | token-bucket 44 | 1.7 45 | 46 | 47 | 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-data-redis-reactive 53 | 54 | 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-security 60 | 61 | 62 | org.springframework.session 63 | spring-session-data-redis 64 | 65 | 66 | 67 | 68 | 69 | 73 | 74 | 75 | org.springframework.cloud 76 | spring-cloud-starter-netflix-eureka-client 77 | 78 | 79 | 80 | org.springframework.cloud 81 | spring-cloud-starter-netflix-hystrix 82 | 83 | 84 | org.springframework.cloud 85 | spring-cloud-starter-netflix-ribbon 86 | 87 | 88 | 89 | org.projectlombok 90 | lombok 91 | 92 | 93 | 94 | org.springframework.boot 95 | spring-boot-starter-test 96 | test 97 | 98 | 99 | io.projectreactor 100 | reactor-test 101 | test 102 | 103 | 104 | 105 | 106 | 107 | 108 | org.springframework.cloud 109 | spring-cloud-dependencies 110 | ${spring-cloud.version} 111 | pom 112 | import 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | org.springframework.boot 121 | spring-boot-maven-plugin 122 | 123 | 124 | 125 | 126 | 127 | 128 | spring-snapshots 129 | Spring Snapshots 130 | https://repo.spring.io/snapshot 131 | 132 | true 133 | 134 | 135 | 136 | spring-milestones 137 | Spring Milestones 138 | https://repo.spring.io/milestone 139 | 140 | false 141 | 142 | 143 | 144 | 145 | 146 | 147 | spring-snapshots 148 | Spring Snapshots 149 | https://repo.spring.io/snapshot 150 | 151 | true 152 | 153 | 154 | 155 | spring-milestones 156 | Spring Milestones 157 | https://repo.spring.io/milestone 158 | 159 | false 160 | 161 | 162 | 163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /gateway/src/main/java/com/example/gateway/GatewayApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.gateway; 2 | 3 | import lombok.*; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.isomorphism.util.TokenBucket; 6 | import org.isomorphism.util.TokenBuckets; 7 | import org.reactivestreams.Publisher; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.SpringApplication; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; 12 | import org.springframework.cloud.client.discovery.DiscoveryClient; 13 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 14 | import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerExchangeFilterFunction; 15 | import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator; 16 | import org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties; 17 | import org.springframework.cloud.gateway.filter.GatewayFilter; 18 | import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; 19 | import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory; 20 | import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; 21 | import org.springframework.cloud.gateway.route.RouteLocator; 22 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; 23 | import org.springframework.cloud.netflix.hystrix.HystrixCommands; 24 | import org.springframework.context.annotation.Bean; 25 | import org.springframework.core.annotation.Order; 26 | import org.springframework.http.HttpMethod; 27 | import org.springframework.http.HttpStatus; 28 | import org.springframework.security.config.web.server.ServerHttpSecurity; 29 | import org.springframework.security.web.server.SecurityWebFilterChain; 30 | import org.springframework.stereotype.Component; 31 | import org.springframework.web.reactive.function.client.*; 32 | import org.springframework.web.reactive.function.server.RouterFunction; 33 | import org.springframework.web.reactive.function.server.ServerRequest; 34 | import org.springframework.web.reactive.function.server.ServerResponse; 35 | import org.springframework.web.server.session.HeaderWebSessionIdResolver; 36 | import org.springframework.web.server.session.WebSessionIdResolver; 37 | import reactor.core.publisher.Flux; 38 | import reactor.core.publisher.Mono; 39 | 40 | import java.time.LocalDateTime; 41 | import java.util.Collections; 42 | import java.util.Map; 43 | import java.util.concurrent.TimeUnit; 44 | 45 | import static org.springframework.cloud.netflix.hystrix.HystrixCommands.from; 46 | import static org.springframework.web.reactive.function.server.RequestPredicates.GET; 47 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 48 | import static org.springframework.web.reactive.function.server.ServerResponse.ok; 49 | 50 | @SpringBootApplication 51 | @EnableDiscoveryClient 52 | @EnableCircuitBreaker 53 | @Slf4j 54 | public class GatewayApplication { 55 | 56 | @Value("${services.auth-service.url}") 57 | private String authServiceUrl; 58 | 59 | @Value("${services.post-service.url}") 60 | private String postServiceUrl; 61 | 62 | @Value("${services.favorite-service.url}") 63 | private String favoriteServiceUrl; 64 | 65 | public static void main(String[] args) { 66 | SpringApplication.run(GatewayApplication.class, args); 67 | 68 | } 69 | 70 | 71 | @Bean 72 | WebSessionIdResolver webSessionIdResolver() { 73 | HeaderWebSessionIdResolver webSessionIdResolver = new HeaderWebSessionIdResolver(); 74 | webSessionIdResolver.setHeaderName("X-AUTH-TOKEN"); 75 | return webSessionIdResolver; 76 | } 77 | 78 | @Bean 79 | SecurityWebFilterChain authorization(ServerHttpSecurity security) { 80 | return security 81 | .authorizeExchange().pathMatchers("/user/**").authenticated() 82 | .anyExchange().permitAll() 83 | .and() 84 | .httpBasic().disable() 85 | .csrf().disable() 86 | .build(); 87 | } 88 | 89 | @Bean 90 | WebClient client(LoadBalancerExchangeFilterFunction lb, CopyRequestAuthTokenHeaderExchangeFilterFunction xtoken) { 91 | return WebClient.builder() 92 | .filter(lb) 93 | .filter(xtoken) 94 | .build(); 95 | } 96 | 97 | @Bean 98 | RouterFunction routes(WebClient webClient) { 99 | log.debug("authServiceUrl:{}", this.authServiceUrl); 100 | log.debug("postServiceUrl:{}", this.postServiceUrl); 101 | log.debug("favoriteServiceUrl:{}", this.favoriteServiceUrl); 102 | 103 | return route( 104 | GET("/posts/{slug}/favorited"), 105 | (req) -> { 106 | Flux favorites = webClient 107 | //.mutate().filter(new CopyRequestAuthTokenHeaderExchangeFilterFunction(req)).build() 108 | .get() 109 | .uri(favoriteServiceUrl + "/posts/{slug}/favorited", req.pathVariable("slug")) 110 | .retrieve() 111 | .bodyToFlux(Map.class); 112 | 113 | Publisher cb = from(favorites) 114 | .commandName("posts-favorites") 115 | .fallback(Flux.just(Collections.singletonMap("favorited", false))) 116 | .eager() 117 | .build(); 118 | 119 | return ok().body(favorites, Map.class); 120 | } 121 | ).andRoute( 122 | GET("/posts/{slug}/favorites"), 123 | (req) -> { 124 | Flux favorites = webClient 125 | .get() 126 | .uri(favoriteServiceUrl + "/posts/{slug}/favorites", req.pathVariable("slug")) 127 | .retrieve() 128 | .bodyToFlux(String.class); 129 | 130 | Publisher cb = from(favorites) 131 | .commandName("posts-favorites") 132 | .fallback(Flux.just("loading favorited users failed!")) 133 | .eager() 134 | .build(); 135 | 136 | return ok().body(cb, String.class); 137 | } 138 | ).andRoute( 139 | GET("/user/favorites"), 140 | (req) -> { 141 | Flux favorites = req.principal() 142 | .flatMapMany( 143 | p -> webClient 144 | //.mutate().filter(new CopyRequestAuthTokenHeaderExchangeFilterFunction(req)).build() 145 | .get() 146 | .uri(favoriteServiceUrl + "/users/{username}/favorites", p.getName()) 147 | .retrieve() 148 | .bodyToFlux(String.class) 149 | .flatMap( 150 | slug -> webClient 151 | .get() 152 | .uri(postServiceUrl + "/posts/{slug}/", slug) 153 | .retrieve() 154 | .bodyToMono(Post.class) 155 | .map(post -> new FavoritedPost(post.getTitle(), slug, post.getCreatedDate())) 156 | ) 157 | ); 158 | 159 | 160 | Publisher cb = HystrixCommands 161 | .from(favorites) 162 | .commandName("posts-favorites") 163 | .fallback(Flux.just(new FavoritedPost("Loading favorited posts failed", "not_loaded", LocalDateTime.now()))) 164 | .eager() 165 | .build(); 166 | 167 | return ok().body(cb, FavoritedPost.class); 168 | } 169 | ); 170 | } 171 | 172 | @Bean 173 | @Order(-1) 174 | RouteLocator gatewayRoutes(RequestRateLimiterGatewayFilterFactory rl, 175 | ThrottleGatewayFilterFactory throttle, 176 | RouteLocatorBuilder locator) { 177 | return locator.routes() 178 | .route("session", predicate -> predicate.path("/session") 179 | .uri(authServiceUrl) 180 | ) 181 | 182 | .route("users", predicate -> predicate.path("/users/**") 183 | .uri(authServiceUrl) 184 | ) 185 | 186 | .route("favorites", predicate -> predicate 187 | .method(HttpMethod.POST) 188 | .or() 189 | .method(HttpMethod.DELETE) 190 | .and() 191 | .path("/posts/*/favorites") 192 | //.or().method(HttpMethod.GET).and().path("/posts/*/favorites/**") 193 | .uri(favoriteServiceUrl) 194 | ) 195 | 196 | .route("posts", predicate -> predicate.path("/posts/**") 197 | .filters( 198 | g -> g 199 | .filter(throttle.apply(ThrottleGatewayFilterFactory.Config.builder().capacity(1).refillPeriod(1).refillTokens(1).refillUnit(TimeUnit.MILLISECONDS).build())) 200 | .filter(rl.apply(new RequestRateLimiterGatewayFilterFactory.Config().setRateLimiter(new RedisRateLimiter(2, 4)))) 201 | 202 | ) 203 | .uri(postServiceUrl) 204 | ) 205 | .build(); 206 | } 207 | 208 | // spring.cloud.gateway.discovery.locator.enabled=true 209 | @Bean 210 | DiscoveryClientRouteDefinitionLocator discoveryRoutes(DiscoveryClient dc, DiscoveryLocatorProperties props) { 211 | return new DiscoveryClientRouteDefinitionLocator(dc, props); 212 | } 213 | 214 | } 215 | 216 | @Data 217 | @AllArgsConstructor 218 | @NoArgsConstructor 219 | @Builder 220 | class Post { 221 | private Long id; 222 | private String slug; 223 | private String title; 224 | private String content; 225 | private LocalDateTime createdDate; 226 | } 227 | 228 | @Data 229 | @AllArgsConstructor 230 | @NoArgsConstructor 231 | @Builder 232 | class FavoritedPost { 233 | private String slug; 234 | private String title; 235 | private LocalDateTime createdDate; 236 | } 237 | 238 | /** 239 | * https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-sample/src/main/java/org/springframework/cloud/gateway/sample/ThrottleGatewayFilter.java 240 | * Sample throttling filter. 241 | * See https://github.com/bbeck/token-bucket 242 | */ 243 | @Slf4j 244 | @Component 245 | class ThrottleGatewayFilterFactory extends AbstractGatewayFilterFactory { 246 | int capacity = 1; 247 | int refillTokens = 1; 248 | int refillPeriod = 1; 249 | TimeUnit refillUnit = TimeUnit.MILLISECONDS; 250 | 251 | @Override 252 | public GatewayFilter apply(Config config) { 253 | int capacity = config.getCapacity() <= 0 ? this.capacity : config.getCapacity(); 254 | int refillTokens = config.getRefillTokens() <= 0 ? this.refillTokens : config.getRefillTokens(); 255 | int refillPeriod = config.getRefillPeriod() <= 0 ? this.refillPeriod : config.getRefillPeriod(); 256 | TimeUnit refillUnit = config.getRefillUnit() == null ? this.refillUnit : config.getRefillUnit(); 257 | 258 | return (exchange, chain) -> { 259 | TokenBucket tokenBucket = TokenBuckets.builder() 260 | .withCapacity(capacity) 261 | .withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit) 262 | .build(); 263 | 264 | //TODO: get a token bucket for a key 265 | log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); 266 | boolean consumed = tokenBucket.tryConsume(); 267 | if (consumed) { 268 | return chain.filter(exchange); 269 | } 270 | exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); 271 | return exchange.getResponse().setComplete(); 272 | }; 273 | } 274 | 275 | @Setter 276 | @Getter 277 | @Builder 278 | public static class Config { 279 | int capacity; 280 | int refillTokens; 281 | int refillPeriod; 282 | TimeUnit refillUnit; 283 | } 284 | } 285 | 286 | @Slf4j 287 | @Component 288 | class CopyRequestAuthTokenHeaderExchangeFilterFunction implements ExchangeFilterFunction { 289 | 290 | 291 | @Override 292 | public Mono filter(ClientRequest clientRequest, ExchangeFunction next) { 293 | 294 | ClientRequest newRequest = ClientRequest.from(clientRequest).build(); 295 | if (clientRequest.headers().containsKey("X-AUTH-TOKEN")) { 296 | newRequest.headers().add( 297 | "X-AUTH-TOKEN", 298 | clientRequest.headers().getFirst("X-AUTH-TOKEN") 299 | ); 300 | } 301 | log.debug("client request header X-AUTH-TOKEN: {}", newRequest.headers().get("X-AUTH-TOKEN")); 302 | 303 | return next.exchange(newRequest); 304 | } 305 | 306 | } 307 | -------------------------------------------------------------------------------- /gateway/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8000 2 | spring.application.name=gateway 3 | services.auth-service.url=${AUTH_SERVICE_URL:http://localhost:8081} 4 | services.post-service.url=${POST_SERVICE_URL:http://localhost:8082} 5 | services.favorite-service.url=${FAVORITE_SERVICE_URL:http://localhost:8083} 6 | 7 | // DiscoveryClient Route Definition Locator 8 | spring.cloud.gateway.discovery.locator.enabled=true 9 | 10 | logging.level.com.example=DEBUG 11 | logging.level.org.springframework.cloud=TRACE 12 | -------------------------------------------------------------------------------- /gateway/src/test/java/com/example/gateway/GatewayApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.gateway; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class GatewayApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hantsylabs.sample.microservice 6 | spring-reactive-microservice-sample-parent 7 | 0.0.1-SNAPSHOT 8 | pom 9 | Spring Reactive Microservice Demo 10 | Reactive Microservice demo by the new Spring 5 Reactive feature 11 | 12 | 13 | eureka-server 14 | gateway 15 | auth-service 16 | post-service 17 | favorite-service 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /post-service/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM frolvlad/alpine-oraclejdk8:slim 2 | VOLUME /tmp 3 | ADD ./target/post-service-0.0.1-SNAPSHOT.jar app.jar 4 | RUN sh -c 'touch /app.jar' 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] -------------------------------------------------------------------------------- /post-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | post-service 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | post-service 12 | Spring Webflux REST demo(RouterFunction,Data Mongo, Data Redis, Data Cassandra etc) 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | Finchley.SR1 25 | 1.8 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-mongodb-reactive 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-redis-reactive 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | org.springframework.session 43 | spring-session-data-redis 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-webflux 48 | 49 | 50 | 51 | org.springframework.cloud 52 | spring-cloud-starter-netflix-eureka-client 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.projectlombok 62 | lombok 63 | true 64 | 65 | 66 | org.slf4j 67 | slf4j-api 68 | 69 | 70 | org.slf4j 71 | jcl-over-slf4j 72 | 73 | 74 | ch.qos.logback 75 | logback-core 76 | 77 | 78 | ch.qos.logback 79 | logback-classic 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-starter-test 84 | test 85 | 86 | 87 | io.projectreactor 88 | reactor-test 89 | test 90 | 91 | 92 | org.springframework.security 93 | spring-security-test 94 | test 95 | 96 | 97 | 98 | 99 | 100 | org.springframework.cloud 101 | spring-cloud-dependencies 102 | ${spring-cloud.version} 103 | pom 104 | import 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | org.springframework.boot 113 | spring-boot-maven-plugin 114 | 115 | 116 | 117 | 118 | 119 | 120 | spring-snapshots 121 | Spring Snapshots 122 | https://repo.spring.io/snapshot 123 | 124 | true 125 | 126 | 127 | 128 | spring-milestones 129 | Spring Milestones 130 | https://repo.spring.io/milestone 131 | 132 | false 133 | 134 | 135 | 136 | 137 | 138 | 139 | spring-snapshots 140 | Spring Snapshots 141 | https://repo.spring.io/snapshot 142 | 143 | true 144 | 145 | 146 | 147 | spring-milestones 148 | Spring Milestones 149 | https://repo.spring.io/milestone 150 | 151 | false 152 | 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/Comment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.time.LocalDateTime; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | import lombok.ToString; 14 | import org.springframework.data.annotation.CreatedBy; 15 | import org.springframework.data.annotation.CreatedDate; 16 | import org.springframework.data.annotation.Id; 17 | import org.springframework.data.mongodb.core.mapping.Document; 18 | 19 | /** 20 | * 21 | * @author hantsy 22 | */ 23 | @Document 24 | @Data 25 | @ToString 26 | @Builder 27 | @NoArgsConstructor 28 | @AllArgsConstructor 29 | class Comment { 30 | 31 | @Id 32 | private String id; 33 | private Slug post; 34 | private String content; 35 | 36 | @CreatedDate 37 | private LocalDateTime createdDate; 38 | 39 | @CreatedBy 40 | private Username author; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/CommentHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.net.URI; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.reactive.function.server.ServerRequest; 11 | import org.springframework.web.reactive.function.server.ServerResponse; 12 | import reactor.core.publisher.Mono; 13 | 14 | /** 15 | * 16 | * @author hantsy 17 | */ 18 | @Component 19 | class CommentHandler { 20 | 21 | private final CommentRepository comments; 22 | 23 | public CommentHandler(CommentRepository comments) { 24 | this.comments = comments; 25 | } 26 | 27 | public Mono all(ServerRequest req) { 28 | return ServerResponse.ok().body(this.comments.findAll(), Comment.class); 29 | } 30 | 31 | public Mono create(ServerRequest req) { 32 | return req 33 | .bodyToMono(Comment.class) 34 | .flatMap((comment) -> this.comments.save(comment)) 35 | .flatMap((p) -> ServerResponse.created(URI.create("/posts/" + req.pathVariable("slug") + "/comments/" + p.getId())).build()); 36 | } 37 | 38 | public Mono get(ServerRequest req) { 39 | return this.comments 40 | .findById(req.pathVariable("commentid")) 41 | .flatMap((comment) -> ServerResponse.ok().body(Mono.just(comment), Comment.class)) 42 | .switchIfEmpty(ServerResponse.notFound().build()); 43 | } 44 | 45 | public Mono update(ServerRequest req) { 46 | return Mono 47 | .zip( 48 | (data) -> { 49 | Comment p = (Comment) data[0]; 50 | Comment p2 = (Comment) data[1]; 51 | 52 | p.setContent(p2.getContent()); 53 | return p; 54 | }, 55 | this.comments.findById(req.pathVariable("commentid")), 56 | req.bodyToMono(Comment.class) 57 | ) 58 | .cast(Comment.class) 59 | .flatMap((comment) -> this.comments.save(comment)) 60 | .flatMap((comment) -> ServerResponse.noContent().build()); 61 | } 62 | 63 | public Mono delete(ServerRequest req) { 64 | return ServerResponse.noContent().build(this.comments.deleteById(req.pathVariable("commentid"))); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/CommentRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import org.springframework.data.mongodb.repository.ReactiveMongoRepository; 9 | 10 | /** 11 | * 12 | * @author hantsy 13 | */ 14 | interface CommentRepository extends ReactiveMongoRepository { 15 | } 16 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/DataInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.util.Arrays; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.boot.CommandLineRunner; 11 | import org.springframework.stereotype.Component; 12 | import reactor.core.publisher.Flux; 13 | 14 | /** 15 | * 16 | * @author hantsy 17 | */ 18 | @Component 19 | @Slf4j 20 | class DataInitializer implements CommandLineRunner { 21 | 22 | private final PostRepository posts; 23 | 24 | public DataInitializer(PostRepository posts) { 25 | this.posts = posts; 26 | } 27 | 28 | @Override 29 | public void run(String[] args) { 30 | log.info("start data initialization ..."); 31 | this.posts 32 | .deleteAll() 33 | .thenMany( 34 | Flux 35 | .just("Post one", "Post two") 36 | .flatMap((title) -> this.posts.save(Post.builder().title(title).content("content of " + title).build())) 37 | ) 38 | .log() 39 | .subscribe( 40 | null, 41 | null, 42 | () -> log.info("done posts initialization...") 43 | ); 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/Post.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.time.LocalDateTime; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | import lombok.ToString; 14 | import org.springframework.data.annotation.CreatedBy; 15 | import org.springframework.data.annotation.CreatedDate; 16 | import org.springframework.data.annotation.Id; 17 | import org.springframework.data.mongodb.core.mapping.Document; 18 | 19 | /** 20 | * 21 | * @author hantsy 22 | */ 23 | @Document 24 | @Data 25 | @ToString 26 | @Builder 27 | @NoArgsConstructor 28 | @AllArgsConstructor 29 | class Post { 30 | 31 | @Id 32 | private String id; 33 | private String title; 34 | private String content; 35 | private String slug; 36 | 37 | @CreatedDate 38 | private LocalDateTime createdDate; 39 | 40 | @CreatedBy 41 | private Username author; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/PostHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.net.URI; 9 | import java.time.Duration; 10 | 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.reactive.function.BodyInserters; 13 | import org.springframework.web.reactive.function.server.ServerRequest; 14 | import org.springframework.web.reactive.function.server.ServerResponse; 15 | import reactor.core.publisher.Flux; 16 | import reactor.core.publisher.Mono; 17 | 18 | import static org.springframework.web.reactive.function.server.ServerResponse.*; 19 | 20 | 21 | /** 22 | * @author hantsy 23 | */ 24 | @Component 25 | class PostHandler { 26 | 27 | private final PostRepository posts; 28 | 29 | public PostHandler(PostRepository posts) { 30 | this.posts = posts; 31 | } 32 | 33 | public Mono all(ServerRequest req) { 34 | return ok().body(this.posts.findAll(), Post.class); 35 | } 36 | 37 | public Mono stream(ServerRequest req) { 38 | return ok().body(Flux.interval(Duration.ofSeconds(30L)).flatMap(s -> this.posts.findAll()), Post.class); 39 | } 40 | 41 | public Mono create(ServerRequest req) { 42 | return req 43 | .bodyToMono(Post.class) 44 | .flatMap((post) -> this.posts.save(post)) 45 | .flatMap((p) -> created(URI.create("/posts/" + p.getSlug())).build()); 46 | } 47 | 48 | public Mono get(ServerRequest req) { 49 | return this.posts 50 | .findBySlug(req.pathVariable("slug")) 51 | .flatMap((post) -> ok().body(BodyInserters.fromObject(post))) 52 | .switchIfEmpty(notFound().build()); 53 | } 54 | 55 | public Mono update(ServerRequest req) { 56 | return Mono 57 | .zip( 58 | (data) -> { 59 | Post p = (Post) data[0]; 60 | Post p2 = (Post) data[1]; 61 | p.setTitle(p2.getTitle()); 62 | p.setContent(p2.getContent()); 63 | return p; 64 | }, 65 | this.posts.findById(req.pathVariable("slug")), 66 | req.bodyToMono(Post.class) 67 | ) 68 | .cast(Post.class) 69 | .flatMap((post) -> this.posts.save(post)) 70 | .flatMap((post) -> noContent().build()); 71 | } 72 | 73 | public Mono delete(ServerRequest req) { 74 | return this.posts.findBySlug(req.pathVariable("slug")) 75 | .flatMap((post) -> noContent().build()) 76 | .switchIfEmpty(notFound().build()); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/PostRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import org.springframework.data.mongodb.repository.ReactiveMongoRepository; 9 | import reactor.core.publisher.Mono; 10 | 11 | /** 12 | * 13 | * @author hantsy 14 | */ 15 | interface PostRepository extends ReactiveMongoRepository { 16 | Mono findBySlug(String slug); 17 | } 18 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/PostServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.data.domain.AuditorAware; 9 | import org.springframework.data.mongodb.config.EnableMongoAuditing; 10 | import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; 11 | import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; 12 | import org.springframework.http.HttpMethod; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.security.authentication.AnonymousAuthenticationToken; 15 | import org.springframework.security.config.web.server.ServerHttpSecurity; 16 | import org.springframework.security.core.context.ReactiveSecurityContextHolder; 17 | import org.springframework.security.core.context.SecurityContext; 18 | import org.springframework.security.core.userdetails.UserDetails; 19 | 20 | import org.springframework.security.web.server.SecurityWebFilterChain; 21 | import org.springframework.web.reactive.function.server.RouterFunction; 22 | 23 | import static org.springframework.web.reactive.function.server.RequestPredicates.*; 24 | import static org.springframework.web.reactive.function.server.RouterFunctions.nest; 25 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 26 | 27 | import org.springframework.web.reactive.function.server.ServerResponse; 28 | import org.springframework.web.server.session.HeaderWebSessionIdResolver; 29 | import org.springframework.web.server.session.WebSessionIdResolver; 30 | 31 | @SpringBootApplication 32 | @EnableMongoAuditing 33 | @EnableDiscoveryClient 34 | @Slf4j 35 | public class PostServiceApplication { 36 | 37 | public static void main(String[] args) { 38 | SpringApplication.run(PostServiceApplication.class, args); 39 | } 40 | 41 | @Bean 42 | WebSessionIdResolver webSessionIdResolver() { 43 | HeaderWebSessionIdResolver webSessionIdResolver = new HeaderWebSessionIdResolver(); 44 | webSessionIdResolver.setHeaderName("X-AUTH-TOKEN"); 45 | return webSessionIdResolver; 46 | } 47 | 48 | @Bean 49 | SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { 50 | return http 51 | .csrf().disable() 52 | .authorizeExchange() 53 | .pathMatchers(HttpMethod.GET, "/posts/**").permitAll() 54 | .pathMatchers(HttpMethod.DELETE, "/posts/**").hasRole("ADMIN") 55 | .anyExchange().authenticated() 56 | .and() 57 | .build(); 58 | } 59 | 60 | @Bean 61 | public RouterFunction routes( 62 | PostRepository posts, 63 | PostHandler postController, 64 | CommentHandler commentHandler) { 65 | RouterFunction commentsRoutes = route(GET("/"), commentHandler::all) 66 | .andRoute(POST("/"), commentHandler::create) 67 | .andRoute(GET("/{commentid}"), commentHandler::get) 68 | .andRoute(PUT("/{commentid}"), commentHandler::update) 69 | .andRoute(DELETE("/{commentid}"), commentHandler::delete); 70 | 71 | RouterFunction postsRoutes = 72 | route(accept(MediaType.APPLICATION_JSON_UTF8).and(GET("/")), postController::all) 73 | .andRoute(accept(MediaType.APPLICATION_STREAM_JSON).and(GET("/")), postController::stream) 74 | .andRoute(POST("/"), postController::create) 75 | .andRoute(GET("/{slug}"), postController::get) 76 | .andRoute(PUT("/{slug}"), postController::update) 77 | .andRoute(DELETE("/{slug}"), postController::delete) 78 | .andNest(path("/{slug}/comments"), commentsRoutes); 79 | 80 | return nest(path("/posts"), postsRoutes); 81 | } 82 | 83 | @Bean 84 | public AuditorAware auditorAware() { 85 | return () -> ReactiveSecurityContextHolder.getContext() 86 | .map(SecurityContext::getAuthentication) 87 | .map(auth -> { 88 | 89 | if (auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) { 90 | UserDetails userDetails = (UserDetails) auth.getPrincipal(); 91 | 92 | return new Username(userDetails.getUsername()); 93 | } 94 | 95 | return null; 96 | } 97 | ) 98 | .blockOptional(); 99 | } 100 | 101 | @Bean 102 | public AbstractMongoEventListener mongoEventListener() { 103 | return new AbstractMongoEventListener() { 104 | 105 | @Override 106 | public void onBeforeConvert(BeforeConvertEvent event) { 107 | super.onBeforeConvert(event); 108 | event.getSource().setSlug(Utils.slugify(event.getSource().getTitle())); 109 | 110 | log.debug("after set slug:: onBeforeConvert({}, {})", event.getSource(), event.getDocument()); 111 | } 112 | 113 | }; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/Slug.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import java.io.Serializable; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | /** 14 | * 15 | * @author hantsy 16 | */ 17 | @Data 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | class Slug implements Serializable { 21 | 22 | private String slug; 23 | } 24 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/Username.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | /** 14 | * 15 | * @author hantsy 16 | */ 17 | @Data 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | @Builder 21 | public class Username { 22 | private String username; 23 | } 24 | -------------------------------------------------------------------------------- /post-service/src/main/java/com/example/demo/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | /** 9 | * 10 | * @author hantsy 11 | */ 12 | public final class Utils { 13 | 14 | private Utils() { 15 | } 16 | 17 | public static String slugify(String source) { 18 | String result = source.toLowerCase(); 19 | result = result.replaceAll("\r\n", ""); 20 | result = result.replaceAll("\n", ""); 21 | result = result.replaceAll("\r", ""); 22 | result = result.replaceAll("[\\s]+", "-"); 23 | return result; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /post-service/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | application: 6 | name: post-service 7 | 8 | logging: 9 | level: 10 | com.example: DEBUG 11 | org.springframework.data: DEBUG 12 | org.springframework.web: DEBUG 13 | org.springframework.security: DEBUG 14 | -------------------------------------------------------------------------------- /post-service/src/test/java/com/example/demo/PostServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.security.test.context.support.WithMockUser; 12 | import org.springframework.security.web.server.WebFilterChainProxy; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | import org.springframework.test.web.reactive.server.EntityExchangeResult; 15 | import org.springframework.test.web.reactive.server.FluxExchangeResult; 16 | import org.springframework.test.web.reactive.server.WebTestClient; 17 | import org.springframework.web.reactive.function.BodyInserters; 18 | import org.springframework.web.reactive.function.server.RouterFunction; 19 | 20 | import java.net.URI; 21 | import java.time.Duration; 22 | import java.util.Random; 23 | 24 | import static org.junit.Assert.assertNotNull; 25 | import static org.junit.Assert.assertTrue; 26 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; 27 | import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication; 28 | 29 | @RunWith(SpringRunner.class) 30 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 31 | @Slf4j 32 | public class PostServiceApplicationTests { 33 | 34 | @Autowired 35 | RouterFunction routerFunction; 36 | @Autowired 37 | WebFilterChainProxy springSecurityFilterChain; 38 | 39 | WebTestClient client; 40 | 41 | @Before 42 | public void setup() { 43 | this.client = WebTestClient 44 | .bindToRouterFunction(this.routerFunction) 45 | .webFilter(this.springSecurityFilterChain) 46 | .apply(springSecurity()) 47 | .configureClient() 48 | .filter(basicAuthentication()) 49 | .build(); 50 | } 51 | 52 | @Test 53 | public void getAllPostsWithoutAuthWillBeOK() { 54 | client 55 | .get() 56 | .uri("/posts") 57 | .exchange() 58 | .expectStatus().isEqualTo(HttpStatus.OK); 59 | } 60 | 61 | @Test 62 | public void getNonExistedPostsWithoutAuthShouldRetrun404() { 63 | client 64 | .get() 65 | .uri("/posts/xxx") 66 | .exchange() 67 | .expectStatus().isEqualTo(HttpStatus.NOT_FOUND); 68 | } 69 | 70 | @Test 71 | public void addPostWithoutAuthWillReturn401() { 72 | client 73 | .post() 74 | .uri("/posts") 75 | .exchange() 76 | .expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); 77 | } 78 | 79 | // @Test 80 | // public void testPostStream() { 81 | // client.mutate().responseTimeout(Duration.ofSeconds(60L)).build() 82 | // .get() 83 | // .uri("/posts") 84 | // .accept(MediaType.APPLICATION_STREAM_JSON) 85 | // .exchange() 86 | // .expectStatus().isOk(); 87 | // } 88 | 89 | @Test 90 | @WithMockUser(roles = "ADMIN") 91 | public void postCrudOperations() { 92 | int randomInt = new Random().nextInt(Integer.MAX_VALUE); 93 | String title = "Post test " + randomInt; 94 | FluxExchangeResult postResult = client 95 | .post() 96 | .uri("/posts") 97 | .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build())) 98 | .exchange() 99 | .expectStatus().isEqualTo(HttpStatus.CREATED) 100 | .returnResult(Void.class); 101 | 102 | URI location = postResult.getResponseHeaders().getLocation(); 103 | log.debug("post header location:" + location); 104 | assertNotNull(location); 105 | 106 | EntityExchangeResult getResult = client 107 | .get() 108 | .uri(location) 109 | .exchange() 110 | .expectStatus().isOk() 111 | .expectBody().jsonPath("$.title").isEqualTo(title) 112 | .returnResult(); 113 | 114 | String getPost = new String(getResult.getResponseBody()); 115 | assertTrue(getPost.contains(title)); 116 | 117 | client 118 | .delete() 119 | .uri(location) 120 | .exchange() 121 | .expectStatus().isEqualTo(HttpStatus.NO_CONTENT); 122 | } 123 | 124 | 125 | } 126 | -------------------------------------------------------------------------------- /post-service/src/test/java/com/example/demo/SlugifyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.example.demo; 7 | 8 | import static org.junit.Assert.assertTrue; 9 | import org.junit.Test; 10 | 11 | /** 12 | * 13 | * @author hantsy 14 | */ 15 | public class SlugifyTest { 16 | 17 | @Test 18 | public void testSlugify() { 19 | assertTrue(Utils.slugify("Hello world").equals("hello-world")); 20 | assertTrue(Utils.slugify("Hello \n world").equals("hello-world")); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /vbox-ports-forward.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # forward prots of VirtualBox to local host. 4 | # VBoxManage modifyvm "springms" --natpf1 "tcp-port8761,tcp,localhost,8761,,8761" 5 | VBoxManage modifyvm "springms" --natpf1 "tcp-port5672,tcp,localhost,5672,,5672" 6 | VBoxManage modifyvm "springms" --natpf1 "tcp-port15672,tcp,localhost,15672,,15672" 7 | VBoxManage modifyvm "springms" --natpf1 "tcp-port6379,tcp,localhost,6379,,6379" 8 | VBoxManage modifyvm "springms" --natpf1 "tcp-port27017,tcp,localhost,27017,,27017" 9 | VBoxManage modifyvm "springms" --natpf1 "tcp-port9042,tcp,localhost,9042,,9042" 10 | # VBoxManage modifyvm "springms" --natpf1 "tcp-port8081,tcp,localhost,8081,,8081" 11 | # VBoxManage modifyvm "springms" --natpf1 "tcp-port8082,tcp,localhost,8082,,8082" 12 | # VBoxManage modifyvm "springms" --natpf1 "tcp-port8083,tcp,localhost,8083,,8083" 13 | # VBoxManage modifyvm "springms" --natpf1 "tcp-port8000,tcp,localhost,8000,,8000" 14 | 15 | --------------------------------------------------------------------------------