From d2a2a65566b928e9500097b3998f59f184ff87f8 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:39:09 +0200 Subject: [PATCH] cleanup work --- libraries/helloWorld.docx | Bin 76887 -> 76893 bytes .../bouncycastle/BouncyCastleCrypto.java | 16 +- .../main/java/com/baeldung/bytebuddy/Bar.java | 13 +- .../main/java/com/baeldung/bytebuddy/Foo.java | 4 +- .../com/baeldung/caffeine/DataObject.java | 4 +- .../chronicle/queue/ChronicleQueue.java | 4 +- .../commons/beanutils/CourseEntity.java | 2 +- .../commons/beanutils/CourseService.java | 24 +- .../baeldung/commons/chain/AuditFilter.java | 2 +- .../commons/collectionutil/Customer.java | 2 +- .../com/baeldung/commons/dbutils/Email.java | 1 - .../commons/lang3/BuilderMethods.java | 28 +- .../commons/lang3/SampleLazyInitializer.java | 2 +- .../baeldung/commons/lang3/SampleObject.java | 4 +- .../java/com/baeldung/docx/Docx4jExample.java | 10 +- .../com/baeldung/fj/FunctionalJavaIOMain.java | 14 +- .../com/baeldung/fj/FunctionalJavaMain.java | 12 +- .../java/com/baeldung/flink/LineSplitter.java | 4 +- .../java/com/baeldung/flink/WordCount.java | 4 +- .../google/sheets/GoogleAuthorizeUtil.java | 16 +- .../google/sheets/SheetsServiceUtil.java | 5 +- .../googlehttpclientguide/GitHubExample.java | 25 +- .../googlehttpclientguide/GitHubUrl.java | 10 +- .../baeldung/googlehttpclientguide/User.java | 7 +- .../com/baeldung/hikaricp/DataSource.java | 29 +- .../com/baeldung/hikaricp/HikariCPDemo.java | 6 +- .../infinispan/CacheConfiguration.java | 24 +- .../infinispan/service/HelloWorldService.java | 9 +- .../service/TransactionalService.java | 6 +- .../java/com/baeldung/javasisst/Point.java | 1 - .../javasisst/ThreeDimensionalPoint.java | 1 - .../java/com/baeldung/javers/Address.java | 1 - .../baeldung/javers/PersonWithAddress.java | 1 - .../com/baeldung/jdeffered/FilterDemo.java | 4 +- .../java/com/baeldung/jdeffered/PipeDemo.java | 9 +- .../com/baeldung/jdeffered/PromiseDemo.java | 5 +- .../baeldung/jdeffered/ThreadSafeDemo.java | 4 +- .../DeferredManagerWithExecutorDemo.java | 4 +- .../manager/SimpleDeferredManagerDemo.java | 4 +- .../java/com/baeldung/jdo/GuideToJDO.java | 72 ++--- .../java/com/baeldung/jdo/query/MyApp.java | 53 ++-- .../com/baeldung/jdo/query/ProductItem.java | 15 +- .../com/baeldung/jdo/xml/AnnotadedPerson.java | 12 +- .../main/java/com/baeldung/jdo/xml/MyApp.java | 60 ++-- .../java/com/baeldung/jdo/xml/Person.java | 1 - .../java/com/baeldung/jdo/xml/Product.java | 23 +- .../com/baeldung/jetty/BlockingServlet.java | 1 - .../java/com/baeldung/jetty/JettyServer.java | 2 +- .../baeldung/jetty/JettyServerFactory.java | 126 +++++---- .../baeldung/jetty/LoggingRequestHandler.java | 261 +++++++++--------- .../com/baeldung/netty/ChannelHandlerB.java | 3 +- .../java/com/baeldung/netty/NettyServerB.java | 16 +- .../java/com/baeldung/netty/RequestData.java | 5 +- .../java/com/baeldung/netty/ResponseData.java | 4 +- .../java/com/baeldung/neuroph/NeurophXOR.java | 10 +- .../noexception/CustomExceptionHandler.java | 5 +- .../protonpack/StreamUtilsExample.java | 28 +- .../com/baeldung/quartz/QuartzExample.java | 40 +-- .../java/com/baeldung/quartz/SimpleJob.java | 3 +- .../retrofit/basic/GitHubBasicApi.java | 8 +- .../retrofit/basic/GitHubBasicApp.java | 3 +- .../retrofit/basic/GitHubBasicService.java | 26 +- .../baeldung/retrofit/models/Contributor.java | 13 +- .../baeldung/retrofit/models/Repository.java | 9 +- .../com/baeldung/retrofit/rx/GitHubRxApi.java | 8 +- .../com/baeldung/retrofit/rx/GitHubRxApp.java | 3 +- .../baeldung/retrofit/rx/GitHubRxService.java | 16 +- .../retrofitguide/GitHubServiceGenerator.java | 15 +- .../java/com/baeldung/retrofitguide/Main.java | 10 +- .../serenity/membership/Commodity.java | 2 +- .../baeldung/serenity/membership/Member.java | 12 +- .../serenity/membership/MemberGrade.java | 2 +- .../smooks/converter/OrderConverter.java | 1 - .../java/com/baeldung/smooks/model/Item.java | 19 +- .../com/baeldung/smooks/model/Supplier.java | 9 +- .../main/java/com/baeldung/stm/Account.java | 3 +- .../java/com/baeldung/streamex/StreamEX.java | 70 ++--- .../com/baeldung/streamutils/CopyStream.java | 18 +- .../com/baeldung/streamutils/DrainStream.java | 6 +- .../java/com/baeldung/tomcat/MyServlet.java | 5 +- .../baeldung/tomcat/ProgrammaticTomcat.java | 24 +- .../com/baeldung/yarg/DocumentController.java | 14 +- .../AsyncHttpClientTestCase.java | 9 +- .../AsyncServiceLongRunningUnitTest.java | 15 +- .../bouncycastle/BouncyCastleLiveTest.java | 7 +- .../baeldung/bytebuddy/ByteBuddyUnitTest.java | 43 +-- .../baeldung/caffeine/CaffeineUnitTest.java | 52 +--- .../proxy/BeanGeneratorIntegrationTest.java | 15 +- .../baeldung/cglib/proxy/MixinUnitTest.java | 9 +- .../cglib/proxy/ProxyIntegrationTest.java | 18 +- .../queue/ChronicleQueueIntegrationTest.java | 6 +- .../commons/beanutils/CourseServiceTest.java | 6 +- .../collections/CollectionUtilsGuideTest.java | 10 +- .../commons/collections/MapUtilsTest.java | 28 +- .../commons/collections/SetUtilsUnitTest.java | 3 +- .../orderedmap/OrderedMapUnitTest.java | 4 +- .../commons/collections4/BagTests.java | 58 ++-- .../commons/csv/CSVReaderWriterTest.java | 9 +- .../commons/dbutils/DbUtilsUnitTest.java | 20 +- .../commons/io/CommonsIOUnitTest.java | 74 ++--- .../commons/lang3/ArrayUtilsUnitTest.java | 62 ++--- .../commons/math/IntegrationTest.java | 2 +- .../commons/math/LinearAlgebraUnitTest.java | 4 +- .../commons/math/StatisticsUnitTest.java | 4 +- .../test/java/com/baeldung/crdt/CRDTTest.java | 40 ++- .../DistinctWithJavaFunctionUnitTest.java | 12 +- .../DistinctWithStreamexUnitTest.java | 8 +- .../distinct/DistinctWithVavrUnitTest.java | 8 +- .../baeldung/dockerapi/ContainerLiveTest.java | 108 +++----- .../dockerapi/DockerClientLiveTest.java | 41 +-- .../com/baeldung/dockerapi/ImageLiveTest.java | 67 ++--- .../baeldung/dockerapi/NetworkLiveTest.java | 41 +-- .../baeldung/dockerapi/VolumeLiveTest.java | 31 +-- .../CollectPatternTest.java | 3 +- .../ConvertContainerToAnotherTest.java | 3 +- .../eclipsecollections/DetectPatternTest.java | 3 +- .../eclipsecollections/FlatCollectTest.java | 3 +- .../InjectIntoPatternTest.java | 2 +- .../eclipsecollections/LazyIterationTest.java | 3 +- .../PartitionPatternTest.java | 12 +- .../eclipsecollections/RejectPatternTest.java | 6 +- .../eclipsecollections/SelectPatternTest.java | 12 +- .../baeldung/eclipsecollections/ZipTest.java | 3 +- .../eclipsecollections/ZipWithIndexTest.java | 3 +- .../com/baeldung/fj/FunctionalJavaTest.java | 50 ++-- .../flink/WordCountIntegrationTest.java | 95 +++---- .../sheets/GoogleSheetsIntegrationTest.java | 96 ++----- .../baeldung/hll/HLLLongRunningUnitTest.java | 34 +-- .../hoverfly/HoverflyApiIntegrationTest.java | 86 ++---- .../infinispan/ConfigurationTest.java | 19 +- .../service/HelloWorldServiceUnitTest.java | 39 +-- .../service/TransactionalServiceUnitTest.java | 5 +- .../com/baeldung/jasypt/JasyptUnitTest.java | 30 +- .../java/io/JavaDirectoryDeleteUnitTest.java | 5 +- .../baeldung/javassist/JavasisstUnitTest.java | 33 +-- .../javatuples/JavaTuplesUnitTest.java | 2 +- .../com/baeldung/javers/JaversUnitTest.java | 42 ++- .../com/baeldung/jcache/CacheLoaderTest.java | 6 +- .../baeldung/jcache/EntryProcessorTest.java | 3 +- .../baeldung/jcache/EventListenerTest.java | 6 +- ...heTest.java => JCacheIntegrationTest.java} | 2 +- .../jdo/GuideToJDOIntegrationTest.java | 1 - .../baeldung/jetty/JettyIntegrationTest.java | 9 +- .../jetty/JettyServerFactoryUnitTest.java | 118 ++++---- .../test/java/com/baeldung/jool/JOOLTest.java | 143 +++------- .../jsonassert/JsonAssertUnitTest.java | 28 +- .../junitparams/SafeAdditionUtilTest.java | 6 +- .../junitparams/TestDataProvider.java | 4 +- .../kafkastreams/KafkaStreamsLiveTest.java | 11 +- .../lsh/LocalSensitiveHashingUnitTest.java | 14 +- .../mbassador/MBassadorConfigurationTest.java | 4 +- .../baeldung/neuroph/XORIntegrationTest.java | 2 +- .../PactConsumerDrivenContractUnitTest.java | 45 +-- .../pairs/ApacheCommonsPairUnitTest.java | 1 - .../pairs/CoreJavaSimpleEntryUnitTest.java | 8 +- .../pcollections/PCollectionsUnitTest.java | 3 +- .../protonpack/CollectorUtilsTests.java | 19 +- .../baeldung/protonpack/StreamUtilsTests.java | 50 +--- .../basic/GitHubBasicApiLiveTest.java | 37 +-- .../baeldung/retrofit/rx/GitHubRxApiTest.java | 36 +-- .../serenity/GoogleSearchLiveTest.java | 8 +- .../github/GithubRestUserAPISteps.java | 5 +- .../membership/MemberStatusSteps.java | 2 +- .../pageobjects/GoogleSearchPageObject.java | 4 +- .../serenity/screenplay/GoogleSearchPage.java | 8 +- .../screenplay/GoogleSearchResults.java | 5 +- .../serenity/screenplay/SearchForKeyword.java | 9 +- .../serenity/screenplay/StartWith.java | 4 +- ...derClassDirtiesContextIntegrationTest.java | 8 +- ...xtDependencyWorkaroundIntegrationTest.java | 6 +- ...sContextInitWorkaroundIntegrationTest.java | 6 +- ...erMethodDirtiesContextIntegrationTest.java | 6 +- .../AdderMethodRuleIntegrationTest.java | 9 +- .../spring/AdderMockMvcIntegrationTest.java | 3 +- .../spring/AdderServiceIntegrationTest.java | 3 +- ...erSpringSerenityRunnerIntegrationTest.java | 6 +- .../baeldung/serenity/spring/AdderTest.java | 2 +- .../serenity/spring/steps/AdderRestSteps.java | 17 +- .../spring/steps/AdderServiceSteps.java | 3 +- .../serenity/spring/stories/AdderStory.java | 3 +- .../converter/SmooksIntegrationTest.java | 36 +-- .../java/com/baeldung/stm/AccountTest.java | 34 ++- .../baeldung/stream/JoolMergeStreamsTest.java | 13 +- .../com/baeldung/stream/MergeStreamsTest.java | 16 +- .../stream/StreamExMergeStreamsTest.java | 18 +- .../baeldung/streamutils/CopyStreamTest.java | 128 ++++----- .../test/java/com/baeldung/text/DiffTest.java | 4 +- .../text/LongestCommonSubsequenceTest.java | 6 +- .../com/baeldung/text/StrBuilderTest.java | 4 +- .../tomcat/ProgrammaticTomcatTest.java | 13 +- spring-5-reactive-client/pom.xml | 2 +- spring-5-reactive/pom.xml | 2 +- spring-boot/.factorypath | 183 ++++++------ 193 files changed, 1504 insertions(+), 2388 deletions(-) rename libraries/src/test/java/com/baeldung/jcache/{JCacheTest.java => JCacheIntegrationTest.java} (95%) diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx index 6e0a372dad8c2da5c7739237c17315706b5b4ef2..28196dc241963b5a6c3a992cc19b883f0e95560a 100644 GIT binary patch delta 4369 zcmZ8lbyU>d)8D08S-QKWT}eT@r9nDGkQSCuI=+C?Al(wu-3^MQOG-#c2urtsG%UV6 z{?7Zp{+>B!&YhY2nK|>vy)$?2%q+&@ECy6d6&-^VgoA?vij20Zh1!GB@78*6F!LWF zv6hHDu>tKN@ab&kXIw(XyncsCZj=}SBsM)(;1@J3$q!|b%ENn0gktKDzkjFrGniESfC9D(M3HN$)Dj!3jo^~oGZsCKjCg}~ zdQ|$dumYqdw}*foydvP|Cbd9Flb%GYnB^8;=XI@BoNV7XNybo1@~#sKScaq|mrTF# z&rv52w=xy@d)k+H@5@#7n95R6>KjANq#w%b@05aNNPfUr- zHT;TW?_D(Co|jliJHBEjEMdZ{gGg&#vA}oj2&yq6w;^OQvZ%8#z|%t9l2J!FQAZ6* zGQ?s%pEsR{2@D5trpP~$@lLnUY1-bxGfy!F&_=_RlH!!u26s4Crm%W+sCs(hTY~pR z%fpfIhdf?tW+S``ot{wvIV6j5@{0-KFI}3Lm9EJ(*=X$-bmh4-3)!zRLcT0;ku0#h z`J{#Bj{bEzn&x2!FM5Y-Q!4o>D&fXsr+X z0D%)L;5fV0yH?kPGQX=-zY@HA`2 zgdts8yZ{d|$<9NGj_iwK1A|lw+f=izvQo`rjLang!VPlagVF_oy03JEhw$SPK->hC ztLTy>+sB!==dX^WL^lub2YC%epW|Wulz^06{hDMC{Ek>%7FOY#%^mvrwl;Wr45&A@;l$L zTJS$zRFaLY$cUKnkd{l@;9EPj3e*Q1J2X<;bgZwc6*SrTGMi!RM;B=D4G6wqr z#*m{ZO-z*!-o@87H-UL9BRSvT`7a$=bH*DLpH=%()Js;$cFK!KKR+|{O*qRrcPr;@ z*9g8Lk6ThW_Eqx!Lg|+S*!fKQ?v_@FpJb1B9}rk7!Rlt|l_ldA9=bDL0vdHRyN?3! z^-wcIA>D!K1K0@!tj=K6_7h3nQ~C&V7zG3!pOxVb-hp{ie81Ib>epBPL|(*IB;GY2{6(qv9Ka?a%9^z%_G?bo_erYL@N(T zvP@bEmzbC|j-J&ojV)kz-V{$}<^v!tRcxF?H&CH8CJ5BX3cAz(s;%`jI2`|}sfxJ$ z0EuvaNiTwpJpVmkpGj1kM4Kt`y|9YsEf%3mruQvA?;wbdT8i|SEj8tJV0(;Uv1RU+ zUvD$#Q)pgS)d@i}D@&^@?DuDgdTi{nCLOeAX0&a)i5j09!V;I@>d9!W`g9Sdz4U0m zF=nrymt(qydqF}}XI+Z%GfQ>_j9|UlfM8T2%(jm;#TSI@~R;N|(Y7N_|Sw=)vgFLW;luY@@+ZE9kiSb-}j3wAs$(<5=gL!CW z!Lb4Tj!x0u^@lH_R}LpvHTiz5Q36K2@P1BQD+$W<^e|NTgW-zJLE_G#7opkHcPG&+fg(AJlyLXm5J|{D_K|S9+S%9f)P8n z;^FaS<*Y(?Q2YQ;h7sCPY745Pp}&FBo;-qYlhc&9=oSdJe+A@oOng_INhx5{f|>p^*$(D zW%uiV#yS+l`W1r_D=9HAW+)6-IE7eLo*Zjq`_bi*!Ll?u1Y_#SRylE59-@g@Q5Fgw z?c*t{3c`3G6?Tzm~;xWY87mH@8Sk2$9CcJN&wICi!ylIDA9(7jRI9)l(FRGdt$}^DE zDMWIMlLwBk41`6XdL58Fb-RgKv6LQGi(YIYA<6@ZYD5GaRf5y9wehZ&_w%n%$o0?S z5+g&jgJa6G^N7S~z+t-%rki9PB<&1%nNT2QjOvp?{3CL*apC+SmD#c>-vyZ@UshEO zjHNv*UsdrYo}-7Ibq20E{D|_ABr!TqZma8U`>drN)E$->!0BG~)t=GH2X(VmkU%ES z#b%(6)HM?P0F*}-$;KKB4vfaSn$*G*B-+}Z%$ZLLPI2@DdHB`?#@MUlBSw^Q-Bd+& z1Z8+bXa++Ww%k@ddj=vI_OA-(S$Bn5Z)-CPg=AAY8VbeQHRPk z44=9s-=LO(-%#H?`zx6Prl0UQHW+t{Qpc&f=cj@G=8d9K%gv5^3p;%5^EA^S|LaGf zmrK-`H9INpvVl9uw5eY|+3|l&q+%K$TE3W$uSv{}gdv~e&(frxtFFsLFI3BmZ8*aC z9{Xx$eOg}F|D5r(`t`TKdpn^@=7H5MW81;w+Q-Jg~rSC$oEF3vzOS<(6h{804Z_ z@|tSK9k7#-U4eOU0rQ|^f&GLgGj{*u=Wm!j78%_w>oy)oFw{R`%%)vmW^+8#7}OwpmeIAKdKo<11XQl0jvuk{KtIpTZ!h-`B!0xT#;Mxvo&bZ-5=gjN`< z_f7q)GUdMfeX>!l`K)r6P+tvG%xGa%(}6M6W+eo>5-IpV*cD~@{9D+;uF|Cew#H2hui&kRGN5b?goV=ufMJLkNL#LX_Q$~N3tXhM z?+QGKJE$9dZ8#77fM1mKX7~|Zv=Uq4pkBu5s7ho&@vC<1VI4vP+LD4E)oLxWPTFMn zS#~<>2CqQx4QyM60^6ZwGin4{Z8&W4(BIWCqAh8qHI4hlpd-<7HFS0Fqz!A#BL#E~ zJSq;9WcRlp@|IVr15iTqW)81)T|y-N;BZ|7!|gTAqNm3;ChL&P;|5A*Yt;+VMloue zuX@c6!Ug56W(-rMY$_3te;)&Bw_}|*Glh<|F0Va-d*08$!_!B2@l|`!2}88-YL5Dc z%+&);3vce( zuGyPmy01Mpc`>sJ%AZ~hJmG%3_xn!|_s%Xyz;HmIA9DZd;dkSZ5THAyKXu?hkUZfZ z*p-b@eo@?nYn2laMu^7rS^>e-bu|3tW9TxREEM9)|)DO(GTlh*hTV-wu$6b};e zIky)=a+}I}HpqRy0DwV-kjoA>zDT7Ev1y!q3G_7Jo%--n9%vWPFCOGrO@sC*A3O9% z*|f^9zvSkzS>}ZBk@X7+iY6;&+V4&_5BX)B`*96Z3bcgekxWe*c7Dr*60w6cC#;Gt zPYPucVrrFxQHT*CBy^pNDE+Ygqbs!E`UUKC+Bx2^rX9Qql*x8}ZkDT=_lr3$q%cbf zK2-uS==IBmKQq0w(ZxMiHvQZm?8vC7b`;*=2d@oEO7wHD)Y*5kDc6DDUQBiI^k=ZIePSgLXJoe4CPp=ilb z!{eu{7KX%0EVhr`R?1UV<&-jx>Bcqc-y^E*4litXdngVMme0su~xFxdQ(ovAR9%} zx7a-#-P3hDt*tY>)wke(9-K7=4^Pw4Kp;BEzYgo0Fw*8QQg9o|KNEebJO>#0N8sQD z&;Ak6xxkYD+2R5V>XTS8Z<(jL@pe9J1tc(8Y$@iJ_^+Sz9Iym zzv(e92;}MPX7%9JYi~#ESA1Shj{kQ4J7uE3eL*Fu=Gj)07NpXmdY6jx~BC{f!u#U zY94_qrfKu?2>CVmd#pc&kKWonoXCNvLpv@hrAEHecC|8k++a5oDVzD88fOymLRIXf zW=-dFdi86nMJ}7L)XWcD-!DD9eR59=I|nm7mH-4(Xi;ybUbP1XLpr}VD8w+m1fMX5!-Rb-m&W>Yb(%aa_T>P z70&dqGJ?_DJM4arQZW|z(G0OXQH@-cGxRG~&8yZqIV+W3GsQ>{}TZ zVG{R?87x{A23`PgWx=B)W3eufgn>>*eKoxzT~vr#OQLFleOfG-6WNCZ!5kaPp$)tEN?0U-VFUtlhNT;CKV$ldyjm4WyYp?jQ=RI$K zay^LigZ^%_JUmZXPvhN4S4M@`OWc)i2oS`nEtT+@%?eV@!1!fWjhJ`XnGYjxl(7WV z3LJ(7y96nKREU;eS9YfSLS8oQi?#I)CYB;ZOs7KbQ2oFffJJGpDDjw~{8rsbr$Hx%QwzQ_H*VN^gA*-tt)>=}x6>E196)r6v z5|iNIs68ck8!d4m^h>>m9QP;8CukyiJ+}OI^cm_WmG&4;Aiiip6rQ0=gh=L&c-Jg2 z&r3XalFjgvQ?cUY;Jc1E;I z*O;oq5n?BY8yowJn{~HMsE*EZtPTQ+KaEE|_-*h@?Cl5}?XLTN8LRmvra;95tkfg$ zYBMMS2LV||_W}Y2;}0l_cNDuZ)pE1a5B6a1<&p~H;f6^ZlieHza!yfkABYy|nkR3t z<}|AaAwRSL7u(!$kH>0zXO@OcZ~eaQ?!PNc`XKQB5I%2fZ<43S_u+(|2h?%JCxoF! zwTob7Y3dP)3`6)s1N5tS%w&U}^g4fjH!zf8a%#5{m>A>+76};pey=YdG>+gb6W(g< z7Sqhamz1ols1r9Fp?Y$mKO?-qIZHlyR>w@p$)mc(;bP)Vq?@LZJ)+$G+${wEGj7%t zSjFx$+oM>!ZM&-bEe$C)=u-5p>FYvrh4Z%K{Wl#A$3_jgN8^N*nBwH;R4;#pNQ_v6 z@9dj?oG+_cDBZu!nO!ub=+DE|Gd3P=eMZ9dh~l*W%niZR`UoUu@1k+rgOJ`o%)Tk- z0iQ95_`=bvInyG%vJmu<&1ON{O~~8mXR(7O^M*$PcEkDcPtHnN^{A1+=E*b**gZ5w z-wyX#+v^tF_;#I!HcsZ&qpwEnfg|fyG$ge!h^Z?LFNfN8rgYMUJnSwT{%$Iogb4$T zvAn}X4x+vm$tATC9hSnHEhY~}L>oi9rwFt2M$|>0{YKjQOSfgUzB?2yxZK_sEWQ~> zTegipsg1>OvZ(U#_T}f7=C^|r7)v&YKSAh>gH=|0DyJHn+;g`aI|_?AF81@apFF<; z>S~gZau`-q$Pobmjl2NB-zk*r-#N6Njg59)9}WgfiLloT!do%su*mz?X9NvL2MNFYmS432yf-MhHW!@(eueU*KM|6hfoY|*Znu<-G76?^;J1rL`Xuf^hCjg@ z5dt*M8Z1|23Gaa?sFglJ+06U0*%9}UJeMV~OGc||U2a+EzLcP(s%kl(f3TWUUSINR zPO$M$2e@ie-Z=#M85%3^VR$hFZ?5iGI)`TSa<-)RpHZMU@GJ zSeNHv%G1a*>A|=R7c<&l&C$6-!iL&A&tgj!u_;E@(j8_q=*YU}M8O;6F=+%!8H6mF zF|6DapaY+ri&MBq0gxzcgZI#o%uvtHoQ$Us3s|#ZG@MchOV3vd8Yc8X`K0$@aPL`s zgD!nOliG*;h})hqos;SkZiY4`6y`ArsyVkY)b7c{H-lHEg?%oc(%T?E&%O#J=@{N~ zepjF!HOs-p{9BX}lo`eA)804soRu+2D^J%^2BtY6qsyy~Y=?S9)E)Vaw1zDzWDV%T zAvla z9T`W{S8KboE5&#>czCQK_zs?V{?>bF{L6j}&hch^mw}z4(`j$Hs~c_8=)pL1)c-}5 z5?SZon(|4pXj#1^ngnco)1`2_PpURm@A7Kb%PKE#)t=hkiFea&SzVbjE|@jiVR-*xp{h`p-P-5( zRVIjjc8hu5ts3X7$6#AMOjMm+RrucesvxBrj`HCQi6PcLw8DP4o}teAxPoQ4p;_PU z)z+7n&h&=$Z}{?81XtZ1MG}_<9pH`vz3ur6$#yYjpOfP)`;xH;`lXGQf#jx^;ehnn zc$y{2@OgJJsgzmDNArB%EC-Wr1McBWPgPN%SIC(iKF>OA+_y&)M`>To2Xh8!+FDa5=q(-fc%`kgZL(8b@O z42qXaG->Uu3Sd&qiS<7024oe+lEI2A&qcKjs98XZA7}0w7A=k)lRK7eeKC~kl7&?h zsANN{?bfdjj3UFod1NtVzekJQ*-$zO3Y^R1;Bgwkt8QKad73cxc+hbexyNY4>x&8y z3_Ztq6NBU}!qjyrbyIf$Aj>X97NfUE9x3QtM0ga)dcNy?sel7|IgEucWwMf^9df99 zU#IA=+!}u72)*Ai(L4`w5Qv6T8;s+Mjmu&!pKBljN3?Dnq%qr|GY$*lKoWBYJ*!w_ z!PU1J?NXJ>78-k~p_d}|O{8a2SWmxa79c02W=L=j=Ai;dYJ0N zdqoa81fm>X>9Y@;5O`W&|fQB3+Bb=|+BI4lUYC~~Z;JKwaR zUSv;UltyY_o6JrK;^x;2VO&XLu0er0&R25N;y58sqGN6o?b@Y_=Z8K1goC-K!rZPx zF3IY-KmpXomn4(+Uhv*0&5F3$eC9K=_TZg}@a)nAl^VpNoLl*V4sT$j)pR4;nZX*&h{h&GO$uzXC>kw@Fbj`_cfukM3Z(4JaJQykQ?PRg zZ^um+p75?PD(eah8{OMzi|HDz1w-G%-E_wmRLsfp()?H$zkAtAD6Od(I^d4Ho?=)u zXm2^)@grAxA{mCOcW72#af$Asl(~!3w?=8gUuDzhfrlQKBCcYcX9}pXbg&jVnf^*p z5R&FCD_|LgaT1d?vo6tnANh)Da-XNP#cJvWqLu=fgYY+;$ z!SuF~(>$8aTZUUG-`tgJMKC|7mUON-8kW~QQ4JZ^SE>x~R~i|}EsE{0ie>3uq0=)o zMe*1OGPBoL!1%w)SM_dVZhp9GFx9p)ZuA=(5{q=bPfs&GCA9Uq5YUMEhuBTP1sTrYcfZ*s7> zkmtc!o>PsfTz|Fm?kNo4<+!`6#5qirwr$>Kw;iveoI>{C$Vu9SZocK9SI1`}K7Vuz znkGw2e<7of>{A?<@fy`}#WWDm3(A&n2;&rKw&z0>jdlLw-w5&cxSUKfDfar(y2-&K z1kV=R5FK7f#*j3E%K7>i^UaHec$u4T%Af?-l@KMrgOBznEb+f@HS*gKr5Kbu)Q2sZ z-#0lA#@;qNYdnq9iT!Kf4IRHi)U39GbTh+5JxX9R#6bldkzj4@$Y**qw}59C{-@*o z?s+1VP5=O~k^kRw4Nm~SO8^5~=>MMF(>3^kxIaKx066^zklg~x{Uf>slq9>>(fZT8 zrpH{f9DlPZHAiS1006jm?Va_S{%29AFWdsc|0w|X8uPv^wH|_sevZRX(0(poJ1%TJb{{l^B)` certList = new ArrayList(); CMSTypedData cmsData = new CMSProcessableByteArray(data); @@ -51,17 +50,14 @@ public class BouncyCastleCrypto { Store certs = new JcaCertStore(certList); CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); - cmsGenerator.addSignerInfoGenerator( - new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) - .build(contentSigner, signingCertificate)); + cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate)); cmsGenerator.addCertificates(certs); CMSSignedData cms = cmsGenerator.generate(cmsData, true); signedMessage = cms.getEncoded(); return signedMessage; } - public static boolean verifSignData(final byte[] signedData) - throws CMSException, IOException, OperatorCreationException, CertificateException { + public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException { ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ASN1InputStream aIn = new ASN1InputStream(bIn); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); @@ -81,16 +77,14 @@ public class BouncyCastleCrypto { return true; } - public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) - throws CertificateEncodingException, CMSException, IOException { + public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); - OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC") - .build(); + OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build(); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); encryptedData = cmsEnvelopedData.getEncoded(); } diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java index d0362a6c92..849e363c4b 100644 --- a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java @@ -5,12 +5,17 @@ import net.bytebuddy.implementation.bind.annotation.BindingPriority; public class Bar { @BindingPriority(3) - public static String sayHelloBar() { return "Holla in Bar!"; } + public static String sayHelloBar() { + return "Holla in Bar!"; + } @BindingPriority(2) - public static String sayBar() { return "bar"; } - - public String bar() { return Bar.class.getSimpleName() + " - Bar"; } + public static String sayBar() { + return "bar"; + } + public String bar() { + return Bar.class.getSimpleName() + " - Bar"; + } } diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java index 4be06785b1..9410fc6a13 100644 --- a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java @@ -2,6 +2,8 @@ package com.baeldung.bytebuddy; public class Foo { - public String sayHelloFoo() { return "Hello in Foo!"; } + public String sayHelloFoo() { + return "Hello in Foo!"; + } } diff --git a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java index a90b3e9f21..65c4c6919f 100644 --- a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java +++ b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java @@ -19,9 +19,7 @@ final class DataObject { @Override public String toString() { - return "DataObject{" + - "data='" + data + '\'' + - '}'; + return "DataObject{" + "data='" + data + '\'' + '}'; } public static DataObject get(String data) { diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java index f6bd25c0fe..354291ebd7 100644 --- a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java +++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java @@ -7,9 +7,7 @@ import net.openhft.chronicle.ExcerptAppender; public class ChronicleQueue { - static void writeToQueue( - Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) - throws IOException { + static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException { ExcerptAppender appender = chronicle.createAppender(); appender.startExcerpt(); appender.writeUTF(stringValue); diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java index 4a0b59404d..b88ee6624d 100644 --- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java @@ -24,7 +24,7 @@ public class CourseEntity { public void setCodes(List codes) { this.codes = codes; } - + public void setStudent(String id, Student student) { students.put(id, student); } diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java index 1f566a782a..538fa3accb 100644 --- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java @@ -8,33 +8,27 @@ import org.apache.commons.beanutils.PropertyUtils; public class CourseService { - public static void setValues(Course course, String name, List codes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public static void setValues(Course course, String name, List codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the simple properties PropertyUtils.setSimpleProperty(course, "name", name); PropertyUtils.setSimpleProperty(course, "codes", codes); } - - public static void setIndexedValue(Course course, int codeIndex, String code) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + + public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the indexed properties PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code); } - public static void setMappedValue(Course course, String enrollId, Student student) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the mapped properties PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student); } - - public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - return (String) PropertyUtils.getNestedProperty( - course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName); + + public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName); } - - public static void copyProperties(Course course, CourseEntity courseEntity) - throws IllegalAccessException, InvocationTargetException { + + public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException { BeanUtils.copyProperties(course, courseEntity); } } diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java index 973e2d498e..0acb222aa1 100644 --- a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java +++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java @@ -7,7 +7,7 @@ public class AuditFilter implements Filter { @Override public boolean postprocess(Context context, Exception exception) { - // Send notification to customer & bank. + // Send notification to customer & bank. return false; } diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java index e22f13861e..1c6a8dc4f1 100644 --- a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java +++ b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java @@ -73,7 +73,7 @@ public class Customer implements Comparable { this.name = name; this.phone = phone; } - + public Customer(String name) { super(); this.name = name; diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java index c82798d52d..7f24230c43 100644 --- a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java +++ b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java @@ -20,7 +20,6 @@ public class Email { public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } - public String getAddress() { return address; diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java index 35cae7426d..74e775383b 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java @@ -26,9 +26,7 @@ public class BuilderMethods { @Override public int hashCode() { - return new HashCodeBuilder().append(this.intValue) - .append(this.strSample) - .toHashCode(); + return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode(); } @Override @@ -41,16 +39,12 @@ public class BuilderMethods { } final BuilderMethods otherObject = (BuilderMethods) obj; - return new EqualsBuilder().append(this.intValue, otherObject.intValue) - .append(this.strSample, otherObject.strSample) - .isEquals(); + return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals(); } @Override public String toString() { - return new ToStringBuilder(this).append("INTVALUE", this.intValue) - .append("STRINGVALUE", this.strSample) - .toString(); + return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString(); } public static void main(final String[] arguments) { @@ -58,21 +52,21 @@ public class BuilderMethods { System.out.println(simple1.getName()); System.out.println(simple1.hashCode()); System.out.println(simple1.toString()); - + SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer(); - + try { sampleLazyInitializer.get(); } catch (ConcurrentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } - + SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer(); sampleBackgroundInitializer.start(); - + // Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish. - + try { Object result = sampleBackgroundInitializer.get(); } catch (ConcurrentException e) { @@ -81,13 +75,13 @@ public class BuilderMethods { } } -class SampleBackgroundInitializer extends BackgroundInitializer{ +class SampleBackgroundInitializer extends BackgroundInitializer { @Override protected String initialize() throws Exception { return null; } - + // Any complex task that takes some time - + } diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java index 56a49d2659..52c6e9c9aa 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java @@ -3,7 +3,7 @@ package com.baeldung.commons.lang3; import org.apache.commons.lang3.concurrent.LazyInitializer; public class SampleLazyInitializer extends LazyInitializer { - + @Override protected SampleObject initialize() { return new SampleObject(); diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java index 0e61176732..4595f4c6d0 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java @@ -1,7 +1,7 @@ package com.baeldung.commons.lang3; public class SampleObject { - - //Ignored + + // Ignored } diff --git a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java index d9c87b3889..97fbf4adc7 100644 --- a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java +++ b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java @@ -53,16 +53,12 @@ class Docx4jExample { File image = new File(imagePath); byte[] fileContent = Files.readAllBytes(image.toPath()); - BinaryPartAbstractImage imagePart = BinaryPartAbstractImage - .createImagePart(wordPackage, fileContent); - Inline inline = imagePart.createImageInline( - "Baeldung Image", "Alt Text", 1, 2, false); + BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent); + Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false); P Imageparagraph = addImageToParagraph(inline); mainDocumentPart.getContent().add(Imageparagraph); - int writableWidthTwips = wordPackage.getDocumentModel() - .getSections().get(0).getPageDimensions() - .getWritableWidthTwips(); + int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips(); int columnNumber = 3; Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber); List rows = tbl.getContent(); diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java index ebf0fa4d2d..eaa201d1ba 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java @@ -7,7 +7,7 @@ import fj.data.IO; import fj.data.IOFunctions; public class FunctionalJavaIOMain { - + public static IO printLetters(final String s) { return () -> { for (int i = 0; i < s.length(); i++) { @@ -21,8 +21,7 @@ public class FunctionalJavaIOMain { F> printLetters = i -> printLetters(i); - IO lowerCase = IOFunctions - .stdoutPrintln("What's your first Name ?"); + IO lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?"); IO input = IOFunctions.stdoutPrint("First Name: "); @@ -32,14 +31,11 @@ public class FunctionalJavaIOMain { F toUpperCase = i -> i.toUpperCase(); - F> transformInput = F1Functions - ., String> o(printLetters).f(toUpperCase); + F> transformInput = F1Functions., String> o(printLetters).f(toUpperCase); - IO readAndPrintResult = IOFunctions.bind(readInput, - transformInput); + IO readAndPrintResult = IOFunctions.bind(readInput, transformInput); - IO program = IOFunctions.bind(userInput, - nothing -> readAndPrintResult); + IO program = IOFunctions.bind(userInput, nothing -> readAndPrintResult); IOFunctions.toSafe(program).run(); diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java index e4d731454d..c6412f2923 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java @@ -11,16 +11,16 @@ import fj.function.Integers; public class FunctionalJavaMain { public static final F isEven = i -> i % 2 == 0; - + public static void main(String[] args) { - + List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); Show.listShow(Show.booleanShow).println(evenList); - + fList = fList.map(i -> i + 1); Show.listShow(Show.intShow).println(fList); - + Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); Array b = a.filter(Integers.even); Show.arrayShow(Show.intShow).println(b); @@ -28,11 +28,11 @@ public class FunctionalJavaMain { Array array = Array.array("Welcome", "To", "baeldung"); Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); System.out.println(isExist); - + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sum = intArray.foldLeft(Integers.add, 0); System.out.println(sum); - + Option n1 = Option.some(1); Option n2 = Option.some(2); diff --git a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java index 8deeeb01c4..f4e322f1e8 100644 --- a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java +++ b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java @@ -13,8 +13,6 @@ public class LineSplitter implements FlatMapFunction> out) { String[] tokens = value.toLowerCase().split("\\W+"); - Stream.of(tokens) - .filter(t -> t.length() > 0) - .forEach(token -> out.collect(new Tuple2<>(token, 1))); + Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1))); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/flink/WordCount.java b/libraries/src/main/java/com/baeldung/flink/WordCount.java index ab109bdbce..fc5064bafa 100644 --- a/libraries/src/main/java/com/baeldung/flink/WordCount.java +++ b/libraries/src/main/java/com/baeldung/flink/WordCount.java @@ -12,9 +12,7 @@ public class WordCount { public static DataSet> startWordCount(ExecutionEnvironment env, List lines) throws Exception { DataSet text = env.fromCollection(lines); - return text.flatMap(new LineSplitter()) - .groupBy(0) - .aggregate(Aggregations.SUM, 1); + return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java index 650a1d084c..641fae42dd 100644 --- a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java +++ b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java @@ -20,21 +20,13 @@ import com.google.api.services.sheets.v4.SheetsScopes; public class GoogleAuthorizeUtil { public static Credential authorize() throws IOException, GeneralSecurityException { InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json"); - GoogleClientSecrets clientSecrets = GoogleClientSecrets - .load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in)); + GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in)); List scopes = Arrays.asList(SheetsScopes.SPREADSHEETS); - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow - .Builder(GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), - clientSecrets, - scopes) - .setDataStoreFactory(new MemoryDataStoreFactory()) - .setAccessType("offline") - .build(); - Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) - .authorize("user"); + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory()) + .setAccessType("offline").build(); + Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); return credential; } diff --git a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java index bbce96f389..8a78d50551 100644 --- a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java +++ b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java @@ -14,10 +14,7 @@ public class SheetsServiceUtil { public static Sheets getSheetsService() throws IOException, GeneralSecurityException { Credential credential = GoogleAuthorizeUtil.authorize(); - return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), credential) - .setApplicationName(APPLICATION_NAME) - .build(); + return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build(); } } diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java index 0618a7294d..3b2c58d1e1 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java @@ -21,30 +21,23 @@ import java.util.concurrent.Future; public class GitHubExample { static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); - //static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); + // static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); static final JsonFactory JSON_FACTORY = new JacksonFactory(); - //static final JsonFactory JSON_FACTORY = new GsonFactory(); + // static final JsonFactory JSON_FACTORY = new GsonFactory(); private static void run() throws Exception { - HttpRequestFactory requestFactory - = HTTP_TRANSPORT.createRequestFactory( - (HttpRequest request) -> { - request.setParser(new JsonObjectParser(JSON_FACTORY)); - }); + HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> { + request.setParser(new JsonObjectParser(JSON_FACTORY)); + }); GitHubUrl url = new GitHubUrl("https://api.github.com/users"); url.per_page = 10; url.page = 1; HttpRequest request = requestFactory.buildGetRequest(url); - ExponentialBackOff backoff = new ExponentialBackOff.Builder() - .setInitialIntervalMillis(500) - .setMaxElapsedTimeMillis(900000) - .setMaxIntervalMillis(6000) - .setMultiplier(1.5) - .setRandomizationFactor(0.5) - .build(); + ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build(); request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); - Type type = new TypeToken>() {}.getType(); - List users = (List)request.execute().parseAs(type); + Type type = new TypeToken>() { + }.getType(); + List users = (List) request.execute().parseAs(type); System.out.println(users); url.appendRawPath("/eugenp"); request = requestFactory.buildGetRequest(url); diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java index c44de1e145..ea1b83e9fb 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java @@ -3,16 +3,16 @@ package com.baeldung.googlehttpclientguide; import com.google.api.client.http.GenericUrl; import com.google.api.client.util.Key; -public class GitHubUrl extends GenericUrl{ +public class GitHubUrl extends GenericUrl { public GitHubUrl(String encodedUrl) { super(encodedUrl); - } - + } + @Key public int per_page; - + @Key public int page; - + } diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java index bf4ee96b25..88361e158e 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java @@ -16,7 +16,7 @@ public class User extends GenericJson { private String blog; @Key private String email; - + @Key("subscriptions_url") private String subscriptionsUrl; @@ -71,7 +71,6 @@ public class User extends GenericJson { @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; - } - - + } + } diff --git a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java index ff4bc939aa..d96c0eb107 100644 --- a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java +++ b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java @@ -14,15 +14,15 @@ public class DataSource { private static HikariDataSource ds; static { -// config = new HikariConfig("datasource.properties"); - -// Properties props = new Properties(); -// props.setProperty("dataSourceClassName", "org.h2.Driver"); -// props.setProperty("dataSource.user", ""); -// props.setProperty("dataSource.password", ""); -// props.put("dataSource.logWriter", new PrintWriter(System.out)); -// config = new HikariConfig(props); - + // config = new HikariConfig("datasource.properties"); + + // Properties props = new Properties(); + // props.setProperty("dataSourceClassName", "org.h2.Driver"); + // props.setProperty("dataSource.user", ""); + // props.setProperty("dataSource.password", ""); + // props.put("dataSource.logWriter", new PrintWriter(System.out)); + // config = new HikariConfig(props); + config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); config.setUsername(""); config.setPassword(""); @@ -30,13 +30,14 @@ public class DataSource { config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); ds = new HikariDataSource(config); - -// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); -// ds.setUsername(""); -// ds.setPassword(""); + + // ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); + // ds.setUsername(""); + // ds.setPassword(""); } - private DataSource() {} + private DataSource() { + } public static Connection getConnection() throws SQLException { return ds.getConnection(); diff --git a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java index af36ab7508..57d124fd5d 100644 --- a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java +++ b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java @@ -12,9 +12,7 @@ public class HikariCPDemo { public static List fetchData() { final String SQL_QUERY = "select * from emp"; List employees = null; - try (Connection con = DataSource.getConnection(); - PreparedStatement pst = con.prepareStatement(SQL_QUERY); - ResultSet rs = pst.executeQuery();) { + try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) { employees = new ArrayList(); Employee employee; while (rs.next()) { @@ -38,5 +36,5 @@ public class HikariCPDemo { public static void main(String[] args) { fetchData(); } - + } diff --git a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java index 58929c0111..eda511d7a7 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java +++ b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java @@ -43,8 +43,7 @@ public class CacheConfiguration { return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration()); } - private Cache buildCache(String cacheName, DefaultCacheManager cacheManager, - CacheListener listener, Configuration configuration) { + private Cache buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) { cacheManager.defineConfiguration(cacheName, configuration); Cache cache = cacheManager.getCache(cacheName); @@ -53,32 +52,19 @@ public class CacheConfiguration { } private Configuration expiringConfiguration() { - return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS) - .build(); + return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build(); } private Configuration evictingConfiguration() { - return new ConfigurationBuilder() - .memory().evictionType(EvictionType.COUNT).size(1) - .build(); + return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build(); } private Configuration passivatingConfiguration() { - return new ConfigurationBuilder() - .memory().evictionType(EvictionType.COUNT).size(1) - .persistence() - .passivation(true) - .addSingleFileStore() - .purgeOnStartup(true) - .location(System.getProperty("java.io.tmpdir")) - .build(); + return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build(); } private Configuration transactionalConfiguration() { - return new ConfigurationBuilder() - .transaction().transactionMode(TransactionMode.TRANSACTIONAL) - .lockingMode(LockingMode.PESSIMISTIC) - .build(); + return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build(); } } diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java index 3ecefcc21a..de30cd5c8e 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java +++ b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java @@ -15,11 +15,8 @@ public class HelloWorldService { private final Cache evictingHelloWorldCache; private final Cache passivatingHelloWorldCache; - public HelloWorldService(HelloWorldRepository repository, CacheListener listener, - Cache simpleHelloWorldCache, - Cache expiringHelloWorldCache, - Cache evictingHelloWorldCache, - Cache passivatingHelloWorldCache) { + public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache simpleHelloWorldCache, Cache expiringHelloWorldCache, Cache evictingHelloWorldCache, + Cache passivatingHelloWorldCache) { this.repository = repository; @@ -66,7 +63,7 @@ public class HelloWorldService { public String findEvictingHelloWorld(String key) { String value = evictingHelloWorldCache.get(key); - if(value == null) { + if (value == null) { value = repository.getHelloWorld(); evictingHelloWorldCache.put(key, value); } diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java index b0dbf5475f..26862b8d65 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java +++ b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java @@ -28,8 +28,7 @@ public class TransactionalService { watch.start(); transactionalCache.put(KEY, howManyVisits); watch.stop(); - System.out.println("I was able to set HowManyVisits to " + howManyVisits + - " after waiting " + watch.getTotalTimeSeconds() + " seconds"); + System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds"); tm.commit(); return howManyVisits; @@ -44,8 +43,7 @@ public class TransactionalService { TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager(); tm.begin(); transactionalCache.put(KEY, 1000); - System.out.println("HowManyVisits should now be 1000, " + - "but we are holding the transaction"); + System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction"); Thread.sleep(1000L); tm.rollback(); System.out.println("The slow batch suffered a rollback"); diff --git a/libraries/src/main/java/com/baeldung/javasisst/Point.java b/libraries/src/main/java/com/baeldung/javasisst/Point.java index 7e5c1cedd5..7f10e8c371 100644 --- a/libraries/src/main/java/com/baeldung/javasisst/Point.java +++ b/libraries/src/main/java/com/baeldung/javasisst/Point.java @@ -1,6 +1,5 @@ package com.baeldung.javasisst; - public class Point { public int x = 0; public int y = 0; diff --git a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java index fb24d4b85d..780604738e 100644 --- a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java +++ b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java @@ -1,6 +1,5 @@ package com.baeldung.javasisst; - public class ThreeDimensionalPoint { public int x = 0; public int y = 0; diff --git a/libraries/src/main/java/com/baeldung/javers/Address.java b/libraries/src/main/java/com/baeldung/javers/Address.java index 14f5907ef6..9b0c119046 100644 --- a/libraries/src/main/java/com/baeldung/javers/Address.java +++ b/libraries/src/main/java/com/baeldung/javers/Address.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - public class Address { private String country; diff --git a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java index 0b4e33fcb5..16be083d83 100644 --- a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java +++ b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - import java.util.List; public class PersonWithAddress { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java index ec2c52d3b5..8da601b0cf 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java @@ -7,9 +7,9 @@ import org.jdeferred.impl.DeferredObject; class FilterDemo { private static String modifiedMsg; - + static String filter(String msg) { - + Deferred d = new DeferredObject<>(); Promise p = d.promise(); Promise filtered = p.then((result) -> { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java index 95250cff76..94fe0b70a6 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java @@ -19,14 +19,11 @@ class PipeDemo { p.then((DonePipe) result -> { if (result < 90) { - return new DeferredObject() - .resolve(result); + return new DeferredObject().resolve(result); } else { - return new DeferredObject() - .reject(new Exception("Unacceptable value")); + return new DeferredObject().reject(new Exception("Unacceptable value")); } - }).done(r -> status = Result.SUCCESS) - .fail(r -> status = Result.FAILURE); + }).done(r -> status = Result.SUCCESS).fail(r -> status = Result.FAILURE); d.resolve(num); diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java index 2a9f83dc35..4efb1ad997 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java @@ -11,10 +11,7 @@ class PromiseDemo { Deferred deferred = new DeferredObject<>(); Promise promise = deferred.promise(); - promise.done(result -> System.out.println("Job done")) - .fail(rejection -> System.out.println("Job fail")) - .progress(progress -> System.out.println("Job is in progress")) - .always((state, result, rejection) -> System.out.println("Job execution started")); + promise.done(result -> System.out.println("Job done")).fail(rejection -> System.out.println("Job fail")).progress(progress -> System.out.println("Job is in progress")).always((state, result, rejection) -> System.out.println("Job execution started")); deferred.resolve(jobName); // deferred.notify(""); diff --git a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java index 22fd51ed92..c48b916b4b 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java @@ -12,9 +12,7 @@ public class ThreadSafeDemo { DeferredManager dm = new DefaultDeferredManager(); Deferred deferred = new DeferredObject<>(); Promise p1 = deferred.promise(); - Promise p = dm.when(p1) - .done(r -> System.out.println("done")) - .fail(r -> System.out.println("fail")); + Promise p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail")); synchronized (p) { while (p.isPending()) { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java index 2abe9bc10f..68a113d6a2 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java @@ -16,9 +16,7 @@ class DeferredManagerWithExecutorDemo { Deferred deferred = new DeferredObject<>(); DeferredManager dm = new DefaultDeferredManager(executor); Promise p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise(); - dm.when(p1, p2, p3) - .done(r -> System.out.println("done")) - .fail(r -> System.out.println("fail")); + dm.when(p1, p2, p3).done(r -> System.out.println("done")).fail(r -> System.out.println("fail")); deferred.resolve("done"); } } diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java index dc2e82495f..e1ffa3b6bc 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java @@ -7,8 +7,6 @@ class SimpleDeferredManagerDemo { public static void initiate() { DeferredManager dm = new DefaultDeferredManager(); - dm.when(() -> 1) - .done(r -> System.out.println("done")) - .fail(Throwable::printStackTrace); + dm.when(() -> 1).done(r -> System.out.println("done")).fail(Throwable::printStackTrace); } } diff --git a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java index 387c8c4e00..bd459f963c 100644 --- a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java +++ b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java @@ -42,8 +42,8 @@ public class GuideToJDO { listXMLProducts(); } - public void CreateH2Properties(){ - + public void CreateH2Properties() { + pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addClassName("com.baeldung.jdo.Product"); pumd.setExcludeUnlistedClasses(); @@ -51,18 +51,18 @@ public class GuideToJDO { pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence"); pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); - pumd.addProperty("datanucleus.autoCreateSchema", "true"); - + pumd.addProperty("datanucleus.autoCreateSchema", "true"); + } - - public void CreateXMLProperties(){ + + public void CreateXMLProperties() { pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumdXML.addClassName("com.baeldung.jdo.ProductXML"); pumdXML.setExcludeUnlistedClasses(); pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml"); - pumdXML.addProperty("datanucleus.autoCreateSchema", "true"); + pumdXML.addProperty("datanucleus.autoCreateSchema", "true"); } - + public void CreateProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); @@ -91,7 +91,7 @@ public class GuideToJDO { } @SuppressWarnings("rawtypes") - public void UpdateProducts(){ + public void UpdateProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -105,13 +105,13 @@ public class GuideToJDO { } finally { if (tx.isActive()) { tx.rollback(); - } + } pm.close(); } } - + @SuppressWarnings("rawtypes") - public void DeleteProducts(){ + public void DeleteProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -125,11 +125,11 @@ public class GuideToJDO { } finally { if (tx.isActive()) { tx.rollback(); - } + } pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) public void ListProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); @@ -155,9 +155,9 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QueryJDOQL (){ + public void QueryJDOQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -177,7 +177,7 @@ public class GuideToJDO { LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -187,28 +187,28 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QuerySQL (){ + public void QuerySQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - //SQL : + // SQL : LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------"); Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT"); query.setClass(Product.class); List results = query.executeList(); - + Iterator iter = results.iterator(); while (iter.hasNext()) { Product p = iter.next(); LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -218,27 +218,27 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QueryJPQL (){ + public void QueryJPQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - //JPQL : + // JPQL : LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------"); - Query q = pm.newQuery("JPQL", "SELECT p FROM "+Product.class.getName()+" p WHERE p.name = 'Laptop'"); - List results = (List)q.execute(); - + Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'"); + List results = (List) q.execute(); + Iterator iter = results.iterator(); while (iter.hasNext()) { Product p = iter.next(); LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -248,18 +248,18 @@ public class GuideToJDO { pm.close(); } } - - public void persistXML(){ + + public void persistXML() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - ProductXML productXML = new ProductXML(0,"Tablet", 80.0); + ProductXML productXML = new ProductXML(0, "Tablet", 80.0); pm.makePersistent(productXML); - ProductXML productXML2 = new ProductXML(1,"Phone", 20.0); + ProductXML productXML2 = new ProductXML(1, "Phone", 20.0); pm.makePersistent(productXML2); - ProductXML productXML3 = new ProductXML(2,"Laptop", 200.0); + ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0); pm.makePersistent(productXML3); tx.commit(); } finally { @@ -269,9 +269,9 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void listXMLProducts(){ + public void listXMLProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java index 384dde48d1..c902083e62 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java @@ -26,19 +26,19 @@ public class MyApp { } - public static void createTestData(){ - ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5); - ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8); - ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15); + public static void createTestData() { + ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5); + ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8); + ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15); - if( pm != null ){ + if (pm != null) { pm.makePersistent(item1); pm.makePersistent(item2); - pm.makePersistent(item3); + pm.makePersistent(item3); } } - public static void defineDynamicPersistentUnit(){ + public static void defineDynamicPersistentUnit() { PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db"); @@ -51,53 +51,46 @@ public class MyApp { pm = pmf.getPersistenceManager(); } - public static void queryUsingJDOQL(){ + public static void queryUsingJDOQL() { - Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " - + "WHERE price < threshold PARAMETERS double threshold"); - List explicitParamResults = (List)query.execute(10); + Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold"); + List explicitParamResults = (List) query.execute(10); - query = pm.newQuery("SELECT FROM " - + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); query.setParameters("double threshold"); - List explicitParamResults2 = (List)query.execute(10); + List explicitParamResults2 = (List) query.execute(10); - query = pm.newQuery("SELECT FROM " - + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); - List implicitParamResults = (List)query.execute(10); + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + List implicitParamResults = (List) query.execute(10); } - public static void queryUsingTypedJDOQL(){ + public static void queryUsingTypedJDOQL() { JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); QProductItem cand = QProductItem.candidate(); - tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); + tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); List results = tq.executeList(); } - public static void queryUsingSQL(){ + public static void queryUsingSQL() { - Query query = pm.newQuery("javax.jdo.query.SQL","select * from " - + "product_item where price < ? and status = ?"); + Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?"); query.setClass(ProductItem.class); - query.setParameters(10,"InStock"); + query.setParameters(10, "InStock"); List results = query.executeList(); } - public static void queryUsingJPQL(){ - Query query = pm.newQuery("JPQL","select i from " - + "com.baeldung.jdo.query.ProductItem i where i.price < 10" - + " and i.status = 'InStock'"); + public static void queryUsingJPQL() { + Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'"); List results = (List) query.execute(); } - public static void namedQuery(){ - Query query = pm.newNamedQuery( - ProductItem.class, "PriceBelow10"); + public static void namedQuery() { + Query query = pm.newNamedQuery(ProductItem.class, "PriceBelow10"); List results = query.executeList(); } diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java index 52221a7d97..3343febb89 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java @@ -10,25 +10,24 @@ import javax.jdo.annotations.PrimaryKey; public class ProductItem { @PrimaryKey - @Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT) + @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) int id; String name; String description; String status; double price; - public ProductItem(){ + public ProductItem() { } - public ProductItem(String name,String description,String status,double price){ - this.name=name; + public ProductItem(String name, String description, String status, double price) { + this.name = name; this.description = description; this.status = status; this.price = price; } - public int getId() { return id; } @@ -40,18 +39,23 @@ public class ProductItem { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } @@ -64,5 +68,4 @@ public class ProductItem { this.status = status; } - } diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java index 53e86524a5..d2518586b4 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java @@ -12,10 +12,7 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; -@PersistenceCapable( - schema="/myproduct/people", - table="person" - ) +@PersistenceCapable(schema = "/myproduct/people", table = "person") public class AnnotadedPerson { @XmlAttribute private long personNum; @@ -24,12 +21,11 @@ public class AnnotadedPerson { private String firstName; private String lastName; - @XmlElementWrapper(name="phone-numbers") - @XmlElement(name="phone-number") - @Element(types=String.class) + @XmlElementWrapper(name = "phone-numbers") + @XmlElement(name = "phone-number") + @Element(types = String.class) private List phoneNumbers = new ArrayList(); - public AnnotadedPerson(long personNum, String firstName, String lastName) { super(); this.personNum = personNum; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java index 97ec49eec1..c75d3695f7 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java @@ -17,35 +17,35 @@ public class MyApp { private static PersistenceManagerFactory pmf; private static PersistenceManager pm; - public static void main( String[] args ) { - - //persist product object using dynamic persistence unit + public static void main(String[] args) { + + // persist product object using dynamic persistence unit defineDynamicPersistentUnit(); - Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99); + Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99); persistObject(product); closePersistenceManager(); - - //persist AnnotatedPerson object using named pmf + + // persist AnnotatedPerson object using named pmf defineNamedPersistenceManagerFactory("XmlDatastore"); - AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person"); + AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person"); annotatedPerson.getPhoneNumbers().add("999999999"); annotatedPerson.getPhoneNumbers().add("000000000"); persistObject(annotatedPerson); queryAnnotatedPersonsInXML(); closePersistenceManager(); - - //persist Person object using PMF created by properties file + + // persist Person object using PMF created by properties file definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties"); - Person person = new Person(654321,"bealdung","author"); + Person person = new Person(654321, "bealdung", "author"); person.getPhoneNumbers().add("123456789"); person.getPhoneNumbers().add("987654321"); persistObject(person); queryPersonsInXML(); closePersistenceManager(); - } + } + + public static void defineDynamicPersistentUnit() { - public static void defineDynamicPersistentUnit(){ - PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); @@ -55,27 +55,27 @@ public class MyApp { pm = pmf.getPersistenceManager(); } - public static void defineNamedPersistenceManagerFactory(String pmfName){ - + public static void defineNamedPersistenceManagerFactory(String pmfName) { + pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); pm = pmf.getPersistenceManager(); } - public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){ - + public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { + pmf = JDOHelper.getPersistenceManagerFactory(filePath); pm = pmf.getPersistenceManager(); } - public static void closePersistenceManager(){ - - if(pm!=null && !pm.isClosed()){ + public static void closePersistenceManager() { + + if (pm != null && !pm.isClosed()) { pm.close(); } } - public static void persistObject(Object obj){ - + public static void persistObject(Object obj) { + Transaction tx = pm.currentTransaction(); try { @@ -88,18 +88,18 @@ public class MyApp { } } } - - public static void queryPersonsInXML(){ - + + public static void queryPersonsInXML() { + Query query = pm.newQuery(Person.class); List result = query.executeList(); - System.out.println("name: "+result.get(0).getFirstName()); + System.out.println("name: " + result.get(0).getFirstName()); } - - public static void queryAnnotatedPersonsInXML(){ - + + public static void queryAnnotatedPersonsInXML() { + Query query = pm.newQuery(AnnotadedPerson.class); List result = query.executeList(); - System.out.println("name: "+result.get(0).getFirstName()); + System.out.println("name: " + result.get(0).getFirstName()); } } diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java index e3ec5c6bab..b5750a2069 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java @@ -12,7 +12,6 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; - @PersistenceCapable public class Person { private long personNum; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java index d8d3bb17b2..83eed50624 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java @@ -14,19 +14,18 @@ public class Product { String name; String description; double price; - - public Product(){ - + + public Product() { + } - - public Product(String id,String name,String description,double price){ + + public Product(String id, String name, String description, double price) { this.id = id; - this.name=name; + this.name = name; this.description = description; this.price = price; } - - + public String getId() { return id; } @@ -38,21 +37,25 @@ public class Product { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } - - + } diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java index f1de71beeb..6bc73b055a 100644 --- a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java +++ b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java @@ -14,4 +14,3 @@ public class BlockingServlet extends HttpServlet { response.getWriter().println("{ \"status\": \"ok\"}"); } } - diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java index 364b05473a..82428642c1 100644 --- a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java @@ -21,7 +21,7 @@ class JettyServer { server = new Server(threadPool); ServerConnector connector = new ServerConnector(server); connector.setPort(8090); - server.setConnectors(new Connector[]{connector}); + server.setConnectors(new Connector[] { connector }); ServletHandler servletHandler = new ServletHandler(); server.setHandler(servletHandler); diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java index 00ba84368a..46a2e8102a 100644 --- a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java @@ -14,81 +14,79 @@ import org.eclipse.jetty.webapp.WebAppContext; */ public class JettyServerFactory { - /** - * Exposed context of the app. - */ - public final static String APP_PATH = "/myApp"; - - /** - * The server port. - */ - public final static int SERVER_PORT = 13133; + /** + * Exposed context of the app. + */ + public final static String APP_PATH = "/myApp"; - /** - * Private constructor to avoid instantiation. - */ - private JettyServerFactory() { - } + /** + * The server port. + */ + public final static int SERVER_PORT = 13133; - /** - * Returns a simple server listening on port 80 with a timeout of 30 seconds - * for connections and no handlers. - * - * @return a server - */ - public static Server createBaseServer() { - Server server = new Server(); + /** + * Private constructor to avoid instantiation. + */ + private JettyServerFactory() { + } - // Adds a connector for port 80 with a timeout of 30 seconds. - ServerConnector connector = new ServerConnector(server); - connector.setPort(SERVER_PORT); - connector.setHost("127.0.0.1"); - connector.setIdleTimeout(30000); - server.addConnector(connector); + /** + * Returns a simple server listening on port 80 with a timeout of 30 seconds + * for connections and no handlers. + * + * @return a server + */ + public static Server createBaseServer() { + Server server = new Server(); - return server; - } + // Adds a connector for port 80 with a timeout of 30 seconds. + ServerConnector connector = new ServerConnector(server); + connector.setPort(SERVER_PORT); + connector.setHost("127.0.0.1"); + connector.setIdleTimeout(30000); + server.addConnector(connector); - /** - * Creates a server which delegates the request handling to a web - * application. - * - * @return a server - */ - public static Server createWebAppServer() { - // Adds an handler to a server and returns it. - Server server = createBaseServer(); - String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") - .getPath(); - Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); - server.setHandler(webAppHandler); + return server; + } - return server; - } + /** + * Creates a server which delegates the request handling to a web + * application. + * + * @return a server + */ + public static Server createWebAppServer() { + // Adds an handler to a server and returns it. + Server server = createBaseServer(); + String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); + Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); + server.setHandler(webAppHandler); - /** - * Creates a server which delegates the request handling to both a logging - * handler and to a web application, in this order. - * - * @return a server - */ - public static Server createMultiHandlerServer() { - Server server = createBaseServer(); + return server; + } - // Creates the handlers and adds them to the server. - HandlerCollection handlers = new HandlerCollection(); + /** + * Creates a server which delegates the request handling to both a logging + * handler and to a web application, in this order. + * + * @return a server + */ + public static Server createMultiHandlerServer() { + Server server = createBaseServer(); - String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") - .getPath(); - Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); - handlers.addHandler(customRequestHandler); + // Creates the handlers and adds them to the server. + HandlerCollection handlers = new HandlerCollection(); - Handler loggingRequestHandler = new LoggingRequestHandler(); - handlers.addHandler(loggingRequestHandler); + String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); + Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); + handlers.addHandler(customRequestHandler); - server.setHandler(handlers); + Handler loggingRequestHandler = new LoggingRequestHandler(); + handlers.addHandler(loggingRequestHandler); - return server; - } + server.setHandler(handlers); + + return server; + } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java index a38759c903..a5c6d09c16 100644 --- a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java +++ b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java @@ -19,150 +19,149 @@ import org.slf4j.LoggerFactory; */ public class LoggingRequestHandler implements Handler { - /** - * Logger. - */ - private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class); + /** + * Logger. + */ + private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class); - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org. - * eclipse.jetty.util.component.LifeCycle.Listener) - */ - @Override - public void addLifeCycleListener(Listener arg0) { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org. + * eclipse.jetty.util.component.LifeCycle.Listener) + */ + @Override + public void addLifeCycleListener(Listener arg0) { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isFailed() - */ - @Override - public boolean isFailed() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isFailed() + */ + @Override + public boolean isFailed() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isRunning() - */ - @Override - public boolean isRunning() { - return true; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isRunning() + */ + @Override + public boolean isRunning() { + return true; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStarted() - */ - @Override - public boolean isStarted() { - return true; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStarted() + */ + @Override + public boolean isStarted() { + return true; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStarting() - */ - @Override - public boolean isStarting() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStarting() + */ + @Override + public boolean isStarting() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStopped() - */ - @Override - public boolean isStopped() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStopped() + */ + @Override + public boolean isStopped() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStopping() - */ - @Override - public boolean isStopping() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStopping() + */ + @Override + public boolean isStopping() { + return false; + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org. - * eclipse.jetty.util.component.LifeCycle.Listener) - */ - @Override - public void removeLifeCycleListener(Listener arg0) { - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org. + * eclipse.jetty.util.component.LifeCycle.Listener) + */ + @Override + public void removeLifeCycleListener(Listener arg0) { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#start() - */ - @Override - public void start() throws Exception { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#start() + */ + @Override + public void start() throws Exception { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#stop() - */ - @Override - public void stop() throws Exception { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#stop() + */ + @Override + public void stop() throws Exception { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#destroy() - */ - @Override - public void destroy() { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#destroy() + */ + @Override + public void destroy() { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#getServer() - */ - @Override - public Server getServer() { - return null; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#getServer() + */ + @Override + public Server getServer() { + return null; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, - * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) - */ - @Override - public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) - throws IOException, ServletException { - LOG.info("Received a new request"); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, + * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException { + LOG.info("Received a new request"); + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. - * Server) - */ - @Override - public void setServer(Server server) { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. + * Server) + */ + @Override + public void setServer(Server server) { + } } diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java index c5bdeb1013..abb6bf7dd9 100644 --- a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java +++ b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java @@ -5,7 +5,6 @@ import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.logging.Logger; - public class ChannelHandlerB extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(getClass().getName()); @@ -14,7 +13,7 @@ public class ChannelHandlerB extends ChannelInboundHandlerAdapter { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.info("Exception Handled in ChannelHandler B"); logger.info(cause.getLocalizedMessage()); - //do more exception handling + // do more exception handling ctx.close(); } } diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java index c8004623c2..49a6aa6bfd 100644 --- a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java +++ b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java @@ -9,7 +9,7 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; -public class NettyServerB { +public class NettyServerB { private int port; @@ -24,15 +24,11 @@ public class NettyServerB { try { ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new ChannelInitializer() { - public void initChannel(SocketChannel ch) throws Exception { - ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); - } - }) - .option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { + public void initChannel(SocketChannel ch) throws Exception { + ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); + } + }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); // (7) f.channel().closeFuture().sync(); } finally { diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries/src/main/java/com/baeldung/netty/RequestData.java index 402aa1ef91..475c0a4dc1 100644 --- a/libraries/src/main/java/com/baeldung/netty/RequestData.java +++ b/libraries/src/main/java/com/baeldung/netty/RequestData.java @@ -22,9 +22,6 @@ public class RequestData { @Override public String toString() { - return "RequestData{" + - "intValue=" + intValue + - ", stringValue='" + stringValue + '\'' + - '}'; + return "RequestData{" + "intValue=" + intValue + ", stringValue='" + stringValue + '\'' + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries/src/main/java/com/baeldung/netty/ResponseData.java index 51d1adaafb..8849e8a4cb 100644 --- a/libraries/src/main/java/com/baeldung/netty/ResponseData.java +++ b/libraries/src/main/java/com/baeldung/netty/ResponseData.java @@ -13,8 +13,6 @@ public class ResponseData { @Override public String toString() { - return "ResponseData{" + - "intValue=" + intValue + - '}'; + return "ResponseData{" + "intValue=" + intValue + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java index fb6a01d4c1..4cb11c3c05 100644 --- a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java +++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java @@ -41,7 +41,7 @@ public class NeurophXOR { ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); ann.addLayer(3, outputLayer); ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); - ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false); ann.setInputNeurons(inputLayer.getNeurons()); ann.setOutputNeurons(outputLayer.getNeurons()); @@ -55,13 +55,13 @@ public class NeurophXOR { int outputSize = 1; DataSet ds = new DataSet(inputSize, outputSize); - DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); + DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 }); ds.addRow(rOne); - DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); + DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 }); ds.addRow(rTwo); - DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); + DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 }); ds.addRow(rThree); - DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); + DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 }); ds.addRow(rFour); BackPropagation backPropagation = new BackPropagation(); diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java index 59e13efaa0..48abe35287 100644 --- a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java +++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -11,10 +11,7 @@ public class CustomExceptionHandler extends ExceptionHandler { @Override public boolean handle(Throwable throwable) { - if (throwable.getClass() - .isAssignableFrom(RuntimeException.class) - || throwable.getClass() - .isAssignableFrom(Error.class)) { + if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) { return false; } else { logger.error("Caught Exception ", throwable); diff --git a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java index eead34af71..b872696510 100644 --- a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java +++ b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java @@ -20,18 +20,14 @@ public class StreamUtilsExample { public void zipAStreamWithIndex() { Stream source = Stream.of("Foo", "Bar", "Baz"); - List> zipped = StreamUtils - .zipWithIndex(source) - .collect(Collectors.toList()); + List> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList()); } public void zipAPairOfStreams() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, (a, b) -> a + " is for " + b) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList()); } public void zipThreeStreams() { @@ -39,9 +35,7 @@ public class StreamUtilsExample { Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream streamC = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList()); } public void mergeThreeStreams() { @@ -79,24 +73,16 @@ public class StreamUtilsExample { public void windowedStream() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2) - .collect(toList()); - List> windowsWithSkipIndex = StreamUtils - .windowed(integerStream, 3, 2) - .collect(toList()); - List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils - .windowed(integerStream, 2, 2, true) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); + List> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); + List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList()); } public void groupRunsStreams() { Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); - List> runs = StreamUtils - .groupRuns(integerStream) - .collect(toList()); + List> runs = StreamUtils.groupRuns(integerStream).collect(toList()); } public void aggreagateOnBiElementPredicate() { diff --git a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java index 4757d912f8..b55517b6d1 100644 --- a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java +++ b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java @@ -19,45 +19,17 @@ public class QuartzExample { Scheduler sched = schedFact.getScheduler(); - JobDetail job = JobBuilder.newJob(SimpleJob.class) - .withIdentity("myJob", "group1") - .usingJobData("jobSays", "Hello World!") - .usingJobData("myFloatValue", 3.141f) - .build(); + JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build(); - Trigger trigger = TriggerBuilder.newTrigger() - .withIdentity("myTrigger", "group1") - .startNow() - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); + Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); - JobDetail jobA = JobBuilder.newJob(JobA.class) - .withIdentity("jobA", "group2") - .build(); + JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build(); - JobDetail jobB = JobBuilder.newJob(JobB.class) - .withIdentity("jobB", "group2") - .build(); + JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build(); - Trigger triggerA = TriggerBuilder.newTrigger() - .withIdentity("triggerA", "group2") - .startNow() - .withPriority(15) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); + Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); - Trigger triggerB = TriggerBuilder.newTrigger() - .withIdentity("triggerB", "group2") - .startNow() - .withPriority(10) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(20) - .repeatForever()) - .build(); + Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build(); sched.scheduleJob(job, trigger); sched.scheduleJob(jobA, triggerA); diff --git a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java index 554d3b9358..03730ee6e5 100644 --- a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java +++ b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java @@ -8,8 +8,7 @@ import org.quartz.JobExecutionException; public class SimpleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - JobDataMap dataMap = context.getJobDetail() - .getJobDataMap(); + JobDataMap dataMap = context.getJobDetail().getJobDataMap(); String jobSays = dataMap.getString("jobSays"); float myFloatValue = dataMap.getFloat("myFloatValue"); diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java index 4e071d3384..2b5c1f6f62 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java @@ -18,7 +18,7 @@ public interface GitHubBasicApi { */ @GET("users/{user}/repos") Call> listRepos(@Path("user") String user); - + /** * List Contributors of a GitHub Repository * @param user GitHub Account @@ -26,8 +26,6 @@ public interface GitHubBasicApi { * @return GitHub Repository Contributors */ @GET("repos/{user}/{repo}/contributors") - Call> listRepoContributors( - @Path("user") String user, - @Path("repo") String repo); - + Call> listRepoContributors(@Path("user") String user, @Path("repo") String repo); + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java index 6b2cd14252..df0d90af7f 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java @@ -7,8 +7,7 @@ public class GitHubBasicApp { public static void main(String[] args) throws IOException { String userName = "eugenp"; - List topContributors = new GitHubBasicService() - .getTopContributors(userName); + List topContributors = new GitHubBasicService().getTopContributors(userName); topContributors.forEach(System.out::println); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java index 20256fb540..ff6ef82183 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java @@ -16,45 +16,29 @@ class GitHubBasicService { private GitHubBasicApi gitHubApi; GitHubBasicService() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build(); gitHubApi = retrofit.create(GitHubBasicApi.class); } List getTopContributors(String userName) throws IOException { - List repos = gitHubApi - .listRepos(userName) - .execute() - .body(); + List repos = gitHubApi.listRepos(userName).execute().body(); repos = repos != null ? repos : Collections.emptyList(); - return repos.stream() - .flatMap(repo -> getContributors(userName, repo)) - .sorted((a, b) -> b.getContributions() - a.getContributions()) - .map(Contributor::getName) - .distinct() - .sorted() - .collect(Collectors.toList()); + return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList()); } private Stream getContributors(String userName, Repository repo) { List contributors = null; try { - contributors = gitHubApi - .listRepoContributors(userName, repo.getName()) - .execute() - .body(); + contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body(); } catch (IOException e) { e.printStackTrace(); } contributors = contributors != null ? contributors : Collections.emptyList(); - return contributors.stream() - .filter(c -> c.getContributions() > 100); + return contributors.stream().filter(c -> c.getContributions() > 100); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java index 2f8697f603..f98b19de96 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java @@ -3,28 +3,31 @@ package com.baeldung.retrofit.models; import com.google.gson.annotations.SerializedName; public class Contributor { - + @SerializedName("login") private String name; - + private Integer contributions; - + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Integer getContributions() { return contributions; } + public void setContributions(Integer contributions) { this.contributions = contributions; } - + @Override public String toString() { return "Contributer [name=" + name + ", contributions=" + contributions + "]"; } - + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java index f12fcdf8f2..6bc91eb772 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java @@ -1,20 +1,23 @@ package com.baeldung.retrofit.models; public class Repository { - + private String name; - + private String description; - + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java index 4e40aff448..aa0f550115 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java @@ -18,7 +18,7 @@ public interface GitHubRxApi { */ @GET("users/{user}/repos") Observable> listRepos(@Path("user") String user); - + /** * List Contributors of a GitHub Repository * @param user GitHub Account @@ -26,8 +26,6 @@ public interface GitHubRxApi { * @return GitHub Repository Contributors */ @GET("repos/{user}/{repo}/contributors") - Observable> listRepoContributors( - @Path("user") String user, - @Path("repo") String repo); - + Observable> listRepoContributors(@Path("user") String user, @Path("repo") String repo); + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java index b136a1e40b..4941a65717 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java @@ -6,7 +6,6 @@ public class GitHubRxApp { public static void main(String[] args) throws IOException { String userName = "eugenp"; - new GitHubRxService().getTopContributors(userName) - .subscribe(System.out::println); + new GitHubRxService().getTopContributors(userName).subscribe(System.out::println); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java index 2ad50a9f39..f2c5114149 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java @@ -11,23 +11,13 @@ class GitHubRxService { private GitHubRxApi gitHubApi; GitHubRxService() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); gitHubApi = retrofit.create(GitHubRxApi.class); } Observable getTopContributors(String userName) { - return gitHubApi.listRepos(userName) - .flatMapIterable(x -> x) - .flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())) - .flatMapIterable(x -> x) - .filter(c -> c.getContributions() > 100) - .sorted((a, b) -> b.getContributions() - a.getContributions()) - .map(Contributor::getName) - .distinct(); + return gitHubApi.listRepos(userName).flatMapIterable(x -> x).flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())).flatMapIterable(x -> x).filter(c -> c.getContributions() > 100) + .sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct(); } } diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java index d32891be9e..dc6bfbddb1 100644 --- a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java +++ b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java @@ -13,19 +13,13 @@ public class GitHubServiceGenerator { private static final String BASE_URL = "https://api.github.com/"; - private static Retrofit.Builder builder - = new Retrofit.Builder() - .baseUrl(BASE_URL) - .addConverterFactory(GsonConverterFactory.create()); + private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()); private static Retrofit retrofit = builder.build(); - private static OkHttpClient.Builder httpClient - = new OkHttpClient.Builder(); + private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); - private static HttpLoggingInterceptor logging - = new HttpLoggingInterceptor() - .setLevel(HttpLoggingInterceptor.Level.BASIC); + private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC); public static S createService(Class serviceClass) { if (!httpClient.interceptors().contains(logging)) { @@ -43,8 +37,7 @@ public class GitHubServiceGenerator { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); - Request.Builder builder = original.newBuilder() - .header("Authorization", token); + Request.Builder builder = original.newBuilder().header("Authorization", token); Request request = builder.build(); return chain.proceed(request); } diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java index 8a674f634b..be7e15e3c9 100644 --- a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java +++ b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java @@ -11,15 +11,11 @@ import retrofit2.converter.gson.GsonConverterFactory; public class Main { public static void main(String[] args) { - //Manual creation + // Manual creation OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .client(httpClient.build()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build(); UserService service = retrofit.create(UserService.class); - //Using GitHubServiceGenerator + // Using GitHubServiceGenerator service = GitHubServiceGenerator.createService(UserService.class); Call callSync = service.getUser("eugenp"); Call callAsync = service.getUser("eugenp"); diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java index 208b73d4af..c889871b3d 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java @@ -9,7 +9,7 @@ public enum Commodity { public final int price; - Commodity(int price){ + Commodity(int price) { this.price = price; } diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java index 6e7c4db08e..f2f443020d 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java @@ -12,7 +12,8 @@ public class Member { private int points; private Member(int points) { - if (points < 0) throw new IllegalArgumentException("points must not be negative!"); + if (points < 0) + throw new IllegalArgumentException("points must not be negative!"); this.points = points; } @@ -22,9 +23,12 @@ public class Member { } public MemberGrade getGrade() { - if (points < 1000) return Bronze; - else if (points >= 1000 && points < 5000) return Silver; - else return Gold; + if (points < 1000) + return Bronze; + else if (points >= 1000 && points < 5000) + return Silver; + else + return Gold; } public void spend(int moneySpent) { diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java index 7bb6f76495..389749c2ca 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java @@ -3,7 +3,7 @@ package com.baeldung.serenity.membership; /** * @author aiet */ -public enum MemberGrade { +public enum MemberGrade { Bronze, Silver, Gold; diff --git a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java index d11f5a29b2..fa317f93b7 100644 --- a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java +++ b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java @@ -21,7 +21,6 @@ public class OrderConverter { smooks.close(); } } - public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException { return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml"); diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Item.java b/libraries/src/main/java/com/baeldung/smooks/model/Item.java index a7f7783b3f..3e1f4a7ef4 100644 --- a/libraries/src/main/java/com/baeldung/smooks/model/Item.java +++ b/libraries/src/main/java/com/baeldung/smooks/model/Item.java @@ -15,7 +15,6 @@ public class Item { private Double price; private Integer quantity; - public String getCode() { return code; } @@ -42,13 +41,17 @@ public class Item { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Item item = (Item) o; - if (code != null ? !code.equals(item.code) : item.code != null) return false; - if (price != null ? !price.equals(item.price) : item.price != null) return false; + if (code != null ? !code.equals(item.code) : item.code != null) + return false; + if (price != null ? !price.equals(item.price) : item.price != null) + return false; return quantity != null ? quantity.equals(item.quantity) : item.quantity == null; } @@ -62,10 +65,6 @@ public class Item { @Override public String toString() { - return "Item{" + - "code='" + code + '\'' + - ", price=" + price + - ", quantity=" + quantity + - '}'; + return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java index 31a9e1f43f..827a0fc907 100644 --- a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java +++ b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java @@ -31,12 +31,15 @@ public class Supplier { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Supplier supplier = (Supplier) o; - if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false; + if (name != null ? !name.equals(supplier.name) : supplier.name != null) + return false; return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null; } diff --git a/libraries/src/main/java/com/baeldung/stm/Account.java b/libraries/src/main/java/com/baeldung/stm/Account.java index 8b17f87120..4dc2c492df 100644 --- a/libraries/src/main/java/com/baeldung/stm/Account.java +++ b/libraries/src/main/java/com/baeldung/stm/Account.java @@ -44,7 +44,6 @@ public class Account { @Override public String toString() { - return StmUtils.atomic((TxnCallable) - txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); + return StmUtils.atomic((TxnCallable) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java index 7cbfec4421..56a3860f05 100644 --- a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java +++ b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java @@ -15,69 +15,43 @@ import one.util.streamex.StreamEx; public class StreamEX { public static void main(String[] args) { - //Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) - List users = Arrays.asList( - new User("name"), new User(), new User()); - users.stream() - .map(User::getName) - .collect(Collectors.toList()); - List userNames = StreamEx.of(users) - .map(User::getName) - .toList(); - Map> role2users = StreamEx.of(users) - .groupingBy(User::getRole); - StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3" - //Selecting stream elements of specific type + // Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) + List users = Arrays.asList(new User("name"), new User(), new User()); + users.stream().map(User::getName).collect(Collectors.toList()); + List userNames = StreamEx.of(users).map(User::getName).toList(); + Map> role2users = StreamEx.of(users).groupingBy(User::getRole); + StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3" + // Selecting stream elements of specific type List usersAndRoles = Arrays.asList(new User(), new Role()); - List roles = IntStreamEx.range(usersAndRoles.size()) - .mapToObj(usersAndRoles::get) - .select(Role.class) - .toList(); + List roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList(); System.out.println(roles); - //adding elements to Stream - List appendedUsers = StreamEx.of(users) - .map(User::getName) - .prepend("(none)") - .append("LAST") - .toList(); + // adding elements to Stream + List appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList(); System.out.println(appendedUsers); - //Removing unwanted elements and using the stream as Iterable: - for (String line : StreamEx.of(users).map(User::getName) - .nonNull()) { + // Removing unwanted elements and using the stream as Iterable: + for (String line : StreamEx.of(users).map(User::getName).nonNull()) { System.out.println(line); } - //Selecting map keys by value predicate: + // Selecting map keys by value predicate: Map nameToRole = new HashMap<>(); nameToRole.put("first", new Role()); nameToRole.put("second", null); - Set nonNullRoles = StreamEx. - ofKeys(nameToRole, Objects::nonNull) - .toSet(); + Set nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet(); System.out.println(nonNullRoles); - //Operating on key-value pairs: + // Operating on key-value pairs: Map> users2roles = transformMap(role2users); - Map mapToString = EntryStream.of(users2roles) - .mapKeys(String::valueOf) - .mapValues(String::valueOf) - .toMap(); - //Support of byte/char/short/float types: - short[] src = {1, 2, 3}; - char[] output = IntStreamEx.of(src) - .map(x -> x * 5) - .toCharArray(); + Map mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap(); + // Support of byte/char/short/float types: + short[] src = { 1, 2, 3 }; + char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray(); } public double[] getDiffBetweenPairs(double... numbers) { - return DoubleStreamEx.of(numbers) - .pairMap((a, b) -> b - a).toArray(); + return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray(); } - public static Map> transformMap( - Map> role2users) { - Map> users2roles = EntryStream.of(role2users) - .flatMapValues(List::stream) - .invert() - .grouping(); + public static Map> transformMap(Map> role2users) { + Map> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping(); return users2roles; } diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java index 430759f3a0..d9097188b3 100644 --- a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -9,14 +9,14 @@ import org.apache.commons.io.IOUtils; import org.springframework.util.StreamUtils; public class CopyStream { - public static String getStringFromInputStream(InputStream input) throws IOException { - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer, "UTF-8"); - return writer.toString(); - } + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } - public InputStream getNonClosingInputStream() throws IOException { - InputStream in = new FileInputStream("src/test/resources/input.txt"); - return StreamUtils.nonClosing(in); - } + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } } diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java index 6ee4a1ef3a..1ce67a075a 100644 --- a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -5,7 +5,7 @@ import java.io.InputStream; import org.springframework.util.StreamUtils; public class DrainStream { - public InputStream getInputStream() { - return StreamUtils.emptyInput(); - } + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } } diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java index 4bbf3c03a7..1b48e2d90b 100644 --- a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java +++ b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java @@ -9,10 +9,7 @@ import java.io.IOException; /** * Created by adi on 1/10/18. */ -@WebServlet( - name = "com.baeldung.tomcat.programmatic.MyServlet", - urlPatterns = {"/my-servlet"} -) +@WebServlet(name = "com.baeldung.tomcat.programmatic.MyServlet", urlPatterns = { "/my-servlet" }) public class MyServlet extends HttpServlet { @Override diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java index b84b6b5c6d..6c4fed6d07 100644 --- a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java +++ b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java @@ -15,29 +15,27 @@ public class ProgrammaticTomcat { private Tomcat tomcat = null; - //uncomment for live test - // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { - // startTomcat(); - // } + // uncomment for live test + // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { + // startTomcat(); + // } public void startTomcat() throws LifecycleException { tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.setHostname("localhost"); String appBase = "."; - tomcat - .getHost() - .setAppBase(appBase); + tomcat.getHost().setAppBase(appBase); File docBase = new File(System.getProperty("java.io.tmpdir")); Context context = tomcat.addContext("", docBase.getAbsolutePath()); - //add a servlet + // add a servlet Class servletClass = MyServlet.class; Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName()); context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName()); - //add a filter and filterMapping + // add a filter and filterMapping Class filterClass = MyFilter.class; FilterDef myFilterDef = new FilterDef(); myFilterDef.setFilterClass(filterClass.getName()); @@ -50,10 +48,10 @@ public class ProgrammaticTomcat { context.addFilterMap(myFilterMap); tomcat.start(); - //uncomment for live test - // tomcat - // .getServer() - // .await(); + // uncomment for live test + // tomcat + // .getServer() + // .await(); } public void stopTomcat() throws LifecycleException { diff --git a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java index 0e1bbca561..ff0d452108 100644 --- a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java +++ b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java @@ -30,25 +30,17 @@ public class DocumentController { @RequestMapping(path = "/generate/doc", method = RequestMethod.GET) public void generateDocument(HttpServletResponse response) throws IOException { ReportBuilder reportBuilder = new ReportBuilder(); - ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder() - .documentPath("./src/main/resources/Letter.docx") - .documentName("Letter.docx") - .outputType(ReportOutputType.docx) - .readFileFromPath(); + ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder().documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx").outputType(ReportOutputType.docx).readFileFromPath(); reportBuilder.template(reportTemplateBuilder.build()); BandBuilder bandBuilder = new BandBuilder(); String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json")); - ReportBand main = bandBuilder.name("Main") - .query("Main", "parameter=param1 $.main", "json") - .build(); + ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build(); reportBuilder.band(main); Report report = reportBuilder.build(); Reporting reporting = new Reporting(); reporting.setFormatterFactory(new DefaultFormatterFactory()); - reporting.setLoaderFactory( - new DefaultLoaderFactory() - .setJsonDataLoader(new JsonDataLoader())); + reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader())); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream()); } diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java index 1398c2ba41..7ff81c20c3 100644 --- a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java +++ b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java @@ -186,17 +186,12 @@ public class AsyncHttpClientTestCase { WebSocket WEBSOCKET_CLIENT = null; try { - WEBSOCKET_CLIENT = Dsl.asyncHttpClient() - .prepareGet("ws://localhost:5590/websocket") - .addHeader("header_name", "header_value") - .addQueryParam("key", "value") - .setRequestTimeout(5000) - .execute(wsHandler).get(); + WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get(); if (WEBSOCKET_CLIENT.isOpen()) { WEBSOCKET_CLIENT.sendPingFrame(); WEBSOCKET_CLIENT.sendTextFrame("test message"); - WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'}); + WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' }); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index 7ca656efbf..87c0b13bcc 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest { public void givenAsyncService_whenInitialize_thenInitOccurs2() { asyncService.initialize(); Callable isInitialized = asyncService::isInitialized; - await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) - .atMost(Duration.FIVE_SECONDS) - .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) - .until(isInitialized); + await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized); } @Test @@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest { @Test public void givenAsyncService_whenInitialize_thenInitOccurs3() { asyncService.initialize(); - await().until(fieldIn(asyncService) - .ofType(boolean.class) - .andWithName("initialized"), equalTo(true)); + await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true)); } @Test @@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest { @Test public void givenAsyncService_whenGetValue_thenExceptionIgnored() { asyncService.initialize(); - given().ignoreException(IllegalStateException.class) - .await() - .atMost(Duration.FIVE_SECONDS) - .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) - .until(asyncService::getValue, equalTo(0L)); + given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L)); } } diff --git a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java index 3965eeecd4..009119d97a 100644 --- a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java +++ b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java @@ -28,14 +28,11 @@ public class BouncyCastleLiveTest { char[] keyPassword = "password".toCharArray(); @Test - public void givenCryptographicResource_whenOperationSuccess_returnTrue() - throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, - KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { + public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { Security.addProvider(new BouncyCastleProvider()); CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC"); - X509Certificate certificate = (X509Certificate) certFactory - .generateCertificate(new FileInputStream(certificatePath)); + X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath)); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(privateKeyPath), p12Password); PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword); diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java index 6b7364a0a5..5f721025c3 100644 --- a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java +++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -21,14 +21,9 @@ public class ByteBuddyUnitTest { @Test public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { - DynamicType.Unloaded unloadedType = new ByteBuddy() - .subclass(Object.class) - .method(ElementMatchers.isToString()) - .intercept(FixedValue.value("Hello World ByteBuddy!")) - .make(); + DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make(); - Class dynamicType = unloadedType.load(getClass().getClassLoader()) - .getLoaded(); + Class dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded(); assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); } @@ -36,12 +31,7 @@ public class ByteBuddyUnitTest { @Test public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { ByteBuddyAgent.install(); - new ByteBuddy() - .redefine(Foo.class) - .method(named("sayHelloFoo")) - .intercept(FixedValue.value("Hello Foo Redefined")) - .make() - .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); + new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); Foo f = new Foo(); assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); } @@ -49,34 +39,16 @@ public class ByteBuddyUnitTest { @Test public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { - String r = new ByteBuddy() - .subclass(Foo.class) - .method( - named("sayHelloFoo") - .and(isDeclaredBy(Foo.class) - .and(returns(String.class))) - ) - .intercept(MethodDelegation.to(Bar.class)) - .make() - .load(getClass().getClassLoader()) - .getLoaded() - .newInstance() - .sayHelloFoo(); + String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance() + .sayHelloFoo(); assertEquals(r, Bar.sayHelloBar()); } @Test public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { - Class type = new ByteBuddy() - .subclass(Object.class) - .name("MyClassName") - .defineMethod("custom", String.class, Modifier.PUBLIC) - .intercept(MethodDelegation.to(Bar.class)) - .defineField("x", String.class, Modifier.PUBLIC) - .make() - .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); + Class type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded(); Method m = type.getDeclaredMethod("custom", null); @@ -85,5 +57,4 @@ public class ByteBuddyUnitTest { } - } diff --git a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java index 56dbda5974..d523d0ff8b 100644 --- a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java +++ b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java @@ -16,10 +16,7 @@ public class CaffeineUnitTest { @Test public void givenCache_whenPopulate_thenValueStored() { - Cache cache = Caffeine.newBuilder() - .expireAfterWrite(1, TimeUnit.MINUTES) - .maximumSize(100) - .build(); + Cache cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build(); String key = "A"; DataObject dataObject = cache.getIfPresent(key); @@ -44,10 +41,7 @@ public class CaffeineUnitTest { @Test public void givenLoadingCache_whenGet_thenValuePopulated() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .expireAfterWrite(1, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); String key = "A"; DataObject dataObject = cache.get(key); @@ -63,10 +57,7 @@ public class CaffeineUnitTest { @Test public void givenAsyncLoadingCache_whenGet_thenValuePopulated() { - AsyncLoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .expireAfterWrite(1, TimeUnit.MINUTES) - .buildAsync(k -> DataObject.get("Data for " + k)); + AsyncLoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k)); String key = "A"; cache.get(key).thenAccept(dataObject -> { @@ -74,16 +65,12 @@ public class CaffeineUnitTest { assertEquals("Data for " + key, dataObject.getData()); }); - cache.getAll(Arrays.asList("A", "B", "C")) - .thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size())); + cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size())); } @Test public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(1) - .refreshAfterWrite(10, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); assertEquals(0, cache.estimatedSize()); @@ -99,10 +86,7 @@ public class CaffeineUnitTest { @Test public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() { - LoadingCache cache = Caffeine.newBuilder() - .maximumWeight(10) - .weigher((k,v) -> 5) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k)); assertEquals(0, cache.estimatedSize()); @@ -122,20 +106,11 @@ public class CaffeineUnitTest { @Test public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() { - LoadingCache cache = Caffeine.newBuilder() - .expireAfterAccess(5, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.SECONDS) - .weakKeys() - .weakValues() - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.SECONDS) - .softValues() - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k)); cache = Caffeine.newBuilder().expireAfter(new Expiry() { @Override @@ -154,17 +129,12 @@ public class CaffeineUnitTest { } }).build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .refreshAfterWrite(1, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); } @Test public void givenCache_whenStatsEnabled_thenStatsRecorded() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .recordStats() - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k)); cache.get("A"); cache.get("A"); diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java index 1224d73724..080444d7b1 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.cglib.proxy; - import net.sf.cglib.beans.BeanGenerator; import org.junit.Test; @@ -12,21 +11,17 @@ public class BeanGeneratorIntegrationTest { @Test public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception { - //given + // given BeanGenerator beanGenerator = new BeanGenerator(); - //when + // when beanGenerator.addProperty("name", String.class); Object myBean = beanGenerator.create(); - Method setter = myBean - .getClass() - .getMethod("setName", String.class); + Method setter = myBean.getClass().getMethod("setName", String.class); setter.invoke(myBean, "some string value set by a cglib"); - //then - Method getter = myBean - .getClass() - .getMethod("getName"); + // then + Method getter = myBean.getClass().getMethod("getName"); assertEquals("some string value set by a cglib", getter.invoke(myBean)); } } diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java index 93b34bf92b..fc2f6cc1e1 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java @@ -14,14 +14,11 @@ public class MixinUnitTest { @Test public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception { - //when - Mixin mixin = Mixin.create( - new Class[]{Interface1.class, Interface2.class, MixinInterface.class}, - new Object[]{new Class1(), new Class2()} - ); + // when + Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() }); MixinInterface mixinDelegate = (MixinInterface) mixin; - //then + // then assertEquals("first behaviour", mixinDelegate.first()); assertEquals("second behaviour", mixinDelegate.second()); } diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java index c22a148d4f..d5c8a1b589 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java @@ -10,34 +10,34 @@ import static org.junit.Assert.assertEquals; public class ProxyIntegrationTest { @Test public void givenPersonService_whenSayHello_thenReturnResult() { - //given + // given PersonService personService = new PersonService(); - //when + // when String res = personService.sayHello("Tom"); - //then + // then assertEquals(res, "Hello Tom"); } @Test public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception { - //given + // given Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PersonService.class); enhancer.setCallback((FixedValue) () -> "Hello Tom!"); PersonService proxy = (PersonService) enhancer.create(); - //when + // when String res = proxy.sayHello(null); - //then + // then assertEquals("Hello Tom!", res); } @Test public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception { - //given + // given Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PersonService.class); enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { @@ -48,10 +48,10 @@ public class ProxyIntegrationTest { } }); - //when + // when PersonService proxy = (PersonService) enhancer.create(); - //then + // then assertEquals("Hello Tom!", proxy.sayHello(null)); int lengthOfName = proxy.lengthOfName("Mary"); assertEquals(4, lengthOfName); diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java index 9c0a0ac910..00e9500318 100644 --- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -14,12 +14,12 @@ import net.openhft.chronicle.ExcerptTailer; import net.openhft.chronicle.tools.ChronicleTools; public class ChronicleQueueIntegrationTest { - + @Test public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { File queueDir = Files.createTempDirectory("chronicle-queue").toFile(); ChronicleTools.deleteOnExit(queueDir.getPath()); - + Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build(); String stringVal = "Hello World"; int intVal = 101; @@ -37,7 +37,7 @@ public class ChronicleQueueIntegrationTest { } tailer.finish(); tailer.close(); - chronicle.close(); + chronicle.close(); } } diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java index 5407477a00..fd09f4d9f6 100644 --- a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java +++ b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java @@ -10,8 +10,7 @@ import org.junit.Test; public class CourseServiceTest { @Test - public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Course course = new Course(); String name = "Computer Science"; List codes = Arrays.asList("CS", "CS01"); @@ -36,8 +35,7 @@ public class CourseServiceTest { } @Test - public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Course course = new Course(); course.setName("Computer Science"); course.setCodes(Arrays.asList("CS")); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java index aa8b799c9d..f34f431d8e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java @@ -1,6 +1,5 @@ package com.baeldung.commons.collections; - import com.baeldung.commons.collectionutil.Address; import com.baeldung.commons.collectionutil.Customer; import org.apache.commons.collections4.CollectionUtils; @@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue; public class CollectionUtilsGuideTest { - Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); List list1, list2, list3, linkedList1; @@ -77,8 +75,8 @@ public class CollectionUtilsGuideTest { } }); - //filterInverse does the opposite. It removes the element from the list if the Predicate returns true - //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection + // filterInverse does the opposite. It removes the element from the list if the Predicate returns true + // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection assertTrue(isModified && linkedList1.size() == 2); } @@ -88,8 +86,8 @@ public class CollectionUtilsGuideTest { List emptyList = new ArrayList<>(); List nullList = null; - //Very handy at times where we want to check if a collection is not null and not empty too. - //isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading + // Very handy at times where we want to check if a collection is not null and not empty too. + // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading assertTrue(CollectionUtils.isNotEmpty(list1)); assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(emptyList)); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 4685d84781..0033d0786e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -27,16 +27,8 @@ import static org.junit.Assert.assertTrue; public class MapUtilsTest { - private String[][] color2DArray = new String[][]{ - {"RED", "#FF0000"}, - {"GREEN", "#00FF00"}, - {"BLUE", "#0000FF"} - }; - private String[] color1DArray = new String[]{ - "RED", "#FF0000", - "GREEN", "#00FF00", - "BLUE", "#0000FF" - }; + private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }; + private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }; private Map colorMap; @Before @@ -92,34 +84,26 @@ public class MapUtilsTest { Map invColorMap = MapUtils.invertMap(this.colorMap); int size = invColorMap.size(); - Assertions.assertThat(invColorMap) - .hasSameSizeAs(colorMap) - .containsKeys(this.colorMap.values().toArray(new String[size])) - .containsValues(this.colorMap.keySet().toArray(new String[size])); + Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size])); } @Test(expected = IllegalArgumentException.class) public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { - Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll( - new HashMap(), - this.color1DArray)); + Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap(), this.color1DArray)); rgbMap.put("ORANGE", "#FFA500"); } @Test(expected = IllegalArgumentException.class) public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { - Map uniqValuesMap - = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); + Map uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); uniqValuesMap.put("NEW_RED", "#FF0000"); } @Test public void whenCreateLazyMap_theMapIsCreated() { - Map intStrMap = MapUtils.lazyMap( - new HashMap(), - TransformerUtils.stringValueTransformer()); + Map intStrMap = MapUtils.lazyMap(new HashMap(), TransformerUtils.stringValueTransformer()); assertThat(intStrMap, is(anEmptyMap())); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java index 7d214bc5c5..aa73ed6109 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java @@ -17,8 +17,7 @@ public class SetUtilsUnitTest { public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { Set sourceSet = new HashSet<>(); sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1")); - Set validatingSet - = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); + Set validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); validatingSet.add("Err Source2"); } diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java index 7a05228e51..c64143cba7 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java @@ -14,8 +14,8 @@ import static org.junit.Assert.assertEquals; public class OrderedMapUnitTest { - private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"}; - private Integer[] ages = {37, 28, 40, 36, 21}; + private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" }; + private Integer[] ages = { 37, 28, 40, 36, 21 }; private int RUNNERS_COUNT = names.length; diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java index 55fadcbf85..4408dcc195 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -15,94 +15,88 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; public class BagTests { - + @Test public void givenMultipleCopies_whenAdded_theCountIsKept() { - Bag bag = new HashBag<>( - Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + assertThat(bag.getCount(1), equalTo(2)); } - + @Test public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { Collection collection = new ArrayList<>(); - + // Collection contract defines that add() should return true assertThat(collection.add(9), is(true)); - + // Even when element is already in the collection collection.add(1); assertThat(collection.add(1), is(true)); - + Bag bag = new HashBag<>(); - + // Bag returns true on adding a new element assertThat(bag.add(9), is(true)); - + bag.add(1); // But breaks the contract with false when it has to increment the count assertThat(bag.add(1), is(not(true))); } - + @Test public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { Bag bag = CollectionBag.collectionBag(new HashBag<>()); - + bag.add(1); // This time the behavior is compliant to the Java Collection assertThat(bag.add(1), is((true))); } - + @Test public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { Bag bag = new HashBag<>(); - + // Adding 1 for 5 times bag.add(1, 5); assertThat(bag.getCount(1), equalTo(5)); } - + @Test public void givenMultipleCopies_whenRemove_allAreRemoved() { - Bag bag = new HashBag<>( - Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + // From 3 we delete 1, 2 remain bag.remove(3, 1); assertThat(bag.getCount(3), equalTo(2)); - + // From 2 we delete all bag.remove(1); assertThat(bag.getCount(1), equalTo(0)); } - + @Test public void givenTree_whenDuplicateElementsAdded_thenSort() { - TreeBag bag = new TreeBag<>( - Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); - + TreeBag bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); + assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); assertThat(bag.getCount(bag.last()), equalTo(3)); } - + @Test public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { - SortedBag bag = CollectionSortedBag - .collectionSortedBag(new TreeBag<>()); - + SortedBag bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>()); + bag.add(1); assertThat(bag.add(1), is((true))); } - + @Test public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { - SynchronizedSortedBag bag = SynchronizedSortedBag - .synchronizedSortedBag(new TreeBag<>( - Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); - + SynchronizedSortedBag bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); + assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java index 6f47b89396..6210bb51a9 100644 --- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -29,10 +29,7 @@ public class CSVReaderWriterTest { @Test public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { Reader in = new FileReader("src/test/resources/book.csv"); - Iterable records = CSVFormat.DEFAULT - .withHeader(HEADERS) - .withFirstRecordAsHeader() - .parse(in); + Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); for (CSVRecord record : records) { String author = record.get("author"); String title = record.get("title"); @@ -52,9 +49,7 @@ public class CSVReaderWriterTest { } }); } - assertEquals(EXPECTED_FILESTREAM, sw - .toString() - .trim()); + assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); } } diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java index bc7623589c..02cec7d53a 100644 --- a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java @@ -47,10 +47,8 @@ public class DbUtilsUnitTest { List> list = runner.query(connection, "SELECT * FROM employee", beanListHandler); assertEquals(list.size(), 5); - assertEquals(list.get(0) - .get("firstname"), "John"); - assertEquals(list.get(4) - .get("firstname"), "Christian"); + assertEquals(list.get(0).get("firstname"), "John"); + assertEquals(list.get(4).get("firstname"), "Christian"); } @Test @@ -61,10 +59,8 @@ public class DbUtilsUnitTest { List employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler); assertEquals(employeeList.size(), 5); - assertEquals(employeeList.get(0) - .getFirstName(), "John"); - assertEquals(employeeList.get(4) - .getFirstName(), "Christian"); + assertEquals(employeeList.get(0).getFirstName(), "John"); + assertEquals(employeeList.get(4).getFirstName(), "Christian"); } @Test @@ -85,12 +81,8 @@ public class DbUtilsUnitTest { QueryRunner runner = new QueryRunner(); List employees = runner.query(connection, "SELECT * FROM employee", employeeHandler); - assertEquals(employees.get(0) - .getEmails() - .size(), 2); - assertEquals(employees.get(2) - .getEmails() - .size(), 3); + assertEquals(employees.get(0).getEmails().size(), 2); + assertEquals(employees.get(2).getEmails().size(), 3); assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId()); } diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java index 3c82c30d9b..7481e5a1a3 100644 --- a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java @@ -25,30 +25,23 @@ import java.nio.charset.Charset; public class CommonsIOUnitTest { @Test - public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() - throws IOException { + public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - File file = FileUtils.getFile(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); + File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath()); File tempDir = FileUtils.getTempDirectory(); FileUtils.copyFileToDirectory(file, tempDir); File newTempFile = FileUtils.getFile(tempDir, file.getName()); - String data = FileUtils.readFileToString(newTempFile, - Charset.defaultCharset()); + String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset()); Assert.assertEquals(expectedData, data.trim()); } @Test - public void whenUsingFileNameUtils_thenshowdifferentFileOperations() - throws IOException { + public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException { - String path = getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath(); + String path = getClass().getClassLoader().getResource("fileTest.txt").getPath(); String fullPath = FilenameUtils.getFullPath(path); String extension = FilenameUtils.getExtension(path); @@ -60,70 +53,54 @@ public class CommonsIOUnitTest { } @Test - public void whenUsingFileSystemUtils_thenDriveFreeSpace() - throws IOException { + public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException { long freeSpace = FileSystemUtils.freeSpaceKb("/"); } @SuppressWarnings("resource") @Test - public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() - throws IOException { + public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException { final String str = "Hello World."; ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes()); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); - - FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2); + + FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2); new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]); - + Assert.assertEquals(str, String.valueOf(outputStream1)); Assert.assertEquals(str, String.valueOf(outputStream2)); - } + } @Test - public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() - throws IOException { + public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException { final String testFile = "fileTest.txt"; - String path = getClass().getClassLoader() - .getResource(testFile) - .getPath(); + String path = getClass().getClassLoader().getResource(testFile).getPath(); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); String[] possibleNames = { "NotThisOne", testFile }; - Assert.assertEquals(testFile, - dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]); + Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]); } @Test - public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() - throws IOException { + public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException { - String path = getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath(); + String path = getClass().getClassLoader().getResource("fileTest.txt").getPath(); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); - Assert.assertEquals("sample.txt", - dir.list(new AndFileFilter( - new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), - new SuffixFileFilter("txt")))[0]); + Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]); } @Test - public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() - throws IOException { + public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException { - PathFileComparator pathFileComparator = new PathFileComparator( - IOCase.INSENSITIVE); - String path = FilenameUtils.getFullPath(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); + PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE); + String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath()); File dir = new File(path); File[] files = dir.listFiles(); @@ -133,16 +110,11 @@ public class CommonsIOUnitTest { } @Test - public void whenSizeFileComparator_thenLargerFile() - throws IOException { + public void whenSizeFileComparator_thenLargerFile() throws IOException { SizeFileComparator sizeFileComparator = new SizeFileComparator(); - File largerFile = FileUtils.getFile(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); - File smallerFile = FileUtils.getFile(getClass().getClassLoader() - .getResource("sample.txt") - .getPath()); + File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath()); + File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath()); int i = sizeFileComparator.compare(largerFile, smallerFile); diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java index 97db4ddbe4..f34008fb1f 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java @@ -9,71 +9,71 @@ import static org.junit.Assert.assertEquals; public class ArrayUtilsUnitTest { @Test public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = {2, 3, 4, 5}; + int[] oldArray = { 2, 3, 4, 5 }; int[] newArray = ArrayUtils.add(oldArray, 0, 1); - int[] expectedArray = {1, 2, 3, 4, 5}; + int[] expectedArray = { 1, 2, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingElementAtTheEnd_thenCorrect() { - int[] oldArray = {2, 3, 4, 5}; + int[] oldArray = { 2, 3, 4, 5 }; int[] newArray = ArrayUtils.add(oldArray, 1); - int[] expectedArray = {2, 3, 4, 5, 1}; + int[] expectedArray = { 2, 3, 4, 5, 1 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() { - int[] oldArray = {0, 1, 2}; + int[] oldArray = { 0, 1, 2 }; int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5); - int[] expectedArray = {0, 1, 2, 3, 4, 5}; + int[] expectedArray = { 0, 1, 2, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.remove(oldArray, 1); - int[] expectedArray = {1, 3, 4, 5}; + int[] expectedArray = { 1, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3); - int[] expectedArray = {1, 3, 5}; + int[] expectedArray = { 1, 3, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAnElement_thenCorrect() { - int[] oldArray = {1, 2, 3, 3, 4}; + int[] oldArray = { 1, 2, 3, 3, 4 }; int[] newArray = ArrayUtils.removeElement(oldArray, 3); - int[] expectedArray = {1, 2, 3, 4}; + int[] expectedArray = { 1, 2, 3, 4 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElements_thenCorrect() { - int[] oldArray = {1, 2, 3, 3, 4}; + int[] oldArray = { 1, 2, 3, 3, 4 }; int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5); - int[] expectedArray = {1, 3, 4}; + int[] expectedArray = { 1, 3, 4 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementOccurences_thenCorrect() { - int[] oldArray = {1, 2, 2, 2, 3}; + int[] oldArray = { 1, 2, 2, 2, 3 }; int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2); - int[] expectedArray = {1, 3}; + int[] expectedArray = { 1, 3 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenCheckingExistingElement_thenCorrect() { - int[] array = {1, 3, 5, 7, 9}; + int[] array = { 1, 3, 5, 7, 9 }; boolean evenContained = ArrayUtils.contains(array, 2); boolean oddContained = ArrayUtils.contains(array, 7); assertEquals(false, evenContained); @@ -82,57 +82,57 @@ public class ArrayUtilsUnitTest { @Test public void givenArray_whenReversingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(originalArray, 1, 4); - int[] expectedArray = {1, 4, 3, 2, 5}; + int[] expectedArray = { 1, 4, 3, 2, 5 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenReversingAllElements_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(originalArray); - int[] expectedArray = {5, 4, 3, 2, 1}; + int[] expectedArray = { 5, 4, 3, 2, 1 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.shift(originalArray, 1, 4, 1); - int[] expectedArray = {1, 4, 2, 3, 5}; + int[] expectedArray = { 1, 4, 2, 3, 5 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingAllElements_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.shift(originalArray, 1); - int[] expectedArray = {5, 1, 2, 3, 4}; + int[] expectedArray = { 5, 1, 2, 3, 4 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenExtractingElements_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.subarray(oldArray, 2, 7); - int[] expectedArray = {3, 4, 5}; + int[] expectedArray = { 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenSwapingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.swap(originalArray, 0, 3, 2); - int[] expectedArray = {4, 5, 3, 1, 2}; + int[] expectedArray = { 4, 5, 3, 1, 2 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.swap(originalArray, 0, 3); - int[] expectedArray = {4, 2, 3, 1, 5}; + int[] expectedArray = { 4, 2, 3, 1, 5 }; assertArrayEquals(expectedArray, originalArray); } } diff --git a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java b/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java index 65c1a0db8e..7e047577e5 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java @@ -15,7 +15,7 @@ public class IntegrationTest { final double i = integrator.integrate(100, function, 0, 10); - Assert.assertEquals(16 + 2d/3d, i, 1e-7); + Assert.assertEquals(16 + 2d / 3d, i, 1e-7); } } diff --git a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java index 278f54a67f..49bf33baa5 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java @@ -8,9 +8,7 @@ public class LinearAlgebraUnitTest { @Test public void whenDecompositionSolverSolve_thenCorrect() { - RealMatrix a = - new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, - false); + RealMatrix a = new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, false); RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false); DecompositionSolver solver = new LUDecomposition(a).getSolver(); diff --git a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java index 025880fc12..3069446c3c 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java @@ -12,10 +12,10 @@ public class StatisticsUnitTest { @Before public void setUp() { - values = new double[] {65, 51 , 16, 11 , 6519, 191 ,0 , 98, 19854, 1, 32}; + values = new double[] { 65, 51, 16, 11, 6519, 191, 0, 98, 19854, 1, 32 }; descriptiveStatistics = new DescriptiveStatistics(); - for(double v : values) { + for (double v : values) { descriptiveStatistics.addValue(v); } } diff --git a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java index 8309e755ce..3d3c952863 100644 --- a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java +++ b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java @@ -13,42 +13,41 @@ public class CRDTTest { @Test public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); crdtStore1.connect(crdtStore2); final GSet replica1 = crdtStore1.createGSet("ID_1"); - final GSet replica2 = crdtStore2.findGSet("ID_1").get(); + final GSet replica2 = crdtStore2. findGSet("ID_1").get(); - //when + // when replica1.add("apple"); replica2.add("banana"); - //then + // then assertThat(replica1).contains("apple", "banana"); assertThat(replica2).contains("apple", "banana"); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.add("strawberry"); replica2.add("pear"); - assertThat(replica1).contains("apple", "banana", "strawberry"); assertThat(replica2).contains("apple", "banana", "pear"); crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1).contains("apple", "banana", "strawberry", "pear"); assertThat(replica2).contains("apple", "banana", "strawberry", "pear"); } @Test public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); crdtStore1.connect(crdtStore2); @@ -56,21 +55,20 @@ public class CRDTTest { final GCounter replica1 = crdtStore1.createGCounter("ID_1"); final GCounter replica2 = crdtStore2.findGCounter("ID_1").get(); - //when + // when replica1.increment(); replica2.increment(2L); - //then + // then assertThat(replica1.get()).isEqualTo(3L); assertThat(replica2.get()).isEqualTo(3L); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.increment(3L); replica2.increment(5L); - assertThat(replica1.get()).isEqualTo(6L); assertThat(replica2.get()).isEqualTo(8L); @@ -91,15 +89,15 @@ public class CRDTTest { final PNCounter replica1 = crdtStore1.createPNCounter("ID_1"); final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get(); - //when + // when replica1.increment(); replica2.decrement(2L); - //then + // then assertThat(replica1.get()).isEqualTo(-1L); assertThat(replica2.get()).isEqualTo(-1L); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.decrement(3L); @@ -110,22 +108,22 @@ public class CRDTTest { crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1.get()).isEqualTo(1L); assertThat(replica2.get()).isEqualTo(1L); } @Test public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1"); final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2"); crdtStore1.connect(crdtStore2); final LWWRegister replica1 = crdtStore1.createLWWRegister("ID_1"); - final LWWRegister replica2 = crdtStore2.findLWWRegister("ID_1").get(); + final LWWRegister replica2 = crdtStore2. findLWWRegister("ID_1").get(); - //when + // when replica1.set("apple"); replica2.set("banana"); @@ -133,20 +131,18 @@ public class CRDTTest { assertThat(replica1.get()).isEqualTo("banana"); assertThat(replica2.get()).isEqualTo("banana"); - // when crdtStore1.disconnect(crdtStore2); replica1.set("strawberry"); replica2.set("pear"); - assertThat(replica1.get()).isEqualTo("strawberry"); assertThat(replica2.get()).isEqualTo("pear"); crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1.get()).isEqualTo("pear"); assertThat(replica2.get()).isEqualTo("pear"); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java index 68775fac66..936fd3e839 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -19,25 +19,19 @@ public class DistinctWithJavaFunctionUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = personList.stream() - .filter(distinctByKey(p -> p.getName())) - .collect(Collectors.toList()); + List personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList()); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = personList.stream() - .filter(distinctByKey(p -> p.getAge())) - .collect(Collectors.toList()); + List personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList()); assertTrue(personListFiltered.size() == 2); } @Test public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { - List personListFiltered = personList.stream() - .distinct() - .collect(Collectors.toList()); + List personListFiltered = personList.stream().distinct().collect(Collectors.toList()); assertTrue(personListFiltered.size() == 5); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java index f50c76a486..c06a5d7e8b 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java @@ -19,17 +19,13 @@ public class DistinctWithStreamexUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = StreamEx.of(personList) - .distinct(Person::getName) - .toList(); + List personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList(); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = StreamEx.of(personList) - .distinct(Person::getAge) - .toList(); + List personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList(); assertTrue(personListFiltered.size() == 2); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java index b4025cd313..24593273a1 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java @@ -17,17 +17,13 @@ public class DistinctWithVavrUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = io.vavr.collection.List.ofAll(personList) - .distinctBy(Person::getName) - .toJavaList(); + List personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList(); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = io.vavr.collection.List.ofAll(personList) - .distinctBy(Person::getAge) - .toJavaList(); + List personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList(); assertTrue(personListFiltered.size() == 2); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java index 531e7e7c5b..e6f0fd1c31 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java @@ -27,138 +27,96 @@ public class ContainerLiveTest { @Test public void whenListingRunningContainers_thenReturnNonEmptyList() { - //when + // when List containers = dockerClient.listContainersCmd().exec(); - //then + // then assertThat(containers.size(), is(not(0))); } @Test public void whenListingExitedContainers_thenReturnNonEmptyList() { - //when - List containers = dockerClient.listContainersCmd() - .withShowSize(true) - .withShowAll(true) - .withStatusFilter("exited") - .exec(); + // when + List containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec(); - //then + // then assertThat(containers.size(), is(not(0))); } @Test public void whenCreatingContainer_thenMustReturnContainerId() { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("mongo:3.6") - .withCmd("--bind_ip_all") - .withName("mongo") - .withHostName("baeldung") - .withEnv("MONGO_LATEST_VERSION=3.6") - .withPortBindings(PortBinding.parse("9999:27017")) - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec(); - //then + // then assertThat(container.getId(), is(not(null))); } - @Test public void whenHavingContainer_thenRunContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); Thread.sleep(3000); - //then - dockerClient.startContainerCmd(container.getId()) - .exec(); + // then + dockerClient.startContainerCmd(container.getId()).exec(); - dockerClient.stopContainerCmd(container.getId()) - .exec(); + dockerClient.stopContainerCmd(container.getId()).exec(); } @Test public void whenRunningContainer_thenStopContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); Thread.sleep(3000); - dockerClient.startContainerCmd(container.getId()) - .exec(); + dockerClient.startContainerCmd(container.getId()).exec(); - //then - dockerClient.stopContainerCmd(container.getId()) - .exec(); + // then + dockerClient.stopContainerCmd(container.getId()).exec(); } @Test public void whenRunningContainer_thenKillContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - dockerClient.startContainerCmd(container.getId()) - .exec(); + dockerClient.startContainerCmd(container.getId()).exec(); Thread.sleep(3000); - dockerClient.stopContainerCmd(container.getId()) - .exec(); + dockerClient.stopContainerCmd(container.getId()).exec(); - //then - dockerClient.killContainerCmd(container.getId()) - .exec(); + // then + dockerClient.killContainerCmd(container.getId()).exec(); } @Test public void whenHavingContainer_thenInspectContainer() { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - //then - InspectContainerResponse containerResponse - = dockerClient.inspectContainerCmd(container.getId()) - .exec(); + // then + InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); assertThat(containerResponse.getId(), is(container.getId())); } - @Test public void givenContainer_whenCommittingContainer_thenMustReturnImageId() { - //given - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // given + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - //when - String imageId = dockerClient.commitCmd(container.getId()) - .withEnv("SNAPSHOT_YEAR=2018") - .withMessage("add git support") - .withCmd("sleep", "10000") - .withRepository("alpine") - .withTag("3.6.v2").exec(); + // when + String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec(); - //then + // then assertThat(imageId, is(not(null))); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java index 1023298e25..bedcc66c53 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java @@ -14,52 +14,40 @@ public class DockerClientLiveTest { @Test public void whenCreatingDockerClient_thenReturnDefaultInstance() { - //when - DefaultDockerClientConfig.Builder config - = DefaultDockerClientConfig.createDefaultConfigBuilder(); + // when + DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() { - //when - DockerClient dockerClient - = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375") - .build(); + // when + DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingAdvanceDockerClient_thenReturnInstance() { - //when - DefaultDockerClientConfig config - = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withRegistryEmail("info@bealdung.com") - .withRegistryUrl("register.bealdung.io/v2/") - .withRegistryPassword("strongpassword") - .withRegistryUsername("bealdung") - .withDockerCertPath("/home/bealdung/public/.docker/certs") - .withDockerConfig("/home/bealdung/public/.docker/") - .withDockerTlsVerify("1") - .withDockerHost("tcp://docker.beauldung.com:2376") - .build(); + // when + DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung") + .withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingDockerClientWithProperties_thenReturnInstance() { - //when + // when Properties properties = new Properties(); properties.setProperty("registry.email", "info@bealdung.com"); properties.setProperty("registry.url", "register.bealdung.io/v2/"); @@ -70,14 +58,11 @@ public class DockerClientLiveTest { properties.setProperty("DOCKER_TLS_VERIFY", "1"); properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376"); - DefaultDockerClientConfig config - = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withProperties(properties) - .build(); + DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java index ef894b2773..7e8cd6a354 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java @@ -33,99 +33,84 @@ public class ImageLiveTest { @Test public void whenListingImages_thenReturnNonEmptyList() { - //when + // when List images = dockerClient.listImagesCmd().exec(); - //then + // then assertThat(images.size(), is(not(0))); } @Test public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() { - //when - List images = dockerClient.listImagesCmd() - .withShowAll(true).exec(); + // when + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); - //then + // then assertThat(images.size(), is(not(0))); } @Test public void whenListingDanglingImages_thenReturnNonNullList() { - //when - List images = dockerClient.listImagesCmd() - .withDanglingFilter(true).exec(); + // when + List images = dockerClient.listImagesCmd().withDanglingFilter(true).exec(); - //then + // then assertThat(images, is(not(null))); } @Test public void whenBuildingImage_thenMustReturnImageId() { - //when - String imageId = dockerClient.buildImageCmd() - .withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")) - .withPull(true) - .withNoCache(true) - .withTag("alpine:git") - .exec(new BuildImageResultCallback()) - .awaitImageId(); + // when + String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId(); - //then + // then assertThat(imageId, is(not(null))); } @Test public void givenListOfImages_whenInspectImage_thenMustReturnObject() { - //given + // given List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); - //when - InspectImageResponse imageResponse - = dockerClient.inspectImageCmd(image.getId()).exec(); + // when + InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec(); - //then + // then assertThat(imageResponse.getId(), is(image.getId())); } @Test public void givenListOfImages_whenTagImage_thenListMustIncrement() { - //given + // given List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); - //when + // when dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec(); - //then + // then List imagesNow = dockerClient.listImagesCmd().exec(); assertThat(imagesNow.size(), is(greaterThan(images.size()))); } public void pushingAnImage() throws InterruptedException { - dockerClient.pushImageCmd("baeldung/alpine") - .withTag("3.6.v2") - .exec(new PushImageResultCallback()) - .awaitCompletion(90, TimeUnit.SECONDS); + dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS); } @Test public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException { - //when - dockerClient.pullImageCmd("alpine") - .withTag("latest") - .exec(new PullImageResultCallback()) - .awaitCompletion(30, TimeUnit.SECONDS); + // when + dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS); - //then + // then List images = dockerClient.listImagesCmd().exec(); assertThat(images.size(), is(not(0))); } @@ -133,12 +118,12 @@ public class ImageLiveTest { @Test public void whenRemovingImage_thenImageListDecrease() { - //when + // when List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); dockerClient.removeImageCmd(image.getId()).exec(); - //then + // then List imagesNow = dockerClient.listImagesCmd().exec(); assertThat(imagesNow.size(), is(lessThan(images.size()))); } @@ -146,10 +131,10 @@ public class ImageLiveTest { @Test public void whenSearchingImage_thenMustReturn25Items() { - //when + // when List items = dockerClient.searchImagesCmd("Java").exec(); - //then + // then assertThat(items.size(), is(25)); } } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java index 2031a3ebb4..1acbf00e3c 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java @@ -27,64 +27,51 @@ public class NetworkLiveTest { @Test public void whenListingNetworks_thenSizeMustBeGreaterThanZero() { - //when + // when List networks = dockerClient.listNetworksCmd().exec(); - //then + // then assertThat(networks.size(), is(greaterThan(0))); } @Test public void whenCreatingNetwork_thenRetrieveResponse() { - //when - CreateNetworkResponse networkResponse - = dockerClient.createNetworkCmd() - .withName("baeldungDefault") - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec(); - //then + // then assertThat(networkResponse, is(not(null))); } @Test public void whenCreatingAdvanceNetwork_thenRetrieveResponse() { - //when - CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd() - .withName("baeldungAdvanced") - .withIpam(new Ipam() - .withConfig(new Ipam.Config() - .withSubnet("172.36.0.0/16") - .withIpRange("172.36.5.0/24"))) - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec(); - //then + // then assertThat(networkResponse, is(not(null))); } @Test public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() { - //when + // when String networkName = "bridge"; - Network network - = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); + Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); - //then + // then assertThat(network.getName(), is(networkName)); } @Test public void whenCreatingNetwork_thenRemove() throws InterruptedException { - //when - CreateNetworkResponse networkResponse - = dockerClient.createNetworkCmd() - .withName("baeldungDefault") - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec(); - //then + // then Thread.sleep(4000); dockerClient.removeNetworkCmd(networkResponse.getId()).exec(); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java index 060af0728c..9e60a76b33 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java @@ -27,10 +27,10 @@ public class VolumeLiveTest { @Test public void whenListingVolumes_thenSizeMustBeGreaterThanZero() { - //when + // when ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); - //then + // then List volumes = volumesResponse.getVolumes(); assertThat(volumes.size(), is(greaterThan(0))); } @@ -38,48 +38,45 @@ public class VolumeLiveTest { @Test public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() { - //given + // given ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); List volumes = volumesResponse.getVolumes(); InspectVolumeResponse volume = volumes.get(0); - //when - InspectVolumeResponse volumeResponse - = dockerClient.inspectVolumeCmd(volume.getName()).exec(); + // when + InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec(); - //then + // then assertThat(volumeResponse, is(not(null))); } @Test public void whenCreatingUnnamedVolume_thenGetVolumeId() { - //when + // when CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec(); - //then + // then assertThat(unnamedVolume.getName(), is(not(null))); } @Test public void whenCreatingNamedVolume_thenGetVolumeId() { - //when - CreateVolumeResponse namedVolume - = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); + // when + CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); - //then + // then assertThat(namedVolume.getName(), is(not(null))); } @Test public void whenGettingNamedVolume_thenRemove() throws InterruptedException { - //when - CreateVolumeResponse namedVolume - = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec(); + // when + CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec(); - //then + // then Thread.sleep(4000); dockerClient.removeVolumeCmd(namedVolume.getName()).exec(); } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index ee384c2f9d..b1aaceb09b 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -17,7 +17,6 @@ public class CollectPatternTest { MutableList lastNames = students.collect(Student::getLastName); - Assertions.assertThat(lastNames) - .containsExactly("Hopkins", "Adams"); + Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams"); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java index 4655431872..e279314034 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -12,7 +12,6 @@ public class ConvertContainerToAnotherTest { public void whenConvertContainerToAnother_thenCorrect() { MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); - Assertions.assertThat(cars) - .containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); + Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java index c5b5e1c412..4ef7348a0d 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -20,7 +20,6 @@ public class DetectPatternTest { public void whenDetect_thenCorrect() { Integer result = list.detect(Predicates.greaterThan(30)); - Assertions.assertThat(result) - .isEqualTo(41); + Assertions.assertThat(result).isEqualTo(41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java index 021c72e91e..3091f90908 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -44,7 +44,6 @@ public class FlatCollectTest { public void whenFlatCollect_thenCorrect() { MutableList addresses = students.flatCollect(Student::getAddresses); - Assertions.assertThat(addresses) - .containsExactlyElementsOf(this.expectedAddresses); + Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java index bcd34021b1..01a8fcaef4 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java @@ -17,7 +17,7 @@ public class InjectIntoPatternTest { Integer v = list.get(i); result = result + v.intValue(); } - + assertEquals(15, result); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java index 9c216ecc87..bcb816c34a 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -18,7 +18,6 @@ public class LazyIterationTest { LazyIterable lazyStudents = students.asLazy(); LazyIterable lastNames = lazyStudents.collect(Student::getLastName); - Assertions.assertThat(lastNames) - .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); + Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index c055413cd9..8ef18004aa 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -31,14 +31,10 @@ public class PartitionPatternTest { return each > 30; } }); - MutableList greaterThanThirty = partitionedFolks.getSelected() - .sortThis(); - MutableList smallerThanThirty = partitionedFolks.getRejected() - .sortThis(); + MutableList greaterThanThirty = partitionedFolks.getSelected().sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected().sortThis(); - Assertions.assertThat(smallerThanThirty) - .containsExactly(1, 5, 8, 17, 23); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java index 1666c86333..bd743d56e8 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -20,10 +20,8 @@ public class RejectPatternTest { @Test public void whenReject_thenCorrect() { - MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) - .sortThis(); + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis(); - Assertions.assertThat(notGreaterThanThirty) - .containsExactlyElementsOf(this.expectedList); + Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java index d79c864fc5..154be08f08 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -18,17 +18,14 @@ public class SelectPatternTest { @Test public void givenListwhenSelect_thenCorrect() { - MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) - .sortThis(); + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis(); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } @SuppressWarnings("rawtypes") public MutableList selectUsingLambda() { - return list.select(each -> each > 30) - .sortThis(); + return list.select(each -> each > 30).sortThis(); } @SuppressWarnings("unchecked") @@ -36,7 +33,6 @@ public class SelectPatternTest { public void givenListwhenSelectUsingLambda_thenCorrect() { MutableList greaterThanThirty = selectUsingLambda(); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java index 29f0c23954..2b5aa06289 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -28,7 +28,6 @@ public class ZipTest { MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); MutableList> pairs = numbers.zip(cars); - Assertions.assertThat(pairs) - .containsExactlyElementsOf(this.expectedPairs); + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java index a2d8be44ec..724f693011 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -27,7 +27,6 @@ public class ZipWithIndexTest { MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); MutableList> pairs = cars.zipWithIndex(); - Assertions.assertThat(pairs) - .containsExactlyElementsOf(this.expectedPairs); + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java index 04ab6e43be..33952c8669 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java @@ -12,49 +12,49 @@ import fj.function.Characters; import fj.function.Integers; public class FunctionalJavaTest { - - public static final F isEven = i -> i % 2 == 0; - + + public static final F isEven = i -> i % 2 == 0; + @Test public void calculateEvenNumbers_givenIntList_returnTrue() { - List fList = List.list(3, 4, 5, 6); + List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); List evenListTrueResult = List.list(false, true, false, true); List evenListFalseResult = List.list(true, false, false, true); assertEquals(evenList.equals(evenListTrueResult), true); assertEquals(evenList.equals(evenListFalseResult), false); } - + @Test public void mapList_givenIntList_returnResult() { - List fList = List.list(3, 4, 5, 6); - fList = fList.map(i -> i + 100); - List resultList = List.list(103, 104, 105, 106); - List falseResultList = List.list(15, 504, 105, 106); - assertEquals(fList.equals(resultList), true); - assertEquals(fList.equals(falseResultList), false); + List fList = List.list(3, 4, 5, 6); + fList = fList.map(i -> i + 100); + List resultList = List.list(103, 104, 105, 106); + List falseResultList = List.list(15, 504, 105, 106); + assertEquals(fList.equals(resultList), true); + assertEquals(fList.equals(falseResultList), false); } - + @Test public void filterList_givenIntList_returnResult() { - Array array = Array.array(3, 4, 5, 6); - Array filteredArray = array.filter(Integers.even); - Array result = Array.array(4, 6); - Array wrongResult = Array.array(3, 5); - assertEquals(filteredArray.equals(result), true); - assertEquals(filteredArray.equals(wrongResult), false); + Array array = Array.array(3, 4, 5, 6); + Array filteredArray = array.filter(Integers.even); + Array result = Array.array(4, 6); + Array wrongResult = Array.array(3, 5); + assertEquals(filteredArray.equals(result), true); + assertEquals(filteredArray.equals(wrongResult), false); } - + @Test public void checkForLowerCase_givenStringArray_returnResult() { - Array array = Array.array("Welcome", "To", "baeldung"); - Array array2 = Array.array("Welcome", "To", "Baeldung"); + Array array = Array.array("Welcome", "To", "baeldung"); + Array array2 = Array.array("Welcome", "To", "Baeldung"); Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); assertEquals(isExist, true); assertEquals(isExist2, false); } - + @Test public void checkOptions_givenOptions_returnResult() { Option n1 = Option.some(1); @@ -64,16 +64,16 @@ public class FunctionalJavaTest { Option result1 = n1.bind(f1); Option result2 = n2.bind(f1); - + assertEquals(result1, Option.none()); assertEquals(result2, Option.some(102)); } - + @Test public void foldLeft_givenArray_returnResult() { Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sum = intArray.foldLeft(Integers.add, 0); assertEquals(sum, 260); } - + } diff --git a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java index f864c5f017..5c788e86d6 100644 --- a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java @@ -20,51 +20,45 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; - public class WordCountIntegrationTest { private final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); @Test public void givenDataSet_whenExecuteWordCount_thenReturnWordCount() throws Exception { - //given + // given List lines = Arrays.asList("This is a first sentence", "This is a second sentence with a one word"); - //when + // when DataSet> result = WordCount.startWordCount(env, lines); - //then + // then List> collect = result.collect(); - assertThat(collect).containsExactlyInAnyOrder( - new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), - new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), - new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1)); + assertThat(collect).containsExactlyInAnyOrder(new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), new Tuple2<>("first", 1), new Tuple2<>("with", 1), + new Tuple2<>("one", 1)); } @Test public void givenListOfAmounts_whenUseMapReduce_thenSumAmountsThatAreOnlyAboveThreshold() throws Exception { - //given + // given DataSet amounts = env.fromElements(1, 29, 40, 50); int threshold = 30; - //when - List collect = amounts - .filter(a -> a > threshold) - .reduce((integer, t1) -> integer + t1) - .collect(); + // when + List collect = amounts.filter(a -> a > threshold).reduce((integer, t1) -> integer + t1).collect(); - //then + // then assertThat(collect.get(0)).isEqualTo(90); } @Test public void givenDataSetOfComplexObjects_whenMapToGetOneField_thenReturnedListHaveProperElements() throws Exception { - //given + // given DataSet personDataSource = env.fromCollection(Arrays.asList(new Person(23, "Tom"), new Person(75, "Michael"))); - //when + // when List ages = personDataSource.map(p -> p.age).collect(); - //then + // then assertThat(ages).hasSize(2); assertThat(ages).contains(23, 75); @@ -72,44 +66,33 @@ public class WordCountIntegrationTest { @Test public void givenDataSet_whenSortItByOneField_thenShouldReturnSortedDataSet() throws Exception { - //given + // given Tuple2 secondPerson = new Tuple2<>(4, "Tom"); Tuple2 thirdPerson = new Tuple2<>(5, "Scott"); Tuple2 fourthPerson = new Tuple2<>(200, "Michael"); Tuple2 firstPerson = new Tuple2<>(1, "Jack"); - DataSet> transactions = env.fromElements(fourthPerson, secondPerson, - thirdPerson, firstPerson); + DataSet> transactions = env.fromElements(fourthPerson, secondPerson, thirdPerson, firstPerson); + // when + List> sorted = transactions.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING).collect(); - //when - List> sorted = transactions - .sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING) - .collect(); - - //then + // then assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson); } - @Test public void giveTwoDataSets_whenJoinUsingId_thenProduceJoinedData() throws Exception { - //given + // given Tuple3 address = new Tuple3<>(1, "5th Avenue", "London"); DataSet> addresses = env.fromElements(address); Tuple2 firstTransaction = new Tuple2<>(1, "Transaction_1"); - DataSet> transactions = - env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); + DataSet> transactions = env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); + // when + List, Tuple3>> joined = transactions.join(addresses).where(new IdKeySelectorTransaction()).equalTo(new IdKeySelectorAddress()).collect(); - //when - List, Tuple3>> joined = - transactions.join(addresses) - .where(new IdKeySelectorTransaction()) - .equalTo(new IdKeySelectorAddress()) - .collect(); - - //then + // then assertThat(joined).hasSize(1); assertThat(joined).contains(new Tuple2<>(firstTransaction, address)); @@ -117,48 +100,40 @@ public class WordCountIntegrationTest { @Test public void givenStreamOfEvents_whenProcessEvents_thenShouldPrintResultsOnSinkOperation() throws Exception { - //given + // given final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - DataStream text - = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); - + DataStream text = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); SingleOutputStreamOperator upperCase = text.map(String::toUpperCase); upperCase.print(); - //when + // when env.execute(); } - @Test public void givenStreamOfEvents_whenProcessEvents_thenShouldApplyWindowingOnTransformation() throws Exception { - //given + // given final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - SingleOutputStreamOperator> windowed = env.fromElements( - new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), - new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond()) - ).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor>(Time.seconds(20)) { - @Override - public long extractTimestamp(Tuple2 element) { - return element.f1 * 1000; - } - }); + SingleOutputStreamOperator> windowed = env.fromElements(new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())) + .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor>(Time.seconds(20)) { + @Override + public long extractTimestamp(Tuple2 element) { + return element.f1 * 1000; + } + }); - SingleOutputStreamOperator> reduced = windowed - .windowAll(TumblingEventTimeWindows.of(Time.seconds(5))) - .maxBy(0, true); + SingleOutputStreamOperator> reduced = windowed.windowAll(TumblingEventTimeWindows.of(Time.seconds(5))).maxBy(0, true); reduced.print(); - //when + // when env.execute(); } - private static class IdKeySelectorTransaction implements KeySelector, Integer> { @Override public Integer getKey(Tuple2 value) { diff --git a/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java b/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java index 5280073be2..ba1861937b 100644 --- a/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java @@ -30,7 +30,7 @@ public class GoogleSheetsIntegrationTest { private static Sheets sheetsService; - // this id can be replaced with your spreadsheet id + // this id can be replaced with your spreadsheet id // otherwise be advised that multiple people may run this test and update the public spreadsheet private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI"; @@ -41,100 +41,56 @@ public class GoogleSheetsIntegrationTest { @Test public void whenWriteSheet_thenReadSheetOk() throws IOException { - ValueRange body = new ValueRange() - .setValues(Arrays.asList( - Arrays.asList("Expenses January"), - Arrays.asList("books", "30"), - Arrays.asList("pens", "10"), - Arrays.asList("Expenses February"), - Arrays.asList("clothes", "20"), - Arrays.asList("shoes", "5"))); - UpdateValuesResponse result = sheetsService.spreadsheets().values() - .update(SPREADSHEET_ID, "A1", body) - .setValueInputOption("RAW") - .execute(); - - List data = new ArrayList<>(); - data.add(new ValueRange() - .setRange("D1") - .setValues(Arrays.asList( - Arrays.asList("January Total", "=B2+B3")))); - data.add(new ValueRange() - .setRange("D4") - .setValues(Arrays.asList( - Arrays.asList("February Total", "=B5+B6")))); + ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5"))); + UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute(); + + List data = new ArrayList<>(); + data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3")))); + data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6")))); + + BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data); + BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute(); + + List ranges = Arrays.asList("E1", "E4"); + BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute(); - BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest() - .setValueInputOption("USER_ENTERED") - .setData(data); - BatchUpdateValuesResponse batchResult = - sheetsService.spreadsheets().values() - .batchUpdate(SPREADSHEET_ID, batchBody) - .execute(); - - List ranges = Arrays.asList("E1","E4"); - BatchGetValuesResponse readResult = - sheetsService.spreadsheets().values() - .batchGet(SPREADSHEET_ID) - .setRanges(ranges) - .execute(); - ValueRange januaryTotal = readResult.getValueRanges().get(0); assertThat(januaryTotal.getValues().get(0).get(0)).isEqualTo("40"); ValueRange febTotal = readResult.getValueRanges().get(1); assertThat(febTotal.getValues().get(0).get(0)).isEqualTo("25"); - ValueRange appendBody = new ValueRange() - .setValues(Arrays.asList( - Arrays.asList("Total", "=E1+E4"))); - AppendValuesResponse appendResult = - sheetsService.spreadsheets().values() - .append(SPREADSHEET_ID, "A1", appendBody) - .setValueInputOption("USER_ENTERED") - .setInsertDataOption("INSERT_ROWS") - .setIncludeValuesInResponse(true) - .execute(); + ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4"))); + AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); ValueRange total = appendResult.getUpdates().getUpdatedData(); assertThat(total.getValues().get(0).get(1)).isEqualTo("65"); } - @Test public void whenUpdateSpreadSheetTitle_thenOk() throws IOException { - - UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest() - .setFields("*") - .setProperties(new SpreadsheetProperties().setTitle("Expenses")); - - CopyPasteRequest copyRequest = new CopyPasteRequest() - .setSource(new GridRange().setSheetId(0) - .setStartColumnIndex(0).setEndColumnIndex(2) - .setStartRowIndex(0).setEndRowIndex(1)) - .setDestination(new GridRange().setSheetId(1) - .setStartColumnIndex(0).setEndColumnIndex(2) - .setStartRowIndex(0).setEndRowIndex(1)) - .setPasteType("PASTE_VALUES"); - + + UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle("Expenses")); + + CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)) + .setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES"); + List requests = new ArrayList<>(); - + requests.add(new Request().setCopyPaste(copyRequest)); requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest)); - BatchUpdateSpreadsheetRequest body = - new BatchUpdateSpreadsheetRequest().setRequests(requests); + BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests); sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute(); } - + @Test public void whenCreateSpreadSheet_thenIdOk() throws IOException { - Spreadsheet spreadSheet = new Spreadsheet() - .setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet")); + Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet")); Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute(); - assertThat(result.getSpreadsheetId()).isNotNull(); + assertThat(result.getSpreadsheetId()).isNotNull(); } } diff --git a/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java index 5ecd4442d8..f762096811 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.hll; - import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import net.agkn.hll.HLL; @@ -15,47 +14,44 @@ public class HLLLongRunningUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { - //given + // given long numberOfElements = 100_000_000; long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL hll = new HLL(14, 5); - //when + // when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - hll.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + hll.addRaw(hashedValue); + }); - //then + // then long cardinality = hll.cardinality(); assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference)); } @Test public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() { - //given + // given long numberOfElements = 100_000_000; long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL firstHll = new HLL(15, 5); HLL secondHLL = new HLL(15, 5); - //when + // when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - firstHll.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + firstHll.addRaw(hashedValue); + }); LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - secondHLL.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + secondHLL.addRaw(hashedValue); + }); - //then + // then firstHll.union(secondHLL); long cardinality = firstHll.cardinality(); assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2)); diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java index 167aef5ec6..09d31eac21 100644 --- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java @@ -33,38 +33,21 @@ import io.specto.hoverfly.junit.rule.HoverflyRule; public class HoverflyApiIntegrationTest { - private static final SimulationSource source = dsl( - service("http://www.baeldung.com") - .get("/api/courses/1") - .willReturn(success().body( - jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) - - .post("/api/courses") - .willReturn(success()) - - .andDelay(3, TimeUnit.SECONDS) - .forMethod("POST"), - - service(matches("www.*dung.com")) - .get(startsWith("/api/student")) - .queryParam("page", any()) - .willReturn(success()) - - .post(equalsTo("/api/student")) - .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))) - .willReturn(success()) - - .put("/api/student/1") - .body(matchesJsonPath("$.name")) - .willReturn(success()) - - .post("/api/student") - .body(equalsToXml("2John")) - .willReturn(success()) - - .put("/api/student/2") - .body(matchesXPath("/student/name")) - .willReturn(success())); + private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses").willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS).forMethod("POST"), + + service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success()) + + .post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success()) + + .put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success()) + + .post("/api/student").body(equalsToXml("2John")).willReturn(success()) + + .put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success())); @ClassRule public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); @@ -72,19 +55,17 @@ public class HoverflyApiIntegrationTest { @Test public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity( - "http://www.baeldung.com/api/courses/1", String.class); - + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class); + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); } - + @Test public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/courses", null, Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class); stopWatch.stop(); long postTime = stopWatch.getTime(); @@ -94,45 +75,36 @@ public class HoverflyApiIntegrationTest { @Test public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity( - "http://www.baeldung.com/api/student?page=3", Void.class); - + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class); + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); } - + @Test public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); assertEquals(HttpStatus.OK, postResponse.getStatusCode()); } - + @Test public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity - .put(new URI("http://www.baeldung.com/api/student/1")) - .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}"); ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); assertEquals(HttpStatus.OK, putResponse.getStatusCode()); } - + @Test public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/student", "2John", Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "2John", Void.class); assertEquals(HttpStatus.OK, postResponse.getStatusCode()); } - - + @Test public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity - .put(new URI("http://www.baeldung.com/api/student/2")) - .body("" - + "2Monica"); + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("" + "2Monica"); ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); assertEquals(HttpStatus.OK, putResponse.getStatusCode()); diff --git a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java b/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java index c9ebe77679..9210b18f0c 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java @@ -27,24 +27,17 @@ public class ConfigurationTest { cacheManager = configuration.cacheManager(); - Cache transactionalCache = - configuration.transactionalCache(cacheManager, listener); + Cache transactionalCache = configuration.transactionalCache(cacheManager, listener); - Cache simpleHelloWorldCache = - configuration.simpleHelloWorldCache(cacheManager, listener); + Cache simpleHelloWorldCache = configuration.simpleHelloWorldCache(cacheManager, listener); - Cache expiringHelloWorldCache = - configuration.expiringHelloWorldCache(cacheManager, listener); + Cache expiringHelloWorldCache = configuration.expiringHelloWorldCache(cacheManager, listener); - Cache evictingHelloWorldCache = - configuration.evictingHelloWorldCache(cacheManager, listener); + Cache evictingHelloWorldCache = configuration.evictingHelloWorldCache(cacheManager, listener); - Cache passivatingHelloWorldCache = - configuration.passivatingHelloWorldCache(cacheManager, listener); + Cache passivatingHelloWorldCache = configuration.passivatingHelloWorldCache(cacheManager, listener); - this.helloWorldService = new HelloWorldService(repository, - listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, - passivatingHelloWorldCache); + this.helloWorldService = new HelloWorldService(repository, listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, passivatingHelloWorldCache); this.transactionalService = new TransactionalService(transactionalCache); } diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java index c9ecd57995..232186fedb 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java @@ -12,59 +12,46 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest { @Test public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isLessThan(100); } @Test public void whenGetIsCalledTwoTimesQuickly_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isLessThan(100); } @Test - public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() - throws InterruptedException { + public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); Thread.sleep(1100); - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); } @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); } @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100); } diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java index 99efacd18a..49681dd893 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java @@ -13,10 +13,9 @@ public class TransactionalServiceUnitTest extends ConfigurationTest { Thread backgroundThread = new Thread(backGroundJob); transactionalService.getQuickHowManyVisits(); backgroundThread.start(); - Thread.sleep(100); //lets wait our thread warm up + Thread.sleep(100); // lets wait our thread warm up - assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits())) - .isGreaterThan(500).isLessThan(1000); + assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits())).isGreaterThan(500).isLessThan(1000); } } diff --git a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java index 5e65c585aa..d67c2a5cb2 100644 --- a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jasypt; - import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.util.password.BasicPasswordEncryptor; @@ -17,16 +16,16 @@ public class JasyptUnitTest { @Test public void givenTextPrivateData_whenDecrypt_thenCompareToEncrypted() { - //given + // given BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); String privateData = "secret-data"; textEncryptor.setPasswordCharArray("some-random-data".toCharArray()); - //when + // when String myEncryptedText = textEncryptor.encrypt(privateData); - assertNotSame(privateData, myEncryptedText); //myEncryptedText can be save in db + assertNotSame(privateData, myEncryptedText); // myEncryptedText can be save in db - //then + // then String plainText = textEncryptor.decrypt(myEncryptedText); assertEquals(plainText, privateData); } @@ -37,10 +36,10 @@ public class JasyptUnitTest { BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); - //when + // when boolean result = passwordEncryptor.checkPassword("secret-pass", encryptedPassword); - //then + // then assertTrue(result); } @@ -50,28 +49,27 @@ public class JasyptUnitTest { BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); - //when + // when boolean result = passwordEncryptor.checkPassword("secret-pass-not-same", encryptedPassword); - //then + // then assertFalse(result); } - @Test @Ignore("should have installed local_policy.jar") public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() { - //given + // given StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); String privateData = "secret-data"; encryptor.setPassword("some-random-data"); encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); - //when + // when String encryptedText = encryptor.encrypt("secret-pass"); assertNotSame(privateData, encryptedText); - //then + // then String plainText = encryptor.decrypt(encryptedText); assertEquals(plainText, privateData); } @@ -79,18 +77,18 @@ public class JasyptUnitTest { @Test @Ignore("should have installed local_policy.jar") public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() { - //given + // given String privateData = "secret-data"; PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); encryptor.setPoolSize(4); encryptor.setPassword("some-random-data"); encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); - //when + // when String encryptedText = encryptor.encrypt(privateData); assertNotSame(privateData, encryptedText); - //then + // then String plainText = encryptor.decrypt(encryptedText); assertEquals(plainText, privateData); } diff --git a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java index 1cd390b873..53d9d11bbb 100644 --- a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java +++ b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java @@ -110,10 +110,7 @@ public class JavaDirectoryDeleteUnitTest { public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - Files.walk(pathToBeDeleted) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); + Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); } diff --git a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java index 30c034aa5e..2dae2adc51 100644 --- a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.javassist; - import javassist.CannotCompileException; import javassist.ClassPool; import javassist.NotFoundException; @@ -33,20 +32,20 @@ import static org.junit.Assert.assertTrue; public class JavasisstUnitTest { @Test public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { - //given + // given String classNameWithPackage = "com.baeldung.JavassistGeneratedClass"; ClassFile cf = new ClassFile(false, classNameWithPackage, null); - cf.setInterfaces(new String[]{"java.lang.Cloneable"}); + cf.setInterfaces(new String[] { "java.lang.Cloneable" }); FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I"); f.setAccessFlags(AccessFlag.PUBLIC); cf.addField(f); - //when + // when String className = "JavassistGeneratedClass.class"; cf.write(new DataOutputStream(new FileOutputStream(className))); - //then + // then ClassPool classPool = ClassPool.getDefault(); Field[] fields = classPool.makeClass(cf).toClass().getFields(); assertEquals(fields[0].getName(), "id"); @@ -57,14 +56,14 @@ public class JavasisstUnitTest { @Test public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode { - //given + // given ClassPool cp = ClassPool.getDefault(); ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile(); MethodInfo minfo = cf.getMethod("move"); CodeAttribute ca = minfo.getCodeAttribute(); CodeIterator ci = ca.iterator(); - //when + // when List operations = new LinkedList<>(); while (ci.hasNext()) { int index = ci.next(); @@ -72,23 +71,21 @@ public class JavasisstUnitTest { operations.add(Mnemonic.OPCODE[op]); } - //then - assertEquals(operations, - Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); + // then + assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); } @Test public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException { - //given + // given ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile(); - //when + // when FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I"); f.setAccessFlags(AccessFlag.PUBLIC); cf.addField(f); - ClassPool classPool = ClassPool.getDefault(); Field[] fields = classPool.makeClass(cf).toClass().getFields(); List fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList()); @@ -98,19 +95,19 @@ public class JavasisstUnitTest { @Test public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode { - //given + // given ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile(); Bytecode code = new Bytecode(cf.getConstPool()); code.addAload(0); code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V"); code.addReturn(null); - //when + // when MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V"); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); - //then + // then CodeIterator ci = code.toCodeAttribute().iterator(); List operations = new LinkedList<>(); while (ci.hasNext()) { @@ -119,9 +116,7 @@ public class JavasisstUnitTest { operations.add(Mnemonic.OPCODE[op]); } - assertEquals(operations, - Arrays.asList("aload_0", "invokespecial", "return")); - + assertEquals(operations, Arrays.asList("aload_0", "invokespecial", "return")); } } diff --git a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java index a341d5957a..73dfbae3b2 100644 --- a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java @@ -26,7 +26,7 @@ public class JavaTuplesUnitTest { Pair pairFromList = Pair.fromIterable(collectionOfNames, 2); - String[] names = new String[]{"john", "doe", "anne"}; + String[] names = new String[] { "john", "doe", "anne" }; Triplet triplet2 = Triplet.fromArray(names); } diff --git a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java index 3cdb833953..a8a7df659b 100644 --- a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - import org.javers.common.collections.Lists; import org.javers.core.Javers; import org.javers.core.JaversBuilder; @@ -21,16 +20,16 @@ public class JaversUnitTest { @Test public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); Person person = new Person(1, "Michael Program"); Person personAfterModification = new Person(1, "Michael Java"); - //when + // when Diff diff = javers.compare(person, personAfterModification); - //then + // then ValueChange change = diff.getChangesByType(ValueChange.class).get(0); assertThat(diff.getChanges()).hasSize(1); @@ -39,22 +38,20 @@ public class JaversUnitTest { assertThat(change.getRight()).isEqualTo("Michael Java"); } - @Test public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() { - //given + // given Javers javers = JaversBuilder.javers().build(); Person personThatWillBeRemoved = new Person(2, "Thomas Link"); List oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved); List newList = Lists.asList(new Person(1, "Michael Not Program")); - //when + // when Diff diff = javers.compareCollections(oldList, newList, Person.class); - //then + // then assertThat(diff.getChanges()).hasSize(3); - ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0); assertThat(valueChange.getPropertyName()).isEqualTo("name"); assertThat(valueChange.getLeft()).isEqualTo("Michael Program"); @@ -70,43 +67,36 @@ public class JaversUnitTest { @Test public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); - PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); - PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", - Arrays.asList(new Address("England"), new Address("USA"))); + PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA"))); - - //when + // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class); - //then + // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("USA"))); } @Test public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); - PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); - PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", Collections.emptyList()); + PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList()); - - //when + // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class); - //then + // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("England"))); } diff --git a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java index da4f51674f..a4747785cd 100644 --- a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java @@ -23,15 +23,13 @@ public class CacheLoaderTest { public void setup() { CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); - MutableConfiguration config = new MutableConfiguration().setReadThrough(true) - .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); + MutableConfiguration config = new MutableConfiguration().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); this.cache = cacheManager.createCache("SimpleCache", config); } @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java index eb40e63ef0..ab35d23768 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java @@ -29,8 +29,7 @@ public class EntryProcessorTest { @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java index be83e572d8..e32e4ad3cc 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java @@ -33,14 +33,12 @@ public class EventListenerTest { @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test public void whenRunEvent_thenCorrect() throws InterruptedException { - this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder - .factoryOf(this.listener), null, false, true); + this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(this.listener), null, false, true); this.cache.registerCacheEntryListener(this.listenerConfiguration); assertEquals(false, this.listener.getCreated()); diff --git a/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java b/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java similarity index 95% rename from libraries/src/test/java/com/baeldung/jcache/JCacheTest.java rename to libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index c98539a9ec..fac3d32bcb 100644 --- a/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -10,7 +10,7 @@ import javax.cache.spi.CachingProvider; import static org.junit.Assert.assertEquals; -public class JCacheTest { +public class JCacheIntegrationTest { @Test public void instantiateCache() { diff --git a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index e916a229f7..03e63c2580 100644 --- a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -106,5 +106,4 @@ public class GuideToJDOIntegrationTest { } } - } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java index 28d4f57e77..e6af244752 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jetty; - import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -32,26 +31,26 @@ public class JettyIntegrationTest { @Test public void givenServer_whenSendRequestToBlockingServlet_thenReturnStatusOK() throws Exception { - //given + // given String url = "http://localhost:8090/status"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); - //then + // then assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); } @Test public void givenServer_whenSendRequestToNonBlockingServlet_thenReturnStatusOK() throws Exception { - //when + // when String url = "http://localhost:8090/heavy/async"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); - //then + // then assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); assertThat(responseContent).isEqualTo("This is some heavy resource that will be served in an async way"); diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java index 849ba24f55..75b86e46b2 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java @@ -18,69 +18,69 @@ import org.junit.Test; */ public class JettyServerFactoryUnitTest { - /** - * Tests that when a base server is provided a request returns a status 404. - * - * @throws Exception - */ - @Test - public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception { - Server server = JettyServerFactory.createBaseServer(); - server.start(); - - int statusCode = sendGetRequest(); - - Assert.assertEquals(404, statusCode); - server.stop(); - } + /** + * Tests that when a base server is provided a request returns a status 404. + * + * @throws Exception + */ + @Test + public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception { + Server server = JettyServerFactory.createBaseServer(); + server.start(); - /** - * Tests that when a web app server is provided a request returns a status - * 200. - * - * @throws Exception - */ - @Test - public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception { - Server server = JettyServerFactory.createWebAppServer(); - server.start(); + int statusCode = sendGetRequest(); - int statusCode = sendGetRequest(); - - Assert.assertEquals(200, statusCode); - server.stop(); - } + Assert.assertEquals(404, statusCode); + server.stop(); + } - /** - * Tests that when a multi handler server is provided a request returns a - * status 200. - * - * @throws Exception - */ - @Test - public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception { - Server server = JettyServerFactory.createMultiHandlerServer(); - server.start(); + /** + * Tests that when a web app server is provided a request returns a status + * 200. + * + * @throws Exception + */ + @Test + public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception { + Server server = JettyServerFactory.createWebAppServer(); + server.start(); - int statusCode = sendGetRequest(); - - Assert.assertEquals(200, statusCode); - server.stop(); - } + int statusCode = sendGetRequest(); - /** - * Sends a default HTTP GET request to the server and returns the response - * status code. - * - * @return the status code of the response - * @throws Exception - */ - private int sendGetRequest() throws Exception { - HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT); - HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH); - HttpClient client = HttpClientBuilder.create().build(); - HttpResponse response = client.execute(target, request); - return response.getStatusLine().getStatusCode(); - } + Assert.assertEquals(200, statusCode); + server.stop(); + } + + /** + * Tests that when a multi handler server is provided a request returns a + * status 200. + * + * @throws Exception + */ + @Test + public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception { + Server server = JettyServerFactory.createMultiHandlerServer(); + server.start(); + + int statusCode = sendGetRequest(); + + Assert.assertEquals(200, statusCode); + server.stop(); + } + + /** + * Sends a default HTTP GET request to the server and returns the response + * status code. + * + * @return the status code of the response + * @throws Exception + */ + private int sendGetRequest() throws Exception { + HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT); + HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH); + HttpClient client = HttpClientBuilder.create().build(); + HttpResponse response = client.execute(target, request); + return response.getStatusLine().getStatusCode(); + } } diff --git a/libraries/src/test/java/com/baeldung/jool/JOOLTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java index ba20e153fd..2cb393abd3 100644 --- a/libraries/src/test/java/com/baeldung/jool/JOOLTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -28,86 +28,53 @@ public class JOOLTest { assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6)); - assertTrue(Seq.of(1, 2, 3, 4).contains(2)); - assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3)); - assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5)); } @Test public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() { - //given + // given Stream left = Stream.of(1, 2, 4); Stream right = Stream.of(1, 2, 3); - //when + // when List rightCollected = right.collect(Collectors.toList()); List collect = left.filter(rightCollected::contains).collect(Collectors.toList()); - //then + // then assertEquals(collect, Arrays.asList(1, 2)); } @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { - assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) - ); + assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2))); + assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))); - assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) - ); + assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))); - assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) - ); - - assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) - ); + assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { - assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) - ); + assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)); - assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) - ); + assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))); - assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) - ); + assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4)); - assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5); - assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); - assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) - ); + assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1)); } @Test @@ -117,66 +84,38 @@ public class JOOLTest { expectedAfterGroupBy.put(1, Arrays.asList(1, 3)); expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); - assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy - ); + assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy); + assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc"); - assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" - ); - - - assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" - ); + assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!"); } @Test public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { - assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5)); - assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5)); } @Test public void givenSeq_whenZip_shouldHaveZippedSeq() { - assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) - ); + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))); - assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") - ); + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c")); - - assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) - ); + assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))); } - public Integer methodThatThrowsChecked(String arg) throws Exception { return arg.length(); } @Test public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() { - //when + // when List collect = Stream.of("a", "b", "c").map(elem -> { try { return methodThatThrowsChecked(elem); @@ -186,55 +125,43 @@ public class JOOLTest { } }).collect(Collectors.toList()); - //then - assertEquals( - collect, - Arrays.asList(1, 1, 1) - ); + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); } - @Test public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { - //when - List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(this::methodThatThrowsChecked)) - .collect(Collectors.toList()); + // when + List collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList()); - //then - assertEquals( - collect, - Arrays.asList(1, 1, 1) - ); + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); } @Test public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() { - //given + // given Function2 addTwoNumbers = (v1, v2) -> v1 + v2; addTwoNumbers.toBiFunction(); Function1 addToTwo = addTwoNumbers.applyPartially(2); - //when + // when Integer result = addToTwo.apply(5); - //then + // then assertEquals(result, (Integer) 7); } @Test public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() { - //given + // given Seq> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43)); Tuple2 tuple = tuple("winter", "summer"); - //when + // when List> result = personDetails.map(t -> t.limit2().concat(tuple)).toList(); - //then - assertEquals( - result, - Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) - ); + // then + assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))); } } diff --git a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index bdbc101b15..ce9638c4af 100644 --- a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jsonassert; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -62,10 +61,8 @@ public class JsonAssertUnitTest { @Test public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException { - String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}"; - JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}", result, false); + String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}"; + JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}", result, false); } @Test @@ -98,32 +95,19 @@ public class JsonAssertUnitTest { @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; - JSONAssert.assertEquals( - "{names:[4]}", - names, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT)); } @Test public void whenComparingContentsOfArray_thenPass() throws JSONException { String ratings = "{ratings:[3.2,3.5,4.1,5,1]}"; - JSONAssert.assertEquals( - "{ratings:[1,5]}", - ratings, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + JSONAssert.assertEquals("{ratings:[1,5]}", ratings, new ArraySizeComparator(JSONCompareMode.LENIENT)); } @Test public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException { - JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", - new CustomComparator( - JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); + JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher("\\d")))); - JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", - new CustomComparator(JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); + JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher("\\d")))); } } diff --git a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index 1c95956761..c8718aef8d 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -14,7 +14,7 @@ public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) + @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -26,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; } @Test @@ -36,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; } @Test diff --git a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java index 08a472502e..d318345a56 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; } public static Object[] provideEdgeCaseData() { - return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; + return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; } } diff --git a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java index 32568e9ea5..4406494d30 100644 --- a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java +++ b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java @@ -22,7 +22,7 @@ public class KafkaStreamsLiveTest { @Test @Ignore("it needs to have kafka broker running on local") public void shouldTestKafkaStreams() throws InterruptedException { - //given + // given String inputTopic = "inputTopic"; Properties streamsConfiguration = new Properties(); @@ -35,15 +35,12 @@ public class KafkaStreamsLiveTest { // Use a temporary directory for storing state, which will be automatically removed after the test. streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath()); - //when + // when KStreamBuilder builder = new KStreamBuilder(); KStream textLines = builder.stream(inputTopic); Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); - KTable wordCounts = textLines - .flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))) - .groupBy((key, word) -> word) - .count(); + KTable wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count(); wordCounts.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); @@ -55,7 +52,7 @@ public class KafkaStreamsLiveTest { KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration); streams.start(); - //then + // then Thread.sleep(30000); streams.close(); } diff --git a/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java b/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java index fbcda2a70d..5928765aaa 100644 --- a/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java +++ b/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java @@ -8,16 +8,15 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; - public class LocalSensitiveHashingUnitTest { @Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results") @Test() public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() { - //given - boolean[] vector1 = new boolean[]{true, true, true, true, true}; - boolean[] vector2 = new boolean[]{false, false, false, true, false}; - boolean[] vector3 = new boolean[]{false, false, true, true, false}; + // given + boolean[] vector1 = new boolean[] { true, true, true, true, true }; + boolean[] vector2 = new boolean[] { false, false, false, true, false }; + boolean[] vector3 = new boolean[] { false, false, true, true, false }; int sizeOfVectors = 5; int numberOfBuckets = 10; @@ -25,7 +24,7 @@ public class LocalSensitiveHashingUnitTest { LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors); - //when + // when int[] firstHash = lsh.hash(vector1); int[] secondHash = lsh.hash(vector2); int[] thirdHash = lsh.hash(vector3); @@ -34,7 +33,7 @@ public class LocalSensitiveHashingUnitTest { System.out.println(Arrays.toString(secondHash)); System.out.println(Arrays.toString(thirdHash)); - //then + // then int lastIndexOfResult = stages - 1; assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]); assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]); @@ -45,4 +44,3 @@ public class LocalSensitiveHashingUnitTest { return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2; } } - diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java index fe9c130d93..afbebb15c9 100644 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java @@ -25,8 +25,8 @@ public class MBassadorConfigurationTest implements IPublicationErrorHandler { @Before public void prepareTests() { - dispatcher = new MBassador(this); - dispatcher.subscribe(this); + dispatcher = new MBassador(this); + dispatcher.subscribe(this); } @Test diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java index 5da1d166f6..ea5c09a4d8 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java @@ -10,7 +10,7 @@ import static org.junit.Assert.*; public class XORIntegrationTest { private NeuralNetwork ann = null; - private void print(String input, double output, double actual) { + private void print(String input, double output, double actual) { System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output); } diff --git a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java index cc3b441aa4..70d3e41579 100644 --- a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.pact; - import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRuleMk2; import au.com.dius.pact.consumer.PactVerification; @@ -23,61 +22,37 @@ import static org.assertj.core.api.Assertions.assertThat; public class PactConsumerDrivenContractUnitTest { @Rule - public PactProviderRuleMk2 mockProvider - = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); + public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); @Pact(consumer = "test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { Map headers = new HashMap(); headers.put("Content-Type", "application/json"); - return builder - .given("test GET") - .uponReceiving("GET REQUEST") - .path("/pact") - .method("GET") - .willRespondWith() - .status(200) - .headers(headers) - .body("{\"condition\": true, \"name\": \"tom\"}") - .given("test POST") - .uponReceiving("POST REQUEST") - .method("POST") - .headers(headers) - .body("{\"name\": \"Michael\"}") - .path("/pact") - .willRespondWith() - .status(201) - .toPact(); + return builder.given("test GET").uponReceiving("GET REQUEST").path("/pact").method("GET").willRespondWith().status(200).headers(headers).body("{\"condition\": true, \"name\": \"tom\"}").given("test POST").uponReceiving("POST REQUEST").method("POST") + .headers(headers).body("{\"name\": \"Michael\"}").path("/pact").willRespondWith().status(201).toPact(); } - @Test @PactVerification() public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() { - //when - ResponseEntity response - = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class); + // when + ResponseEntity response = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class); - //then + // then assertThat(response.getStatusCode().value()).isEqualTo(200); assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue(); assertThat(response.getBody()).contains("condition", "true", "name", "tom"); - //and + // and HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); String jsonBody = "{\"name\": \"Michael\"}"; - //when - ResponseEntity postResponse = new RestTemplate().exchange( - mockProvider.getUrl() + "/pact", - HttpMethod.POST, - new HttpEntity<>(jsonBody, httpHeaders), - String.class - ); + // when + ResponseEntity postResponse = new RestTemplate().exchange(mockProvider.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class); - //then + // then assertThat(postResponse.getStatusCode().value()).isEqualTo(201); } diff --git a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java index 0e6242b8a3..205f0e545e 100644 --- a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java @@ -46,5 +46,4 @@ public class ApacheCommonsPairUnitTest { immutablePair.setValue("Another One"); } - } diff --git a/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java index ca425339fa..4271d4e003 100644 --- a/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java @@ -17,15 +17,15 @@ public class CoreJavaSimpleEntryUnitTest { assertEquals(key.intValue(), 1); assertEquals(value, "one"); } - + @Test(expected = UnsupportedOperationException.class) public void givenSimpleImmutableEntry_whenSetValue_thenException() { AbstractMap.SimpleImmutableEntry entry = new AbstractMap.SimpleImmutableEntry(1, "one"); - + entry.setValue("two"); - + } - + @Test public void givenSimpleImmutableEntry_whenGetValue_thenOk() { AbstractMap.SimpleImmutableEntry entry = new AbstractMap.SimpleImmutableEntry(1, "one"); diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index acc7718ea8..1a75624439 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -86,8 +86,7 @@ public class PCollectionsUnitTest { @Test public void whenMapPSetMethods_thenPerformOperations() { - MapPSet pSet = HashTreePSet.empty() - .plusAll(Arrays.asList("e1", "e2", "e3", "e4")); + MapPSet pSet = HashTreePSet.empty().plusAll(Arrays.asList("e1", "e2", "e3", "e4")); assertEquals(pSet.size(), 4); MapPSet pSet1 = pSet.minus("e4"); diff --git a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java index cf6a1e5ec5..e9d5b8ede5 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java @@ -35,32 +35,21 @@ public class CollectorUtilsTests { @Test public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() { - assertThat(Stream - .empty() - .collect(CollectorUtils.unique()), equalTo(Optional.empty())); + assertThat(Stream.empty().collect(CollectorUtils.unique()), equalTo(Optional.empty())); } @Test public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() { - assertThat(Stream - .of(1, 2, 3) - .filter(i -> i > 2) - .collect(CollectorUtils.unique()), equalTo(Optional.of(3))); + assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.unique()), equalTo(Optional.of(3))); } @Test public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() { - assertThat(Stream - .of(1, 2, 3) - .filter(i -> i > 2) - .collect(CollectorUtils.uniqueNullable()), equalTo(3)); + assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.uniqueNullable()), equalTo(3)); } @Test(expected = NonUniqueValueException.class) public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() { - Stream - .of(1, 2, 3) - .filter(i -> i > 1) - .collect(CollectorUtils.unique()); + Stream.of(1, 2, 3).filter(i -> i > 1).collect(CollectorUtils.unique()); } } diff --git a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java index 37ca71287f..ccd43b7777 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java @@ -24,9 +24,7 @@ public class StreamUtilsTests { public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() { Stream source = Stream.of("Foo", "Bar", "Baz"); - List> zipped = StreamUtils - .zipWithIndex(source) - .collect(Collectors.toList()); + List> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList()); assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz"))); } @@ -36,9 +34,7 @@ public class StreamUtilsTests { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, (a, b) -> a + " is for " + b) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList()); assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot")); } @@ -49,15 +45,13 @@ public class StreamUtilsTests { Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream streamC = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList()); assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot")); } @Test - //givenThreeStreams_whenMerge_shouldReturnMergedStream + // givenThreeStreams_whenMerge_shouldReturnMergedStream public void givenThreeStreams_whenMerge_shouldReturnMergedStream() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("apple", "banana", "carrot", "date"); @@ -69,7 +63,7 @@ public class StreamUtilsTests { } @Test - //givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream + // givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() { Stream streamA = Stream.of("Peter", "Paul", "Mary"); Stream streamB = Stream.of("A", "B", "C", "D", "E"); @@ -81,7 +75,7 @@ public class StreamUtilsTests { } @Test - //givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 + // givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() { Stream infiniteInts = Stream.iterate(0, i -> i + 1); Stream finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10); @@ -125,9 +119,7 @@ public class StreamUtilsTests { @Test public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() { Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); - List> runs = StreamUtils - .groupRuns(integerStream) - .collect(toList()); + List> runs = StreamUtils.groupRuns(integerStream).collect(toList()); assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5))); } @@ -143,21 +135,17 @@ public class StreamUtilsTests { public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5))); } @Test - //givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip + // givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 3, 2) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5))); } @@ -166,15 +154,9 @@ public class StreamUtilsTests { public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() { ArrayList ints = new ArrayList<>(); - ints - .stream() - .collect(maxBy((a, b) -> a - .toString() - .compareTo(b.toString()))); + ints.stream().collect(maxBy((a, b) -> a.toString().compareTo(b.toString()))); - List> windows = StreamUtils - .windowed(ints.stream(), 2) - .collect(toList()); + List> windows = StreamUtils.windowed(ints.stream(), 2).collect(toList()); assertThat(windows, iterableWithSize(0)); } @@ -183,18 +165,14 @@ public class StreamUtilsTests { public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2, 2, true) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList()); assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5))); } @Test public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() { - LongStream indices = StreamUtils - .indices() - .limit(500); + LongStream indices = StreamUtils.indices().limit(500); assertThat(indices.count(), equalTo(500)); } diff --git a/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java index 7170d35aa5..46325d4d23 100644 --- a/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java +++ b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java @@ -17,46 +17,33 @@ import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class GitHubBasicApiLiveTest { - + GitHubBasicApi gitHub; - + @Before public void init() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .build(); - + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build(); + gitHub = retrofit.create(GitHubBasicApi.class); } - + @Test public void whenListRepos_thenExpectReposThatContainTutorials() { try { - List repos = gitHub - .listRepos("eugenp") - .execute() - .body(); - - assertThat(repos) - .isNotEmpty() - .extracting(Repository::getName).contains("tutorials"); + List repos = gitHub.listRepos("eugenp").execute().body(); + + assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials"); } catch (IOException e) { fail("Can not communicate with GitHub API"); } } - + @Test public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { try { - List contributors = gitHub - .listRepoContributors("eugenp", "tutorials") - .execute() - .body(); - - assertThat(contributors) - .isNotEmpty() - .extracting(Contributor::getName).contains("eugenp"); + List contributors = gitHub.listRepoContributors("eugenp", "tutorials").execute().body(); + + assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp"); } catch (IOException e) { fail("Can not communicate with GitHub API"); } diff --git a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java index c2fbd9bf60..48161fa3ee 100644 --- a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java +++ b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java @@ -14,40 +14,28 @@ import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class GitHubRxApiTest { - + GitHubRxApi gitHub; - + @Before public void init() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) - .build(); - + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); + gitHub = retrofit.create(GitHubRxApi.class); } - + @Test public void whenListRepos_thenExpectReposThatContainTutorials() { - gitHub - .listRepos("eugenp") - .subscribe( repos -> { - assertThat(repos) - .isNotEmpty() - .extracting(Repository::getName).contains("tutorials"); - }); + gitHub.listRepos("eugenp").subscribe(repos -> { + assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials"); + }); } - + @Test public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { - gitHub - .listRepoContributors("eugenp", "tutorials") - .subscribe(contributors -> { - assertThat(contributors) - .isNotEmpty() - .extracting(Contributor::getName).contains("eugenp"); - }); + gitHub.listRepoContributors("eugenp", "tutorials").subscribe(contributors -> { + assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp"); + }); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java index 1ebbd49e79..57bb7c1242 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java @@ -23,15 +23,11 @@ public class GoogleSearchLiveTest { public void whenGoogleBaeldungThenShouldSeeEugen() { browser.get("https://www.google.com/ncr"); - browser - .findElement(By.name("q")) - .sendKeys("baeldung", Keys.ENTER); + browser.findElement(By.name("q")).sendKeys("baeldung", Keys.ENTER); new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh"))); - assertThat(browser - .findElement(By.cssSelector("._ksh")) - .getText(), containsString("Eugen (Baeldung)")); + assertThat(browser.findElement(By.cssSelector("._ksh")).getText(), containsString("Eugen (Baeldung)")); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java index 2ba5b1c8ed..887b4cde7d 100644 --- a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java @@ -43,9 +43,6 @@ public class GithubRestUserAPISteps { private static HttpResponse getGithubUserProfile(String api, String username) throws IOException { HttpUriRequest request = new HttpGet(String.format(api, username)); - return HttpClientBuilder - .create() - .build() - .execute(request); + return HttpClientBuilder.create().build().execute(request); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java index 49ed8cae7d..a398c614c4 100644 --- a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java @@ -33,7 +33,7 @@ public class MemberStatusSteps { @Pending @Step("When the member exchange {}") public void aMemberExchangeA(Commodity commodity) { - //TODO + // TODO } @Pending diff --git a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java index bdba8a69bc..d922ea8c85 100644 --- a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java +++ b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java @@ -24,9 +24,7 @@ public class GoogleSearchPageObject extends PageObject { } public void resultMatches(String expected) { - withTimeoutOf(5, SECONDS) - .waitFor(result) - .waitUntilVisible(); + withTimeoutOf(5, SECONDS).waitFor(result).waitUntilVisible(); assertThat(result.getText(), containsString(expected)); } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java index b60c929c05..5663484a5b 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java @@ -10,12 +10,8 @@ import net.thucydides.core.annotations.DefaultUrl; @DefaultUrl("https://www.google.com/ncr") class GoogleSearchPage extends PageObject { - static final Target SEARCH_RESULT_TITLES = Target - .the("search results") - .locatedBy("._ksh"); + static final Target SEARCH_RESULT_TITLES = Target.the("search results").locatedBy("._ksh"); - static final Target SEARCH_INPUT_BOX = Target - .the("search input box") - .locatedBy("#lst-ib"); + static final Target SEARCH_INPUT_BOX = Target.the("search input box").locatedBy("#lst-ib"); } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java index 38990e13b6..67a27e5855 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java @@ -13,9 +13,6 @@ public class GoogleSearchResults implements Question> { } public List answeredBy(Actor actor) { - return Text - .of(GoogleSearchPage.SEARCH_RESULT_TITLES) - .viewedBy(actor) - .asList(); + return Text.of(GoogleSearchPage.SEARCH_RESULT_TITLES).viewedBy(actor).asList(); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java index 1628ef8ed7..2464c439cf 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java @@ -11,10 +11,7 @@ public class SearchForKeyword implements Task { @Step("{0} searches for '#keyword'") public void performAs(T actor) { - actor.attemptsTo(Enter - .theValue(keyword) - .into(GoogleSearchPage.SEARCH_INPUT_BOX) - .thenHit(Keys.RETURN)); + actor.attemptsTo(Enter.theValue(keyword).into(GoogleSearchPage.SEARCH_INPUT_BOX).thenHit(Keys.RETURN)); } private String keyword; @@ -24,9 +21,7 @@ public class SearchForKeyword implements Task { } public static Task of(String keyword) { - return Instrumented - .instanceOf(SearchForKeyword.class) - .withProperties(keyword); + return Instrumented.instanceOf(SearchForKeyword.class).withProperties(keyword); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java index 52c6d07fda..d6e45beb26 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java @@ -17,9 +17,7 @@ public class StartWith implements Task { @Step("{0} starts a google search") public void performAs(T t) { - t.attemptsTo(Open - .browserOn() - .the(googleSearchPage)); + t.attemptsTo(Open.browserOn().the(googleSearchPage)); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java index 82dbad0f11..7eb658ca23 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java @@ -15,9 +15,7 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; @RunWith(Suite.class) -@Suite.SuiteClasses({ - AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class -}) +@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class }) public class AdderClassDirtiesContextIntegrationTest { @RunWith(SerenityRunner.class) @@ -52,7 +50,7 @@ public class AdderClassDirtiesContextIntegrationTest { @Test public void givenNumber_whenAdd_thenSumWrong() { - super.whenAdd_thenSummedUp(); //expecting zero + super.whenAdd_thenSummedUp(); // expecting zero adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt()); super.whenAccumulate_thenSummedUp(); super.whenAdd_thenSumWrong(); @@ -64,7 +62,7 @@ public class AdderClassDirtiesContextIntegrationTest { @Test public void givenNumber_whenAdd_thenSumWrong() { - super.whenAdd_thenSummedUp(); //expecting zero + super.whenAdd_thenSummedUp(); // expecting zero adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt()); super.whenAccumulate_thenSummedUp(); super.whenAdd_thenSumWrong(); diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java index 6524ade190..ecb601b94b 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java @@ -25,7 +25,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest { private AdderConstructorDependencySteps adderSteps; - @Autowired private AdderService adderService; + @Autowired + private AdderService adderService; @Before public void init() { @@ -38,7 +39,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest { adderSteps.summedUp(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java index 87c66f03d9..7221aa7a17 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java @@ -23,7 +23,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @ContextConfiguration(classes = AdderService.class) public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Before public void init() { @@ -36,7 +37,8 @@ public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest { adderServiceSteps.summedUp(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java index 263ffc9854..fc7067520d 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java @@ -22,7 +22,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @ContextConfiguration(classes = AdderService.class) public class AdderMethodDirtiesContextIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Test public void _1_givenNumber_whenAdd_thenSumWrong() { @@ -30,7 +31,8 @@ public class AdderMethodDirtiesContextIntegrationTest { adderServiceSteps.sumWrong(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java index bbf07a2b95..1b3668b756 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java @@ -41,11 +41,14 @@ public class AdderMethodRuleIntegrationTest { LOG.info("adder after test: {}", adder); } - @Rule public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule(); - @Steps private AdderSteps adderSteps; + @Steps + private AdderSteps adderSteps; - @Value("#{props['adder']}") private int adder; + @Value("#{props['adder']}") + private int adder; private static int staticAdder; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java index 2b2777f0ed..d4cf9fc924 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java @@ -21,7 +21,8 @@ public class AdderMockMvcIntegrationTest { RestAssuredMockMvc.standaloneSetup(new PlainAdderController()); } - @Steps AdderRestSteps steps; + @Steps + AdderRestSteps steps; @Test public void givenNumber_whenAdd_thenSummedUp() throws Exception { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java index 5f2aae8e3f..8b307973ba 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java @@ -14,7 +14,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @RunWith(SerenityRunner.class) public class AdderServiceIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Test public void givenNumber_whenAdd_thenSummedUp() { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java index cdabc17980..ddbfd0cfc2 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java @@ -15,9 +15,11 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(locations = "classpath:adder-beans.xml") public class AdderSpringSerenityRunnerIntegrationTest { - @Steps private AdderSteps adderSteps; + @Steps + private AdderSteps adderSteps; - @Value("#{props['adder']}") private int adder; + @Value("#{props['adder']}") + private int adder; @Test public void givenNumber_whenAdd_thenSummedUp() { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java index 771f389cb1..3144771e70 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java @@ -6,7 +6,7 @@ import org.jbehave.core.annotations.BeforeStory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -@ContextConfiguration(classes = {AdderController.class, AdderService.class}) +@ContextConfiguration(classes = { AdderController.class, AdderService.class }) public class AdderTest extends SerenityStory { @Autowired diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java index 0d77ed0849..a38a584645 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java @@ -18,29 +18,18 @@ public class AdderRestSteps { @Step("get the current number") public void givenCurrentNumber() throws UnsupportedEncodingException { - currentNum = Integer.valueOf(given() - .when() - .get("/adder/current") - .mvcResult() - .getResponse() - .getContentAsString()); + currentNum = Integer.valueOf(given().when().get("/adder/current").mvcResult().getResponse().getContentAsString()); } @Step("adding {0}") public void whenAddNumber(int num) { - mockMvcResponse = given() - .queryParam("num", num) - .when() - .post("/adder"); + mockMvcResponse = given().queryParam("num", num).when().post("/adder"); currentNum += num; } @Step("got the sum") public void thenSummedUp() { - mockMvcResponse - .then() - .statusCode(200) - .body(equalTo(currentNum + "")); + mockMvcResponse.then().statusCode(200).body(equalTo(currentNum + "")); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java index b8c2854bf0..227526b8b4 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java @@ -13,7 +13,8 @@ import static org.junit.Assert.assertNotEquals; @ContextConfiguration(classes = AdderService.class) public class AdderServiceSteps { - @Autowired private AdderService adderService; + @Autowired + private AdderService adderService; private int givenNumber; private int base; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java b/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java index b9fa8f1ae0..491c11a38c 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java @@ -11,7 +11,8 @@ import org.jbehave.core.annotations.When; */ public class AdderStory { - @Steps AdderRestSteps restSteps; + @Steps + AdderRestSteps restSteps; @Given("a number") public void givenANumber() throws Exception { diff --git a/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java b/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java index 4d2cb71329..69af042427 100644 --- a/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java @@ -10,22 +10,11 @@ import java.text.SimpleDateFormat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; - public class SmooksIntegrationTest { - private static final String EDIFACT_MESSAGE = - "UNA:+.? '\r\n" + - "UNH+771+IN_PROGRESS+2018-01-14'\r\n" + - "CTA+CompanyX+1234567'\r\n" + - "LIN+1+PX1234+9.99'\r\n" + - "LIN+2+RX990+120.32'\r\n"; - private static final String EMAIL_MESSAGE = - "Hi,\r\n" + - "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" + - "Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" + - "Order items:\r\n" + - "1 X PX1234 (total price 9.99)\r\n" + - "2 X RX990 (total price 240.64)\r\n"; + private static final String EDIFACT_MESSAGE = "UNA:+.? '\r\n" + "UNH+771+IN_PROGRESS+2018-01-14'\r\n" + "CTA+CompanyX+1234567'\r\n" + "LIN+1+PX1234+9.99'\r\n" + "LIN+2+RX990+120.32'\r\n"; + private static final String EMAIL_MESSAGE = "Hi,\r\n" + "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" + "Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" + "Order items:\r\n" + + "1 X PX1234 (total price 9.99)\r\n" + "2 X RX990 (total price 240.64)\r\n"; @Test public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception { @@ -33,14 +22,11 @@ public class SmooksIntegrationTest { OrderConverter xmlToJavaOrderConverter = new OrderConverter(); Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml"); - assertThat(order.getNumber(),is(771L)); - assertThat(order.getStatus(),is(Status.IN_PROGRESS)); - assertThat(order.getCreationDate(),is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14"))); - assertThat(order.getSupplier(),is(new Supplier("CompanyX","1234567"))); - assertThat(order.getItems(),containsInAnyOrder( - new Item("PX1234",9.99,1), - new Item("RX990",120.32,2)) - ); + assertThat(order.getNumber(), is(771L)); + assertThat(order.getStatus(), is(Status.IN_PROGRESS)); + assertThat(order.getCreationDate(), is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14"))); + assertThat(order.getSupplier(), is(new Supplier("CompanyX", "1234567"))); + assertThat(order.getItems(), containsInAnyOrder(new Item("PX1234", 9.99, 1), new Item("RX990", 120.32, 2))); } @@ -51,20 +37,20 @@ public class SmooksIntegrationTest { assertThat(validationResult.getErrors(), hasSize(1)); // 1234567 didn't match ^[0-9\\-\\+]{9,15}$ - assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(),is("supplierPhone")); + assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(), is("supplierPhone")); } @Test public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception { OrderConverter orderConverter = new OrderConverter(); String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml"); - assertThat(edifact,is(EDIFACT_MESSAGE)); + assertThat(edifact, is(EDIFACT_MESSAGE)); } @Test public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception { OrderConverter orderConverter = new OrderConverter(); String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml"); - assertThat(emailMessage,is(EMAIL_MESSAGE)); + assertThat(emailMessage, is(EMAIL_MESSAGE)); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stm/AccountTest.java b/libraries/src/test/java/com/baeldung/stm/AccountTest.java index be3edf058c..eb8693b096 100644 --- a/libraries/src/test/java/com/baeldung/stm/AccountTest.java +++ b/libraries/src/test/java/com/baeldung/stm/AccountTest.java @@ -1,6 +1,5 @@ package com.baeldung.stm; - import org.junit.Test; import java.util.concurrent.CountDownLatch; @@ -16,34 +15,34 @@ public class AccountTest { @Test public void givenAccount_whenDecrement_thenShouldReturnProperValue() { - //given + // given Account a = new Account(10); - //when + // when a.adjustBy(-5); - //then + // then assertThat(a.getBalance()).isEqualTo(5); } @Test(expected = IllegalArgumentException.class) public void givenAccount_whenDecrementTooMuch_thenShouldThrow() { - //given + // given Account a = new Account(10); - //when + // when a.adjustBy(-11); } @Test public void givenTwoThreads_whenBothApplyOperation_thenShouldThrow() throws InterruptedException { - //given + // given ExecutorService ex = Executors.newFixedThreadPool(2); Account a = new Account(10); CountDownLatch countDownLatch = new CountDownLatch(1); AtomicBoolean exceptionThrown = new AtomicBoolean(false); - //when + // when ex.submit(() -> { try { countDownLatch.await(); @@ -74,44 +73,44 @@ public class AccountTest { ex.awaitTermination(1, TimeUnit.SECONDS); ex.shutdown(); - //then + // then assertTrue(exceptionThrown.get()); } @Test public void givenTwoAccounts_whenFailedWhileTransferring_thenShouldRollbackTransaction() { - //given + // given final Account a = new Account(10); final Account b = new Account(10); - //when + // when a.transferTo(b, 5); - //then + // then assertThat(a.getBalance()).isEqualTo(5); assertThat(b.getBalance()).isEqualTo(15); - //and + // and try { a.transferTo(b, 20); } catch (final IllegalArgumentException e) { System.out.println("failed to transfer money"); } - //then + // then assertThat(a.getBalance()).isEqualTo(5); assertThat(b.getBalance()).isEqualTo(15); } @Test public void givenTwoThreads_whenBothTryToTransfer_thenShouldNotDeadlock() throws InterruptedException { - //given + // given ExecutorService ex = Executors.newFixedThreadPool(2); final Account a = new Account(10); final Account b = new Account(10); CountDownLatch countDownLatch = new CountDownLatch(1); - //when + // when ex.submit(() -> { try { countDownLatch.await(); @@ -134,10 +133,9 @@ public class AccountTest { ex.awaitTermination(1, TimeUnit.SECONDS); ex.shutdown(); - //then + // then assertThat(a.getBalance()).isEqualTo(1); assertThat(b.getBalance()).isEqualTo(19); } - } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java index e14a91ce67..4cda0b5940 100644 --- a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java @@ -16,11 +16,9 @@ public class JoolMergeStreamsTest { Stream seq1 = Stream.of(1, 3, 5); Stream seq2 = Stream.of(2, 4, 6); - Stream resultingSeq = Seq.ofType(seq1, Integer.class) - .append(seq2); + Stream resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingSeq.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList())); } @Test @@ -29,11 +27,8 @@ public class JoolMergeStreamsTest { Stream openingBracketSeq = Stream.of("["); Stream closingBracketSeq = Stream.of("]"); - Stream resultingStream = Seq.ofType(seq, String.class) - .append(closingBracketSeq) - .prepend(openingBracketSeq); + Stream resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq); - Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java index 23110947b6..b8748abe03 100644 --- a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java @@ -16,11 +16,9 @@ public class MergeStreamsTest { Stream stream1 = Stream.of(1, 3, 5); Stream stream2 = Stream.of(2, 4, 6); - Stream resultingStream = Stream.concat(stream1, - stream2); + Stream resultingStream = Stream.concat(stream1, stream2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); } @Test @@ -29,12 +27,9 @@ public class MergeStreamsTest { Stream stream2 = Stream.of(2, 4, 6); Stream stream3 = Stream.of(18, 15, 36); - Stream resultingStream = Stream.concat(Stream.concat(stream1, - stream2), - stream3); + Stream resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList())); } @Test @@ -46,8 +41,7 @@ public class MergeStreamsTest { Stream resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity()); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java index 5104ec0682..e5392dff2a 100644 --- a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java @@ -18,8 +18,7 @@ public class StreamExMergeStreamsTest { Stream resultingStream = StreamEx.of(stream1).append(stream2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); } @Test @@ -29,13 +28,9 @@ public class StreamExMergeStreamsTest { Stream stream3 = Stream.of(18, 15, 36); Stream stream4 = Stream.of(99); - Stream resultingStream = StreamEx.of(stream1) - .append(stream2) - .append(stream3) - .append(stream4); + Stream resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); } @@ -45,11 +40,8 @@ public class StreamExMergeStreamsTest { Stream openingBracketStream = Stream.of("["); Stream closingBracketStream = Stream.of("]"); - Stream resultingStream = StreamEx.of(stream1) - .append(closingBracketStream) - .prepend(openingBracketStream); + Stream resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream); - assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); } } diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java index 9a65075e5b..3ed797ccaa 100644 --- a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -18,83 +18,83 @@ import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; public class CopyStreamTest { - @Test - public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); - StreamUtils.copy(in, out); + StreamUtils.copy(in, out); - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent, outputFileContent); - } + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } - @Test - public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); - StreamUtils.copyRange(in, out, 1, 10); + StreamUtils.copyRange(in, out, 1, 10); - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); - } + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } - @Test - public void whenCopyStringToOutputStream_thenCorrect() throws IOException { - String string = "Should be copied to OutputStream."; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - StreamUtils.copy(string, StandardCharsets.UTF_8, out); + StreamUtils.copy(string, StandardCharsets.UTF_8, out); - assertTrue(outputFile.exists()); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } - @Test - public void whenCopyInputStreamToString_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream is = new FileInputStream(inputFileName); - String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } - @Test - public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { - String outputFileName = "src/test/resources/output.txt"; - String string = "Should be copied to OutputStream."; - byte[] byteArray = string.getBytes(); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - StreamUtils.copy(byteArray, out); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } - @Test - public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream in = new FileInputStream(inputFileName); - byte[] out = StreamUtils.copyToByteArray(in); + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); - String content = new String(out); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } } diff --git a/libraries/src/test/java/com/baeldung/text/DiffTest.java b/libraries/src/test/java/com/baeldung/text/DiffTest.java index 95370013b6..932fc96f21 100644 --- a/libraries/src/test/java/com/baeldung/text/DiffTest.java +++ b/libraries/src/test/java/com/baeldung/text/DiffTest.java @@ -6,13 +6,13 @@ import org.junit.Assert; import org.junit.Test; public class DiffTest { - + @Test public void whenEditScript_thenCorrect() { StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG"); EditScript script = cmp.getScript(); int mod = script.getModifications(); - + Assert.assertEquals(4, mod); } } diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java index 80ca0cfbba..e0a00afd84 100644 --- a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java +++ b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java @@ -11,15 +11,15 @@ public class LongestCommonSubsequenceTest { public void whenCompare_thenCorrect() { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); int countLcs = lcs.apply("New York", "New Hampshire"); - + Assert.assertEquals(5, countLcs); } - + @Test public void whenCalculateDistance_thenCorrect() { LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance(); int countLcsd = lcsd.apply("New York", "New Hampshire"); - + Assert.assertEquals(11, countLcsd); } } diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java index f08b43f69b..4ebf00e1ed 100644 --- a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java @@ -13,12 +13,12 @@ public class StrBuilderTest { Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); } - + @Test public void whenCleared_thenEmpty() { StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); strBuilder.clear(); - + Assert.assertEquals(new StrBuilder(""), strBuilder); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java index d559c3d408..6ce11d1895 100644 --- a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java +++ b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java @@ -13,7 +13,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; - import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -37,19 +36,13 @@ public class ProgrammaticTomcatTest { @Test public void givenTomcatStarted_whenAccessServlet_responseIsTestAndResponseHeaderIsSet() throws Exception { - CloseableHttpClient httpClient = HttpClientBuilder - .create() - .build(); + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet getServlet = new HttpGet("http://localhost:8080/my-servlet"); HttpResponse response = httpClient.execute(getServlet); - assertEquals(HttpStatus.SC_OK, response - .getStatusLine() - .getStatusCode()); + assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - String myHeaderValue = response - .getFirstHeader("myHeader") - .getValue(); + String myHeaderValue = response.getFirstHeader("myHeader").getValue(); assertEquals("myHeaderValue", myHeaderValue); HttpEntity responseEntity = response.getEntity(); diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 22a027a58e..8e84c0f364 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT jar - spring-5 + spring-5-reactive-client spring 5 sample project about new features diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 5065457c4b..abd8e42cf5 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT jar - spring-5 + spring-5-reactive spring 5 sample project about new features diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath index aa15485f5c..60dbd696eb 100644 --- a/spring-boot/.factorypath +++ b/spring-boot/.factorypath @@ -1,149 +1,154 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - + + + + + + + + + + + + + + + - + - - + + + + + - - - - - - + + + + + + + - - + - + - - - - + + + + + - - - - - - - - + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + - - - - + + + + - - - - - + + + + + - - - - + + + + + + + + + + - + - - - + + + + - +