├── .gitattributes ├── .gitignore ├── LICENSE ├── pom.xml ├── src ├── main │ ├── java │ │ ├── lombok.config │ │ └── victor │ │ │ └── training │ │ │ └── java │ │ │ ├── advanced │ │ │ ├── Currying.java │ │ │ ├── ExceptionsReturned.java │ │ │ ├── LoanPattern.java │ │ │ ├── OptionalAdvancedApp.java │ │ │ ├── OptionalChain.java │ │ │ ├── Optionals.java │ │ │ ├── ParallelStreams.java │ │ │ ├── SplitLoopToStream.java │ │ │ ├── StreamWreck.java │ │ │ ├── Switch.java │ │ │ ├── model │ │ │ │ ├── Customer.java │ │ │ │ ├── Language.java │ │ │ │ ├── MemberCard.java │ │ │ │ ├── Order.java │ │ │ │ ├── OrderLine.java │ │ │ │ ├── Product.java │ │ │ │ └── User.java │ │ │ ├── repo │ │ │ │ ├── OrderRepo.java │ │ │ │ ├── ProductRepo.java │ │ │ │ ├── UserRepo.java │ │ │ │ ├── custom │ │ │ │ │ ├── CustomJpaRepository.java │ │ │ │ │ ├── CustomJpaRepositoryFactoryBean.java │ │ │ │ │ └── CustomJpaRepositoryImpl.java │ │ │ │ └── package-info.java │ │ │ └── tricks │ │ │ │ ├── ConcurrencyUtil.java │ │ │ │ ├── StableSort.java │ │ │ │ ├── StreamSupplier.java │ │ │ │ └── Trap_toMap_nullKey.java │ │ │ ├── java17 │ │ │ ├── DisplayShape.java │ │ │ ├── Records.java │ │ │ ├── Sealed.java │ │ │ └── TextBlocks.java │ │ │ └── stream │ │ │ ├── BasicsRecap.java │ │ │ ├── menu │ │ │ ├── Dish.java │ │ │ └── DishPlay.java │ │ │ ├── order │ │ │ ├── CreateStreams.java │ │ │ ├── CreateStreamsTest.java │ │ │ ├── SearchStreams.java │ │ │ ├── SearchStreamsTest.java │ │ │ ├── TransformStreams.java │ │ │ ├── TransformStreamsTest.java │ │ │ ├── dto │ │ │ │ ├── AuditDto.java │ │ │ │ ├── OrderDto.java │ │ │ │ └── OrderMapper.java │ │ │ ├── entity │ │ │ │ ├── Audit.java │ │ │ │ ├── Customer.java │ │ │ │ ├── Order.java │ │ │ │ ├── OrderLine.java │ │ │ │ └── Product.java │ │ │ └── repo │ │ │ │ ├── OrderLineRepository.java │ │ │ │ └── OrderRepository.java │ │ │ ├── transaction │ │ │ ├── Trader.java │ │ │ ├── Transaction.java │ │ │ ├── TransactionPlay.java │ │ │ └── TransactionPlaySolved.java │ │ │ └── yatzi │ │ │ ├── Yatzy.java │ │ │ └── YatzyTest.java │ └── resources │ │ └── application.properties └── test │ └── java │ └── victor │ └── training │ └── java │ └── advanced │ ├── ExceptionsReturnedTest.java │ ├── SplitLoopToStreamTest.java │ └── SwitchTest.java ├── test.invalid.txt └── test.ok.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | .settings/* 22 | .project 23 | .classpath 24 | 25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 26 | hs_err_pid* 27 | /target/ 28 | /.idea/* 29 | *.iml 30 | /out/ 31 | -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | org.springframework.boot 6 | spring-boot-starter-parent 7 | 2.6.3 8 | 9 | 10 | 11 | victor 12 | java8-workshop 13 | 0.0.1-SNAPSHOT 14 | 15 | 17 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-data-jpa 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | com.h2database 29 | h2 30 | runtime 31 | 32 | 33 | p6spy 34 | p6spy 35 | 3.9.1 36 | 37 | 38 | 39 | 40 | io.vavr 41 | vavr 42 | 0.10.4 43 | 44 | 45 | 46 | org.jooq 47 | jool 48 | 0.9.14 49 | 50 | 51 | 52 | org.projectlombok 53 | lombok 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-starter-test 59 | compile 60 | 61 | 62 | 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-maven-plugin 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/main/java/lombok.config: -------------------------------------------------------------------------------- 1 | lombok.accessors.chain=true -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/Currying.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import java.util.function.BiFunction; 4 | import java.util.function.Function; 5 | 6 | public class Currying { 7 | // please skip me ! 8 | public static void main(String[] args) { 9 | Function add1 = partialApply(Integer::sum, 1); 10 | System.out.println(add1.apply(2)); 11 | 12 | Function max2 = partialApply(Integer::max, 2); 13 | System.out.println(max2.apply(5)); 14 | System.out.println(max2.apply(1)); 15 | } 16 | 17 | public static Function partialApply(BiFunction f, int arg1) { 18 | return arg2 -> f.apply(arg1, arg2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/ExceptionsReturned.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import java.time.LocalDate; 4 | import java.time.format.DateTimeFormatter; 5 | import java.util.List; 6 | 7 | import static java.util.stream.Collectors.toList; 8 | 9 | public class ExceptionsReturned { 10 | 11 | // ** Requirements ** 12 | // Some dates might have invalid format 13 | // - if >= 50% valid => return the parseable dates, 14 | // - else => throw IllegalArgumentException 15 | /* @see tests */ 16 | public List parseDates(List dateStrList) { 17 | DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd"); 18 | 19 | List dates = dateStrList.stream() 20 | .map(text -> LocalDate.parse(text, pattern)) 21 | .collect(toList()); 22 | 23 | return dates; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/LoanPattern.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import java.io.File; 4 | import java.io.FileWriter; 5 | import java.io.Writer; 6 | 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.boot.CommandLineRunner; 11 | import org.springframework.boot.SpringApplication; 12 | import org.springframework.boot.autoconfigure.SpringBootApplication; 13 | import org.springframework.stereotype.Service; 14 | import victor.training.java.advanced.repo.OrderRepo; 15 | 16 | @Service 17 | class FileExporter { 18 | @Autowired 19 | private OrderRepo orderRepo; 20 | @Value("${export.folder.out}") 21 | private File folder; 22 | 23 | public void exportFile() { 24 | File file = new File(folder, "orders.csv"); 25 | long t0 = System.currentTimeMillis(); 26 | try (Writer writer = new FileWriter(file)) { 27 | System.out.println("Starting export to: " + file.getAbsolutePath()); 28 | 29 | writer.write("OrderID;Date\n"); 30 | // orderRepo.findByActiveTrue() 31 | // .map(o -> o.getId() + ";" + o.getCreationDate() + "\n") 32 | // .forEach(writer::write); 33 | 34 | System.out.println("File export completed: " + file.getAbsolutePath()); 35 | } catch (Exception e) { 36 | System.out.println("Imagine: Send Error Notification Email"); 37 | throw new RuntimeException("Error exporting data", e); 38 | } finally { 39 | System.out.println("Export finished in: " + (System.currentTimeMillis()-t0)); 40 | } 41 | } 42 | } 43 | 44 | @RequiredArgsConstructor 45 | //@SpringBootApplication // enable on demand. 46 | public class LoanPattern implements CommandLineRunner { 47 | public static void main(String[] args) { 48 | SpringApplication.run(LoanPattern.class, args); 49 | } 50 | 51 | private final FileExporter fileExporter; 52 | public void run(String... args) throws Exception { 53 | fileExporter.exportFile(); 54 | 55 | // TODO implement export of users too 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/OptionalAdvancedApp.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.transaction.annotation.Transactional; 11 | import victor.training.java.advanced.model.Order; 12 | import victor.training.java.advanced.model.Product; 13 | import victor.training.java.advanced.repo.ProductRepo; 14 | import victor.training.java.advanced.repo.custom.CustomJpaRepositoryFactoryBean; 15 | 16 | import javax.persistence.EntityManager; 17 | import java.util.Optional; 18 | 19 | @RequiredArgsConstructor 20 | @EnableJpaRepositories(repositoryFactoryBeanClass = CustomJpaRepositoryFactoryBean.class) 21 | @SpringBootApplication 22 | public class OptionalAdvancedApp implements CommandLineRunner { 23 | public static void main(String[] args) { 24 | SpringApplication.run(OptionalAdvancedApp.class, args); 25 | } 26 | 27 | private final ProductRepo productRepo; 28 | @Autowired 29 | private EntityManager entityManager; 30 | 31 | @Transactional 32 | public void run(String... args) throws Exception { 33 | productRepo.save(new Product("Tree")); 34 | // ## --- Streaming queries --- 35 | productRepo.findAllByDeletedFalse() // imagine 1M products 36 | .peek(entityManager::detach) // OTHERWISE : MEMORY LEAK 37 | .forEach(System.out::println); 38 | // Also see JdbcTemplate#queryForStream 39 | 40 | // ## --- Optional Abuse? --- 41 | // Abuse 1: Optional<> as method argument => SRP violation 42 | // TODO @see victor.training.java.advanced.Optionals 43 | 44 | // Abuse 2: Optional created and terminated in the same method. 45 | excessOpt(new DeliveryDto()); 46 | 47 | // Abuse 3: **All** callers do .get / .orElseThrow on the Optional<> you return 48 | // Product p = productRepo.findById(13L); 49 | 50 | 51 | System.out.println("When search finds: "); 52 | System.out.println(productRepo.findByNameContaining("re")); 53 | System.out.println("When search DOESN'T find, repo returns:"); 54 | System.out.println(productRepo.findByNameContaining("rx")); 55 | 56 | } 57 | 58 | 59 | public static void excessOpt(DeliveryDto dto) { 60 | boolean duplicate = Optional.ofNullable(dto.recipientPerson) 61 | .map(name -> existsByName(name)) 62 | .orElse(false); 63 | if (duplicate) { 64 | System.out.println("DUPLICATE person!"); 65 | } 66 | } 67 | 68 | private static boolean existsByName(String name) { 69 | return true; 70 | } 71 | 72 | public void schizoMethod(Long customer, Optional orderOpt) { 73 | System.out.println("Logic Before"); 74 | if (orderOpt.isPresent()) { 75 | System.out.println("Logic With order"); 76 | } 77 | System.out.println("Logic After"); 78 | 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/OptionalChain.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | public class OptionalChain { 4 | static MyMapper mapper = new MyMapper(); 5 | public static void main(String[] args) { 6 | Parcel parcel = new Parcel() 7 | .setDelivery(new Delivery(new Address().setContactPerson(new ContactPerson("John")))); 8 | 9 | DeliveryDto dto = mapper.convert(parcel); 10 | System.out.println(dto); 11 | } 12 | } 13 | 14 | class MyMapper { 15 | public DeliveryDto convert(Parcel parcel) { 16 | DeliveryDto dto = new DeliveryDto(); 17 | // Game: how many NPE can you spot below ? 18 | dto.recipientPerson = parcel.getDelivery().getAddress().getContactPerson().getName().toUpperCase(); 19 | return dto; 20 | } 21 | 22 | public DeliveryDto pyramidOfNull(Parcel parcel) { 23 | DeliveryDto dto = new DeliveryDto(); 24 | if ( 25 | parcel!=null && 26 | parcel.getDelivery()!=null && 27 | parcel.getDelivery().getAddress()!=null && 28 | parcel.getDelivery().getAddress().getContactPerson()!=null && 29 | parcel.getDelivery().getAddress().getContactPerson().getName()!=null) { // null terror 30 | dto.recipientPerson = parcel.getDelivery().getAddress().getContactPerson().getName().toUpperCase(); 31 | } else { 32 | dto.recipientPerson = ""; 33 | } 34 | return dto; 35 | } 36 | 37 | 38 | } 39 | 40 | class DeliveryDto { 41 | public String recipientPerson; 42 | } 43 | 44 | class Parcel { 45 | private Delivery delivery; // NULL until a delivery is scheduled 46 | 47 | public Delivery getDelivery() { 48 | return delivery; 49 | } 50 | public Parcel setDelivery(Delivery delivery) { 51 | this.delivery = delivery; 52 | return this; 53 | } 54 | } 55 | 56 | 57 | class Delivery { 58 | private Address address; // 'NOT NULL' IN DB 59 | 60 | public Delivery(Address address) { 61 | this.address = address; 62 | } 63 | 64 | public void setAddress(Address address) { 65 | this.address = address; // TODO null safe 66 | } 67 | 68 | public Address getAddress() { 69 | return address; 70 | } 71 | } 72 | 73 | class Address { 74 | private ContactPerson contactPerson; // can be null 75 | 76 | public Address() { 77 | } 78 | 79 | public Address setContactPerson(ContactPerson contactPerson) { 80 | this.contactPerson = contactPerson; 81 | return this; 82 | } 83 | 84 | public ContactPerson getContactPerson() { 85 | return contactPerson; 86 | } 87 | } 88 | 89 | class ContactPerson { 90 | private final String name; // 'NOT NULL' in DB 91 | 92 | public ContactPerson(String name) { 93 | this.name = name; 94 | } 95 | 96 | public String getName() { 97 | return name; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/Optionals.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import lombok.Data; 4 | import victor.training.java.advanced.model.Customer; 5 | import victor.training.java.advanced.model.MemberCard; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | @SuppressWarnings("ConstantConditions") 11 | public class Optionals { 12 | public static void main(String[] args) { 13 | // test: 60, 10, no MemberCard 14 | System.out.println(getDiscountLine(new Customer(new MemberCard(60)))); 15 | } 16 | 17 | public static String getDiscountLine(Customer customer) { 18 | return "Discount: " + getApplicableDiscountPercentage(customer.getMemberCard()).getGlobalPercentage(); 19 | } 20 | 21 | private static Discount getApplicableDiscountPercentage(MemberCard card) { 22 | if (card.getFidelityPoints() >= 100) { 23 | return new Discount(5); 24 | } 25 | if (card.getFidelityPoints() >= 50) { 26 | return new Discount(3); 27 | } 28 | return null; 29 | } 30 | } 31 | 32 | @Data 33 | class Discount { 34 | private final int globalPercentage; 35 | private Map categoryDiscounts = new HashMap<>(); 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/ParallelStreams.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import lombok.SneakyThrows; 4 | import lombok.extern.slf4j.Slf4j; 5 | 6 | import java.util.List; 7 | import java.util.stream.IntStream; 8 | 9 | import static java.util.Arrays.asList; 10 | import static java.util.stream.Collectors.toList; 11 | import static victor.training.java.advanced.tricks.ConcurrencyUtil.sleepq; 12 | 13 | @Slf4j 14 | public class ParallelStreams { 15 | public static void main(String[] args) { 16 | // Enemy.parallelRequest(); 17 | 18 | long t0 = System.currentTimeMillis(); 19 | 20 | List list = IntStream.range(1,100).boxed().collect(toList()); 21 | 22 | List result = list.stream() 23 | .filter(i -> { 24 | log.debug("Filter " + i); 25 | return i % 2 == 0; 26 | }) 27 | .map(i -> { 28 | log.debug("Map " + i); 29 | sleepq(100); // do some 'paralellizable' I/O work (DB, REST, SOAP) 30 | return i * 2; 31 | }) 32 | .collect(toList()); 33 | log.debug("Got result: " + result); 34 | 35 | long t1 = System.currentTimeMillis(); 36 | log.debug("Took {} ms", t1 - t0); 37 | } 38 | } 39 | 40 | // =========== far away, in a distant Package ...... ============= 41 | @Slf4j 42 | class Enemy { 43 | @SneakyThrows 44 | public static void parallelRequest() { 45 | Thread thread = new Thread(Enemy::optimized); 46 | thread.setDaemon(true); // to exit program 47 | thread.start(); 48 | Thread.sleep(100); 49 | } 50 | public static void optimized() { 51 | int result = IntStream.range(1, 1000) 52 | .parallel() 53 | .map(Enemy::callNetworkOrDB) 54 | .sum(); 55 | System.out.println(result); 56 | } 57 | 58 | @SneakyThrows 59 | public static int callNetworkOrDB(int id) { 60 | log.debug("Blocking..."); 61 | Thread.sleep(1000); 62 | return id*2; 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/SplitLoopToStream.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import victor.training.java.advanced.model.User; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | public class SplitLoopToStream { 10 | 11 | // see tests 12 | public void bossLevel(List users) { 13 | List allUsernames = new ArrayList<>(); 14 | int missingLanguageCount = 0; 15 | int totalTickets = 0; 16 | for (User user : users) { 17 | allUsernames.add(user.getUsername()); 18 | if (user.getLanguage() == null) { 19 | missingLanguageCount++; 20 | } 21 | if (!user.getActive()) { 22 | insertInactiveAlert(user.getId()); 23 | continue; 24 | } 25 | totalTickets += user.getTicketsRaised(); 26 | } 27 | double noLanguagePercent = 100d * missingLanguageCount / users.size(); 28 | System.out.printf("No language set = %.2f%%\n", noLanguagePercent); 29 | System.out.printf("Number of tickets = %d\n", totalTickets); 30 | writeToFile(allUsernames); 31 | } 32 | 33 | private void writeToFile(List usernames) { 34 | System.out.println("Write to file: " + usernames); 35 | // omitted 36 | } 37 | 38 | private void insertInactiveAlert(Long userId) { 39 | System.out.println("Alert inactive user: " + userId); 40 | // omitted 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/StreamWreck.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import victor.training.java.advanced.model.Order; 4 | import victor.training.java.advanced.model.OrderLine; 5 | import victor.training.java.advanced.model.Product; 6 | import victor.training.java.advanced.repo.ProductRepo; 7 | 8 | import java.time.LocalDate; 9 | import java.util.List; 10 | import java.util.Map.Entry; 11 | 12 | import static java.util.stream.Collectors.*; 13 | 14 | public class StreamWreck { 15 | private ProductRepo productRepo; 16 | 17 | public List getFrequentOrderedProducts(List orders) { 18 | return orders.stream() 19 | .filter(o -> o.getCreationDate().isAfter(LocalDate.now().minusYears(1))) 20 | .flatMap(o -> o.getOrderLines().stream()) 21 | .collect(groupingBy(OrderLine::getProduct, summingInt(OrderLine::getItemCount))) 22 | .entrySet() 23 | .stream() 24 | .filter(e -> e.getValue() >= 10) 25 | .map(Entry::getKey) 26 | .filter(p -> !p.isDeleted()) 27 | .filter(p -> !productRepo.findByHiddenTrue().contains(p)) 28 | .collect(toList()); 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/Switch.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.stereotype.Service; 6 | 7 | enum MovieType { 8 | REGULAR, 9 | NEW_RELEASE, 10 | CHILDREN, 11 | 12 | } 13 | 14 | @Service 15 | public class Switch { 16 | @Value("${children.price}") 17 | private int childrenPrice = 5; // pretend Spring is ON 18 | 19 | // @see tests 20 | public static int computePrice(MovieType type, int days) { 21 | switch (type) { 22 | case REGULAR: 23 | return days + 1; 24 | case NEW_RELEASE: 25 | return days * 2; 26 | case CHILDREN: 27 | return 5; 28 | } 29 | return 0; // opinions? 30 | } 31 | 32 | public void auditDelayReturn(MovieType movieType, int delayDays) { 33 | switch (movieType) { 34 | case REGULAR: 35 | System.out.println("Regular delayed by " + delayDays);break; 36 | case NEW_RELEASE: 37 | System.out.println("CRITICAL: new release return delayed by " + delayDays);break; 38 | } 39 | } 40 | } 41 | 42 | 43 | class MySpecialCaseNotFoundException extends RuntimeException { 44 | } -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/Customer.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | // @Entity - The HOLY ENTITY ! 4 | public class Customer { 5 | private MemberCard memberCard; 6 | 7 | public Customer() { 8 | } 9 | 10 | public Customer(MemberCard profile) { 11 | this.memberCard = profile; 12 | } 13 | 14 | public MemberCard getMemberCard() { 15 | return memberCard; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/Language.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | public enum Language { 4 | ENGLISH, 5 | FRENCH, 6 | ITALIAN, 7 | GERMAN 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/MemberCard.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | public class MemberCard { 4 | private final int fidelityPoints; 5 | 6 | public MemberCard(int fidelityPoints) { 7 | this.fidelityPoints = fidelityPoints; 8 | } 9 | 10 | public int getFidelityPoints() { 11 | return fidelityPoints; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/Order.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.time.LocalDate; 7 | import java.util.List; 8 | 9 | @Data 10 | @Entity 11 | @Table(name = "ORDERS") 12 | public class Order { 13 | @Id 14 | @GeneratedValue 15 | private Long id; 16 | @Transient // cheat 17 | private List orderLines; 18 | private LocalDate creationDate; 19 | @Transient // cheat 20 | private Customer customer; 21 | private Boolean active; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/OrderLine.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderLine { 7 | private Product product; 8 | private int itemCount; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/Product.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | 9 | import static lombok.AccessLevel.PRIVATE; 10 | 11 | @Getter 12 | @Setter 13 | @ToString 14 | @Entity 15 | @NoArgsConstructor(access = PRIVATE) 16 | public class Product { 17 | @Id 18 | @GeneratedValue 19 | @EqualsAndHashCode.Exclude 20 | private Long id; 21 | private String name; 22 | private boolean deleted; 23 | private boolean hidden; 24 | 25 | public Product(String name) { 26 | this.name = name; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/model/User.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.Enumerated; 8 | import javax.persistence.Id; 9 | 10 | import static javax.persistence.EnumType.STRING; 11 | 12 | @Getter 13 | @Setter 14 | @Entity 15 | public class User { 16 | @Id 17 | private Long id; 18 | private String username; 19 | private String fullName; 20 | private Boolean active = true; 21 | private Integer ticketsRaised; 22 | @Enumerated(STRING) 23 | private Language language; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/OrderRepo.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import victor.training.java.advanced.model.Order; 5 | 6 | import java.util.stream.Stream; 7 | 8 | public interface OrderRepo extends JpaRepository { // Spring Data FanClub 9 | Stream findByActiveTrue(); // 1 Mln orders ;) 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/ProductRepo.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import victor.training.java.advanced.model.Product; 5 | import victor.training.java.advanced.repo.custom.CustomJpaRepository; 6 | 7 | import java.util.List; 8 | import java.util.stream.Stream; 9 | 10 | public interface ProductRepo extends CustomJpaRepository { 11 | List findByHiddenTrue(); 12 | 13 | Product findByNameContaining(String namePart); 14 | 15 | Stream findAllByDeletedFalse(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/UserRepo.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import victor.training.java.advanced.model.User; 5 | 6 | public interface UserRepo extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/custom/CustomJpaRepository.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo.custom; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.repository.NoRepositoryBean; 5 | 6 | import java.io.Serializable; 7 | 8 | @NoRepositoryBean 9 | public interface CustomJpaRepository extends JpaRepository { 10 | /** 11 | * @param id the PK to lookup 12 | * @return the Entity. Never null. 13 | * @throws javax.persistence.EntityNotFoundException when ID not found in DB 14 | */ 15 | T findOneById(ID id); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/custom/CustomJpaRepositoryFactoryBean.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo.custom; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.support.JpaEntityInformation; 5 | import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; 6 | import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; 7 | import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation; 8 | import org.springframework.data.repository.core.RepositoryInformation; 9 | import org.springframework.data.repository.core.RepositoryMetadata; 10 | import org.springframework.data.repository.core.support.RepositoryFactorySupport; 11 | 12 | import javax.persistence.EntityManager; 13 | import java.io.Serializable; 14 | 15 | public class CustomJpaRepositoryFactoryBean, T, ID extends Serializable> 16 | extends JpaRepositoryFactoryBean { 17 | public CustomJpaRepositoryFactoryBean(Class repositoryInterface) { 18 | super(repositoryInterface); 19 | } 20 | 21 | @SuppressWarnings("rawtypes") 22 | protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) { 23 | return new EntityRepositoryFactory(em); 24 | } 25 | 26 | private static class EntityRepositoryFactory extends JpaRepositoryFactory { 27 | public EntityRepositoryFactory(EntityManager entityManager) { 28 | super(entityManager); 29 | } 30 | 31 | @Override 32 | @SuppressWarnings("unchecked") 33 | protected JpaRepositoryImplementation getTargetRepository(RepositoryInformation information, EntityManager entityManager) { 34 | JpaEntityInformation entityInformation = (JpaEntityInformation) getEntityInformation(information.getDomainType()); 35 | return new CustomJpaRepositoryImpl( entityInformation, entityManager); 36 | } 37 | @Override 38 | protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { 39 | return CustomJpaRepositoryImpl.class; 40 | } 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/custom/CustomJpaRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.repo.custom; 2 | 3 | import org.springframework.data.jpa.repository.support.JpaEntityInformation; 4 | import org.springframework.data.jpa.repository.support.SimpleJpaRepository; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityNotFoundException; 8 | import java.io.Serializable; 9 | 10 | public class CustomJpaRepositoryImpl extends SimpleJpaRepository implements CustomJpaRepository { 11 | 12 | protected EntityManager entityManager; 13 | 14 | public CustomJpaRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { 15 | super(entityInformation, entityManager); 16 | this.entityManager = entityManager; 17 | } 18 | 19 | @Override 20 | public T findOneById(ID id) { 21 | return findById(id).orElseThrow(() -> 22 | new EntityNotFoundException("No " + getDomainClass().getSimpleName() + " with id " + id)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/repo/package-info.java: -------------------------------------------------------------------------------- 1 | //@NonNullApi 2 | package victor.training.java.advanced.repo; 3 | 4 | // @NotNullApi on the Spring Data Repos package will cause 5 | // any generated repo method to return a null. 6 | 7 | // Instead of returning raw type (eg Order getLastOrderByCustomerId(customerId)) 8 | // it will force you to return an Optional if the calling code 9 | // is ever able to accept not finding a last order for the customer. 10 | 11 | // With this annotation, if there is no last order: 12 | // Order getLastOrderByCustomerId(customerId) => throws 13 | // Optional getLastOrderByCustomerId(customerId) => returns Optional.empty() -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/tricks/ConcurrencyUtil.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.tricks; 2 | 3 | public class ConcurrencyUtil { 4 | /** 5 | * Sleeps quietly (without throwing anything out) 6 | */ 7 | public static void sleepq(long millis) { 8 | try { 9 | Thread.sleep(millis); 10 | } catch (InterruptedException e) { 11 | throw new RuntimeException(e); 12 | } 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/tricks/StableSort.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.tricks; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import static java.util.Comparator.comparing; 8 | 9 | public class StableSort { 10 | public static void main(String[] args) { 11 | System.out.println("first click on the 'name' column -> ASC"); 12 | fetchDataFromDb().stream() 13 | .sorted(comparing(Record::getFirstName)) 14 | .forEach(System.out::println); 15 | 16 | System.out.println("\nsecond click on the 'name' column -> DESC"); 17 | fetchDataFromDb().stream() 18 | .sorted(comparing(Record::getFirstName).reversed()) 19 | .forEach(System.out::println); 20 | 21 | // UX sucks. TODO Fix it: the order within the "Alfred" subgroup is variable 22 | } 23 | 24 | private static List fetchDataFromDb() { 25 | List list = Arrays.asList( 26 | new Record(1L, "Alfred", "12345"), 27 | new Record(2L, "Alfred", "12346"), 28 | new Record(3L, "Alfred", "12347"), 29 | new Record(4L, "Alfred", "12348"), 30 | new Record(5L, "Bob", "12350")); 31 | Collections.shuffle(list); // simulate random result order from datastore 32 | return list; 33 | } 34 | } 35 | 36 | class Record { 37 | private Long id; 38 | private String firstName; 39 | private String cnp; 40 | 41 | public Record(Long id, String firstName, String cnp) { 42 | this.id = id; 43 | this.firstName = firstName; 44 | this.cnp = cnp; 45 | } 46 | 47 | public String getFirstName() { 48 | return firstName; 49 | } 50 | 51 | public Long getId() { 52 | return id; 53 | } 54 | 55 | public String getCnp() { 56 | return cnp; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "Record{" + 62 | "id=" + id + 63 | ", firstName='" + firstName + '\'' + 64 | ", cnp='" + cnp + '\'' + 65 | '}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/tricks/StreamSupplier.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.tricks; 2 | 3 | import org.jooq.lambda.Unchecked; 4 | 5 | import java.io.File; 6 | import java.nio.file.Files; 7 | import java.util.function.Supplier; 8 | import java.util.stream.Stream; 9 | 10 | import static java.util.Comparator.comparing; 11 | 12 | public class StreamSupplier { 13 | public static void main(String[] args) { 14 | supplierOfStream(); 15 | } 16 | 17 | private static void supplierOfStream() { 18 | File file = new File("test.ok.txt"); 19 | processRecords(Unchecked.supplier(() -> Files.lines(file.toPath()))); 20 | } 21 | 22 | private static void processRecords(Supplier> lineSupplier) { 23 | try (Stream lines = lineSupplier.get()) { 24 | System.out.println("Lines count: " + lines.count()); 25 | } 26 | try (Stream lines = lineSupplier.get()) { 27 | System.out.println("Longest line: " + lines.max(comparing(String::length))); 28 | } 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/advanced/tricks/Trap_toMap_nullKey.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced.tricks; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.stream.Collectors; 8 | 9 | import static java.util.Arrays.asList; 10 | 11 | public class Trap_toMap_nullKey { 12 | @Data 13 | private static class Person { 14 | private final Long id; 15 | private final String name; 16 | } 17 | public static void main(String[] args) { 18 | toMapWithNullValues(); 19 | } 20 | private static void toMapWithNullValues() { 21 | List list = asList(new Person(1L, "John"), new Person(2L, null)); 22 | Map map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName)); 23 | System.out.println(map); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/java17/DisplayShape.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.java17; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.util.function.Consumer; 6 | 7 | public class DisplayShape { 8 | 9 | public static void display(Consumer drawFunction) { 10 | class MyPanel extends JPanel { 11 | public Dimension getPreferredSize() { 12 | return new Dimension(250,200); 13 | } 14 | public void paintComponent(Graphics g) { 15 | super.paintComponent(g); 16 | // TODO draw here 17 | drawFunction.accept(g); 18 | } 19 | } 20 | SwingUtilities.invokeLater(() -> { 21 | JFrame f = new JFrame("Demo"); 22 | f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 23 | f.add(new MyPanel()); 24 | f.pack(); 25 | f.setLocationByPlatform(true); 26 | f.setVisible(true); 27 | }); 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/java17/Records.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.java17; 2 | 3 | import org.jooq.lambda.tuple.Tuple; 4 | import org.jooq.lambda.tuple.Tuple2; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Objects; 10 | import java.util.stream.IntStream; 11 | 12 | import static java.util.stream.Collectors.joining; 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | public class Records { 16 | 17 | public Map>> extremeFP() { 18 | Long customerId = 1L; 19 | Integer product1Count = 2; 20 | Integer product2Count = 4; 21 | return Map.of(customerId, List.of( 22 | Tuple.tuple("Table", product1Count), 23 | Tuple.tuple("Chair", product2Count) 24 | )); 25 | } 26 | 27 | @Test 28 | void lackOfAbstractions() { 29 | Map>> map = extremeFP(); 30 | // Joke: try "var" above :) 31 | 32 | for (Long cid : map.keySet()) { 33 | String pl = map.get(cid).stream() 34 | .map(t -> t.v2 + " of " + t.v1) 35 | .collect(joining(", ")); 36 | System.out.println("cid=" + cid + " got " + pl); 37 | } 38 | } 39 | 40 | @Test 41 | void immutables() { 42 | List numbers = IntStream.range(1, 10).boxed().toList(); 43 | Immutable obj = new Immutable("John", new Other("halo"), numbers); 44 | 45 | String original = obj.toString(); 46 | System.out.println(obj); 47 | 48 | unknownFierceCode(obj); 49 | 50 | System.out.println(obj); 51 | 52 | assertThat(original).describedAs("State should not change!").isEqualTo(obj.toString()); 53 | } 54 | 55 | private static void unknownFierceCode(Immutable obj) { 56 | // TODO what can go wrong here ? 57 | } 58 | } 59 | 60 | // -- RECORD -- 61 | // methods: add extra, overriding generated 62 | // constructor: 63 | // inheritance: 64 | 65 | 66 | class Immutable { 67 | private final String name; 68 | private final Other other; 69 | private final List list; 70 | 71 | public Immutable(String name, Other other, List list) { 72 | this.name = name; 73 | this.other = other; 74 | this.list = list; 75 | } 76 | 77 | public String getName() { 78 | return name; 79 | } 80 | 81 | public Other getOther() { 82 | return other; 83 | } 84 | 85 | public List getList() { 86 | return list; 87 | } 88 | 89 | @Override 90 | public boolean equals(Object o) { 91 | if (this == o) return true; 92 | if (o == null || getClass() != o.getClass()) return false; 93 | Immutable immutable = (Immutable) o; 94 | return Objects.equals(name, immutable.name) && Objects.equals(other, immutable.other) && Objects.equals(list, immutable.list); 95 | } 96 | 97 | @Override 98 | public int hashCode() { 99 | return Objects.hash(name, other, list); 100 | } 101 | 102 | @Override 103 | public String toString() { 104 | return "Immutable{" + 105 | "name='" + name + '\'' + 106 | ", other=" + other + 107 | ", list=" + list + 108 | '}'; 109 | } 110 | } 111 | 112 | class Other { 113 | private String data; 114 | 115 | public Other(String data) { 116 | this.data = data; 117 | } 118 | 119 | public String getData() { 120 | return data; 121 | } 122 | 123 | public Other setData(String data) { 124 | this.data = data; 125 | return this; 126 | } 127 | 128 | @Override 129 | public String toString() { 130 | return "Other{" + 131 | "data='" + data + '\'' + 132 | '}'; 133 | } 134 | } -------------------------------------------------------------------------------- /src/main/java/victor/training/java/java17/Sealed.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.java17; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.List; 6 | 7 | public class Sealed { 8 | private static final List shapes = List.of( 9 | new Circle(10), 10 | new Square(10), 11 | new Square(5)); 12 | 13 | @Test 14 | void perimeter() { 15 | double totalPerimeter = 0; 16 | for (Shape shape : shapes) { 17 | // TODO 18 | } 19 | System.out.println("Total perimeter: " + totalPerimeter); 20 | } 21 | 22 | public static void main(String[] args) { 23 | for (Shape shape : shapes) { 24 | // TODO display all shapes 25 | } 26 | // examples 27 | DisplayShape.display(graphics -> { 28 | graphics.drawOval(10, 10, 10, 20); 29 | }); 30 | DisplayShape.display(graphics -> { 31 | graphics.drawRect(10, 10, 10, 30); 32 | }); 33 | } 34 | 35 | } 36 | 37 | 38 | interface Shape { 39 | 40 | } 41 | 42 | final class Circle implements Shape { 43 | private final int radius; 44 | 45 | Circle(int radius) { 46 | this.radius = radius; 47 | } 48 | 49 | public int radius() { 50 | return radius; 51 | } 52 | } 53 | 54 | final class Square implements Shape { 55 | private final int edge; 56 | 57 | Square(int edge) { 58 | this.edge = edge; 59 | } 60 | 61 | public int edge() { 62 | return edge; 63 | } 64 | } 65 | 66 | // ======== HAZARD AREA: VISITOR PATTERN ========== 67 | interface ShapeVisitor { 68 | void visit(Square square); 69 | 70 | void visit(Circle circle); 71 | } 72 | 73 | class PerimeterCalculatorVisitor implements ShapeVisitor { 74 | private double total; 75 | 76 | @Override 77 | public void visit(Square square) { 78 | total += 4 * square.edge(); 79 | } 80 | 81 | @Override 82 | public void visit(Circle circle) { 83 | total += circle.radius() * 2 * Math.PI; 84 | } 85 | 86 | public double getTotal() { 87 | return total; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/java17/TextBlocks.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.java17; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.test.web.servlet.MockMvc; 8 | import victor.training.java.stream.order.entity.Order; 9 | 10 | import java.util.List; 11 | 12 | import static org.hamcrest.Matchers.hasSize; 13 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 15 | 16 | public class TextBlocks { 17 | 18 | interface SomeSpringDataRepo extends JpaRepository { 19 | @Query("SELECT t FROM TeachingActivity a JOIN a.teachers t WHERE " 20 | + "a.id IN (SELECT c.id FROM StudentsYear y JOIN y.courses c WHERE y.id = :yearId) " 21 | + "OR a.id IN (SELECT lab.id FROM StudentsYear y JOIN y.groups g JOIN g.labs lab WHERE y.id = :yearId)") 22 | List complexQuery(long id1, long id2); // bogus 23 | } 24 | 25 | @Autowired 26 | MockMvc mockMvc; 27 | @Test 28 | void test() throws Exception { 29 | mockMvc.perform(post("/product/search") 30 | .contentType("application/json") 31 | .content("{\"name\":\"somth\"}") // add one more criteria 32 | ) 33 | .andExpect(status().isOk()) // 200 34 | .andExpect(jsonPath("$", hasSize(1))); 35 | } 36 | 37 | // TODO + test of Loan Pattern -> 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/BasicsRecap.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.function.BiFunction; 7 | import java.util.function.Consumer; 8 | import java.util.function.Function; 9 | 10 | import static java.lang.Integer.parseInt; 11 | 12 | public class BasicsRecap { 13 | public static void main(String[] args) { 14 | List strings = new ArrayList<>(); 15 | 16 | Consumer f1 = strings::add; 17 | BiFunction f2 = BasicsRecap::convert; 18 | 19 | MyEntity myEntity = new MyEntity(); 20 | MyDto dto = new MyDto(myEntity); // compiles 21 | Function f3 = MyDto::new; 22 | 23 | 24 | } 25 | 26 | public Integer convert(String s) { 27 | return parseInt(s); 28 | } 29 | static class MyEntity {} 30 | static class MyDto { 31 | public MyDto(MyEntity entity) {} 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/menu/Dish.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.menu; 2 | 3 | public class Dish { 4 | private final String name; 5 | private final boolean vegetarian; 6 | private final int calories; 7 | private final Type type; 8 | 9 | public enum Type { MEAT, FISH, OTHER } 10 | 11 | public Dish(String name, boolean vegetarian, int calories, Type type) { 12 | this.name = name; 13 | this.vegetarian = vegetarian; 14 | this.calories = calories; 15 | this.type = type; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public boolean isVegetarian() { 23 | return vegetarian; 24 | } 25 | 26 | public int getCalories() { 27 | return calories; 28 | } 29 | 30 | public Type getType() { 31 | return type; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return name; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/menu/DishPlay.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.menu; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class DishPlay { 7 | public static final List menu = Arrays.asList( 8 | new Dish("pork", false, 800, Dish.Type.MEAT), 9 | new Dish("beef", false, 700, Dish.Type.MEAT), 10 | new Dish("chicken", false, 400, Dish.Type.MEAT), 11 | new Dish("french fries", true, 530, Dish.Type.OTHER), 12 | new Dish("rice", true, 350, Dish.Type.OTHER), 13 | new Dish("season fruit", true, 120, Dish.Type.OTHER), 14 | new Dish("pizza", true, 550, Dish.Type.OTHER), 15 | new Dish("prawns", false, 300, Dish.Type.FISH), 16 | new Dish("salmon", false, 450, Dish.Type.FISH)); 17 | 18 | public static void main(String[] args) { 19 | // The above code sample + problems are from Java 8 in Action book (Manning) 20 | 21 | // TODO select the low-calories (<400) items 22 | 23 | // TODO find out three high-calorie dish names 24 | 25 | // TODO find out the 2nd and 3rd most caloric items 26 | 27 | // TODO find vegetarian dishes 28 | 29 | // TODO find 2 dishes with meat 30 | 31 | // TODO Map>> dishesByTypeAndCaloricLevel 32 | 33 | // TODO Map typesCount 34 | 35 | // TODO Map> groupedAsSets 36 | 37 | // TODO Map totalCaloriesByType 38 | 39 | // TODO Map> mostCaloricByType 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/CreateStreams.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import victor.training.java.stream.order.entity.OrderLine; 4 | import victor.training.java.stream.order.entity.Product; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.util.List; 9 | import java.util.stream.Stream; 10 | 11 | public class CreateStreams { 12 | 13 | 14 | /** 15 | * - Read lines from file as Strings. 16 | * - Where do you close the opened file? 17 | * - Parse those to OrderLine using the function bellow 18 | * - Validate the created OrderLine. Throw ? :S 19 | */ 20 | public List p1_readOrderFromFile(File file) throws IOException { 21 | 22 | Stream lines = null; // ?? 23 | //return lines 24 | //.map(line -> line.split(";")) // Stream 25 | //.filter(cell -> "LINE".equals(cell[0])) 26 | //.map(this::parseOrderLine) // Stream 27 | //.peek(this::validateOrderLine) 28 | //.collect(toList()); 29 | 30 | // TODO check the number of lines is >= 2 31 | 32 | return null; 33 | 34 | } 35 | 36 | private OrderLine parseOrderLine(String[] cells) { 37 | return new OrderLine(new Product(cells[1]), Integer.parseInt(cells[2])); 38 | } 39 | 40 | private void validateOrderLine(OrderLine orderLine) { 41 | if (orderLine.getCount() < 0) { 42 | throw new IllegalArgumentException("Negative items"); 43 | } 44 | } 45 | 46 | public Stream p2_createFibonacciStream() { 47 | return Stream.of(1,1,2,3,5); 48 | } 49 | 50 | public Stream p3_createPseudoRandomStream(int seed) { 51 | return Stream.of(1); 52 | } 53 | 54 | public Stream p4_getAllPaths(File folder) { 55 | // TODO print cannonical paths of all files in given directory and subdirectories 56 | System.out.println("folder = " + folder.getAbsolutePath()); 57 | return null; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/CreateStreamsTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import org.junit.jupiter.api.MethodOrderer.MethodName; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.TestMethodOrder; 6 | import victor.training.java.stream.order.entity.OrderLine; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.Set; 13 | import java.util.stream.Stream; 14 | 15 | import static java.util.stream.Collectors.toList; 16 | import static java.util.stream.Collectors.toSet; 17 | import static org.junit.jupiter.api.Assertions.*; 18 | 19 | @TestMethodOrder(MethodName.class) 20 | public class CreateStreamsTest { 21 | private CreateStreams service = new CreateStreams(); 22 | 23 | 24 | @Test 25 | public void p1_readOrderFromFile() throws IOException { 26 | List orderLines = service.p1_readOrderFromFile(new File("test.ok.txt")); 27 | assertEquals("Chair", orderLines.get(0).getProduct().getName()); 28 | assertEquals(2, orderLines.get(0).getCount()); 29 | assertEquals("Table", orderLines.get(1).getProduct().getName()); 30 | assertEquals(1, orderLines.get(1).getCount()); 31 | } 32 | 33 | @Test 34 | public void p1_readOrderFromFile_throws() throws IOException { 35 | assertThrows(IllegalArgumentException.class, () -> 36 | service.p1_readOrderFromFile(new File("test.invalid.txt"))); // look at stacktrace 37 | // TODO uncomment to see the exception trace :S 38 | } 39 | 40 | @Test 41 | public void p2_fibonacci() { 42 | List actual10 = service.p2_createFibonacciStream().limit(10).collect(toList()); 43 | List expected10 = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55); 44 | assertEquals(expected10, actual10); 45 | } 46 | 47 | @Test 48 | public void p4_getAllPaths() { 49 | Stream pathsStream = service.p4_getAllPaths(new File("src/main/java")); 50 | Set set = pathsStream.collect(toSet()); 51 | assertTrue(set.stream().anyMatch(p -> p.contains("/CreateStreamsTest.java"))); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/SearchStreams.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import static java.util.stream.Collectors.toList; 4 | 5 | import java.util.List; 6 | 7 | import victor.training.java.stream.order.entity.Customer; 8 | import victor.training.java.stream.order.entity.Order; 9 | 10 | public class SearchStreams { 11 | /** 12 | * - shorten/clean it up 13 | */ 14 | public List p1_getActiveOrders(Customer customer) { 15 | return customer.getOrders().stream() 16 | .filter(order -> order.getStatus() == Order.Status.ACTIVE) 17 | .collect(toList()); 18 | } 19 | 20 | /** 21 | * @return the Order in the list with the given id, or null if not found 22 | * - findAny or findFirst ? 23 | */ 24 | public Order p2_getOrderById(List orders, long orderId) { 25 | return null; 26 | } 27 | 28 | /** 29 | * @return true if customer has at least one order with status ACTIVE 30 | */ 31 | public boolean p3_hasActiveOrders(Customer customer) { 32 | return true; 33 | } 34 | 35 | /** 36 | * An Order can be returned if it doesn't contain 37 | * any OrderLine with isSpecialOffer()==true 38 | */ 39 | public boolean p4_canBeReturned(Order order) { 40 | return true; // order.getOrderLines().stream() 41 | } 42 | 43 | /** 44 | * Return the Order with maximum getTotalPrice. 45 | * i.e. the most expensive Order, or null if no Orders 46 | * - Challenge: return an Optional 47 | */ 48 | public Order p5_getMaxPriceOrder(Customer customer) { 49 | return null; 50 | } 51 | 52 | /** 53 | * last 3 Orders sorted descending by creationDate 54 | */ 55 | public List p6_getLatestOrders(Customer customer) { 56 | return null; 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/SearchStreamsTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import static java.time.LocalDate.now; 4 | import static org.junit.jupiter.api.Assertions.*; 5 | 6 | import java.math.BigDecimal; 7 | import java.time.LocalDate; 8 | import java.util.Arrays; 9 | import java.util.List; 10 | 11 | import org.junit.jupiter.api.MethodOrderer.MethodName; 12 | import org.junit.jupiter.api.Test; 13 | import org.junit.jupiter.api.TestMethodOrder; 14 | 15 | import victor.training.java.stream.order.entity.Customer; 16 | import victor.training.java.stream.order.entity.Order; 17 | import victor.training.java.stream.order.entity.OrderLine; 18 | import victor.training.java.stream.order.entity.Order.Status; 19 | 20 | @TestMethodOrder(MethodName.class) 21 | public class SearchStreamsTest { 22 | 23 | private SearchStreams service = new SearchStreams(); 24 | 25 | @Test 26 | public void p1_getActiveOrders() { 27 | Order order1 = new Order(Status.ACTIVE); 28 | Order order2 = new Order(Status.ACTIVE); 29 | Order order3 = new Order(Status.DRAFT); 30 | Customer customer = new Customer(order1, order2, order3); 31 | assertEquals(Arrays.asList(order1, order2), service.p1_getActiveOrders(customer)); 32 | } 33 | 34 | @Test 35 | public void p2_getOrderById() { 36 | List orders = Arrays.asList(new Order(1L), new Order(2L), new Order(3L)); 37 | assertEquals(2L, (long) service.p2_getOrderById(orders, 2L).getId()); 38 | } 39 | 40 | @Test 41 | // @Ignore 42 | public void p2_getOrderById_whenIdNotFound() { 43 | List orders = Arrays.asList(new Order(1L)); 44 | assertEquals(null, service.p2_getOrderById(orders, 1000L)); 45 | } 46 | 47 | @Test 48 | public void p3_hasActiveOrders_true() { 49 | Customer customer = new Customer(new Order(Status.INACTIVE), new Order(Status.ACTIVE)); 50 | assertTrue(service.p3_hasActiveOrders(customer)); 51 | } 52 | 53 | @Test 54 | public void p3_hasActiveOrders_false() { 55 | Customer customer = new Customer(new Order(Status.INACTIVE)); 56 | assertFalse(service.p3_hasActiveOrders(customer)); 57 | } 58 | 59 | @Test 60 | public void p4_canBeReturned_frue() { 61 | Order order = new Order(new OrderLine()); 62 | assertTrue(service.p4_canBeReturned(order)); 63 | } 64 | 65 | @Test 66 | public void p4_canBeReturned_false() { 67 | OrderLine specialOffer = new OrderLine().setSpecialOffer(true); 68 | Order order = new Order(specialOffer, new OrderLine()); 69 | assertFalse(service.p4_canBeReturned(order)); 70 | } 71 | 72 | @Test 73 | public void p5_getMaxPriceOrder() { 74 | LocalDate yesterday = now().minusDays(1); 75 | Order order1 = new Order().setTotalPrice(BigDecimal.ONE).setCreationDate(now()); 76 | Order order2 = new Order().setTotalPrice(BigDecimal.TEN).setCreationDate(yesterday); 77 | assertEquals(order2, service.p5_getMaxPriceOrder(new Customer(order1, order2))); 78 | // assertEquals(yesterday, service.p5_getMaxPriceOrder(new Customer(order1, order2)).get()); 79 | } 80 | 81 | @Test 82 | public void p5_getMaxPriceOrder_whenNoOrders_returnsNothing() { 83 | assertNull(service.p5_getMaxPriceOrder(new Customer())); 84 | // assertFalse(service.p5_getMaxPriceOrder(new Customer()).isPresent()); 85 | } 86 | 87 | @Test 88 | public void p6_getLast3Orders() { 89 | Order order1 = new Order().setCreationDate(LocalDate.parse("2016-01-01")); 90 | Order order2 = new Order().setCreationDate(LocalDate.parse("2016-01-02")); 91 | Order order3 = new Order().setCreationDate(LocalDate.parse("2016-01-03")); 92 | Order order4 = new Order().setCreationDate(LocalDate.parse("2016-01-04")); 93 | 94 | Customer customer = new Customer(order1, order2, order3, order4); 95 | assertEquals(Arrays.asList(order4,order3,order2), service.p6_getLatestOrders(customer)); 96 | } 97 | 98 | @Test 99 | public void p6_getLast3Orders_whenOnlyTwoOrders() { 100 | Order order1 = new Order().setCreationDate(LocalDate.parse("2016-01-01")); 101 | Order order2 = new Order().setCreationDate(LocalDate.parse("2016-01-02")); 102 | 103 | Customer customer = new Customer(order1, order2); 104 | assertEquals(Arrays.asList(order2, order1), service.p6_getLatestOrders(customer)); 105 | } 106 | 107 | @Test 108 | public void p6_getLast3Orders_whenNoOrders() { 109 | Customer customer = new Customer(); 110 | assertEquals(Arrays.asList(), service.p6_getLatestOrders(customer)); 111 | } 112 | 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/TransformStreams.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import static java.util.stream.Collectors.groupingBy; 4 | import static java.util.stream.Collectors.joining; 5 | import static java.util.stream.Collectors.toMap; 6 | 7 | import java.time.LocalDate; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.Set; 12 | import java.util.SortedSet; 13 | 14 | import victor.training.java.stream.order.dto.OrderDto; 15 | import victor.training.java.stream.order.entity.Customer; 16 | import victor.training.java.stream.order.entity.Order; 17 | import victor.training.java.stream.order.entity.OrderLine; 18 | import victor.training.java.stream.order.entity.Product; 19 | import victor.training.java.stream.order.entity.Order.PaymentMethod; 20 | 21 | public class TransformStreams { 22 | 23 | /** 24 | * Transform all entities to DTOs. 25 | * use .map 26 | */ 27 | public List p01_toDtos(List orders) { 28 | 29 | List dtos = new ArrayList<>(); 30 | for (Order order : orders) { 31 | OrderDto dto = new OrderDto(); 32 | dto.totalPrice = order.getTotalPrice(); 33 | dto.creationDate = order.getCreationDate(); 34 | dtos.add(dto); 35 | } 36 | return dtos; 37 | 38 | } 39 | 40 | /** 41 | * Note: Order.getPaymentMethod() 42 | */ 43 | public Set p02_getUsedPaymentMethods(Customer customer) { 44 | return null; 45 | } 46 | 47 | /** 48 | * When did the customer created orders ? 49 | * Note: Order.getCreationDate() 50 | */ 51 | public SortedSet p03_getOrderDatesAscending(Customer customer) { 52 | return null; 53 | } 54 | 55 | 56 | /** 57 | * @return a map order.id -> order 58 | */ 59 | public Map p04_mapOrdersById(Customer customer) { 60 | return null; 61 | } 62 | 63 | /** 64 | * Orders grouped by Order.paymentMethod 65 | */ 66 | public Map> p05_getProductsByPaymentMethod(Customer customer) { 67 | return null; 68 | } 69 | 70 | // -------------- MOVIE BREAK :p -------------------- 71 | 72 | /** 73 | * A hard one ! 74 | * Get total number of products bought by a customer, across all her orders. 75 | * Customer --->* Order --->* OrderLines(.count .product) 76 | * The sum of all counts for the same product. 77 | * i.e. SELECT PROD_ID, SUM(COUNT) FROM PROD GROUPING BY PROD_ID 78 | */ 79 | public Map p06_getProductCount(Customer customer) { 80 | 81 | List allLines = new ArrayList<>(); 82 | 83 | for (Order order : customer.getOrders()) { 84 | allLines.addAll(order.getOrderLines()); 85 | } 86 | return null; 87 | 88 | } 89 | 90 | /** 91 | * All the unique products bought by the customer, 92 | * sorted by Product.name. 93 | */ 94 | public List p07_getAllOrderedProducts(Customer customer) { 95 | return null; 96 | } 97 | 98 | 99 | /** 100 | * The names of all the products bought by Customer, 101 | * sorted and then concatenated by ",". 102 | * Example: "Armchair,Chair,Table". 103 | * Hint: Reuse the previous function. 104 | */ 105 | public String p08_getProductsJoined(Customer customer) { 106 | return null; 107 | } 108 | 109 | /** 110 | * Sum of all Order.getTotalPrice(), truncated to Long. 111 | */ 112 | public Long p09_getApproximateTotalOrdersPrice(Customer customer) { 113 | // TODO +, longValue(), reduce() 114 | return null; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/TransformStreamsTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order; 2 | 3 | import java.math.BigDecimal; 4 | import java.time.LocalDate; 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | import java.util.Collections; 9 | import java.util.HashMap; 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import org.junit.jupiter.api.MethodOrderer.MethodName; 15 | import org.junit.jupiter.api.Test; 16 | import org.junit.jupiter.api.TestMethodOrder; 17 | 18 | import victor.training.java.stream.order.dto.OrderDto; 19 | import victor.training.java.stream.order.entity.Customer; 20 | import victor.training.java.stream.order.entity.Order; 21 | import victor.training.java.stream.order.entity.OrderLine; 22 | import victor.training.java.stream.order.entity.Product; 23 | import victor.training.java.stream.order.entity.Order.PaymentMethod; 24 | 25 | import static org.junit.jupiter.api.Assertions.assertEquals; 26 | 27 | @TestMethodOrder(MethodName.class) 28 | 29 | public class TransformStreamsTest { 30 | 31 | private TransformStreams service = new TransformStreams(); 32 | 33 | private LocalDate today = LocalDate.now(); 34 | private LocalDate yesterday = LocalDate.now().minusDays(1); 35 | 36 | @Test 37 | public void p01_toDtos() { 38 | Order order1 = new Order().setCreationDate(today).setTotalPrice(BigDecimal.TEN); 39 | Order order2 = new Order().setCreationDate(yesterday).setTotalPrice(BigDecimal.ONE); 40 | 41 | List dtos = service.p01_toDtos(Arrays.asList(order1, order2)); 42 | 43 | assertEquals(today, dtos.get(0).creationDate); 44 | assertEquals(BigDecimal.TEN, dtos.get(0).totalPrice); 45 | assertEquals(yesterday, dtos.get(1).creationDate); 46 | } 47 | 48 | @Test 49 | public void p02_getUsedPaymentMethods() { 50 | Order cardOrder = new Order().setPaymentMethod(PaymentMethod.CARD); 51 | Order cardOrder2 = new Order().setPaymentMethod(PaymentMethod.CARD); 52 | Order cashOnDeliveryOrder = new Order().setPaymentMethod(PaymentMethod.CASH_ON_DELIVERY); 53 | 54 | HashSet expected = new HashSet<>(Arrays.asList(PaymentMethod.CARD, PaymentMethod.CASH_ON_DELIVERY)); 55 | assertEquals(expected, service.p02_getUsedPaymentMethods(new Customer(cardOrder, cardOrder2, cashOnDeliveryOrder))); 56 | } 57 | 58 | @Test 59 | public void p03_getOrderDatesAscending() { 60 | Order order1 = new Order().setCreationDate(today); 61 | Order order1bis = new Order().setCreationDate(today); 62 | Order order2 = new Order().setCreationDate(yesterday); 63 | 64 | List expected = Arrays.asList(yesterday, today); 65 | Collection actual = service.p03_getOrderDatesAscending(new Customer(order1, order1bis, order2)); 66 | 67 | assertEquals(expected, new ArrayList<>(actual)); 68 | } 69 | 70 | @Test 71 | public void p04_mapOrdersById() { 72 | Order order1 = new Order(1L); 73 | 74 | Map actual = service.p04_mapOrdersById(new Customer(order1)); 75 | Map expected = Collections.singletonMap(1L, order1); 76 | assertEquals(expected, actual); 77 | } 78 | 79 | 80 | @Test 81 | public void p05_getProductsByPaymentMethod() { 82 | Order order1 = new Order().setPaymentMethod(PaymentMethod.CARD); 83 | Order order2 = new Order().setPaymentMethod(PaymentMethod.CASH_ON_DELIVERY); 84 | Order order3 = new Order().setPaymentMethod(PaymentMethod.CARD); 85 | Map> actual = service.p05_getProductsByPaymentMethod(new Customer(order1, order2, order3)); 86 | assertEquals(Arrays.asList(order2), actual.get(PaymentMethod.CASH_ON_DELIVERY)); 87 | assertEquals(Arrays.asList(order1, order3), actual.get(PaymentMethod.CARD)); 88 | } 89 | 90 | 91 | @Test 92 | public void p06_getProductCount() { 93 | Product chair = new Product("Chair"); 94 | Product table = new Product("Table"); 95 | 96 | Order order1 = new Order( 97 | new OrderLine(chair, 3)); 98 | Order order2 = new Order( 99 | new OrderLine(table, 1), 100 | new OrderLine(chair, 1)); 101 | 102 | Map actual = service.p06_getProductCount(new Customer(order1, order2)); 103 | Map expected = new HashMap(){{ 104 | put(chair, 4L); 105 | put(table, 1L); 106 | }}; 107 | assertEquals(expected, actual); 108 | } 109 | 110 | 111 | @Test 112 | public void p07_getAllOrderedProducts() { 113 | Product chair = new Product("Chair"); 114 | Product table = new Product("Table"); 115 | 116 | Order order1 = new Order( 117 | new OrderLine(chair, 3)); 118 | Order order2 = new Order( 119 | new OrderLine(table, 1), 120 | new OrderLine(chair, 1)); 121 | 122 | List actual = service.p07_getAllOrderedProducts(new Customer(order1, order2)); 123 | assertEquals(Arrays.asList(chair, table), actual); 124 | } 125 | 126 | @Test 127 | public void p08_getProductsNamesJoined() { 128 | Product armchair = new Product("Armchair"); 129 | Product chair = new Product("Chair"); 130 | Product table = new Product("Table"); 131 | 132 | Order order1 = new Order( 133 | new OrderLine(chair, 3)); 134 | Order order2 = new Order( 135 | new OrderLine(armchair, 1), 136 | new OrderLine(table, 1), 137 | new OrderLine(chair, 1)); 138 | 139 | String actual = service.p08_getProductsJoined(new Customer(order1, order2)); 140 | assertEquals("Armchair,Chair,Table", actual); 141 | } 142 | 143 | 144 | @Test 145 | public void p09_getApproximateTotalOrdersPrice() { 146 | Order order1 = new Order().setTotalPrice(BigDecimal.TEN); 147 | Order order2 = new Order().setTotalPrice(BigDecimal.ONE); 148 | 149 | long actual = service.p09_getApproximateTotalOrdersPrice(new Customer(order1, order2)); 150 | assertEquals(11L, actual); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/dto/AuditDto.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.dto; 2 | 3 | import java.time.LocalDate; 4 | 5 | import victor.training.java.stream.order.entity.Audit.Action; 6 | 7 | public class AuditDto { 8 | public String username; 9 | public LocalDate date; 10 | public Action action; 11 | 12 | public final LocalDate getDate() { 13 | return date; 14 | } 15 | public final Action getAction() { 16 | return action; 17 | } 18 | public final String getUsername() { 19 | return username; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/dto/OrderDto.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.dto; 2 | 3 | import java.math.BigDecimal; 4 | import java.time.LocalDate; 5 | 6 | public class OrderDto { 7 | 8 | public BigDecimal totalPrice; 9 | public LocalDate creationDate; 10 | 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/dto/OrderMapper.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.dto; 2 | 3 | public class OrderMapper { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/entity/Audit.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.entity; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class Audit { 6 | 7 | public enum Action { 8 | CREATE, MODIFY, DELETE, DEACTIVATE, ACTIVATE 9 | } 10 | 11 | private String user; 12 | private LocalDate date; 13 | private Action action; 14 | private String modifiedField; 15 | 16 | public LocalDate getDate() { 17 | return date; 18 | } 19 | 20 | public Audit setDate(LocalDate date) { 21 | this.date = date; 22 | return this; 23 | } 24 | 25 | public Action getAction() { 26 | return action; 27 | } 28 | 29 | public Audit setAction(Action action) { 30 | this.action = action; 31 | return this; 32 | } 33 | 34 | public String getModifiedField() { 35 | return modifiedField; 36 | } 37 | 38 | public void setModifiedField(String modifiedField) { 39 | this.modifiedField = modifiedField; 40 | } 41 | 42 | public String getUser() { 43 | return user; 44 | } 45 | 46 | public Audit setUser(String user) { 47 | this.user = user; 48 | return this; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/entity/Customer.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.entity; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Customer { 8 | 9 | private List orders = new ArrayList<>(); 10 | 11 | public List getOrders() { 12 | return orders; 13 | } 14 | 15 | public void setOrders(List orders) { 16 | this.orders = orders; 17 | } 18 | 19 | public Customer(Order... orders) { 20 | this.orders = Arrays.asList(orders); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/entity/Order.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.entity; 2 | 3 | import static java.util.stream.Collectors.joining; 4 | 5 | import java.math.BigDecimal; 6 | import java.time.LocalDate; 7 | import java.util.ArrayList; 8 | import java.util.Arrays; 9 | import java.util.List; 10 | 11 | 12 | public class Order { 13 | 14 | public enum Status { 15 | DRAFT, ACTIVE, INACTIVE 16 | } 17 | 18 | public enum PaymentMethod { 19 | CARD, 20 | CASH_ON_SITE, 21 | CASH_ON_DELIVERY 22 | } 23 | 24 | private Long id; 25 | private Status status; 26 | private List orderLines; 27 | private LocalDate creationDate; 28 | private BigDecimal totalPrice; 29 | private PaymentMethod paymentMethod; 30 | 31 | private LocalDate deliveryDueDate; 32 | private Customer customer; 33 | 34 | public Order() { 35 | } 36 | 37 | public Order(Status status) { 38 | this.status = status; 39 | } 40 | 41 | public Order(Long id) { 42 | this.id = id; 43 | } 44 | 45 | public Order(OrderLine... lines) { 46 | this.orderLines = Arrays.asList(lines); 47 | } 48 | 49 | // TODO any helper methods ? 50 | 51 | public List getOrderLines() { 52 | return orderLines; 53 | } 54 | 55 | public void setOrderLines(List orderLines) { 56 | this.orderLines = orderLines; 57 | } 58 | public Long getId() { 59 | return id; 60 | } 61 | 62 | public void setId(Long id) { 63 | this.id = id; 64 | } 65 | 66 | public Status getStatus() { 67 | return status; 68 | } 69 | 70 | public Order setStatus(Status status) { 71 | this.status = status; 72 | return this; 73 | } 74 | 75 | public LocalDate getCreationDate() { 76 | return creationDate; 77 | } 78 | 79 | public Order setCreationDate(LocalDate creationDate) { 80 | this.creationDate = creationDate; 81 | return this; 82 | } 83 | 84 | public BigDecimal getTotalPrice() { 85 | return totalPrice; 86 | } 87 | 88 | public Order setTotalPrice(BigDecimal totalPrice) { 89 | this.totalPrice = totalPrice; 90 | return this; 91 | } 92 | 93 | public PaymentMethod getPaymentMethod() { 94 | return paymentMethod; 95 | } 96 | 97 | public Order setPaymentMethod(PaymentMethod paymentMethod) { 98 | this.paymentMethod = paymentMethod; 99 | return this; 100 | } 101 | 102 | public LocalDate getDeliveryDueDate() { 103 | return deliveryDueDate; 104 | } 105 | 106 | public Order setDeliveryDueDate(LocalDate deliveryDueDate) { 107 | this.deliveryDueDate = deliveryDueDate; 108 | return this; 109 | } 110 | 111 | public Customer getCustomer() { 112 | return customer; 113 | } 114 | 115 | public Order setCustomer(Customer customer) { 116 | this.customer = customer; 117 | return this; 118 | } 119 | 120 | public String toString() { 121 | List details = new ArrayList<>(); 122 | if (creationDate != null) { 123 | details.add("created="+creationDate); 124 | } 125 | String detailsStr = details.stream().collect(joining(", ")); 126 | return "Order{"+detailsStr + "}"; 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/entity/OrderLine.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.entity; 2 | 3 | public class OrderLine { 4 | 5 | public enum Status { 6 | IN_STOCK, OUT_OF_STOCK, WAITING_FOR_STOCK 7 | } 8 | 9 | private Product product; 10 | private int count; 11 | private boolean specialOffer; 12 | private Status status; 13 | 14 | public OrderLine(Product product, int items) { 15 | this.product = product; 16 | this.count = items; 17 | } 18 | public OrderLine() { 19 | } 20 | 21 | public OrderLine(Status status) { 22 | this.status = status; 23 | } 24 | public boolean isSpecialOffer() { 25 | return specialOffer; 26 | } 27 | 28 | public OrderLine setSpecialOffer(boolean specialOffer) { 29 | this.specialOffer = specialOffer; 30 | return this; 31 | } 32 | 33 | public Product getProduct() { 34 | return product; 35 | } 36 | 37 | public void setProduct(Product product) { 38 | this.product = product; 39 | } 40 | 41 | public int getCount() { 42 | return count; 43 | } 44 | 45 | public void setCount(int count) { 46 | this.count = count; 47 | } 48 | 49 | public Status getStatus() { 50 | return status; 51 | } 52 | 53 | public void setStatus(Status status) { 54 | this.status = status; 55 | } 56 | 57 | public boolean wasDelivered() { 58 | return true; 59 | } 60 | 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/entity/Product.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.entity; 2 | 3 | public class Product { 4 | 5 | private final String name; 6 | 7 | public Product(String name) { 8 | this.name = name; 9 | } 10 | 11 | public final String getName() { 12 | return name; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "Product{name="+name+"}"; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/repo/OrderLineRepository.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.repo; 2 | 3 | import victor.training.java.stream.order.entity.OrderLine; 4 | 5 | public interface OrderLineRepository { 6 | 7 | void delete(OrderLine line); 8 | 9 | void insert(OrderLine liveLine); 10 | 11 | void update(OrderLine line); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/order/repo/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.order.repo; 2 | 3 | import victor.training.java.stream.order.entity.Order; 4 | 5 | public interface OrderRepository { 6 | void save(Order order); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/transaction/Trader.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.transaction; 2 | public class Trader{ 3 | 4 | private final String name; 5 | private final String city; 6 | 7 | public Trader(String n, String c){ 8 | this.name = n; 9 | this.city = c; 10 | } 11 | 12 | public String getName(){ 13 | return this.name; 14 | } 15 | 16 | public String getCity(){ 17 | return this.city; 18 | } 19 | 20 | public String toString(){ 21 | return "Trader:"+this.name + " in " + this.city; 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/transaction/Transaction.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.transaction; 2 | 3 | public class Transaction { 4 | 5 | private final Trader trader; 6 | private final int year; 7 | private final int value; 8 | 9 | public Transaction(Trader trader, int year, int value) { 10 | this.trader = trader; 11 | this.year = year; 12 | this.value = value; 13 | } 14 | 15 | public Trader getTrader() { 16 | return this.trader; 17 | } 18 | 19 | public int getYear() { 20 | return this.year; 21 | } 22 | 23 | public int getValue() { 24 | return this.value; 25 | } 26 | 27 | public String toString() { 28 | return "{" + this.trader + ", " + "year: " + this.year + ", " + "value:" + this.value + "}"; 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/transaction/TransactionPlay.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.transaction; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static java.util.stream.Collectors.joining; 6 | import static java.util.stream.Collectors.toList; 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.stream.Stream; 13 | 14 | 15 | 16 | public class TransactionPlay { 17 | 18 | private Trader raoul = new Trader("Raoul", "Cambridge"); 19 | private Trader mario = new Trader("Mario","Milan"); 20 | private Trader alan = new Trader("Alan","Cambridge"); 21 | private Trader brian = new Trader("Brian","Cambridge"); 22 | 23 | private List transactions = Arrays.asList( 24 | new Transaction(brian, 2011, 300), 25 | new Transaction(raoul, 2012, 1000), 26 | new Transaction(raoul, 2011, 400), 27 | new Transaction(mario, 2012, 710), 28 | new Transaction(mario, 2012, 700), 29 | new Transaction(alan, 2012, 950) 30 | ); 31 | 32 | private Transaction[] tx = transactions.toArray(new Transaction[0]); 33 | 34 | @Test //1 35 | public void all_2011_transactions_sorted_by_value() { 36 | List expected = Arrays.asList(tx[0], tx[2]); 37 | 38 | List list = null; // TODO 39 | 40 | assertEquals(expected, list); 41 | } 42 | 43 | @Test //2 44 | public void unique_cities_of_the_traders() { 45 | List expected = Arrays.asList("Cambridge", "Milan"); 46 | 47 | List list = null; // TODO 48 | 49 | assertEquals(expected, list); 50 | } 51 | 52 | @Test //3 53 | public void traders_from_Cabridge_sorted_by_name() { 54 | List expected = Arrays.asList(alan, brian, raoul); 55 | 56 | List list = null; // TODO 57 | 58 | assertEquals(expected, list); 59 | } 60 | 61 | @Test //4 62 | public void names_of_all_traders_sorted_joined() { 63 | String expected = "Alan,Brian,Mario,Raoul"; 64 | 65 | String joined = null; // TODO 66 | 67 | assertEquals(expected, joined); 68 | } 69 | 70 | @Test //5 71 | public void are_traders_in_Milano() { 72 | boolean areTradersInMilan = false; // TODO 73 | 74 | assertTrue(areTradersInMilan); 75 | } 76 | 77 | @Test //6 78 | public void sum_of_values_of_transactions_from_Cambridge_traders() { 79 | int sum = -1; // TODO 80 | 81 | assertEquals(2650, sum); 82 | } 83 | 84 | @Test //7 85 | public void max_transaction_value() { 86 | int max = -1; // TODO 87 | 88 | assertEquals(1000, max); 89 | } 90 | 91 | 92 | @Test 93 | public void transaction_with_smallest_value() { 94 | Transaction expected = tx[0]; 95 | Transaction min = null; // TODO 96 | assertEquals(expected, min); 97 | } 98 | @Test 99 | public void fibonacci_first_10() { 100 | List expected = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55); 101 | Stream fibonacci = null; // TODO 102 | 103 | List fib10 = fibonacci.limit(10).collect(toList()); 104 | assertEquals(expected, fib10); 105 | } 106 | 107 | @Test 108 | public void a_transaction_from_2012() { 109 | Transaction expected = tx[1]; 110 | Transaction tx2012 = null; // TODO 111 | 112 | assertEquals(expected, tx2012); 113 | } 114 | 115 | @Test 116 | public void uniqueCharactersOfManyWords() { 117 | List expected = Arrays.asList("a", "b", "c", "d", "f"); 118 | List wordsStream = Arrays.asList("abcd", "acdf"); 119 | 120 | List actual = null; // TODO 121 | assertEquals(expected, actual); 122 | } 123 | 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/transaction/TransactionPlaySolved.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.transaction; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static java.util.stream.Collectors.joining; 6 | import static java.util.stream.Collectors.toList; 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | import java.util.Arrays; 11 | import java.util.Comparator; 12 | import java.util.List; 13 | import java.util.stream.Stream; 14 | 15 | 16 | 17 | public class TransactionPlaySolved { 18 | 19 | 20 | 21 | 22 | 23 | private Trader raoul = new Trader("Raoul", "Cambridge"); 24 | private Trader mario = new Trader("Mario","Milan"); 25 | private Trader alan = new Trader("Alan","Cambridge"); 26 | private Trader brian = new Trader("Brian","Cambridge"); 27 | 28 | private List transactions = Arrays.asList( 29 | new Transaction(brian, 2011, 300), 30 | new Transaction(raoul, 2012, 1000), 31 | new Transaction(raoul, 2011, 400), 32 | new Transaction(mario, 2012, 710), 33 | new Transaction(mario, 2012, 700), 34 | new Transaction(alan, 2012, 950) 35 | ); 36 | 37 | private Transaction[] tx = transactions.toArray(new Transaction[0]); 38 | 39 | @Test //1 40 | public void all_2011_transactions_sorted_by_value() { 41 | List expected = Arrays.asList(tx[0], tx[2]); 42 | 43 | // SOLUTION( 44 | List list = transactions.stream() 45 | .filter(t -> t.getYear() == 2011) 46 | .sorted(Comparator.comparing(Transaction::getValue)) 47 | .collect(toList()); 48 | 49 | assertEquals(expected, list); 50 | // SOLUTION) 51 | } 52 | 53 | @Test //2 54 | public void unique_cities_of_the_traders() { 55 | List expected = Arrays.asList("Cambridge", "Milan"); 56 | 57 | // SOLUTION( 58 | List list = transactions.stream() 59 | .map(Transaction::getTrader) 60 | .map(Trader::getCity) 61 | .distinct() 62 | .collect(toList()); 63 | 64 | assertEquals(expected, list); 65 | // SOLUTION) 66 | } 67 | 68 | @Test //3 69 | public void traders_from_Cabridge_sorted_by_name() { 70 | List expected = Arrays.asList(alan, brian, raoul); 71 | 72 | // SOLUTION( 73 | List list = transactions.stream() 74 | .map(Transaction::getTrader) 75 | .filter(trader -> "Cambridge".equals(trader.getCity())) 76 | .sorted(Comparator.comparing(Trader::getName)) 77 | .distinct() 78 | .collect(toList()); 79 | 80 | assertEquals(expected, list); 81 | // SOLUTION) 82 | } 83 | 84 | @Test //4 85 | public void names_of_all_traders_sorted_joined() { 86 | String expected = "Alan,Brian,Mario,Raoul"; 87 | 88 | // SOLUTION( 89 | String joined = transactions.stream() 90 | .map(Transaction::getTrader) 91 | .map(Trader::getName) 92 | .sorted() 93 | .distinct() 94 | .collect(joining(",")); 95 | 96 | assertEquals(expected, joined); 97 | // SOLUTION) 98 | } 99 | 100 | @Test //5 101 | public void are_traders_in_Milano() { 102 | // SOLUTION( 103 | boolean areTradersInMilan = transactions.stream() 104 | .map(Transaction::getTrader) 105 | .anyMatch(trader -> "Milan".equals(trader.getCity())); 106 | 107 | assertTrue(areTradersInMilan); 108 | // SOLUTION) 109 | } 110 | 111 | @Test //6 112 | public void sum_of_values_of_transactions_from_Cambridge_traders() { 113 | //int sum = -1; // INITIAL 114 | // SOLUTION( 115 | int sum = transactions.stream() 116 | .filter(t-> "Cambridge".equals(t.getTrader().getCity())) 117 | .mapToInt(Transaction::getValue) // returns IntStream 118 | .sum(); 119 | // SOLUTION) 120 | 121 | assertEquals(2650, sum); 122 | } 123 | 124 | @Test //7 125 | public void max_transaction_value() { 126 | //int max = -1; // INITIAL 127 | // SOLUTION( 128 | int max = transactions.stream() 129 | .max(Comparator.comparing(Transaction::getValue)) 130 | .get() 131 | .getValue(); 132 | // SOLUTION) 133 | 134 | assertEquals(1000, max); 135 | } 136 | 137 | 138 | @Test 139 | public void transaction_with_smallest_value() { 140 | Transaction expected = tx[0]; 141 | // SOLUTION( 142 | Transaction min = transactions.stream() 143 | .min(Comparator.comparing(Transaction::getValue)) 144 | .get(); 145 | assertEquals(expected, min); 146 | // SOLUTION) 147 | } 148 | @Test 149 | public void fibonacci_first_10() { 150 | List expected = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55); 151 | // SOLUTION( 152 | Stream fibonacci = Stream.iterate( 153 | new int[]{1,1}, 154 | pair -> new int[] {pair[1], pair[0]+pair[1]}) 155 | .map(pair -> pair[0]); 156 | 157 | List fib10 = fibonacci.limit(10).collect(toList()); 158 | assertEquals(expected, fib10); 159 | // SOLUTION) 160 | } 161 | 162 | @Test 163 | public void a_transaction_from_2012() { 164 | Transaction expected = tx[1]; 165 | // SOLUTION( 166 | Transaction tx2012 = transactions.stream() 167 | .filter(transaction -> transaction.getYear() == 2012) 168 | .findFirst() 169 | .get(); 170 | 171 | assertEquals(expected, tx2012); 172 | // SOLUTION) 173 | } 174 | 175 | @Test 176 | public void uniqueCharactersOfManyWords() { 177 | List expected = Arrays.asList("a", "b", "c", "d", "f"); 178 | List wordsStream = Arrays.asList("abcd", "acdf"); 179 | 180 | // SOLUTION( 181 | List actual = wordsStream.stream() 182 | .flatMap(word -> Arrays.asList(word.split("")).stream()) 183 | .distinct() 184 | .sorted() 185 | .collect(toList()); 186 | assertEquals(expected, actual); 187 | // SOLUTION) 188 | } 189 | 190 | 191 | 192 | } 193 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/yatzi/Yatzy.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.yatzi; 2 | 3 | public class Yatzy { 4 | 5 | public static int chance(int d1, int d2, int d3, int d4, int d5) 6 | { 7 | int total = 0; 8 | total += d1; 9 | total += d2; 10 | total += d3; 11 | total += d4; 12 | total += d5; 13 | return total; 14 | } 15 | 16 | public static int yatzy(int... dice) 17 | { 18 | int[] counts = new int[6]; 19 | for (int die : dice) 20 | counts[die-1]++; 21 | for (int i = 0; i != 6; i++) 22 | if (counts[i] == 5) 23 | return 50; 24 | return 0; 25 | } 26 | 27 | public static int ones(int d1, int d2, int d3, int d4, int d5) { 28 | int sum = 0; 29 | if (d1 == 1) sum++; 30 | if (d2 == 1) sum++; 31 | if (d3 == 1) sum++; 32 | if (d4 == 1) sum++; 33 | if (d5 == 1) 34 | sum++; 35 | 36 | return sum; 37 | } 38 | 39 | public int twos() { 40 | int sum = 0; 41 | if (dice[0] == 2) sum += 2; 42 | if (dice[1] == 2) sum += 2; 43 | if (dice[2] == 2) sum += 2; 44 | if (dice[3] == 2) sum += 2; 45 | if (dice[4] == 2) sum += 2; 46 | return sum; 47 | } 48 | 49 | public int threes() { 50 | int s; 51 | s = 0; 52 | if (dice[0] == 3) s += 3; 53 | if (dice[1] == 3) s += 3; 54 | if (dice[2] == 3) s += 3; 55 | if (dice[3] == 3) s += 3; 56 | if (dice[4] == 3) s += 3; 57 | return s; 58 | } 59 | 60 | protected int[] dice; 61 | 62 | public Yatzy(int d1, int d2, int d3, int d4, int _5) 63 | { 64 | dice = new int[5]; 65 | dice[0] = d1; 66 | dice[1] = d2; 67 | dice[2] = d3; 68 | dice[3] = d4; 69 | dice[4] = _5; 70 | } 71 | 72 | public int fours() 73 | { 74 | int sum; 75 | sum = 0; 76 | for (int at = 0; at != 5; at++) { 77 | if (dice[at] == 4) { 78 | sum += 4; 79 | } 80 | } 81 | return sum; 82 | } 83 | 84 | public int fives() 85 | { 86 | int s = 0; 87 | int i; 88 | for (i = 0; i < dice.length; i++) 89 | if (dice[i] == 5) 90 | s = s + 5; 91 | return s; 92 | } 93 | 94 | public int sixes() 95 | { 96 | int sum = 0; 97 | for (int at = 0; at < dice.length; at++) 98 | if (dice[at] == 6) 99 | sum = sum + 6; 100 | return sum; 101 | } 102 | 103 | public static int score_pair(int d1, int d2, int d3, int d4, int d5) 104 | { 105 | int[] counts = new int[6]; 106 | counts[d1-1]++; 107 | counts[d2-1]++; 108 | counts[d3-1]++; 109 | counts[d4-1]++; 110 | counts[d5-1]++; 111 | int at; 112 | for (at = 0; at != 6; at++) 113 | if (counts[6-at-1] >= 2) 114 | return (6-at)*2; 115 | return 0; 116 | } 117 | 118 | public static int two_pair(int d1, int d2, int d3, int d4, int d5) 119 | { 120 | int[] counts = new int[6]; 121 | counts[d1-1]++; 122 | counts[d2-1]++; 123 | counts[d3-1]++; 124 | counts[d4-1]++; 125 | counts[d5-1]++; 126 | int n = 0; 127 | int score = 0; 128 | for (int i = 0; i < 6; i += 1) 129 | if (counts[6-i-1] >= 2) { 130 | n++; 131 | score += (6-i); 132 | } 133 | if (n == 2) 134 | return score * 2; 135 | else 136 | return 0; 137 | } 138 | 139 | public static int four_of_a_kind(int _1, int _2, int d3, int d4, int d5) 140 | { 141 | int[] tallies; 142 | tallies = new int[6]; 143 | tallies[_1-1]++; 144 | tallies[_2-1]++; 145 | tallies[d3-1]++; 146 | tallies[d4-1]++; 147 | tallies[d5-1]++; 148 | for (int i = 0; i < 6; i++) 149 | if (tallies[i] >= 4) 150 | return (i+1) * 4; 151 | return 0; 152 | } 153 | 154 | public static int three_of_a_kind(int d1, int d2, int d3, int d4, int d5) 155 | { 156 | int[] t; 157 | t = new int[6]; 158 | t[d1-1]++; 159 | t[d2-1]++; 160 | t[d3-1]++; 161 | t[d4-1]++; 162 | t[d5-1]++; 163 | for (int i = 0; i < 6; i++) 164 | if (t[i] >= 3) 165 | return (i+1) * 3; 166 | return 0; 167 | } 168 | 169 | public static int smallStraight(int d1, int d2, int d3, int d4, int d5) 170 | { 171 | int[] tallies; 172 | tallies = new int[6]; 173 | tallies[d1-1] += 1; 174 | tallies[d2-1] += 1; 175 | tallies[d3-1] += 1; 176 | tallies[d4-1] += 1; 177 | tallies[d5-1] += 1; 178 | if (tallies[0] == 1 && 179 | tallies[1] == 1 && 180 | tallies[2] == 1 && 181 | tallies[3] == 1 && 182 | tallies[4] == 1) 183 | return 15; 184 | return 0; 185 | } 186 | 187 | public static int largeStraight(int d1, int d2, int d3, int d4, int d5) 188 | { 189 | int[] tallies; 190 | tallies = new int[6]; 191 | tallies[d1-1] += 1; 192 | tallies[d2-1] += 1; 193 | tallies[d3-1] += 1; 194 | tallies[d4-1] += 1; 195 | tallies[d5-1] += 1; 196 | if (tallies[1] == 1 && 197 | tallies[2] == 1 && 198 | tallies[3] == 1 && 199 | tallies[4] == 1 200 | && tallies[5] == 1) 201 | return 20; 202 | return 0; 203 | } 204 | 205 | public static int fullHouse(int d1, int d2, int d3, int d4, int d5) 206 | { 207 | int[] tallies; 208 | boolean _2 = false; 209 | int i; 210 | int _2_at = 0; 211 | boolean _3 = false; 212 | int _3_at = 0; 213 | 214 | 215 | 216 | 217 | tallies = new int[6]; 218 | tallies[d1-1] += 1; 219 | tallies[d2-1] += 1; 220 | tallies[d3-1] += 1; 221 | tallies[d4-1] += 1; 222 | tallies[d5-1] += 1; 223 | 224 | for (i = 0; i != 6; i += 1) 225 | if (tallies[i] == 2) { 226 | _2 = true; 227 | _2_at = i+1; 228 | } 229 | 230 | for (i = 0; i != 6; i += 1) 231 | if (tallies[i] == 3) { 232 | _3 = true; 233 | _3_at = i+1; 234 | } 235 | 236 | if (_2 && _3) 237 | return _2_at * 2 + _3_at * 3; 238 | else 239 | return 0; 240 | } 241 | } 242 | 243 | 244 | -------------------------------------------------------------------------------- /src/main/java/victor/training/java/stream/yatzi/YatzyTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.stream.yatzi; 2 | 3 | 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 7 | 8 | class YatzyTest { 9 | 10 | @Test 11 | void chance_scores_sum_of_all_dice() { 12 | int expected = 15; 13 | int actual = Yatzy.chance(2,3,4,5,1); 14 | assertThat(actual).isEqualTo(expected); 15 | assertThat(Yatzy.chance(3, 3, 4, 5, 1)).isEqualTo(16); 16 | } 17 | 18 | @Test 19 | void yatzy_scores_50() { 20 | int expected = 50; 21 | int actual = Yatzy.yatzy(4,4,4,4,4); 22 | assertThat(actual).isEqualTo(expected); 23 | assertThat(Yatzy.yatzy(6, 6, 6, 6, 6)).isEqualTo(50); 24 | assertThat(Yatzy.yatzy(6, 6, 6, 6, 3)).isEqualTo(0); 25 | } 26 | 27 | @Test 28 | void test_1s() { 29 | assertThat(Yatzy.ones(1, 2, 3, 4, 5) == 1).isTrue(); 30 | assertThat(Yatzy.ones(1, 2, 1, 4, 5)).isEqualTo(2); 31 | assertThat(Yatzy.ones(6, 2, 2, 4, 5)).isEqualTo(0); 32 | assertThat(Yatzy.ones(1, 2, 1, 1, 1)).isEqualTo(4); 33 | } 34 | 35 | @Test 36 | void test_2s() { 37 | assertThat(new Yatzy(1, 2, 3, 2, 6).twos()).isEqualTo(4); 38 | assertThat(new Yatzy(2, 2, 2, 2, 2).twos()).isEqualTo(10); 39 | } 40 | 41 | @Test 42 | void test_threes() { 43 | assertThat(new Yatzy(1, 2, 3, 2, 3).threes()).isEqualTo(6); 44 | assertThat(new Yatzy(2, 3, 3, 3, 3).threes()).isEqualTo(12); 45 | } 46 | 47 | @Test 48 | void fours_test() 49 | { 50 | assertThat(new Yatzy(4, 4, 4, 5, 5).fours()).isEqualTo(12); 51 | assertThat(new Yatzy(4, 4, 5, 5, 5).fours()).isEqualTo(8); 52 | assertThat(new Yatzy(4, 5, 5, 5, 5).fours()).isEqualTo(4); 53 | } 54 | 55 | @Test 56 | void fives() { 57 | assertThat(new Yatzy(4, 4, 4, 5, 5).fives()).isEqualTo(10); 58 | assertThat(new Yatzy(4, 4, 5, 5, 5).fives()).isEqualTo(15); 59 | assertThat(new Yatzy(4, 5, 5, 5, 5).fives()).isEqualTo(20); 60 | } 61 | 62 | @Test 63 | void sixes_test() { 64 | assertThat(new Yatzy(4, 4, 4, 5, 5).sixes()).isEqualTo(0); 65 | assertThat(new Yatzy(4, 4, 6, 5, 5).sixes()).isEqualTo(6); 66 | assertThat(new Yatzy(6, 5, 6, 6, 5).sixes()).isEqualTo(18); 67 | } 68 | 69 | @Test 70 | void one_pair() { 71 | assertThat(Yatzy.score_pair(3, 4, 3, 5, 6)).isEqualTo(6); 72 | assertThat(Yatzy.score_pair(5, 3, 3, 3, 5)).isEqualTo(10); 73 | assertThat(Yatzy.score_pair(5, 3, 6, 6, 5)).isEqualTo(12); 74 | } 75 | 76 | @Test 77 | void two_Pair() { 78 | assertThat(Yatzy.two_pair(3, 3, 5, 4, 5)).isEqualTo(16); 79 | assertThat(Yatzy.two_pair(3, 3, 5, 5, 5)).isEqualTo(16); 80 | } 81 | 82 | @Test 83 | void three_of_a_kind() 84 | { 85 | assertThat(Yatzy.three_of_a_kind(3, 3, 3, 4, 5)).isEqualTo(9); 86 | assertThat(Yatzy.three_of_a_kind(5, 3, 5, 4, 5)).isEqualTo(15); 87 | assertThat(Yatzy.three_of_a_kind(3, 3, 3, 3, 5)).isEqualTo(9); 88 | } 89 | 90 | @Test 91 | void four_of_a_knd() { 92 | assertThat(Yatzy.four_of_a_kind(3, 3, 3, 3, 5)).isEqualTo(12); 93 | assertThat(Yatzy.four_of_a_kind(5, 5, 5, 4, 5)).isEqualTo(20); 94 | assertThat(Yatzy.three_of_a_kind(3, 3, 3, 3, 3)).isEqualTo(9); 95 | } 96 | 97 | @Test 98 | void smallStraight() { 99 | assertThat(Yatzy.smallStraight(1, 2, 3, 4, 5)).isEqualTo(15); 100 | assertThat(Yatzy.smallStraight(2, 3, 4, 5, 1)).isEqualTo(15); 101 | assertThat(Yatzy.smallStraight(1, 2, 2, 4, 5)).isEqualTo(0); 102 | } 103 | 104 | @Test 105 | void largeStraight() { 106 | assertThat(Yatzy.largeStraight(6, 2, 3, 4, 5)).isEqualTo(20); 107 | assertThat(Yatzy.largeStraight(2, 3, 4, 5, 6)).isEqualTo(20); 108 | assertThat(Yatzy.largeStraight(1, 2, 2, 4, 5)).isEqualTo(0); 109 | } 110 | 111 | @Test 112 | void fullHouse() { 113 | assertThat(Yatzy.fullHouse(6, 2, 2, 2, 6)).isEqualTo(18); 114 | assertThat(Yatzy.fullHouse(2, 3, 4, 5, 6)).isEqualTo(0); 115 | } 116 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | export.folder.out=out 2 | spring.jpa.show-sql=true 3 | children.price = 5 4 | logging.level.p6spy=DEBUG 5 | spring.datasource.url = jdbc:p6spy:h2:mem: 6 | spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver 7 | spring.datasource.username=sa 8 | spring.datasource.password=sa -------------------------------------------------------------------------------- /src/test/java/victor/training/java/advanced/ExceptionsReturnedTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.List; 6 | 7 | import static java.time.LocalDate.parse; 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 10 | 11 | public class ExceptionsReturnedTest { 12 | 13 | private final ExceptionsReturned exceptionsReturned = new ExceptionsReturned(); 14 | 15 | @Test 16 | public void allValid() { 17 | List dates = List.of( 18 | "2020-10-11", 19 | "2020-11-12", 20 | "2020-12-01" 21 | ); 22 | assertThat(exceptionsReturned.parseDates(dates)).containsExactly( 23 | parse("2020-10-11"), parse("2020-11-12"), parse("2020-12-01")); 24 | } 25 | @Test 26 | public void mostValid() { 27 | List dates = List.of( 28 | "2020-10-11", 29 | "2020-nov-12", // INVALID 30 | "2020-12-01" 31 | ); 32 | assertThat(exceptionsReturned.parseDates(dates)).containsExactly( 33 | parse("2020-10-11"), parse("2020-12-01")); 34 | } 35 | @Test 36 | public void mostInvalid() { 37 | List dates = List.of( 38 | "2020-10-11", 39 | "2020-nov-12", // INVALID 40 | "2020-dec-01" // INVALID 41 | ); 42 | assertThatThrownBy(() -> exceptionsReturned.parseDates(dates)) 43 | .isInstanceOf(IllegalArgumentException.class); 44 | } 45 | @Test 46 | public void noneValid() { 47 | List dates = List.of("a"); 48 | 49 | assertThatThrownBy(() -> exceptionsReturned.parseDates(dates)) 50 | .isInstanceOf(IllegalArgumentException.class); 51 | } 52 | } -------------------------------------------------------------------------------- /src/test/java/victor/training/java/advanced/SplitLoopToStreamTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import org.assertj.core.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.extension.ExtendWith; 6 | import org.springframework.boot.test.system.CapturedOutput; 7 | import org.springframework.boot.test.system.OutputCaptureExtension; 8 | import victor.training.java.advanced.model.Language; 9 | import victor.training.java.advanced.model.User; 10 | 11 | import java.util.List; 12 | 13 | import static org.junit.jupiter.api.Assertions.*; 14 | 15 | @ExtendWith(OutputCaptureExtension.class) 16 | class SplitLoopToStreamTest { 17 | 18 | SplitLoopToStream target = new SplitLoopToStream(); 19 | 20 | @Test 21 | void bossLevel(CapturedOutput capturedOutput) { 22 | List users = List.of( 23 | new User() 24 | .setUsername("::user1::") 25 | .setActive(true) 26 | .setTicketsRaised(2) 27 | .setLanguage(null), 28 | new User() 29 | .setUsername("::user2::") 30 | .setActive(true) 31 | .setTicketsRaised(1) 32 | .setLanguage(Language.ENGLISH), 33 | new User() 34 | .setId(3L) 35 | .setUsername("::user3::") 36 | .setActive(false) 37 | ); 38 | 39 | target.bossLevel(users); 40 | 41 | System.out.println(capturedOutput); 42 | Assertions.assertThat(capturedOutput) 43 | .contains("Alert inactive user: 3") 44 | .contains("No language set = 66.67%") 45 | .contains("Number of tickets = 3") 46 | .contains("Write to file: [::user1::, ::user2::, ::user3::]"); 47 | } 48 | } -------------------------------------------------------------------------------- /src/test/java/victor/training/java/advanced/SwitchTest.java: -------------------------------------------------------------------------------- 1 | package victor.training.java.advanced; 2 | 3 | import org.junit.jupiter.api.Nested; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.extension.ExtendWith; 6 | import org.springframework.boot.test.system.CapturedOutput; 7 | import org.springframework.boot.test.system.OutputCaptureExtension; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | import static victor.training.java.advanced.MovieType.*; 11 | 12 | class SwitchTest { 13 | Switch target = new Switch(); 14 | 15 | @Nested 16 | class ComputePrice { 17 | @Test 18 | void regular() { 19 | assertThat(target.computePrice(REGULAR, 2)).isEqualTo(3); 20 | } 21 | 22 | @Test 23 | void newRelease() { 24 | assertThat(target.computePrice(NEW_RELEASE, 2)).isEqualTo(4); 25 | } 26 | 27 | @Test 28 | void children() { 29 | assertThat(target.computePrice(CHILDREN, 3)).isEqualTo(5); 30 | } 31 | } 32 | 33 | @Nested 34 | @ExtendWith(OutputCaptureExtension.class) 35 | class AuditDelayReturn { 36 | @Test 37 | void regular(CapturedOutput capturedOutput) { 38 | target.auditDelayReturn(REGULAR, 3); 39 | assertThat(capturedOutput.getOut()).contains("Regular delayed by 3"); 40 | } 41 | 42 | @Test 43 | void newRelease(CapturedOutput capturedOutput) { 44 | target.auditDelayReturn(NEW_RELEASE, 3); 45 | assertThat(capturedOutput.getOut()).contains("CRITICAL: new release return delayed by 3"); 46 | } 47 | 48 | @Test 49 | void children(CapturedOutput capturedOutput) { 50 | target.auditDelayReturn(CHILDREN, 3); 51 | assertThat(capturedOutput.getOut()).isEmpty(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /test.invalid.txt: -------------------------------------------------------------------------------- 1 | LINE;Chair;-2 2 | LINE;Table;1 -------------------------------------------------------------------------------- /test.ok.txt: -------------------------------------------------------------------------------- 1 | LINE;Chair;2 2 | LINE;Table;1 --------------------------------------------------------------------------------