From b7ea20cf99e620a8085777a204fed81487792639 Mon Sep 17 00:00:00 2001 From: patkorek Date: Thu, 26 Mar 2020 12:02:03 +0100 Subject: [PATCH 01/97] Postman Collection to test GraphQL endpoints --- ...GraphQL collection.postman_collection.json | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json diff --git a/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json new file mode 100644 index 0000000000..7fcaa2c76d --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json @@ -0,0 +1,169 @@ +{ + "info": { + "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", + "name": "GraphQL collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "mutations", + "item": [ + { + "name": "writePost", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + }, + { + "name": "queries", + "item": [ + { + "name": "get recent posts", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", + "variables": "" + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "recentPosts - variables", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "get recent posts - raw", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/graphql", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "00b575be-03d4-4b29-b137-733ead139638", + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", + "key": "url", + "value": "", + "type": "string" + } + ], + "protocolProfileBehavior": {} +} \ No newline at end of file From e189686b4a55267a1a0b369ef0f170576b2a0eb7 Mon Sep 17 00:00:00 2001 From: naXa! Date: Sun, 17 Mar 2019 22:24:10 +0300 Subject: [PATCH 02/97] [BAEL-2749] create new module `dbunit`; add DbUnit tests: `OldSchoolDbUnitTest` + `PrepAndExpectedDbUnitTest` + relevant data --- dbunit/README.md | 6 + dbunit/docs/db_schema.png | Bin 0 -> 17099 bytes dbunit/pom.xml | 35 ++++++ .../main/java/com/baeldung/dbunit/.gitkeep | 0 dbunit/src/main/resources/logback.xml | 13 ++ .../baeldung/dbunit/OldSchoolDbUnitTest.java | 111 ++++++++++++++++++ .../dbunit/PrepAndExpectedDbUnitTest.java | 103 ++++++++++++++++ dbunit/src/test/resources/data.xml | 11 ++ dbunit/src/test/resources/items.xml | 9 ++ .../src/test/resources/items_exp_delete.xml | 8 ++ .../src/test/resources/items_exp_rename.xml | 9 ++ dbunit/src/test/resources/schema.sql | 28 +++++ dbunit/src/test/resources/users.xml | 7 ++ .../src/test/resources/users_exp_delete.xml | 6 + .../src/test/resources/users_exp_rename.xml | 7 ++ 15 files changed, 353 insertions(+) create mode 100644 dbunit/README.md create mode 100644 dbunit/docs/db_schema.png create mode 100644 dbunit/pom.xml create mode 100644 dbunit/src/main/java/com/baeldung/dbunit/.gitkeep create mode 100644 dbunit/src/main/resources/logback.xml create mode 100644 dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java create mode 100644 dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java create mode 100644 dbunit/src/test/resources/data.xml create mode 100644 dbunit/src/test/resources/items.xml create mode 100644 dbunit/src/test/resources/items_exp_delete.xml create mode 100644 dbunit/src/test/resources/items_exp_rename.xml create mode 100644 dbunit/src/test/resources/schema.sql create mode 100644 dbunit/src/test/resources/users.xml create mode 100644 dbunit/src/test/resources/users_exp_delete.xml create mode 100644 dbunit/src/test/resources/users_exp_rename.xml diff --git a/dbunit/README.md b/dbunit/README.md new file mode 100644 index 0000000000..383bd6fb7e --- /dev/null +++ b/dbunit/README.md @@ -0,0 +1,6 @@ +### Database schema + +![db schema](docs/db_schema.png) + +### Relevant Articles: +- [Introduction To DBUnit](https://www.baeldung.com/dbunit) diff --git a/dbunit/docs/db_schema.png b/dbunit/docs/db_schema.png new file mode 100644 index 0000000000000000000000000000000000000000..d9185bacd2c624c8e05aea87bf542cfdfd7f1604 GIT binary patch literal 17099 zcmch91VJ!}GI}RUv>+r(2*N1QqxWuf5_R<6d+(z6 z-!1Yy&%5`2fBT$$UFV!XTv)U2wZ3buZ~d&#JpnIY$Y5iTVIUzPVav%%svsfVi2;60 z(eDB+822AMMnVz~my;BG<)XV4zoAOL7CX9s?c%i38RO6$T#=SwZAPC=hhk8vhx^8Q z*#LRjxRBks5RbaoFYa^Wn-AE&AA=r-3LTBMOb=R@GsRgBsavVYrG>wGOr>)A<@u7s z^fs|#&Wtt9po;d?v-)=(LkBv$2R%Cz>lKM!Z?Tb(M9(jn_pok+y9+`_62*OwKtk$8 zo&_Tz9UxT#?LtWZr<(&I!)U8__hyKYxIU@CNRd7xgOCsIRBmSfPkxJaK+5s27#r~* zG6v{|b|Wo_IW3hMBw6xVuqc&L6v7t0DSG9~u4~{8J^CJ)nh02y2NI}y{pRx+^Gg$FS!w(9&E1EFBz$I6)Zflx43pyBK@pRkNHk|*mL@sdv$r;pt=FadpwQ?=zHNdLYUp` zF=E$=R4ZeDuOJz%!k(2ue$8WNeoEsp^^NH#@Xo(m(OzoI=t5# zzXlZrt-6`k>}PDay%Fq$Rk^rGDj)f3K@vy3E-Dw&-~b*&gh!uFTJcZhM}TWc%fgs1HHhc(^S$SoaX%_2&&^E=uy9?xVmmd3L1=gH@|d3U@_L+}J9#zeZdmZmu-5Pbw4##7NQ+(l99IQMFD~j3~ zbQ^50WpOG3nZE_(Y=$Hm&sz7~mjU`Kjq51&gG^89YIt!*& zd#WI1JErze&qk;QrQdye`bWJ35d(&*au%Wk z>GREqQy__f+kVP0D=Mr)x7kKs63{&`nqOAtAk=@y6kYLS6UuX-|2dD+_DCTp)kbk! zMu%93iQ*MAHv>%bql2bqFd`-Bje>Pc>Tdyr2pL{7ok#oU#wAzC6C4uvtM?uoUD_tD z8Il$6iIs&L+Q$gJ0Yyw+TznB_0F(ic`Q{Of2`GA%yW{d{^;Tj?t#3p`_2ebkcQHxJ zT_Inr9}12`CjHd(3I(Qf_%d2F>n*8mq;hoNY;n#b41%YA9tyL8f6xA<7mAdG;+GX| z08>2E_~5-fd;LV_+Jx9rDmq(0T~~N)%ABq2lanb+jo{gC^ZNGlT0eZ&Ds!A}P z&Z!7d-FXe~awcmkQp;}64$Cxl?*^!7_RHu%(mAkUpCtP)vz0}zRS=PmeGAhJla^!Y zbdm?`!7H(iL7$3>Z&7{EFOmYQYsHjg!btT9pP+}A58-s5x01!rOF;mIu_gV&M3|oP z4zv%-hpCP95y!Qgv*qNISW89c?Bv#rPhvWM)!zc^z;g?&%=Oa?XzLK@Ogqb~ov*bM z3NNKzcKbiLzNjTDv1N!Kc{Z20%|cif-mI_1co}$QUZhS=c zbdFS;ch3BKv~_sr2=ol5$Vs&-#au{%{V438AtYIS=~UMhJcfBwXi`UOD@(~OD|Uts0`5LR5F z@WI`q+3^4-Dv%@4YLZbk@vep@8L_xbaFiaFR9~->;+6fkB*3~x8o4x!udD-b~nU(LH{#@0~J3n-cgI|GUA1He^offg31 z)MK1Tcfbd9^-t4vqIl;;qz4LWJtB!qy6h~Lia--kA2Z{yGHdpS6xltr(NfWf%x~#? zz3zH`t3eNZ@CD_qg~j;Eq$RGrnJy+2{O*5PK|+zV2P|O7VNBdvfr{X=jSau5bF{MN z!6~7z%d6H7d8K2-JUp0bEf!m`==eMhvTW{w7rVs>@71*5SB4$6*goZZ?K^X&5iRP1 zBPvQy0tng+Dp^?!D;=Bbu-T!)KjJWf@v>+->6)1OeDA3Uw;h|4PThJA-<;IzJW$A< zfPPPXG!Dg!q5K^UN}wyjE|6rusxaB!X7JeVx(5=@z}tpVDXUF=$Z|6R1_& z9zt58+uSl_-=svJLwzU%fqfInJ4Q$fet0hnB1|`6(&2el+aRLopRT-tB{GGnBmFWY z5Uq8tEwb{MZ42D5zI62Qnb2dWh{kzG0jrVEUwuy>mB6ka?OT2{Flq04QcNb}lc~vY z)kRMD1g{c{R_!)s%(gg8Lru>F2^^L_Jvtzn1~2du3Pp(Z=Ku13Jad$jw=l5VH*si! zhUpzfJD_GqT2fq6ZsI;nrG<5B(mEk8%Qf)Uf{D*TX4jpxI&xGqeE)uU@nG8iDcCX* z4^QsH?|>q?1-^h_gF(KP?C2euBKXnH8bMVt0VrZiJW8m`XZ=T$UYj_3J6ZV=*qvuJs0Gm~W*xe~S=_I~)B`5j7q|nasUe$W}_1JvL!uet1bvSkAW~|#l zg7x0(CVE=9ceQ=k_MO_j9oXDQ&YSJ!B8&kx(LsmUq>zJT{z|kmuT^U@+b-=R4Dl)T?gZIpq{-GsHt7r}(WGoljovf_K51o8tX4=|s^|4`7@46$FBH)}pl!-^t#OJCm-#^nTeZa-5Vg{^Cn8;_h@&^8KDt)A!a*ZZB+S zL1LUr?C*96rD|h59Jp4UN5=C@lz8U%V;Y~Dk@p7u<$eaX!8Oi|eXTXJY9#p$n;%Le zgD($W?Y``PvDjtVGv?<(>{vEI^{#i>AXGj!u*xKi9+EpAtjQn3666im4jh-hXxxjU zkk+1T({|1qQXuctBxWvAv!3|wrGMe%8WObW*G|VC@&4 z?8!RND4HxeKGOaJ^O~$Psrm3 z3%5pc`J|CWzAf{fgn-YTD%hxl53*!nwK1`>$iYRgDYNl=?XXVw<=1Ou|Ln`*0@(1! zy!2+oyu!eyX)2?<5y7_d^2CckaMVGPu%-+R@62N6rma#}Cz?3T^@aEwj-TbBwhIq2 z1cYexl(JSe#rlvx0+Zd};qUXV&P8m`b{pt0a3pRKW|;j4Rok6TgHSm==pEk!5j=Yqznef{1(Q0DHgUe6)f5sf%)paqr&)!1Fwc*4Ck#kKnoFyL zLtVDOs^=$niu=#+Ip0&%W(C0l0&DdcYQ^_=AH}+ok>!-6gnZwq+gUZ_!;e|bEuyoC z-qO6s`^({R-NVNUP@R$>2j5GHtJxF9&IrVDabqu4RJ#bWR;?g1r--~h z>{QMr9j5@Hi2K-+%{!N&D3{x00dCim?nhFu%xd%)#%XS&Amb+4 z?OX)CMiPciUY!i5^9x~?Nmfb4(C12>?-%1ERIh6dY95P!aoo1*neXopzxHIELGG#+ zBKn0}L8z%<+B2NZnITJtb_n*pDw-gI8^`i!eH$Aa-q<{j4hL0tCag)KZi92UIeK(U z2`6Gq*tUy$bfZU2z~7fSyF+xw=?to6E61?(O2hqhPol)kus%hmN zaa%h(j@87(!{8bHsQDIs_4LhVR%FA?4)1$Aw(>N`3jW^_pt2Pdv~BQ{-sOZ}_aqwq z)<#XBd#7fU|EQ*=RN&^8L5xlDqbj?sZl3wP;+isi33caX#K2p7|s~O(G7? z-vnH-W{Z?Pvhxz{6!N=03fXQT39_G>m=LIzDkR`vt>!275(RxQlC3z7z_7vwLJAZ@ z&ugmz>K95P>G7u5k=8i0il=qR>vrN}Q4h*#Fvtqexnd>>UvMhW`rZMJCI2UQH0ZQ^ z?A0@X#c0VKiEK+whj2eO2R)-tl&CQeV}hAko3aDt3{X`xIZ$iDIP?zDA7M?_tl_zb zDUwV*)QoYnFSa|Oale>2J9_THW0gfp>P0ceCom=KQg&vPmp4k!Kdk8ZZbjxhvzEz^ z#@+U_Am@p&WAdJ(bX4uF%`+4;R&oqBVYjZDp`+cyj`8O*Z+Z5)aZ1{q*e~oCW+nK3 zS#Pz!yPhgaj`Tg0aKw3X1#hG!uXlJz#=;?zC*gZrj^HIAS0Vtrl%(RULm0sPk6}5* zf=`b9Ha^;{JjdN^7AanQ5ECysog6gMhTin*Xx2o(Xm0oFM-@weq5+QxzsI6kie`O7 z@0+#LHTS`r>hO2meh*k3<^*&lboOWWT&s&hDPM4uWi>(y_AZJpQxHC*ZO$2862Amh z53G7c6*05o5;SGXXpMatxJcy5XPOZW!jIRET_}wxZGW|R#2!DRA@O!4gJb%elyL>N z-x#_3Kt*oUx9m0a5?7aW^f3Z|RIiY~A~<@Fw_}w;;ovY&`LW%~qT$KvVaLK}{bQ>P zetuZdxlDY)_AXC&pDHdGM{EqU`l3XeO&R8NKD$M%DtTEEU@X7M5H)^UF&7a^&Y8Db zOdqFF@ul#HBu9Y|3;T-YKkplaY9AjYp_tyEue;-aJvPBUAbO5x3nR@HI;qrwa2LtXPc6oTB&S;9U_mp7mDFL;gVNc2I~a%uf;*W$&HE7e>4UOC}|ii zfpLf;KbO7u*d@DC0bZC8wm!2aUz-4io>N{7dFrTnM~eSEk(08;ME)%(u1|}%(BmB= ztg-ja#dJN!zlgdH04SW-?90n%=YDqvY3%0~ocv_M1XD6~q^DjEg6J|W0j=Oq9HY1T zmxq4q#V=t79ichsqdq=tnQ5D6*L#g^R@-}b+wH2uAGAVImY%Nb9Qf(kNWI)&|1o^k z-ar0M2F@r3;}HCq+^DiYAi%}f43YYSVk#F$OzQeWKoqbQYSP ze!dnYrU|4}&(Nq39su^0YXMU`Ri{gI3K=HvPkkud??L@l?eju^g?!|#F{S#jPsQLr zvuim%A^ym;d(MrQ(mQ-(_!zWPXwQEFHJP)6qjB)%I;9@j6G8?+#Yu@~!H<*kk{fR- zMR6~01c)dAu3#HPqW!1CZ8p@24twC}x&h%6=-fJ)ddK(7seoSqj6?ouWY#EuD|~u( z5=g!cjUP@eUY4(V=n)QQ8!Nd$uXRpVyE+CU@;IB(6H_FubXFQb`)TLnpCT^16OuMh zDTR9?U~#P(6KEo6#_x*Zr*_gq?G&;n@UJLhf{2M7kzEd4?rwz;g-%v`Pz0q)Yo(=K z4AhL#k%y;Q_vhq8V_kLj6}VS*Q$XB{o1FOXz=pM>Gw-3Wy^$QPE4t`7G-1r|wjm-S zQd18xD~<}To7Hn{&bu(p|KYEm4#B?CXwrA=><@xSe;ICSoKn2%(tJXd$l~~uN{wVi z^hEDz0JW^Vas@A+$Ry;OVoWhbv*PwxCIYKiV*Muo$8fEbiR|`NZu}~djYuuDa-`uK z3-&0;xXG;F-_}CoIxR9aPMQZf*2d9sjq^<8Se$w`R6B2pc4vGrQRn%0ihQT0&roe% zcR7&=j#@pj@6|Q{FMd9WnPd2;xU{3)D&DL!TfT#EZVceb7&7W)YI{5OknSg`+7mD8 zJ~n#zY=Sq1O^7fu<49{TrOHQmrwZpRF4m9~+I(`0O@Y!gr=BFfe}s~Tvz#5^>BF0^ zPNp3Y{vxl9ERCoZ`CsRlP$|=_zB}F@h>yVK)Zv$Q+LS$+Ri@k^oU_X111(7R%=M_X zklt)flMp>sk)i4bPz06A6DLy6*EV(m8*dX1g-A@Qn&~!w>(}4O^zRI3e-fI$Oq2ea z!d^2f7lA{?E2%SVyIqW`&he4_b8e&o#CXeC=g7X0*n#v(dI{yP2PUtk#u)I?@V9AB zXIrpfa+M06vXq?W^es@?PeGU-OZXBdA8yN)f42JWR&m9^lvF7ra|P$P)h2V0YrjC1 zXX(bVlV@SbnxRwv9y2+_SJ=3(xH{Ze9@ua;nb$t<+{sJP0rk_>UT7%8N!~nn(9|t*bjofw!YhkPcE4xi49HjQf@-cnHWR(CozXoGwU<~= zVf(ViSQLjvoH1ZlZOuhAxrc(Rs>AI{Okl-6R)XCAt}5FgH7}A*tZmDgtq^dp{bifIn4=x&-vONm|JDZCe&`ouMvOI> zEO_|(9KQJ1lnlGM4vk@|kF!*)nkVC2-&o2x8 zuPPcygj%8F(0(E&Y-lVSFbcyXMw@AK_ZE2vR2vn6g?m%*g#_l7i+ zHj=a59LHDU;^GgdZHiU91uC4gRWGnLvH>g|@X*Pj!1HF#F-4}d55~g6b$WR>8SAqL#OjlsX&} z0EQocs$Y3@oi|NUfTFLVG5ICt}pLtVkxwwhXVWKf9c088HY zDX2R=AY!Jlap%o6#!hW;%cwlwZeV+kImSp>+i=SWM!E>^RkGySeg=b*%%ar6ZBP!Y zOuj>odk*1Gtr(wKqxye9$huw1va?S|S?JR*RdF{@p0jnOo5qzK_t;WOAYHZ88S8i?*4#~cLNp^V#Kbn8l?3?IKDo~qhSB$;^T*9Wq?nz30v zdYE{KCei5HV{4)aI)0Tm`BKpM$?GYFxd)BVHHp!uzUi7(az%)6Ovr1zY(PxK+24Z` z-Jn&rnz0S!&|WTi<{J=hw%Cz+_H1d#;1JiUizWzLdVW zZQ&1uq`O_2GD^`TU?Ra#+U1{N%5u*ZyBOit{b_=v-<<_(z6{#T6+}|x6n!uYCPIR> z`)C<`LnN7@K1KQcx!H*{DOVTL(tE@!BnSic3@|-u5`}FH#(M-k9(Tt-9q&uthGJ$?g}2?<0%H}-VlZmhAW{qIqTCBFR@5jh;`W{Tp6^IRR3@6$=Y zp!}9V2g!&giK2}b5a$2DpQ7JbEO#iYhB%)loS(Lp?kmRxpPi&c1Vl)QX5UNz^FvI? z%uHOdXc1n|&+)pRY@*Dl)5v`bO=!yuO>ArbEwR%byJGgnpeK}|2>QnTK4#Lxy+-Id zGN>9!xjGoEX$(sgcHJ{}w|0GF$p3alKEk`1+@|5(Zp~eDa*Ia4_q!S?8BupK zAJiLh8P)B%2=nQG?&$gx?m~YaZHmh&ukDQ5Qg`)(sy?+V`3W23-s6!`d1y!d(bi!- z4I^ijmJj*4u{^Psi9n?{h{jsmv1p1sk!bruWhM1V_{m8)NJ0?UC6jP)ve2tx9{zod zg$wUq_a;$$x5~|#yT4Bq6R)b%yvMWV7_&pmx^HyT{#%etKa?TJYN46j6W1%tW{v7l z*N`nzWaXlviy{Vx+j(*+-6GCWsa^ONH&rk9||uKd+x+SQBs+Jv!x`L&5nk?}N7CG_E1wjbQD0EBMSIm|Z09ND z0Zb?2^d$UsF@<-ln`zhF+HCC}e>YUm^R&7=-z}4-rEBGinB>YkUuW6oP9|!l!pGHV z=)5Kp5@_J@S>5>I<=Xr2cVLWuz;1|OBhb9!PD_$@a)hoj5Dg+|NjS4$O8jf{5rMNS zN74TG2**!#1x_Ab0@P*=Pyxvqjp{lP$}e0%r<9!>otZ=&Su)!goWA3s{2e7UdhDCY z&do=TGmyhkA?Xqa9%UQn19#+*K?5}ZOudHZp||z_YWOT`-DmPLtG809B8StTBVnuP z>9JjD-;KejRKWg%=vC84;_~Y=MS+>2+s2T+N0g#hDrmn)3<6$MssTC%jZnDs7b zfOrj481k1WpsSpHoz6T7_0M!D#I%@;eoZ5cu`AG&qdw`~qG`;S-K4{ai zCSeV7{NPh9ch(abcWk&WAPOeXklx0 z_FSRtd|EJ(&2R2lGShiBd2iJwVid7ai<3-@wpO}+R9I}tTRkSWPN%7cvpE*po#SS{Q@V6}MtC6LwIH&P% zYW+)fGaa3r#LmK3+y}Gj`OQX*wL2bHHJmd~;SBXXooKgP`o5Y4VE$;X6oTA@rcDjf zvB#{K>$~1U3HRlDwwPEW^QL|-xJ=f3^u zwaF^!4<6~R)rvJOB<!r620E>`aI|rJnF_Dg+o)>a&wL`4KnO3roch+^~yMuT+fh zrKZ+Rl@t~3(N#+Ny%T8x?=a1n zSKW#|E7>-RS1*f)hVcdEjF-wnxJcw@tT~B;(Y)O4t9uQ;m&l(b=2B87UsAjA1fSas z5o#$$eH%_2sug|QKFPMB^&crcD(@7pxWH6@jAR?!Zq^sN2O$5+_56s{#5ostk#`d z1^R*t3phmi4kTB<&35~Sl?07P2C1UmwuqUxM)@KJ|LUy;yR!~h=l_PW|BDTGL!s}} zPv$;SH9*O397dnhm^0T0|E3d4Y|sGSt=|BMVt+Xkz$^dpFwKAL3~&$+|M&yj7-Hl< z-ej#&vM0akg?<1SKv&K5>SJSXok1Fz=e5 zCNkPY6`@!>E2L@VcmG&&FSI2k;LYMdce`1y4pY_L&uVpQrK_g3V!i+d>NA{m&&GzI zH7yd;mudS5Rftl`*j@P>wd}aMAm0v^g<~KIDd6S+!BAmuW1Q`3bE`tiM-|lFG~agm ze}JELcjR={+RBg)g9geG7!&El#%E0P)xk->tV6nk%a-m>=%FlGKHTe>$>G2>>38iS zxLWHLSC&`gN=$-usWy&H+hYiV{uqN8Y)`+dxaV!mm1oR-F0mK`p0AjSfES?7oEIzs zsC9-A<2EY^fpsRH`|1wrM@neoLA0>Bn|uCYT(paArkoQP>g@qm<|5p6(!IvG_Psq9 zNgkw^7m-jo)7FRZ6kak~sFggaDZU1|9~dvKwMQ8P^acK|2pT;b(se$9?|GT0`EEw@ zjin0nOOk&(d8*Bd7A1K}3ysEHb@uKNLq zPR-h@Z9vt4mz3p2#(>k5EPwP4hui56M~~A}r>IGH+8jIjPqEN>J?=kN?5t_Kz`q0L zx{MEif04vJ!?cOnBM(eyr#96%Z3wqH9~#~>J6YX2EAjPfkPVZo0B93V!$-kAXA(g) z*PAYG_XCWptQGH>Y@;Wz8CC!kB70#ml_&w1It75CJBZ{Qlc~c{6Sa7AZ5C9Ynfjh$DFScKj_Qm3Ns9zMPg+hVgkcb`+cj7p zdENnpg$zSqZfJm#hS{jmfOErlB&Ax;wX|oK6uOonG;K0H(=E+2G98EB_dlr(hKT0r z0Sm!_y(Q&;`2EEd<_&=@tVyf>L*9tPf!P!LXD{`|g;-V^tWOqIU95h}DX+@NceR}? zw6*lD9W~|*J+ZLLr9>CVIM@znyI5Y^tNv{3QkgL+B?)no zbaW-RdP7B%)z6!80Wt5hq;}Dr*QW9K@=s{$8cT7;BXcTbWh{g(i^q0%thtmDpAt?V z5%(*@Xv!4-Tssn7t7}{|=%AK)dduHhaWI8e;F=*0>s}E3x}k3Runh(5L3w#mZK&WA zsvj~18jozSs%-?jz82}*(Uo@-OdL#@cFgNI4Ns^M??G^ZV@9zjKem~SRH{YBO zn~4O!DQMAd*CqmnlG2GY=P=tbsQD%Su=OyM4b6fB7FL>7nln;8=XJ!>$<-^2G6^Mg zLoY&vRA^C*#tT9pi~vVXQu*+=iV_TgXwE&F(jc}Vg05GuH(>1C*c_h=2GRl;Fs+>6 z$KB`A!+{+wS{Xl#zwc|qru~&}t_CCE#~v~Oy}3=&{P_oYH~@Uf4W3C|W?}U7q!eKC!ALEZsahr%yz1HC3s{E$6a<S&O8BP!;-*|co0la~~R{eWIAW3M@VX%fZ z>qcl}`YnRyj_ zYeAw=nAmsv|8b`AzcN?Aef*WagoA#}G`EHJ68hOP`yFyDSmv(*crSoWVXLfye>YsY zBCi|Xy+N!Rp*m4@XVFbv_vIye`lo;G*VY9_S1h?l0Z+Ua|D)tDGlbK3r>;->JF)hv zJ1cJoqXcafa}Bo=)aUJ7 zjH^_E`{KgESBhtE4nH*7nL`|)3;(+DDPk}?%Fct~)|xhG0Lf3n=I-`2IwjSMM+V;- zW|%P#Id07Y1-QW@+b}c$5dgU3(@*?=uG^Ku>eVxBG+Fu81|FoNK6gofdX#n^0B|;d z%LNF=t&=j#4RsAe;In*^`w}(onyx<3qQIRWWzjoL!lQIxqPQCg!0)edne` zTr2KTrBZEzhPg$qfanOAKLxyVQkxzLMl6rZhJ$%nI81&SFbaWu&!QWee=FVCN=_)_ zZdjJb#VnnwV7HFgfO-%Dn)1|_IoT&VvFGM8;|ox3qgEn*zKwpB6G~d*s*9;Qz+2^d zVq4qjZxj|UE7sYwd?Rw(t->Vc2&bDm_-;5|&o?gk4%jYMv}(&^!#4%)6aKvTt&za_ z{2Pq~*8E!|fuUl?|D3ulER8!q36Uhsa5HwK4r*BVf0xt#4>axH#w6J)%l>*=EC~bd zrG7FLowpO$mV0A+muCoU)Ifr)yf(RBxY|_efbh)ZX6~_PM7;elyjC^78TM{cr16hj zrY+Ev3e)ejDzC#LsLf=4-%511*WvsAb1i`dcsOwk9jCFBD43QAB`8R>cfVNd%TZNW z(u_`5{eVvrAzYz&oPp{#XZHoP=QkThuJ*gg3yArpVeQ4{lsaqnXrCqYx($+B<5%F1~bhYAeEAnh|6ego`bb*t& z(vIj_7})YnMCKG4>zj}3m*O`JLDZy%v4y}teK-EJWr+Vu-E&|{xj^J0MyKm`g~kfI zjrm2$+Bf5&sr}A#iJ%~WrzCs)d6f+Kl$T60O}yaHs|uBVUSkcA@+1(>=vjzbLqumQpHbtxUhLfFFcL^ zg`ixVf|PZS@c7Zt%lK0j&;kaOj3vLgk$vB1bD=i>EKBNwZ@Dx!So0nnM85Fg^tYfpz*WtA5w5XVa;wy^sN$>BUSI9*(Id)OJ)wu_IKwKl zV2_(1>sZ}6+E! zv0jl&8?;tjVx77~e7@k;!%ALgMhAbxe~*I@7|Zvq80Kmdf3FOD%nPeQ+U;b?feUH3xIqf=6% zlwp*@)}N|!?>K07o;k)}hh@G~U94z#fYp*()C40Gx+L7bA&Nn^nx#o52hUDFsea{L zt|Wn5YPCT9C(GNDyi!V<^tnk_b7LD#u?1?z)7k$98zgtmcWzSh&m*7+7IV_A)Y^Ee zT*I^Icnb(sNkQj_0;PzrCD*P%`gJm<5|1!09mcjyOn~RQMi=#)ndWwrP1FYop}kPD z$*2x8RaLh(DV0Y&0wo}@@{>>LjDPrr#mO>D2QgPXO=SH}uYDsI7!f`;g?ho<{fazvFHe;p~84amD zu3z3MSN*zpHi!-I{?%M84u!Nx%hrgu19OVv6OnT=qPvuYg*8bX6Q<5#4y0mG4JDZm z&AdP6VrT_)mAglKLg2xrBcUkB3s!JqX_b6!)y~@Me#^jeev6%Vck8^#1os(#Su6Qn z{9u(LCJ=}!ThHZT*R_f`Pk9gEYqy95SlOdUGq-&t< zW7m{NkEscc-X4i|ViJW^ZBX6rMjpC3w#VqWh^ChI&Qp_dF(WaU+mh|&?9itR))G!3 zkJp$~d7RFZFD~}!(k#8$>ky;+ojJ3Z?;h3Zy7H+t2|c3ueXjVRRE1_M--J{66;rsG z$rxrFT8qhL<4aqBFRdAY5K@!>vizU9j9H(AZG$u>o(WR?UH#A=a&Yq4>aT(SRt5a5 z&{J2s7y1I?C(-xHldST3t{LT;@!mEwo-yN`=TF`7$LIZm`s78j&TRVb{sMkfQ^ zF+`4GC2Wvjf~I2@{QruHNY9)EYLwCkf31bmE^aUjyJhkIZ$Kfp*Xi>5;DUL6Et|rh z&YCqo(Hzx*H4<8HKKNv<8^Dym<~am~jp!ydbw14+K1R*jDyksbX$+ukfo>i&UB;cl z;USarBJRF!Hmt({S-_!rOt4^#%1m45`i)zRpYik(o2i#v&%cL9Ztmf=(ie4X zYlieW`gkvJ=@Rj6H7|UkZCbQ9rRD7`RyB+xKKd#oBV~c;x50K)1Fkkv{I#E|$0eg< zQJs~XX$x9oEjg&fm~3HtJ53C^Z+#nQUwRPJsNKWKo8)>FyOYzPo5^~E7Wmk61^Zth ztECA2DTh^7i%Wjlk$<+_k~NI9;eG&n{1T7ADtw4?S~~98Az{B<6;{mBGVQu?LVoa& z3K1vs>MJjZaduU+r_-~4^O}(UbB^Zimzy_0%caXL(8B$w@fK+e2g&CPGmMosMICy) zYK>wDu!|{+i$owAwTciRrcb1AW778TFBET)dLs-lES|$zobHuI49j$q`g^d_iEvPM z#tfh6DN6GOuM|6Y%@MJx_JZgr4|_oa!oQ1^C`S(k!#S7tjMAs$6B=ebV-ywYkM=>F z+#KA_N-tmxu`H!yOVbOGD9Qrr^cqBAQ*8QZxLr7N5+^;2;&Ec?W&PBfsDw(3yrz9v z&<7ocd{f3MJ%-WbQQ*C&InNm3n@g5$@V!G0Os%MC^qqOm&n(^0?|DrG4!()-$35i; zBTR!9yO>w{UD1bW>TkNgaKTZJ;Rf+@tm)NE&%EHWgV5Jfhz;qEM)%M$gjc9*xkOP3 z@UofaXF9P#7T+C?vfG-FF+0?(U}JYn_+m}sWOrm}E3pEgU3Egu@=T8`*{)AO6t4B~ zYsC6+zDZ_t$0S<>=o4uxw9|XHDc0xkvBswaeW%2aW?yUf4+F>r?Zc7~(UE(BQ9vYU zj1lx%L5$}8><<5?^yO=QE-zR_`tgb5)~1#;3&}S zP@p5hf1Dw5Dff(5XtL67VZx@KsOPi%83Z+~4oISdf^^h%bf%j6dwXBLe7RdabNQmi zKQMCvd`0JAyF5=6^$l@$^N#rd-hFtd5jZ)Zp#G{VJDZ7(P3flJGI*O#KKujl^0_Q8 z%$Bstx!#_QTcPVRn%mX(#2zCI1Fj)ul@7w=3` zKtbIZMwjGg!Nt3AT`jCqI2|1w;vYr#mxjf{#nG%REhW!ouqF6m$qo`veAOk&FLUb8 zn7IhH;F+19^w7F`y1ImBq&@G+!REHW?ImydC{~Sn6|T6DkY0Mr-`ura?*70vCDTOa z4!b%lxE?p!>O3-|n`ZAJVq{v?S zDcy_Sy@3wO2WAhR~VEP8^(Kghuf#}(c^Wb z6kYOl?c~F-sY(QS*BsB>VDIE)r{dShNS&bCp2u(;6)ba;y;kupYJS+B6(||nD-7=n zQ&E2MRWDJ-{@w+h-VX?aYq=@ocwtQq1@~BQ!94&gNFr;mRLIw9DQoIItG~Y7QMSOm zA5wqSR}U#r{m=^y-*{>XOOB8Xk`0$^5i@yP*GL-9JWF*-whSECl9)$lN(ybe>OCZC zO8SLji%lUG$7K6sg!ObyyUt>!>e%4mD{bwd^!kfm@{588bQQuXsOH&=%ga|G&6Ygc zdBYY(pa^ZWt=>6Xh)X@zp*j2|if55bF?^O;*3&2qLEi&_Y24di2>QlS zrkTy90&fqbA1bT8I=|8>HNYi8#qU@Bz+cpZcQAOK#N%*CBa>jf!6(*!lF}KVjSh=3 zQw!;w2r;Y=Bu9wlBxC!<3p!@Ey>H|888U3p_;S&9QtNeL*=N_cmV88Z) + 4.0.0 + dbunit + 1.0 + dbunit + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.dbunit + dbunit + ${dbunit.version} + test + + + + com.h2database + h2 + 1.4.197 + test + + + + + + 2.6.0 + + + diff --git a/dbunit/src/main/java/com/baeldung/dbunit/.gitkeep b/dbunit/src/main/java/com/baeldung/dbunit/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/dbunit/src/main/resources/logback.xml b/dbunit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/dbunit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java new file mode 100644 index 0000000000..a703863614 --- /dev/null +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSet; +import org.dbunit.operation.DatabaseOperation; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class OldSchoolDbUnitTest { + private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; + private static final String USER = "sa"; + private static final String PASSWORD = ""; + + private static IDatabaseTester tester = null; + + @BeforeClass + public static void setUp() throws Exception { + tester = initDatabaseTester(); + } + + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.NONE); + return tester; + } + + private static IDataSet initDataSet() throws Exception { + final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); + return new FlatXmlDataSet(is); + } + + @Before + public void setup() throws Exception { + tester.onSetup(); + } + + @After + public void tearDown() throws Exception { + tester.onTearDown(); + } + + @Test + public void testSelect() throws Exception { + // Arrange + final Connection connection = tester.getConnection().getConnection(); + + // Act + final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); + + // Assert + assertTrue(rs.next()); + assertEquals("Grey T-Shirt", rs.getString("title")); + } + + @Test + public void testDelete() throws Exception { + // Arrange + final Connection connection = tester.getConnection().getConnection(); + + final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); + ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items"); + //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); + + // Act + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + // Assert + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void testUpdate() throws Exception { + // Arrange + final Connection connection = tester.getConnection().getConnection(); + + final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); + ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items"); + //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); + + // Act + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + // Assert + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + Assertion.assertEquals(expectedTable, actualTable); + } + +} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java new file mode 100644 index 0000000000..c3882d5eab --- /dev/null +++ b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -0,0 +1,103 @@ +package com.baeldung.dbunit; + +import org.dbunit.*; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.dbunit.util.fileloader.DataFileLoader; +import org.dbunit.util.fileloader.FlatXmlDataFileLoader; +import org.junit.Test; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; + +public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { + private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; + private static final String USER = "sa"; + private static final String PASSWORD = ""; + + @Override + public void setUp() throws Exception { + setDatabaseTester(initDatabaseTester()); + setDataFileLoader(initDataFileLoader()); + super.setUp(); + } + + private IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + return tester; + } + + private IDataSet initDataSet() throws Exception { + final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml"); + return new FlatXmlDataSetBuilder().build(is); + } + + private DataFileLoader initDataFileLoader() { + return new FlatXmlDataFileLoader(); + } + + @Test + public void testSelect() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; + final String[] prepDataFiles = {"/users.xml"}; + final String[] expectedDataFiles = {"/users.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = () -> { + // invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example + final ResultSet rs = connection.createStatement().executeQuery("select * from USERS where id = 1"); + + // either place assertions here + //assertTrue(rs.next()); + //assertEquals("Xavier", rs.getString("last_name")); + + return rs; + }; + + // Act + final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + + // or place assertions at the end + assertTrue(rs.next()); + assertEquals("Xavier", rs.getString("last_name")); + } + + @Test + public void testUpdate() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; // define tables to verify + final String[] prepDataFiles = {"/users.xml"}; // define prep files + final String[] expectedDataFiles = {"/users_exp_rename.xml"}; // define expected files + final PrepAndExpectedTestCaseSteps testSteps = () -> { + // invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example + return connection.createStatement().executeUpdate("update USERS set first_name = 'new name' where id = 1"); + // after this method exits, dbUnit will: + // * verify configured tables + // * cleanup tables as configured + }; + + // Act + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } + + @Test + public void testDelete() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; + final String[] prepDataFiles = {"/users.xml"}; + final String[] expectedDataFiles = {"/users_exp_delete.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = + () -> connection.createStatement().executeUpdate("delete from USERS where id = 2"); + + // Act + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } + +} diff --git a/dbunit/src/test/resources/data.xml b/dbunit/src/test/resources/data.xml new file mode 100644 index 0000000000..e4498513e0 --- /dev/null +++ b/dbunit/src/test/resources/data.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/dbunit/src/test/resources/items.xml b/dbunit/src/test/resources/items.xml new file mode 100644 index 0000000000..04a975d7ee --- /dev/null +++ b/dbunit/src/test/resources/items.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dbunit/src/test/resources/items_exp_delete.xml b/dbunit/src/test/resources/items_exp_delete.xml new file mode 100644 index 0000000000..1aaeff59ca --- /dev/null +++ b/dbunit/src/test/resources/items_exp_delete.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dbunit/src/test/resources/items_exp_rename.xml b/dbunit/src/test/resources/items_exp_rename.xml new file mode 100644 index 0000000000..237280e758 --- /dev/null +++ b/dbunit/src/test/resources/items_exp_rename.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dbunit/src/test/resources/schema.sql b/dbunit/src/test/resources/schema.sql new file mode 100644 index 0000000000..9b5018985a --- /dev/null +++ b/dbunit/src/test/resources/schema.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS USERS +( + `id` int AUTO_INCREMENT NOT NULL, + `first_name` varchar(100) NOT NULL, + `last_name` varchar(100) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS ITEMS +( + `id` int AUTO_INCREMENT NOT NULL, + `title` varchar(100) NOT NULL, + `produced` date, + `price` float, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS PURCHASES +( + `id` int NOT NULL AUTO_INCREMENT, + `id_user` int NOT NULL, + `id_item` int NOT NULL, + `total_price` float NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_user`) REFERENCES USERS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/dbunit/src/test/resources/users.xml b/dbunit/src/test/resources/users.xml new file mode 100644 index 0000000000..cebadf2e67 --- /dev/null +++ b/dbunit/src/test/resources/users.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dbunit/src/test/resources/users_exp_delete.xml b/dbunit/src/test/resources/users_exp_delete.xml new file mode 100644 index 0000000000..8b72ceef89 --- /dev/null +++ b/dbunit/src/test/resources/users_exp_delete.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/dbunit/src/test/resources/users_exp_rename.xml b/dbunit/src/test/resources/users_exp_rename.xml new file mode 100644 index 0000000000..9bc1254967 --- /dev/null +++ b/dbunit/src/test/resources/users_exp_rename.xml @@ -0,0 +1,7 @@ + + + + + + + From 6194165f0d1c57ef5d6b5f1111d96107beee735c Mon Sep 17 00:00:00 2001 From: naXa! Date: Mon, 25 Mar 2019 01:37:05 +0300 Subject: [PATCH 03/97] [BAEL-2749] add `SampleDbUnitTest` (extending `DBTestCase`) --- .../com/baeldung/dbunit/SampleDbUnitTest.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java diff --git a/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java new file mode 100644 index 0000000000..cfe4fd4e11 --- /dev/null +++ b/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.DBTestCase; +import org.dbunit.PropertiesBasedJdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.junit.Test; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; + +public class SampleDbUnitTest extends DBTestCase { + private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; + private static final String USER = "sa"; + private static final String PASSWORD = ""; + + public SampleDbUnitTest(String name) { + super(name); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); + // System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, ""); + } + + @Override + protected IDataSet getDataSet() throws Exception { + final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); + return new FlatXmlDataSetBuilder().build(is); + } + + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.NONE; + } + + @Test + public void testSelect() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + + // Act + final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); + + // Assert + assertTrue(rs.next()); + assertEquals("Grey T-Shirt", rs.getString("title")); + } + + @Test + public void testDelete() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + + final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + + // Act + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + // Assert + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void testUpdate() throws Exception { + // Arrange + final Connection connection = getConnection().getConnection(); + + final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + + // Act + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + // Assert + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + Assertion.assertEquals(expectedTable, actualTable); + } + +} From 71fecd658963941c694f0528e981b2f88441999d Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 29 Mar 2020 11:49:46 -0300 Subject: [PATCH 04/97] [BAEL-3793][BAEL-3935] Code snippets --- terraform/best-practices/README.md | 10 +++ .../best-practices/ec2-simple/.gitignore | 4 ++ terraform/best-practices/ec2-simple/SETUP.md | 23 +++++++ terraform/best-practices/ec2-simple/main.tf | 33 +++++++++ .../best-practices/ec2-simple/providers.tf | 6 ++ .../best-practices/ec2-simple/variables.tf | 15 ++++ terraform/best-practices/k8s-basic/.gitignore | 4 ++ terraform/best-practices/k8s-basic/SETUP.md | 15 ++++ terraform/best-practices/k8s-basic/main.tf | 12 ++++ .../best-practices/k8s-basic/providers.tf | 6 ++ .../best-practices/k8s-basic/variables.tf | 9 +++ .../best-practices/k8s-modules/.gitignore | 4 ++ terraform/best-practices/k8s-modules/SETUP.md | 21 ++++++ terraform/best-practices/k8s-modules/main.tf | 27 ++++++++ .../k8s-modules/modules/SvcCustomer/main.tf | 68 ++++++++++++++++++ .../modules/SvcCustomer/outputs.tf | 3 + .../modules/SvcCustomer/variables.tf | 5 ++ .../k8s-modules/modules/SvcFeedback/main.tf | 69 +++++++++++++++++++ .../modules/SvcFeedback/outputs.tf | 3 + .../modules/SvcFeedback/variables.tf | 5 ++ .../ingress/www.petshop.com.br/main.tf | 41 +++++++++++ .../ingress/www.petshop.com.br/outputs.tf | 5 ++ .../ingress/www.petshop.com.br/variables.tf | 20 ++++++ .../best-practices/k8s-modules/provider.tf | 13 ++++ terraform/hello-terraform/.gitignore | 6 ++ terraform/hello-terraform/main.tf | 7 ++ 26 files changed, 434 insertions(+) create mode 100644 terraform/best-practices/README.md create mode 100644 terraform/best-practices/ec2-simple/.gitignore create mode 100644 terraform/best-practices/ec2-simple/SETUP.md create mode 100644 terraform/best-practices/ec2-simple/main.tf create mode 100644 terraform/best-practices/ec2-simple/providers.tf create mode 100644 terraform/best-practices/ec2-simple/variables.tf create mode 100644 terraform/best-practices/k8s-basic/.gitignore create mode 100644 terraform/best-practices/k8s-basic/SETUP.md create mode 100644 terraform/best-practices/k8s-basic/main.tf create mode 100644 terraform/best-practices/k8s-basic/providers.tf create mode 100644 terraform/best-practices/k8s-basic/variables.tf create mode 100644 terraform/best-practices/k8s-modules/.gitignore create mode 100644 terraform/best-practices/k8s-modules/SETUP.md create mode 100644 terraform/best-practices/k8s-modules/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf create mode 100644 terraform/best-practices/k8s-modules/provider.tf create mode 100644 terraform/hello-terraform/.gitignore create mode 100644 terraform/hello-terraform/main.tf diff --git a/terraform/best-practices/README.md b/terraform/best-practices/README.md new file mode 100644 index 0000000000..fd488b1afb --- /dev/null +++ b/terraform/best-practices/README.md @@ -0,0 +1,10 @@ +# Terraform Sample Code + +This folder contains Terraform project samples that illustrates topics covered in the +"Best practices when using Terraform" article. Setup instructions are available in each sample's folder. + +List of available samples: + + * k8s-basic: "Hello world" project that just connects to a Kubernetes cluster and create a new namespace. + * ec2-basic: "Hello world" project that creates a single EC2 instance + * k8s-modules: A more elaborate sample that creates a simple set of services in a Kubernetes cluster diff --git a/terraform/best-practices/ec2-simple/.gitignore b/terraform/best-practices/ec2-simple/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/ec2-simple/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/ec2-simple/SETUP.md b/terraform/best-practices/ec2-simple/SETUP.md new file mode 100644 index 0000000000..3f906b6933 --- /dev/null +++ b/terraform/best-practices/ec2-simple/SETUP.md @@ -0,0 +1,23 @@ +# EC2 Basic Sample + +This Terraform sample project creates a single EC2 instance in the configured region. + +IMPORTANT NOTICE: In order to run this sample you must have an active AWS Account. As you probably know, creating resources on AWS +may result in additional charges in your bill. We recommend creating a test account to run this test as you can then use AWS's free tier +to play around. When finished, ALWAYS REMEMBER TO DESTROY YOUR RESOURCES !!! + +# Setup instructions + +1. Make sure you have a working AWS environment. Use a simple command such as _aws ec2 describe-instances_ and check its output. + If you get a list of existing EC2 instances, you're good to go. Otherwise, please refer to AWS documentation in order to setup your CLI. +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _aws ec2 describe-instances_. The output should list the newly creates EC2 instance +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/ec2-simple/main.tf b/terraform/best-practices/ec2-simple/main.tf new file mode 100644 index 0000000000..57fb9d1757 --- /dev/null +++ b/terraform/best-practices/ec2-simple/main.tf @@ -0,0 +1,33 @@ +# +# Resource definitions +# + +data "aws_ami" "apache" { + filter { + name = "name" + values = [var.ami_name] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + owners = [var.ami_owner] + + most_recent = true +} + +resource "aws_instance" "web" { + ami = data.aws_ami.apache.id + instance_type = "t2.micro" + subnet_id = aws_subnet.frontend.id +} +resource "aws_subnet" "frontend" { + vpc_id = aws_vpc.apps.id + cidr_block = "10.0.1.0/24" +} + +resource "aws_vpc" "apps" { + cidr_block = "10.0.0.0/16" +} diff --git a/terraform/best-practices/ec2-simple/providers.tf b/terraform/best-practices/ec2-simple/providers.tf new file mode 100644 index 0000000000..fa5826b067 --- /dev/null +++ b/terraform/best-practices/ec2-simple/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "aws" { + version = "~> 2.53" +} \ No newline at end of file diff --git a/terraform/best-practices/ec2-simple/variables.tf b/terraform/best-practices/ec2-simple/variables.tf new file mode 100644 index 0000000000..2a7fddcd33 --- /dev/null +++ b/terraform/best-practices/ec2-simple/variables.tf @@ -0,0 +1,15 @@ +# +# Variables +# + +variable "ami_name" { + type = string + description = "AMI name to use for our EC2 instance. Defaults to Ubuntu 18.04 (Bionic)" + default = "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-*" +} + +variable "ami_owner" { + type = string + description = "AMI Owner ID to use for our EC2 instance. Defaults to 099720109477 (Canonical)" + default = "099720109477" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/.gitignore b/terraform/best-practices/k8s-basic/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-basic/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md new file mode 100644 index 0000000000..479bb75274 --- /dev/null +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -0,0 +1,15 @@ +# Setup instructions + +1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/k8s-basic/main.tf b/terraform/best-practices/k8s-basic/main.tf new file mode 100644 index 0000000000..5eb3749930 --- /dev/null +++ b/terraform/best-practices/k8s-basic/main.tf @@ -0,0 +1,12 @@ +# +# Resource definitions +# + +resource "kubernetes_namespace" "hello" { + metadata { + labels = { + terraform = "true" + } + name = var.namespace_name + } +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/providers.tf b/terraform/best-practices/k8s-basic/providers.tf new file mode 100644 index 0000000000..385f857a11 --- /dev/null +++ b/terraform/best-practices/k8s-basic/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "kubernetes" { + version = "~> 1.11" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/variables.tf b/terraform/best-practices/k8s-basic/variables.tf new file mode 100644 index 0000000000..b9217079bf --- /dev/null +++ b/terraform/best-practices/k8s-basic/variables.tf @@ -0,0 +1,9 @@ +# +# Variables +# + +variable "namespace_name" { + type = string + description = "Name to use for the created namespace" + default = "hello-terraform" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/.gitignore b/terraform/best-practices/k8s-modules/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-modules/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md new file mode 100644 index 0000000000..b7e4c2764d --- /dev/null +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -0,0 +1,21 @@ +# Kubernetes multimodule sample + +This sample deploys two services behind a Kubernetes ingress. + +# Setup instructions + +1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get services_. The output should now have a few services. +6. Run _terraform destroy_ to remove the previously creates namespace. + + + diff --git a/terraform/best-practices/k8s-modules/main.tf b/terraform/best-practices/k8s-modules/main.tf new file mode 100644 index 0000000000..86426b33db --- /dev/null +++ b/terraform/best-practices/k8s-modules/main.tf @@ -0,0 +1,27 @@ +/* + * Top-level definitions + */ + +//================================================================== Ingress + +module "ingress_www_petshop_com_br" { + source = "./modules/ingress/www.petshop.com.br" + ingress_host = "www.petshop.com.br" +} + +//================================================================== Deployments + +module "SvcCustomer" { + source = "./modules/SvcCustomer" +} + +module "SvcFeedback" { + source = "./modules/SvcFeedback" +} + + + + + + + diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf new file mode 100644 index 0000000000..1ca0c91545 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf @@ -0,0 +1,68 @@ +/* + * SvcCustomer deployment resources + */ + +resource "kubernetes_deployment" "SvcCustomer" { + + metadata { + name = "svccustomer" + labels = { + app = "SvcCustomer" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcCustomer" + } + } + + template { + metadata { + labels = { + app = "SvcCustomer" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svccustomer-httpd" + env { + name = "PORT" + value = "80" + } + } + } + } + } +} + +resource "kubernetes_service" "SvcCustomer" { + metadata { + name = "svccustomer" + } + + spec { + + selector = { + app = "SvcCustomer" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf new file mode 100644 index 0000000000..8a37fdf375 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcCustomer output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf new file mode 100644 index 0000000000..3dfcfcd264 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcCustomer deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf new file mode 100644 index 0000000000..0f84c9163e --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf @@ -0,0 +1,69 @@ +/* + * SvcFeedback deployment resources + */ + +resource "kubernetes_deployment" "SvcFeedback" { + + metadata { + name = "svcfeedback" + labels = { + app = "SvcFeedback" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcFeedback" + } + } + + template { + metadata { + labels = { + app = "SvcFeedback" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svcfeedback-httpd" + env { + name = "PORT" + value = "80" + } + } + + } + } + } +} + +resource "kubernetes_service" "SvcFeedback" { + metadata { + name = "svcfeedback" + } + + spec { + + selector = { + app = "SvcFeedback" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf new file mode 100644 index 0000000000..e08c17d4b4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcFeedback output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf new file mode 100644 index 0000000000..d8076d41a4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcFeedback deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf new file mode 100644 index 0000000000..0dbda48981 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf @@ -0,0 +1,41 @@ +/* + * Kubernetes Ingress module + */ +locals { + iname = var.ingress_name == "" ? join("-",["ingress",sha1(uuid())]) : var.ingress_name +} + +resource "kubernetes_ingress" "ingress" { + metadata { + name = local.iname + annotations = map( + "nginx.ingress.kubernetes.io/rewrite-target","/" + ) + } + spec { + rule { + http { + path { + backend { + service_name = "svccustomer" + service_port = 80 + } + path = "/customers" + } + path { + backend { + service_name = "svcfeedback" + service_port = 80 + } + path = "/feedback" + } + } + } +/* + tls { + secret_name = "tls-secret" + } +*/ + } +} + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf new file mode 100644 index 0000000000..e604417b05 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf @@ -0,0 +1,5 @@ +/* + * Output variables + */ + + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf new file mode 100644 index 0000000000..9b06128ec5 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf @@ -0,0 +1,20 @@ +/* + * Kubernetes Ingress module + */ + + +variable "ingress_name" { + type = string + description = "Ingress name. Defaults to a random name." + default = "" +} + +variable "ingress_host" { + type = string + description = "Ingress hostname" + default = "www.petshop.com.br" +} + + + + diff --git a/terraform/best-practices/k8s-modules/provider.tf b/terraform/best-practices/k8s-modules/provider.tf new file mode 100644 index 0000000000..bb90d66ecf --- /dev/null +++ b/terraform/best-practices/k8s-modules/provider.tf @@ -0,0 +1,13 @@ +# +# Provider configurations +# This file will *NOT* be overwriten upon regeneration, so it's safe +# to add your own customizations +# + +provider "kubernetes" { + version = "~> 1.10" +} + +provider "random" { + version = "~> 2.2" +} \ No newline at end of file diff --git a/terraform/hello-terraform/.gitignore b/terraform/hello-terraform/.gitignore new file mode 100644 index 0000000000..452502c50f --- /dev/null +++ b/terraform/hello-terraform/.gitignore @@ -0,0 +1,6 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform +hello.txt + diff --git a/terraform/hello-terraform/main.tf b/terraform/hello-terraform/main.tf new file mode 100644 index 0000000000..d6a726fa36 --- /dev/null +++ b/terraform/hello-terraform/main.tf @@ -0,0 +1,7 @@ +provider "local" { + version = "~> 1.4" +} +resource "local_file" "hello" { + content = "Hello, Terraform" + filename = "hello.txt" +} From 405831d3da839c12ca73562112653842ee83ef44 Mon Sep 17 00:00:00 2001 From: patkorek Date: Tue, 31 Mar 2020 07:36:44 +0200 Subject: [PATCH 05/97] changed tabs to spaces --- ...GraphQL collection.postman_collection.json | 334 +++++++++--------- 1 file changed, 167 insertions(+), 167 deletions(-) diff --git a/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json index 7fcaa2c76d..f19bc1febb 100644 --- a/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json +++ b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json @@ -1,169 +1,169 @@ { - "info": { - "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", - "name": "GraphQL collection", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "mutations", - "item": [ - { - "name": "writePost", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "graphql", - "graphql": { - "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", - "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" - }, - "options": { - "graphql": {} - } - }, - "url": { - "raw": "http://localhost:9090/springbootapp/graphql", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "9090", - "path": [ - "springbootapp", - "graphql" - ] - } - }, - "response": [] - } - ], - "protocolProfileBehavior": {} - }, - { - "name": "queries", - "item": [ - { - "name": "get recent posts", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "graphql", - "graphql": { - "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", - "variables": "" - } - }, - "url": { - "raw": "http://localhost:9090/springbootapp/graphql", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "9090", - "path": [ - "springbootapp", - "graphql" - ] - } - }, - "response": [] - }, - { - "name": "recentPosts - variables", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "graphql", - "graphql": { - "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", - "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" - }, - "options": { - "graphql": {} - } - }, - "url": { - "raw": "http://localhost:9090/springbootapp/graphql", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "9090", - "path": [ - "springbootapp", - "graphql" - ] - } - }, - "response": [] - }, - { - "name": "get recent posts - raw", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/graphql", - "type": "text" - } - ], - "body": { - "mode": "raw", - "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" - }, - "url": { - "raw": "http://localhost:9090/springbootapp/graphql", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "9090", - "path": [ - "springbootapp", - "graphql" - ] - } - }, - "response": [] - } - ], - "protocolProfileBehavior": {} - } - ], - "event": [ - { - "listen": "prerequest", - "script": { - "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", - "type": "text/javascript", - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "id": "00b575be-03d4-4b29-b137-733ead139638", - "type": "text/javascript", - "exec": [ - "" - ] - } - } - ], - "variable": [ - { - "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", - "key": "url", - "value": "", - "type": "string" - } - ], - "protocolProfileBehavior": {} + "info": { + "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", + "name": "GraphQL collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "mutations", + "item": [ + { + "name": "writePost", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + }, + { + "name": "queries", + "item": [ + { + "name": "get recent posts", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", + "variables": "" + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "recentPosts - variables", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "get recent posts - raw", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/graphql", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "00b575be-03d4-4b29-b137-733ead139638", + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", + "key": "url", + "value": "", + "type": "string" + } + ], + "protocolProfileBehavior": {} } \ No newline at end of file From aaffd9614fc1675ab05f992eec62c90be5aef76f Mon Sep 17 00:00:00 2001 From: naXa! Date: Mon, 25 Mar 2019 02:00:03 +0300 Subject: [PATCH 06/97] [BAEL-2749] add dbunit module to parent pom --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index 04a2ce054c..734e2c8ab9 100644 --- a/pom.xml +++ b/pom.xml @@ -601,6 +601,8 @@ + dbunit + parent-boot-1 parent-boot-2 parent-spring-4 @@ -1288,6 +1290,8 @@ + dbunit + parent-boot-1 parent-boot-2 parent-spring-4 From a65c5bf202c3326514e7d6c1408bd9e445c06fd9 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Sun, 29 Mar 2020 11:37:19 +0200 Subject: [PATCH 07/97] [BAEL-2749] Introduces Assertj and uses builder pattern --- dbunit/pom.xml | 36 ++++++++++++++++--- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 8 +++-- .../dbunit/PrepAndExpectedDbUnitTest.java | 12 +++++-- 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/dbunit/pom.xml b/dbunit/pom.xml index b77b15f2d4..ab0befcf4c 100644 --- a/dbunit/pom.xml +++ b/dbunit/pom.xml @@ -3,6 +3,16 @@ 4.0.0 dbunit 1.0 + + 1.4.200 + + 1.8 + 1.8 + 3.8.1 + + 3.14.0 + 2.6.0 + dbunit @@ -22,14 +32,30 @@ com.h2database h2 - 1.4.197 + ${h2.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} test - - - 2.6.0 - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.target} + + + + diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index a703863614..2a2f25971b 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -6,6 +6,7 @@ import org.dbunit.JdbcDatabaseTester; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.xml.FlatXmlDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import org.junit.After; import org.junit.Before; @@ -16,6 +17,7 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -74,7 +76,7 @@ public class OldSchoolDbUnitTest { final Connection connection = tester.getConnection().getConnection(); final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); - ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items"); + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); // Act @@ -94,7 +96,7 @@ public class OldSchoolDbUnitTest { final Connection connection = tester.getConnection().getConnection(); final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); - ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items"); + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); // Act @@ -105,7 +107,7 @@ public class OldSchoolDbUnitTest { ITable actualTable = databaseDataSet.getTable("items"); //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - Assertion.assertEquals(expectedTable, actualTable); + assertThat(actualTable).isEqualTo(actualTable); } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index c3882d5eab..c322cf0ae3 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -1,6 +1,10 @@ package com.baeldung.dbunit; -import org.dbunit.*; +import org.dbunit.DefaultPrepAndExpectedTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.PrepAndExpectedTestCaseSteps; +import org.dbunit.VerifyTableDefinition; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; @@ -12,6 +16,8 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; +import static org.assertj.core.api.Assertions.assertThat; + public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; @@ -63,8 +69,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); // or place assertions at the end - assertTrue(rs.next()); - assertEquals("Xavier", rs.getString("last_name")); + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("last_name")).isEqualTo("Xavier"); } @Test From 71ba591868ed0f200f16c17a3d116cf6c32a559b Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Sun, 29 Mar 2020 18:16:45 +0200 Subject: [PATCH 08/97] [BAEL-2749] Select and Delete for OldSchool --- dbunit/pom.xml | 1 + .../baeldung/dbunit/OldSchoolDbUnitTest.java | 39 +++++++++++-------- .../items_exp_delete_no_produced.xml | 8 ++++ 3 files changed, 32 insertions(+), 16 deletions(-) create mode 100644 dbunit/src/test/resources/items_exp_delete_no_produced.xml diff --git a/dbunit/pom.xml b/dbunit/pom.xml index ab0befcf4c..7ca53cd3be 100644 --- a/dbunit/pom.xml +++ b/dbunit/pom.xml @@ -13,6 +13,7 @@ 3.14.0 2.6.0 + dbunit diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index 2a2f25971b..e64b49263a 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -5,7 +5,7 @@ import org.dbunit.IDatabaseTester; import org.dbunit.JdbcDatabaseTester; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; -import org.dbunit.dataset.xml.FlatXmlDataSet; +import org.dbunit.dataset.filter.DefaultColumnFilter; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import org.junit.After; @@ -18,8 +18,7 @@ import java.sql.Connection; import java.sql.ResultSet; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.dbunit.Assertion.assertEquals; public class OldSchoolDbUnitTest { private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); @@ -44,7 +43,7 @@ public class OldSchoolDbUnitTest { private static IDataSet initDataSet() throws Exception { final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); - return new FlatXmlDataSet(is); + return new FlatXmlDataSetBuilder().build(is); } @Before @@ -59,35 +58,43 @@ public class OldSchoolDbUnitTest { @Test public void testSelect() throws Exception { - // Arrange final Connection connection = tester.getConnection().getConnection(); - // Act final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - // Assert - assertTrue(rs.next()); - assertEquals("Grey T-Shirt", rs.getString("title")); + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test public void testDelete() throws Exception { - // Arrange final Connection connection = tester.getConnection().getConnection(); final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); - // Act connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - // Assert final IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("items"); - //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - Assertion.assertEquals(expectedTable, actualTable); + assertEquals(expectedTable, actualTable); + } + + @Test + public void testDeleteWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete_no_produced.xml"); + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + assertEquals(expectedTable, actualTable); } @Test @@ -107,7 +114,7 @@ public class OldSchoolDbUnitTest { ITable actualTable = databaseDataSet.getTable("items"); //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - assertThat(actualTable).isEqualTo(actualTable); + assertEquals(expectedTable, actualTable); } } diff --git a/dbunit/src/test/resources/items_exp_delete_no_produced.xml b/dbunit/src/test/resources/items_exp_delete_no_produced.xml new file mode 100644 index 0000000000..c9b182a1b2 --- /dev/null +++ b/dbunit/src/test/resources/items_exp_delete_no_produced.xml @@ -0,0 +1,8 @@ + + + + + + + + From e4f4f7110b33f753a50b5f56443b8dff8ab014b5 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Sun, 29 Mar 2020 21:47:00 +0200 Subject: [PATCH 09/97] [BAEL-2749] Code refactoring --- dbunit/src/main/resources/logback.xml | 2 +- .../baeldung/dbunit/ConnectionSettings.java | 8 ++++ .../baeldung/dbunit/OldSchoolDbUnitTest.java | 32 ++++++++----- .../dbunit/PrepAndExpectedDbUnitTest.java | 48 +++++++------------ .../com/baeldung/dbunit/SampleDbUnitTest.java | 23 ++++----- dbunit/src/test/resources/data.xml | 12 ++--- .../src/test/resources/items_exp_delete.xml | 8 ++-- .../items_exp_delete_no_produced.xml | 8 ++-- .../src/test/resources/items_exp_rename.xml | 10 ++-- .../items_exp_rename_no_produced.xml | 9 ++++ dbunit/src/test/resources/schema.sql | 34 ++++++------- dbunit/src/test/resources/users.xml | 6 +-- .../src/test/resources/users_exp_delete.xml | 4 +- .../src/test/resources/users_exp_rename.xml | 6 +-- 14 files changed, 108 insertions(+), 102 deletions(-) create mode 100644 dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java create mode 100644 dbunit/src/test/resources/items_exp_rename_no_produced.xml diff --git a/dbunit/src/main/resources/logback.xml b/dbunit/src/main/resources/logback.xml index 7d900d8ea8..26beb6d5b4 100644 --- a/dbunit/src/main/resources/logback.xml +++ b/dbunit/src/main/resources/logback.xml @@ -8,6 +8,6 @@ - + \ No newline at end of file diff --git a/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java new file mode 100644 index 0000000000..e842022292 --- /dev/null +++ b/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -0,0 +1,8 @@ +package com.baeldung.dbunit; + +public class ConnectionSettings { + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; +} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index e64b49263a..0b63184951 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.dbunit; -import org.dbunit.Assertion; import org.dbunit.IDatabaseTester; import org.dbunit.JdbcDatabaseTester; import org.dbunit.dataset.IDataSet; @@ -17,14 +16,14 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; import static org.assertj.core.api.Assertions.assertThat; import static org.dbunit.Assertion.assertEquals; public class OldSchoolDbUnitTest { - private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; - private static final String USER = "sa"; - private static final String PASSWORD = ""; private static IDatabaseTester tester = null; @@ -99,20 +98,31 @@ public class OldSchoolDbUnitTest { @Test public void testUpdate() throws Exception { - // Arrange final Connection connection = tester.getConnection().getConnection(); final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - //expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"}); + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - // Act connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - // Assert final IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("items"); - //actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + assertEquals(expectedTable, actualTable); + } + + @Test + public void testUpdateWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename_no_produced.xml"); + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); assertEquals(expectedTable, actualTable); } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index c322cf0ae3..bb70136de2 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -16,13 +16,13 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; import static org.assertj.core.api.Assertions.assertThat; public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { - private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; - private static final String USER = "sa"; - private static final String PASSWORD = ""; @Override public void setUp() throws Exception { @@ -49,60 +49,46 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { @Test public void testSelect() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> { - // invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example - final ResultSet rs = connection.createStatement().executeQuery("select * from USERS where id = 1"); + final PrepAndExpectedTestCaseSteps testSteps = + () -> connection + .createStatement() + .executeQuery("select * from USERS where id = 1"); - // either place assertions here - //assertTrue(rs.next()); - //assertEquals("Xavier", rs.getString("last_name")); - - return rs; - }; - - // Act final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - // or place assertions at the end assertThat(rs.next()).isTrue(); assertThat(rs.getString("last_name")).isEqualTo("Xavier"); } @Test public void testUpdate() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; // define tables to verify - final String[] prepDataFiles = {"/users.xml"}; // define prep files - final String[] expectedDataFiles = {"/users_exp_rename.xml"}; // define expected files - final PrepAndExpectedTestCaseSteps testSteps = () -> { - // invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example - return connection.createStatement().executeUpdate("update USERS set first_name = 'new name' where id = 1"); - // after this method exits, dbUnit will: - // * verify configured tables - // * cleanup tables as configured - }; + final String[] prepDataFiles = {"/users.xml"}; + final String[] expectedDataFiles = {"/users_exp_rename.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = + () -> connection + .createStatement() + .executeUpdate("update USERS set first_name = 'new name' where id = 1"); - // Act super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } @Test public void testDelete() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users_exp_delete.xml"}; final PrepAndExpectedTestCaseSteps testSteps = - () -> connection.createStatement().executeUpdate("delete from USERS where id = 2"); + () -> connection + .createStatement() + .executeUpdate("delete from USERS where id = 2"); - // Act super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java index cfe4fd4e11..f7970754e7 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java @@ -13,11 +13,13 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; + public class SampleDbUnitTest extends DBTestCase { - private static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; - private static final String USER = "sa"; - private static final String PASSWORD = ""; public SampleDbUnitTest(String name) { super(name); @@ -46,29 +48,23 @@ public class SampleDbUnitTest extends DBTestCase { @Test public void testSelect() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); - // Act final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - // Assert - assertTrue(rs.next()); - assertEquals("Grey T-Shirt", rs.getString("title")); + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test public void testDelete() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - // Act connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - // Assert final IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("items"); @@ -77,16 +73,13 @@ public class SampleDbUnitTest extends DBTestCase { @Test public void testUpdate() throws Exception { - // Arrange final Connection connection = getConnection().getConnection(); final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - // Act connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - // Assert final IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("items"); diff --git a/dbunit/src/test/resources/data.xml b/dbunit/src/test/resources/data.xml index e4498513e0..ac413cfd23 100644 --- a/dbunit/src/test/resources/data.xml +++ b/dbunit/src/test/resources/data.xml @@ -1,11 +1,11 @@ - + - - - - - + + + + + diff --git a/dbunit/src/test/resources/items_exp_delete.xml b/dbunit/src/test/resources/items_exp_delete.xml index 1aaeff59ca..09b78da493 100644 --- a/dbunit/src/test/resources/items_exp_delete.xml +++ b/dbunit/src/test/resources/items_exp_delete.xml @@ -1,8 +1,8 @@ - - - - + + + + diff --git a/dbunit/src/test/resources/items_exp_delete_no_produced.xml b/dbunit/src/test/resources/items_exp_delete_no_produced.xml index c9b182a1b2..dd76e8c6ce 100644 --- a/dbunit/src/test/resources/items_exp_delete_no_produced.xml +++ b/dbunit/src/test/resources/items_exp_delete_no_produced.xml @@ -1,8 +1,8 @@ - - - - + + + + diff --git a/dbunit/src/test/resources/items_exp_rename.xml b/dbunit/src/test/resources/items_exp_rename.xml index 237280e758..830d83499f 100644 --- a/dbunit/src/test/resources/items_exp_rename.xml +++ b/dbunit/src/test/resources/items_exp_rename.xml @@ -1,9 +1,9 @@ - - - - - + + + + + diff --git a/dbunit/src/test/resources/items_exp_rename_no_produced.xml b/dbunit/src/test/resources/items_exp_rename_no_produced.xml new file mode 100644 index 0000000000..991c4726a0 --- /dev/null +++ b/dbunit/src/test/resources/items_exp_rename_no_produced.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dbunit/src/test/resources/schema.sql b/dbunit/src/test/resources/schema.sql index 9b5018985a..dc4738ca76 100644 --- a/dbunit/src/test/resources/schema.sql +++ b/dbunit/src/test/resources/schema.sql @@ -1,28 +1,28 @@ CREATE TABLE IF NOT EXISTS USERS ( - `id` int AUTO_INCREMENT NOT NULL, - `first_name` varchar(100) NOT NULL, - `last_name` varchar(100) NOT NULL, - PRIMARY KEY (`id`) + `id` int AUTO_INCREMENT NOT NULL, + `first_name` varchar(100) NOT NULL, + `last_name` varchar(100) NOT NULL, + PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS ITEMS ( - `id` int AUTO_INCREMENT NOT NULL, - `title` varchar(100) NOT NULL, - `produced` date, - `price` float, - PRIMARY KEY (`id`) + `id` int AUTO_INCREMENT NOT NULL, + `title` varchar(100) NOT NULL, + `produced` date, + `price` float, + PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS PURCHASES ( - `id` int NOT NULL AUTO_INCREMENT, - `id_user` int NOT NULL, - `id_item` int NOT NULL, - `total_price` float NOT NULL, - `quantity` int(11) NOT NULL, - PRIMARY KEY (`id`), - FOREIGN KEY (`id_user`) REFERENCES USERS (`id`) ON DELETE CASCADE, - FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE + `id` int NOT NULL AUTO_INCREMENT, + `id_user` int NOT NULL, + `id_item` int NOT NULL, + `total_price` float NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_user`) REFERENCES USERS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); diff --git a/dbunit/src/test/resources/users.xml b/dbunit/src/test/resources/users.xml index cebadf2e67..d8ff78024e 100644 --- a/dbunit/src/test/resources/users.xml +++ b/dbunit/src/test/resources/users.xml @@ -1,7 +1,7 @@ - - - + + + diff --git a/dbunit/src/test/resources/users_exp_delete.xml b/dbunit/src/test/resources/users_exp_delete.xml index 8b72ceef89..c4ea6e64e5 100644 --- a/dbunit/src/test/resources/users_exp_delete.xml +++ b/dbunit/src/test/resources/users_exp_delete.xml @@ -1,6 +1,6 @@ - - + + diff --git a/dbunit/src/test/resources/users_exp_rename.xml b/dbunit/src/test/resources/users_exp_rename.xml index 9bc1254967..c187e1ebe5 100644 --- a/dbunit/src/test/resources/users_exp_rename.xml +++ b/dbunit/src/test/resources/users_exp_rename.xml @@ -1,7 +1,7 @@ - - - + + + From d5d1cc7d580b1749b9f29df644ea34cbddeee8ac Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 12:02:24 +0200 Subject: [PATCH 10/97] [BAEL-2749] Adds DataSourceBaseDBTestCase --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 46 +++++++++++++++++++ ...{SampleDbUnitTest.java => DbUnitTest.java} | 12 ++--- 2 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java rename dbunit/src/test/java/com/baeldung/dbunit/{SampleDbUnitTest.java => DbUnitTest.java} (85%) diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java new file mode 100644 index 0000000000..154d93e0af --- /dev/null +++ b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.dbunit; + +import org.dbunit.DataSourceBasedDBTestCase; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.Test; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { + @Override + protected DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL( + "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"); + dataSource.setUser("sa"); + dataSource.setPassword("sa"); + return dataSource; + } + + @Override + protected IDataSet getDataSet() throws Exception { + return new FlatXmlDataSetBuilder().build(getClass() + .getClassLoader() + .getResourceAsStream("data.xml")); + } + + @Test + public void testSimpleDataSet() throws SQLException { + final Connection connection = getDataSource() + .getConnection(); + + final ResultSet rs = connection + .createStatement() + .executeQuery("select * from iTEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } +} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java similarity index 85% rename from dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java rename to dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java index f7970754e7..8d6a94279a 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/SampleDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -19,9 +19,9 @@ import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; import static com.baeldung.dbunit.ConnectionSettings.USER; import static org.assertj.core.api.Assertions.assertThat; -public class SampleDbUnitTest extends DBTestCase { +public class DbUnitTest extends DBTestCase { - public SampleDbUnitTest(String name) { + public DbUnitTest(String name) { super(name); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); @@ -32,7 +32,7 @@ public class SampleDbUnitTest extends DBTestCase { @Override protected IDataSet getDataSet() throws Exception { - final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); + final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); return new FlatXmlDataSetBuilder().build(is); } @@ -53,14 +53,14 @@ public class SampleDbUnitTest extends DBTestCase { final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + assertThat(rs.getString( "title")).isEqualTo("Grey T-Shirt"); } @Test public void testDelete() throws Exception { final Connection connection = getConnection().getConnection(); - final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); + final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); @@ -75,7 +75,7 @@ public class SampleDbUnitTest extends DBTestCase { public void testUpdate() throws Exception { final Connection connection = getConnection().getConnection(); - final InputStream is = SampleDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); + final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); From ef19d83db5f48290978f5c4e9e3c738a53e6087c Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 12:38:39 +0200 Subject: [PATCH 11/97] [BAEL-2749] USERS table name changed to CLIENTS --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 18 +++++++++++++++--- .../java/com/baeldung/dbunit/DbUnitTest.java | 1 - .../dbunit/PrepAndExpectedDbUnitTest.java | 12 ++++++------ dbunit/src/test/resources/data.xml | 2 +- dbunit/src/test/resources/schema.sql | 4 ++-- dbunit/src/test/resources/users.xml | 6 +++--- dbunit/src/test/resources/users_exp_delete.xml | 4 ++-- dbunit/src/test/resources/users_exp_rename.xml | 6 +++--- 8 files changed, 32 insertions(+), 21 deletions(-) diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 154d93e0af..c8045394c4 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -1,7 +1,9 @@ package com.baeldung.dbunit; +import org.dbunit.Assertion; import org.dbunit.DataSourceBasedDBTestCase; import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.h2.jdbcx.JdbcDataSource; import org.junit.Test; @@ -11,16 +13,17 @@ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; import static org.assertj.core.api.Assertions.assertThat; public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { + @Override protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL( - "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"); + dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); - dataSource.setPassword("sa"); + dataSource.setPassword(""); return dataSource; } @@ -43,4 +46,13 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { assertThat(rs.next()).isTrue(); assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } + + @Test + public void testEmptySchema() throws Exception { + IDataSet expectedDataSet = getDataSet(); + ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java index 8d6a94279a..479ea3dd51 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -27,7 +27,6 @@ public class DbUnitTest extends DBTestCase { System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); - // System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, ""); } @Override diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index bb70136de2..2c7e5de508 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -50,13 +50,13 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { @Test public void testSelect() throws Exception { final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users.xml"}; final PrepAndExpectedTestCaseSteps testSteps = () -> connection .createStatement() - .executeQuery("select * from USERS where id = 1"); + .executeQuery("select * from CLIENTS where id = 1"); final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); @@ -67,13 +67,13 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { @Test public void testUpdate() throws Exception { final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; // define tables to verify + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users_exp_rename.xml"}; final PrepAndExpectedTestCaseSteps testSteps = () -> connection .createStatement() - .executeUpdate("update USERS set first_name = 'new name' where id = 1"); + .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } @@ -81,13 +81,13 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { @Test public void testDelete() throws Exception { final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users_exp_delete.xml"}; final PrepAndExpectedTestCaseSteps testSteps = () -> connection .createStatement() - .executeUpdate("delete from USERS where id = 2"); + .executeUpdate("delete from CLIENTS where id = 2"); super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } diff --git a/dbunit/src/test/resources/data.xml b/dbunit/src/test/resources/data.xml index ac413cfd23..4230073fc6 100644 --- a/dbunit/src/test/resources/data.xml +++ b/dbunit/src/test/resources/data.xml @@ -1,7 +1,7 @@ - + diff --git a/dbunit/src/test/resources/schema.sql b/dbunit/src/test/resources/schema.sql index dc4738ca76..c2a8d2d630 100644 --- a/dbunit/src/test/resources/schema.sql +++ b/dbunit/src/test/resources/schema.sql @@ -1,4 +1,4 @@ -CREATE TABLE IF NOT EXISTS USERS +CREATE TABLE IF NOT EXISTS CLIENTS ( `id` int AUTO_INCREMENT NOT NULL, `first_name` varchar(100) NOT NULL, @@ -23,6 +23,6 @@ CREATE TABLE IF NOT EXISTS PURCHASES `total_price` float NOT NULL, `quantity` int(11) NOT NULL, PRIMARY KEY (`id`), - FOREIGN KEY (`id_user`) REFERENCES USERS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE, FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); diff --git a/dbunit/src/test/resources/users.xml b/dbunit/src/test/resources/users.xml index d8ff78024e..9c14435362 100644 --- a/dbunit/src/test/resources/users.xml +++ b/dbunit/src/test/resources/users.xml @@ -1,7 +1,7 @@ - - - + + + diff --git a/dbunit/src/test/resources/users_exp_delete.xml b/dbunit/src/test/resources/users_exp_delete.xml index c4ea6e64e5..3780c00c4c 100644 --- a/dbunit/src/test/resources/users_exp_delete.xml +++ b/dbunit/src/test/resources/users_exp_delete.xml @@ -1,6 +1,6 @@ - - + + diff --git a/dbunit/src/test/resources/users_exp_rename.xml b/dbunit/src/test/resources/users_exp_rename.xml index c187e1ebe5..a576cc9e80 100644 --- a/dbunit/src/test/resources/users_exp_rename.xml +++ b/dbunit/src/test/resources/users_exp_rename.xml @@ -1,7 +1,7 @@ - - - + + + From 07947ce4d62daae7bc147fe7b4ac106b070b4d0e Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 13:31:11 +0200 Subject: [PATCH 12/97] [BAEL-2749] Insertion test with ignore cols --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 18 ++++++++++++++++++ dbunit/src/test/resources/expected-user.xml | 5 +++++ 2 files changed, 23 insertions(+) create mode 100644 dbunit/src/test/resources/expected-user.xml diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index c8045394c4..d30305ecf2 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -55,4 +55,22 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { ITable actualTable = databaseDataSet.getTable("CLIENTS"); Assertion.assertEquals(expectedTable, actualTable); } + + + @Test + public void testAssertByQuery() throws Exception { + IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass() + .getClassLoader() + .getResourceAsStream("expected-user.xml")); + ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + Connection conn = getDataSource().getConnection(); + conn.createStatement() + .executeUpdate( + "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + ITable actualData = getConnection() + .createQueryTable( + "result_name", + "SELECT * FROM CLIENTS WHERE id='2'"); + Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"}); + } } diff --git a/dbunit/src/test/resources/expected-user.xml b/dbunit/src/test/resources/expected-user.xml new file mode 100644 index 0000000000..379db13601 --- /dev/null +++ b/dbunit/src/test/resources/expected-user.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From 906d72859f67d1d9d9016d6b689805286d4c2675 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 17:51:04 +0200 Subject: [PATCH 13/97] [BAEL-2749] Test Code Completion --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 49 ++++++++++++++++++- .../java/com/baeldung/dbunit/DbUnitTest.java | 2 +- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 19 ++++++- dbunit/src/test/resources/data.xml | 2 - .../expected-ignoring-registered_at.xml | 9 ++++ .../resources/expected-multiple-failures.xml | 9 ++++ dbunit/src/test/resources/expected-user.xml | 3 +- dbunit/src/test/resources/items.xml | 1 - .../src/test/resources/items_exp_delete.xml | 1 - .../items_exp_delete_no_produced.xml | 1 - .../src/test/resources/items_exp_rename.xml | 1 - .../items_exp_rename_no_produced.xml | 1 - dbunit/src/test/resources/users.xml | 1 - .../src/test/resources/users_exp_delete.xml | 1 - .../src/test/resources/users_exp_rename.xml | 1 - 15 files changed, 85 insertions(+), 16 deletions(-) create mode 100644 dbunit/src/test/resources/expected-ignoring-registered_at.xml create mode 100644 dbunit/src/test/resources/expected-multiple-failures.xml diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index d30305ecf2..7482f38535 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -2,10 +2,15 @@ package com.baeldung.dbunit; import org.dbunit.Assertion; import org.dbunit.DataSourceBasedDBTestCase; +import org.dbunit.assertion.DiffCollectingFailureHandler; +import org.dbunit.assertion.Difference; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; import org.h2.jdbcx.JdbcDataSource; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import javax.sql.DataSource; @@ -14,6 +19,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { @@ -34,6 +40,27 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { .getResourceAsStream("data.xml")); } + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + } + + @Test public void testSimpleDataSet() throws SQLException { final Connection connection = getDataSource() @@ -56,7 +83,6 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { Assertion.assertEquals(expectedTable, actualTable); } - @Test public void testAssertByQuery() throws Exception { IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass() @@ -70,7 +96,26 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { ITable actualData = getConnection() .createQueryTable( "result_name", - "SELECT * FROM CLIENTS WHERE id='2'"); + "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"}); } + + @Test(expected = AssertionError.class) + public void testMultipleFailures() throws Exception { + IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getClassLoader().getResourceAsStream("expected-multiple-failures.xml")); + ITable expectedTable = expectedDataSet.getTable("ITEMS"); + Connection conn = getDataSource().getConnection(); + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); +// throw new AssertionError(message); + } + } + + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java index 479ea3dd51..1dee5afb28 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -42,7 +42,7 @@ public class DbUnitTest extends DBTestCase { @Override protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.NONE; + return DatabaseOperation.DELETE_ALL; } @Test diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index 0b63184951..3b46feb304 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.dbunit; +import org.dbunit.Assertion; import org.dbunit.IDatabaseTester; import org.dbunit.JdbcDatabaseTester; import org.dbunit.dataset.IDataSet; @@ -36,7 +37,7 @@ public class OldSchoolDbUnitTest { final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); tester.setDataSet(initDataSet()); tester.setSetUpOperation(DatabaseOperation.REFRESH); - tester.setTearDownOperation(DatabaseOperation.NONE); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); return tester; } @@ -65,6 +66,22 @@ public class OldSchoolDbUnitTest { assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } + @Test + public void testIgnoringProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = {"id", "produced"}; + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getClassLoader() + .getResourceAsStream("expected-ignoring-registered_at.xml")); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); + } + @Test public void testDelete() throws Exception { final Connection connection = tester.getConnection().getConnection(); diff --git a/dbunit/src/test/resources/data.xml b/dbunit/src/test/resources/data.xml index 4230073fc6..290cc36890 100644 --- a/dbunit/src/test/resources/data.xml +++ b/dbunit/src/test/resources/data.xml @@ -1,8 +1,6 @@ - - diff --git a/dbunit/src/test/resources/expected-ignoring-registered_at.xml b/dbunit/src/test/resources/expected-ignoring-registered_at.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/dbunit/src/test/resources/expected-ignoring-registered_at.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/dbunit/src/test/resources/expected-multiple-failures.xml b/dbunit/src/test/resources/expected-multiple-failures.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/dbunit/src/test/resources/expected-multiple-failures.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/dbunit/src/test/resources/expected-user.xml b/dbunit/src/test/resources/expected-user.xml index 379db13601..631dd84210 100644 --- a/dbunit/src/test/resources/expected-user.xml +++ b/dbunit/src/test/resources/expected-user.xml @@ -1,5 +1,4 @@ - - + \ No newline at end of file diff --git a/dbunit/src/test/resources/items.xml b/dbunit/src/test/resources/items.xml index 04a975d7ee..d13e93bbe0 100644 --- a/dbunit/src/test/resources/items.xml +++ b/dbunit/src/test/resources/items.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/items_exp_delete.xml b/dbunit/src/test/resources/items_exp_delete.xml index 09b78da493..a6fa2b33e8 100644 --- a/dbunit/src/test/resources/items_exp_delete.xml +++ b/dbunit/src/test/resources/items_exp_delete.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/items_exp_delete_no_produced.xml b/dbunit/src/test/resources/items_exp_delete_no_produced.xml index dd76e8c6ce..3e7f854f5f 100644 --- a/dbunit/src/test/resources/items_exp_delete_no_produced.xml +++ b/dbunit/src/test/resources/items_exp_delete_no_produced.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/items_exp_rename.xml b/dbunit/src/test/resources/items_exp_rename.xml index 830d83499f..32f1d57cf6 100644 --- a/dbunit/src/test/resources/items_exp_rename.xml +++ b/dbunit/src/test/resources/items_exp_rename.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/items_exp_rename_no_produced.xml b/dbunit/src/test/resources/items_exp_rename_no_produced.xml index 991c4726a0..b42d3804fa 100644 --- a/dbunit/src/test/resources/items_exp_rename_no_produced.xml +++ b/dbunit/src/test/resources/items_exp_rename_no_produced.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/users.xml b/dbunit/src/test/resources/users.xml index 9c14435362..9ac3909bc5 100644 --- a/dbunit/src/test/resources/users.xml +++ b/dbunit/src/test/resources/users.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/users_exp_delete.xml b/dbunit/src/test/resources/users_exp_delete.xml index 3780c00c4c..2fe97ae6f6 100644 --- a/dbunit/src/test/resources/users_exp_delete.xml +++ b/dbunit/src/test/resources/users_exp_delete.xml @@ -1,5 +1,4 @@ - diff --git a/dbunit/src/test/resources/users_exp_rename.xml b/dbunit/src/test/resources/users_exp_rename.xml index a576cc9e80..95682118bb 100644 --- a/dbunit/src/test/resources/users_exp_rename.xml +++ b/dbunit/src/test/resources/users_exp_rename.xml @@ -1,5 +1,4 @@ - From 0b1c5e01a5108350a493a06e07d2779a0b9e3f60 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 20:18:11 +0200 Subject: [PATCH 14/97] [BAEL-2749] Improves code and makes a copy in libraries-testing --- dbunit/README.md | 2 - dbunit/docs/db_schema.png | Bin 17099 -> 0 bytes .../baeldung/dbunit/DataSourceDBUnitTest.java | 75 ++++---- .../java/com/baeldung/dbunit/DbUnitTest.java | 33 ++-- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 85 +++++---- .../dbunit/PrepAndExpectedDbUnitTest.java | 23 +-- libraries-testing/pom.xml | 37 ++++ .../baeldung/dbunit/ConnectionSettings.java | 8 + .../baeldung/dbunit/DataSourceDBUnitTest.java | 136 +++++++++++++++ .../java/com/baeldung/dbunit/DbUnitTest.java | 90 ++++++++++ .../baeldung/dbunit/OldSchoolDbUnitTest.java | 161 ++++++++++++++++++ .../dbunit/PrepAndExpectedDbUnitTest.java | 89 ++++++++++ .../src/test/resources/dbunit/data.xml | 9 + .../expected-ignoring-registered_at.xml | 9 + .../dbunit/expected-multiple-failures.xml | 9 + .../test/resources/dbunit/expected-user.xml | 4 + .../src/test/resources/dbunit/items.xml | 8 + .../resources/dbunit/items_exp_delete.xml | 7 + .../dbunit/items_exp_delete_no_produced.xml | 7 + .../resources/dbunit/items_exp_rename.xml | 8 + .../dbunit/items_exp_rename_no_produced.xml | 8 + .../src/test/resources/dbunit/schema.sql | 28 +++ .../src/test/resources/dbunit/users.xml | 6 + .../resources/dbunit/users_exp_delete.xml | 5 + .../resources/dbunit/users_exp_rename.xml | 6 + 25 files changed, 758 insertions(+), 95 deletions(-) delete mode 100644 dbunit/docs/db_schema.png create mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java create mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java create mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java create mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java create mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java create mode 100644 libraries-testing/src/test/resources/dbunit/data.xml create mode 100644 libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml create mode 100644 libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml create mode 100644 libraries-testing/src/test/resources/dbunit/expected-user.xml create mode 100644 libraries-testing/src/test/resources/dbunit/items.xml create mode 100644 libraries-testing/src/test/resources/dbunit/items_exp_delete.xml create mode 100644 libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml create mode 100644 libraries-testing/src/test/resources/dbunit/items_exp_rename.xml create mode 100644 libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml create mode 100644 libraries-testing/src/test/resources/dbunit/schema.sql create mode 100644 libraries-testing/src/test/resources/dbunit/users.xml create mode 100644 libraries-testing/src/test/resources/dbunit/users_exp_delete.xml create mode 100644 libraries-testing/src/test/resources/dbunit/users_exp_rename.xml diff --git a/dbunit/README.md b/dbunit/README.md index 383bd6fb7e..333cac9439 100644 --- a/dbunit/README.md +++ b/dbunit/README.md @@ -1,6 +1,4 @@ ### Database schema -![db schema](docs/db_schema.png) - ### Relevant Articles: - [Introduction To DBUnit](https://www.baeldung.com/dbunit) diff --git a/dbunit/docs/db_schema.png b/dbunit/docs/db_schema.png deleted file mode 100644 index d9185bacd2c624c8e05aea87bf542cfdfd7f1604..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17099 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 formatDifference((Difference) d)).collect(joining("\n")); -// throw new AssertionError(message); + try (final InputStream is = getClass() + .getClassLoader() + .getResourceAsStream("expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java index 1dee5afb28..d24410bedf 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -31,8 +31,9 @@ public class DbUnitTest extends DBTestCase { @Override protected IDataSet getDataSet() throws Exception { - final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); - return new FlatXmlDataSetBuilder().build(is); + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } } @Override @@ -52,37 +53,39 @@ public class DbUnitTest extends DBTestCase { final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); assertThat(rs.next()).isTrue(); - assertThat(rs.getString( "title")).isEqualTo("Grey T-Shirt"); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test public void testDelete() throws Exception { final Connection connection = getConnection().getConnection(); - final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); - Assertion.assertEquals(expectedTable, actualTable); + Assertion.assertEquals(expectedTable, actualTable); + } } @Test public void testUpdate() throws Exception { final Connection connection = getConnection().getConnection(); - final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); - Assertion.assertEquals(expectedTable, actualTable); + Assertion.assertEquals(expectedTable, actualTable); + } } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index 3b46feb304..41d7ffd8d4 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -42,8 +42,9 @@ public class OldSchoolDbUnitTest { } private static IDataSet initDataSet() throws Exception { - final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml"); - return new FlatXmlDataSetBuilder().build(is); + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } } @Before @@ -70,78 +71,92 @@ public class OldSchoolDbUnitTest { public void testIgnoringProduced() throws Exception { final Connection connection = tester.getConnection().getConnection(); final String[] excludedColumns = {"id", "produced"}; - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getClassLoader() - .getResourceAsStream("expected-ignoring-registered_at.xml")); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + try (final InputStream is = getClass().getClassLoader() + .getResourceAsStream("expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); - connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); - Assertion.assertEquals(expectedTable, actualTable); + Assertion.assertEquals(expectedTable, actualTable); + } } @Test public void testDelete() throws Exception { final Connection connection = tester.getConnection().getConnection(); - final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml"); - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + try (final InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("items_exp_delete.xml");) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); - assertEquals(expectedTable, actualTable); + assertEquals(expectedTable, actualTable); + } } @Test public void testDeleteWithExcludedColumns() throws Exception { final Connection connection = tester.getConnection().getConnection(); - final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete_no_produced.xml"); - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + try (final InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - assertEquals(expectedTable, actualTable); + assertEquals(expectedTable, actualTable); + } } @Test public void testUpdate() throws Exception { final Connection connection = tester.getConnection().getConnection(); - final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml"); - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + try (final InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); - assertEquals(expectedTable, actualTable); + assertEquals(expectedTable, actualTable); + } } @Test public void testUpdateWithExcludedColumns() throws Exception { final Connection connection = tester.getConnection().getConnection(); - final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename_no_produced.xml"); - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + try (final InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - assertEquals(expectedTable, actualTable); + assertEquals(expectedTable, actualTable); + } } } diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index 2c7e5de508..b4e23f56ff 100644 --- a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -39,8 +39,9 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { } private IDataSet initDataSet() throws Exception { - final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml"); - return new FlatXmlDataSetBuilder().build(is); + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } } private DataFileLoader initDataFileLoader() { @@ -53,10 +54,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = - () -> connection - .createStatement() - .executeQuery("select * from CLIENTS where id = 1"); + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeQuery("select * from CLIENTS where id = 1"); final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); @@ -70,10 +69,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users_exp_rename.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = - () -> connection - .createStatement() - .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } @@ -84,10 +81,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; final String[] prepDataFiles = {"/users.xml"}; final String[] expectedDataFiles = {"/users_exp_delete.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = - () -> connection - .createStatement() - .executeUpdate("delete from CLIENTS where id = 2"); + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeUpdate("delete from CLIENTS where id = 2"); super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); } diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index 3ffbb291a0..c4d2786441 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -130,6 +130,27 @@ ${asciidoctor.version} + + org.dbunit + dbunit + ${dbunit.version} + test + + + + com.h2database + h2 + ${h2.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + @@ -150,6 +171,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.target} + + + @@ -166,6 +197,12 @@ 4.1.1 3.6.2 2.0.0.0 + 1.4.200 + 2.6.0 + 3.14.0 + 1.8 + 1.8 + 3.8.1 diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java new file mode 100644 index 0000000000..cc29d9c58a --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -0,0 +1,8 @@ +package com.baeldung.dbunit; + +public class ConnectionSettings { + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java new file mode 100644 index 0000000000..662ed44fb6 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -0,0 +1,136 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.DataSourceBasedDBTestCase; +import org.dbunit.assertion.DiffCollectingFailureHandler; +import org.dbunit.assertion.Difference; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static java.util.stream.Collectors.joining; +import static org.assertj.core.api.Assertions.assertThat; + +public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { + + private static Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + + @Override + protected javax.sql.DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(JDBC_URL); + dataSource.setUser("sa"); + dataSource.setPassword(""); + return dataSource; + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (java.io.InputStream resourceAsStream = getClass() + .getClassLoader() + .getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(resourceAsStream); + } + } + + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + } + + + @Test + public void testSimpleDataSet() throws SQLException { + final Connection connection = getDataSource() + .getConnection(); + + final ResultSet rs = connection + .createStatement() + .executeQuery("select * from iTEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testEmptySchema() throws Exception { + final IDataSet expectedDataSet = getDataSet(); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void testAssertByQuery() throws Exception { + try (final java.io.InputStream is = getClass() + .getClassLoader() + .getResourceAsStream("dbunit/expected-user.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final Connection conn = getDataSource().getConnection(); + + conn.createStatement() + .executeUpdate( + "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection() + .createQueryTable( + "result_name", + "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + + Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"}); + } + } + + @Test + public void testMultipleFailures() throws Exception { + try (final java.io.InputStream is = getClass() + .getClassLoader() + .getResourceAsStream("dbunit/expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } + } + } + + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java new file mode 100644 index 0000000000..3ed77b2c25 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.DBTestCase; +import org.dbunit.PropertiesBasedJdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.junit.Test; + +import java.sql.Connection; +import java.sql.ResultSet; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; + +public class DbUnitTest extends DBTestCase { + + public DbUnitTest(String name) { + super(name); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } + + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Test + public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java new file mode 100644 index 0000000000..aa6d9143bb --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -0,0 +1,161 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.DefaultColumnFilter; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.sql.Connection; +import java.sql.ResultSet; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEquals; + +public class OldSchoolDbUnitTest { + + private static IDatabaseTester tester = null; + + @BeforeClass + public static void setUp() throws Exception { + tester = initDatabaseTester(); + } + + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); + return tester; + } + + private static IDataSet initDataSet() throws Exception { + try (final java.io.InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } + + @Before + public void setup() throws Exception { + tester.onSetup(); + } + + @After + public void tearDown() throws Exception { + tester.onTearDown(); + } + + @Test + public void testSelect() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testIgnoringProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = {"id", "produced"}; + try (final java.io.InputStream is = getClass().getClassLoader() + .getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void testDelete() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final java.io.InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_delete.xml");) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void testDeleteWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final java.io.InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void testUpdate() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final java.io.InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void testUpdateWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final java.io.InputStream is = + OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("items"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); + + assertEquals(expectedTable, actualTable); + } + } + +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java new file mode 100644 index 0000000000..7e77cd8fc3 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.dbunit; + +import org.dbunit.DefaultPrepAndExpectedTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.PrepAndExpectedTestCaseSteps; +import org.dbunit.VerifyTableDefinition; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.dbunit.util.fileloader.DataFileLoader; +import org.dbunit.util.fileloader.FlatXmlDataFileLoader; +import org.junit.Test; + +import java.sql.Connection; +import java.sql.ResultSet; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; + +public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { + + @Override + public void setUp() throws Exception { + setDatabaseTester(initDatabaseTester()); + setDataFileLoader(initDataFileLoader()); + super.setUp(); + } + + private IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + return tester; + } + + private IDataSet initDataSet() throws Exception { + try (final java.io.InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } + + private DataFileLoader initDataFileLoader() { + return new FlatXmlDataFileLoader(); + } + + @Test + public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; + final String[] prepDataFiles = {"/dbunit/users.xml"}; + final String[] expectedDataFiles = {"/dbunit/users.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeQuery("select * from CLIENTS where id = 1"); + + final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("last_name")).isEqualTo("Xavier"); + } + + @Test + public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify + final String[] prepDataFiles = {"/dbunit/users.xml"}; + final String[] expectedDataFiles = {"/dbunit/users_exp_rename.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); + + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } + + @Test + public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; + final String[] prepDataFiles = {"/dbunit/users.xml"}; + final String[] expectedDataFiles = {"/dbunit/users_exp_delete.xml"}; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() + .executeUpdate("delete from CLIENTS where id = 2"); + + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } + +} diff --git a/libraries-testing/src/test/resources/dbunit/data.xml b/libraries-testing/src/test/resources/dbunit/data.xml new file mode 100644 index 0000000000..290cc36890 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/data.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-user.xml b/libraries-testing/src/test/resources/dbunit/expected-user.xml new file mode 100644 index 0000000000..631dd84210 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-user.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/items.xml b/libraries-testing/src/test/resources/dbunit/items.xml new file mode 100644 index 0000000000..d13e93bbe0 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml new file mode 100644 index 0000000000..a6fa2b33e8 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml new file mode 100644 index 0000000000..3e7f854f5f --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml new file mode 100644 index 0000000000..32f1d57cf6 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml new file mode 100644 index 0000000000..b42d3804fa --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/schema.sql b/libraries-testing/src/test/resources/dbunit/schema.sql new file mode 100644 index 0000000000..c2a8d2d630 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/schema.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS CLIENTS +( + `id` int AUTO_INCREMENT NOT NULL, + `first_name` varchar(100) NOT NULL, + `last_name` varchar(100) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS ITEMS +( + `id` int AUTO_INCREMENT NOT NULL, + `title` varchar(100) NOT NULL, + `produced` date, + `price` float, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS PURCHASES +( + `id` int NOT NULL AUTO_INCREMENT, + `id_user` int NOT NULL, + `id_item` int NOT NULL, + `total_price` float NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/libraries-testing/src/test/resources/dbunit/users.xml b/libraries-testing/src/test/resources/dbunit/users.xml new file mode 100644 index 0000000000..9ac3909bc5 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml new file mode 100644 index 0000000000..2fe97ae6f6 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml new file mode 100644 index 0000000000..95682118bb --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml @@ -0,0 +1,6 @@ + + + + + + From ee185d85b57e3b5036cec9aa3d5b13c08dc94ada Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 31 Mar 2020 20:19:11 +0200 Subject: [PATCH 15/97] [BAEL-2749] Removes dbunit module --- dbunit/README.md | 4 - dbunit/pom.xml | 62 ------- .../main/java/com/baeldung/dbunit/.gitkeep | 0 dbunit/src/main/resources/logback.xml | 13 -- .../baeldung/dbunit/ConnectionSettings.java | 8 - .../baeldung/dbunit/DataSourceDBUnitTest.java | 138 --------------- .../java/com/baeldung/dbunit/DbUnitTest.java | 91 ---------- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 162 ------------------ .../dbunit/PrepAndExpectedDbUnitTest.java | 90 ---------- dbunit/src/test/resources/data.xml | 9 - .../expected-ignoring-registered_at.xml | 9 - .../resources/expected-multiple-failures.xml | 9 - dbunit/src/test/resources/expected-user.xml | 4 - dbunit/src/test/resources/items.xml | 8 - .../src/test/resources/items_exp_delete.xml | 7 - .../items_exp_delete_no_produced.xml | 7 - .../src/test/resources/items_exp_rename.xml | 8 - .../items_exp_rename_no_produced.xml | 8 - dbunit/src/test/resources/schema.sql | 28 --- dbunit/src/test/resources/users.xml | 6 - .../src/test/resources/users_exp_delete.xml | 5 - .../src/test/resources/users_exp_rename.xml | 6 - 22 files changed, 682 deletions(-) delete mode 100644 dbunit/README.md delete mode 100644 dbunit/pom.xml delete mode 100644 dbunit/src/main/java/com/baeldung/dbunit/.gitkeep delete mode 100644 dbunit/src/main/resources/logback.xml delete mode 100644 dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java delete mode 100644 dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java delete mode 100644 dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java delete mode 100644 dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java delete mode 100644 dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java delete mode 100644 dbunit/src/test/resources/data.xml delete mode 100644 dbunit/src/test/resources/expected-ignoring-registered_at.xml delete mode 100644 dbunit/src/test/resources/expected-multiple-failures.xml delete mode 100644 dbunit/src/test/resources/expected-user.xml delete mode 100644 dbunit/src/test/resources/items.xml delete mode 100644 dbunit/src/test/resources/items_exp_delete.xml delete mode 100644 dbunit/src/test/resources/items_exp_delete_no_produced.xml delete mode 100644 dbunit/src/test/resources/items_exp_rename.xml delete mode 100644 dbunit/src/test/resources/items_exp_rename_no_produced.xml delete mode 100644 dbunit/src/test/resources/schema.sql delete mode 100644 dbunit/src/test/resources/users.xml delete mode 100644 dbunit/src/test/resources/users_exp_delete.xml delete mode 100644 dbunit/src/test/resources/users_exp_rename.xml diff --git a/dbunit/README.md b/dbunit/README.md deleted file mode 100644 index 333cac9439..0000000000 --- a/dbunit/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### Database schema - -### Relevant Articles: -- [Introduction To DBUnit](https://www.baeldung.com/dbunit) diff --git a/dbunit/pom.xml b/dbunit/pom.xml deleted file mode 100644 index 7ca53cd3be..0000000000 --- a/dbunit/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - 4.0.0 - dbunit - 1.0 - - 1.4.200 - - 1.8 - 1.8 - 3.8.1 - - 3.14.0 - 2.6.0 - - - dbunit - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.dbunit - dbunit - ${dbunit.version} - test - - - - com.h2database - h2 - ${h2.version} - test - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven-compiler-plugin.source} - ${maven-compiler-plugin.target} - - - - - - diff --git a/dbunit/src/main/java/com/baeldung/dbunit/.gitkeep b/dbunit/src/main/java/com/baeldung/dbunit/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/dbunit/src/main/resources/logback.xml b/dbunit/src/main/resources/logback.xml deleted file mode 100644 index 26beb6d5b4..0000000000 --- a/dbunit/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java deleted file mode 100644 index e842022292..0000000000 --- a/dbunit/src/test/java/com/baeldung/dbunit/ConnectionSettings.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.dbunit; - -public class ConnectionSettings { - public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'"; - public static final String USER = "sa"; - public static final String PASSWORD = ""; -} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java deleted file mode 100644 index 606f1a90a3..0000000000 --- a/dbunit/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.Assertion; -import org.dbunit.DataSourceBasedDBTestCase; -import org.dbunit.assertion.DiffCollectingFailureHandler; -import org.dbunit.assertion.Difference; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.h2.jdbcx.JdbcDataSource; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.platform.commons.logging.Logger; -import org.junit.platform.commons.logging.LoggerFactory; - -import javax.sql.DataSource; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static java.util.stream.Collectors.joining; -import static org.assertj.core.api.Assertions.assertThat; - -public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { - - private static Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); - - @Override - protected DataSource getDataSource() { - JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL(JDBC_URL); - dataSource.setUser("sa"); - dataSource.setPassword(""); - return dataSource; - } - - @Override - protected IDataSet getDataSet() throws Exception { - try (InputStream resourceAsStream = getClass() - .getClassLoader() - .getResourceAsStream("data.xml")) { - return new FlatXmlDataSetBuilder().build(resourceAsStream); - } - } - - @Override - protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override - protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Before - public void setUp() throws Exception { - super.setUp(); - } - - @After - public void tearDown() throws Exception { - super.tearDown(); - } - - - @Test - public void testSimpleDataSet() throws SQLException { - final Connection connection = getDataSource() - .getConnection(); - - final ResultSet rs = connection - .createStatement() - .executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testEmptySchema() throws Exception { - final IDataSet expectedDataSet = getDataSet(); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - final ITable actualTable = databaseDataSet.getTable("CLIENTS"); - Assertion.assertEquals(expectedTable, actualTable); - } - - @Test - public void testAssertByQuery() throws Exception { - try (final InputStream is = getClass() - .getClassLoader() - .getResourceAsStream("expected-user.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final Connection conn = getDataSource().getConnection(); - - conn.createStatement() - .executeUpdate( - "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); - final ITable actualData = getConnection() - .createQueryTable( - "result_name", - "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); - - Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"}); - } - } - - @Test - public void testMultipleFailures() throws Exception { - try (final InputStream is = getClass() - .getClassLoader() - .getResourceAsStream("expected-multiple-failures.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("ITEMS"); - final Connection conn = getDataSource().getConnection(); - final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); - - conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); - final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualData, collectingHandler); - if (!collectingHandler.getDiffList().isEmpty()) { - String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); - logger.error(() -> message); - } - } - } - - private static String formatDifference(Difference diff) { - return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); - } -} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java deleted file mode 100644 index d24410bedf..0000000000 --- a/dbunit/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.Assertion; -import org.dbunit.DBTestCase; -import org.dbunit.PropertiesBasedJdbcDatabaseTester; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.junit.Test; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; -import static com.baeldung.dbunit.ConnectionSettings.USER; -import static org.assertj.core.api.Assertions.assertThat; - -public class DbUnitTest extends DBTestCase { - - public DbUnitTest(String name) { - super(name); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); - } - - @Override - protected IDataSet getDataSet() throws Exception { - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } - - @Override - protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override - protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - -} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java deleted file mode 100644 index 41d7ffd8d4..0000000000 --- a/dbunit/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.Assertion; -import org.dbunit.IDatabaseTester; -import org.dbunit.JdbcDatabaseTester; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.filter.DefaultColumnFilter; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; -import static com.baeldung.dbunit.ConnectionSettings.USER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.dbunit.Assertion.assertEquals; - -public class OldSchoolDbUnitTest { - - private static IDatabaseTester tester = null; - - @BeforeClass - public static void setUp() throws Exception { - tester = initDatabaseTester(); - } - - private static IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); - return tester; - } - - private static IDataSet initDataSet() throws Exception { - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } - - @Before - public void setup() throws Exception { - tester.onSetup(); - } - - @After - public void tearDown() throws Exception { - tester.onTearDown(); - } - - @Test - public void testSelect() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testIgnoringProduced() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - final String[] excludedColumns = {"id", "produced"}; - try (final InputStream is = getClass().getClassLoader() - .getResourceAsStream("expected-ignoring-registered_at.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); - - connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testDelete() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("items_exp_delete.xml");) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testDeleteWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("items_exp_delete_no_produced.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - - assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testUpdate() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("items_exp_rename.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testUpdateWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("items_exp_rename_no_produced.xml")) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - - assertEquals(expectedTable, actualTable); - } - } - -} diff --git a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java deleted file mode 100644 index b4e23f56ff..0000000000 --- a/dbunit/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.DefaultPrepAndExpectedTestCase; -import org.dbunit.IDatabaseTester; -import org.dbunit.JdbcDatabaseTester; -import org.dbunit.PrepAndExpectedTestCaseSteps; -import org.dbunit.VerifyTableDefinition; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.dbunit.util.fileloader.DataFileLoader; -import org.dbunit.util.fileloader.FlatXmlDataFileLoader; -import org.junit.Test; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; -import static com.baeldung.dbunit.ConnectionSettings.USER; -import static org.assertj.core.api.Assertions.assertThat; - -public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { - - @Override - public void setUp() throws Exception { - setDatabaseTester(initDatabaseTester()); - setDataFileLoader(initDataFileLoader()); - super.setUp(); - } - - private IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - return tester; - } - - private IDataSet initDataSet() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } - - private DataFileLoader initDataFileLoader() { - return new FlatXmlDataFileLoader(); - } - - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; - final String[] prepDataFiles = {"/users.xml"}; - final String[] expectedDataFiles = {"/users.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeQuery("select * from CLIENTS where id = 1"); - - final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("last_name")).isEqualTo("Xavier"); - } - - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify - final String[] prepDataFiles = {"/users.xml"}; - final String[] expectedDataFiles = {"/users_exp_rename.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); - - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } - - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; - final String[] prepDataFiles = {"/users.xml"}; - final String[] expectedDataFiles = {"/users_exp_delete.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeUpdate("delete from CLIENTS where id = 2"); - - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } - -} diff --git a/dbunit/src/test/resources/data.xml b/dbunit/src/test/resources/data.xml deleted file mode 100644 index 290cc36890..0000000000 --- a/dbunit/src/test/resources/data.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/dbunit/src/test/resources/expected-ignoring-registered_at.xml b/dbunit/src/test/resources/expected-ignoring-registered_at.xml deleted file mode 100644 index ea57b6a961..0000000000 --- a/dbunit/src/test/resources/expected-ignoring-registered_at.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/dbunit/src/test/resources/expected-multiple-failures.xml b/dbunit/src/test/resources/expected-multiple-failures.xml deleted file mode 100644 index ea57b6a961..0000000000 --- a/dbunit/src/test/resources/expected-multiple-failures.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/dbunit/src/test/resources/expected-user.xml b/dbunit/src/test/resources/expected-user.xml deleted file mode 100644 index 631dd84210..0000000000 --- a/dbunit/src/test/resources/expected-user.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/dbunit/src/test/resources/items.xml b/dbunit/src/test/resources/items.xml deleted file mode 100644 index d13e93bbe0..0000000000 --- a/dbunit/src/test/resources/items.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/dbunit/src/test/resources/items_exp_delete.xml b/dbunit/src/test/resources/items_exp_delete.xml deleted file mode 100644 index a6fa2b33e8..0000000000 --- a/dbunit/src/test/resources/items_exp_delete.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/dbunit/src/test/resources/items_exp_delete_no_produced.xml b/dbunit/src/test/resources/items_exp_delete_no_produced.xml deleted file mode 100644 index 3e7f854f5f..0000000000 --- a/dbunit/src/test/resources/items_exp_delete_no_produced.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/dbunit/src/test/resources/items_exp_rename.xml b/dbunit/src/test/resources/items_exp_rename.xml deleted file mode 100644 index 32f1d57cf6..0000000000 --- a/dbunit/src/test/resources/items_exp_rename.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/dbunit/src/test/resources/items_exp_rename_no_produced.xml b/dbunit/src/test/resources/items_exp_rename_no_produced.xml deleted file mode 100644 index b42d3804fa..0000000000 --- a/dbunit/src/test/resources/items_exp_rename_no_produced.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/dbunit/src/test/resources/schema.sql b/dbunit/src/test/resources/schema.sql deleted file mode 100644 index c2a8d2d630..0000000000 --- a/dbunit/src/test/resources/schema.sql +++ /dev/null @@ -1,28 +0,0 @@ -CREATE TABLE IF NOT EXISTS CLIENTS -( - `id` int AUTO_INCREMENT NOT NULL, - `first_name` varchar(100) NOT NULL, - `last_name` varchar(100) NOT NULL, - PRIMARY KEY (`id`) -); - -CREATE TABLE IF NOT EXISTS ITEMS -( - `id` int AUTO_INCREMENT NOT NULL, - `title` varchar(100) NOT NULL, - `produced` date, - `price` float, - PRIMARY KEY (`id`) -); - -CREATE TABLE IF NOT EXISTS PURCHASES -( - `id` int NOT NULL AUTO_INCREMENT, - `id_user` int NOT NULL, - `id_item` int NOT NULL, - `total_price` float NOT NULL, - `quantity` int(11) NOT NULL, - PRIMARY KEY (`id`), - FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE, - FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); diff --git a/dbunit/src/test/resources/users.xml b/dbunit/src/test/resources/users.xml deleted file mode 100644 index 9ac3909bc5..0000000000 --- a/dbunit/src/test/resources/users.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/dbunit/src/test/resources/users_exp_delete.xml b/dbunit/src/test/resources/users_exp_delete.xml deleted file mode 100644 index 2fe97ae6f6..0000000000 --- a/dbunit/src/test/resources/users_exp_delete.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/dbunit/src/test/resources/users_exp_rename.xml b/dbunit/src/test/resources/users_exp_rename.xml deleted file mode 100644 index 95682118bb..0000000000 --- a/dbunit/src/test/resources/users_exp_rename.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - From dc75e11440a687431620b26d3ed4f8d812e0a293 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Wed, 1 Apr 2020 07:44:25 +0200 Subject: [PATCH 16/97] [BAEL-2749] DBUnit documentation --- libraries-testing/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-testing/README.md b/libraries-testing/README.md index 332debfe18..7098c10d28 100644 --- a/libraries-testing/README.md +++ b/libraries-testing/README.md @@ -11,3 +11,4 @@ This module contains articles about test libraries. - [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing) - [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly) - [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide) +- [Introduction To DBUnit](https://www.baeldung.com/dbunit) From c0abc0ed354f073d0f3958308acb4939f11c49fb Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Wed, 1 Apr 2020 19:44:48 +0200 Subject: [PATCH 17/97] [BAEL-2749] Uses static imports and uses code format --- .../baeldung/dbunit/ConnectionSettings.java | 8 +- .../baeldung/dbunit/DataSourceDBUnitTest.java | 178 ++++++-------- .../java/com/baeldung/dbunit/DbUnitTest.java | 117 +++++----- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 219 ++++++++---------- .../dbunit/PrepAndExpectedDbUnitTest.java | 100 ++++---- pom.xml | 1 - 6 files changed, 285 insertions(+), 338 deletions(-) diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java index cc29d9c58a..b30d636a12 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -1,8 +1,8 @@ package com.baeldung.dbunit; public class ConnectionSettings { - public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; - public static final String USER = "sa"; - public static final String PASSWORD = ""; + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 662ed44fb6..1cb7489688 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -15,6 +15,7 @@ import org.junit.Test; import org.junit.platform.commons.logging.Logger; import org.junit.platform.commons.logging.LoggerFactory; +import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -25,112 +26,87 @@ import static org.assertj.core.api.Assertions.assertThat; public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { - private static Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); - @Override - protected javax.sql.DataSource getDataSource() { - JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL(JDBC_URL); - dataSource.setUser("sa"); - dataSource.setPassword(""); - return dataSource; - } - - @Override - protected IDataSet getDataSet() throws Exception { - try (java.io.InputStream resourceAsStream = getClass() - .getClassLoader() - .getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(resourceAsStream); + @Override protected javax.sql.DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(JDBC_URL); + dataSource.setUser("sa"); + dataSource.setPassword(""); + return dataSource; } - } - @Override - protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override - protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Before - public void setUp() throws Exception { - super.setUp(); - } - - @After - public void tearDown() throws Exception { - super.tearDown(); - } - - - @Test - public void testSimpleDataSet() throws SQLException { - final Connection connection = getDataSource() - .getConnection(); - - final ResultSet rs = connection - .createStatement() - .executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testEmptySchema() throws Exception { - final IDataSet expectedDataSet = getDataSet(); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - final ITable actualTable = databaseDataSet.getTable("CLIENTS"); - Assertion.assertEquals(expectedTable, actualTable); - } - - @Test - public void testAssertByQuery() throws Exception { - try (final java.io.InputStream is = getClass() - .getClassLoader() - .getResourceAsStream("dbunit/expected-user.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final Connection conn = getDataSource().getConnection(); - - conn.createStatement() - .executeUpdate( - "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); - final ITable actualData = getConnection() - .createQueryTable( - "result_name", - "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); - - Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"}); + @Override protected IDataSet getDataSet() throws Exception { + try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(resourceAsStream); + } } - } - @Test - public void testMultipleFailures() throws Exception { - try (final java.io.InputStream is = getClass() - .getClassLoader() - .getResourceAsStream("dbunit/expected-multiple-failures.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("ITEMS"); - final Connection conn = getDataSource().getConnection(); - final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); - - conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); - final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualData, collectingHandler); - if (!collectingHandler.getDiffList().isEmpty()) { - String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); - logger.error(() -> message); - } + @Override protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; } - } - private static String formatDifference(Difference diff) { - return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); - } + @Override protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before public void setUp() throws Exception { + super.setUp(); + } + + @After public void tearDown() throws Exception { + super.tearDown(); + } + + @Test public void testSimpleDataSet() throws SQLException { + final Connection connection = getDataSource().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test public void testEmptySchema() throws Exception { + final IDataSet expectedDataSet = getDataSet(); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test public void testAssertByQuery() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final Connection conn = getDataSource().getConnection(); + + conn.createStatement().executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection().createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + + Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); + } + } + + @Test public void testMultipleFailures() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } + } + } + + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java index 3ed77b2c25..a3a41b9b8d 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -9,6 +9,7 @@ import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import org.junit.Test; +import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; @@ -20,71 +21,65 @@ import static org.assertj.core.api.Assertions.assertThat; public class DbUnitTest extends DBTestCase { - public DbUnitTest(String name) { - super(name); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); - } - - @Override - protected IDataSet getDataSet() throws Exception { - try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); + public DbUnitTest(String name) { + super(name); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); } - } - @Override - protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override - protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - Assertion.assertEquals(expectedTable, actualTable); + @Override protected IDataSet getDataSet() throws Exception { + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } } - } - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - Assertion.assertEquals(expectedTable, actualTable); + @Override protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Test public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } } - } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index aa6d9143bb..be6023d432 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -13,6 +13,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; @@ -25,137 +26,119 @@ import static org.dbunit.Assertion.assertEquals; public class OldSchoolDbUnitTest { - private static IDatabaseTester tester = null; + private static IDatabaseTester tester = null; - @BeforeClass - public static void setUp() throws Exception { - tester = initDatabaseTester(); - } - - private static IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); - return tester; - } - - private static IDataSet initDataSet() throws Exception { - try (final java.io.InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); + @BeforeClass public static void setUp() throws Exception { + tester = initDatabaseTester(); } - } - @Before - public void setup() throws Exception { - tester.onSetup(); - } - - @After - public void tearDown() throws Exception { - tester.onTearDown(); - } - - @Test - public void testSelect() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testIgnoringProduced() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - final String[] excludedColumns = {"id", "produced"}; - try (final java.io.InputStream is = getClass().getClassLoader() - .getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); - - connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); - - Assertion.assertEquals(expectedTable, actualTable); + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); + return tester; } - } - @Test - public void testDelete() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final java.io.InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("dbunit/items_exp_delete.xml");) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - assertEquals(expectedTable, actualTable); + private static IDataSet initDataSet() throws Exception { + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } } - } - @Test - public void testDeleteWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final java.io.InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - - assertEquals(expectedTable, actualTable); + @Before public void setup() throws Exception { + tester.onSetup(); } - } - @Test - public void testUpdate() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final java.io.InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("dbunit/items_exp_rename.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - - assertEquals(expectedTable, actualTable); + @After public void tearDown() throws Exception { + tester.onTearDown(); } - } - @Test - public void testUpdateWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); + @Test public void testSelect() throws Exception { + final Connection connection = tester.getConnection().getConnection(); - try (final java.io.InputStream is = - OldSchoolDbUnitTest.class.getClassLoader() - .getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items"); + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("items"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"}); - - assertEquals(expectedTable, actualTable); + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test public void testIgnoringProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = { "id", "produced" }; + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test public void testDelete() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test public void testDeleteWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); + } + } + + @Test public void testUpdate() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test public void testUpdateWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); + } } - } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index 7e77cd8fc3..f797f153a0 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -12,6 +12,7 @@ import org.dbunit.util.fileloader.DataFileLoader; import org.dbunit.util.fileloader.FlatXmlDataFileLoader; import org.junit.Test; +import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; @@ -23,67 +24,60 @@ import static org.assertj.core.api.Assertions.assertThat; public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { - @Override - public void setUp() throws Exception { - setDatabaseTester(initDatabaseTester()); - setDataFileLoader(initDataFileLoader()); - super.setUp(); - } - - private IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - return tester; - } - - private IDataSet initDataSet() throws Exception { - try (final java.io.InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); + @Override public void setUp() throws Exception { + setDatabaseTester(initDatabaseTester()); + setDataFileLoader(initDataFileLoader()); + super.setUp(); } - } - private DataFileLoader initDataFileLoader() { - return new FlatXmlDataFileLoader(); - } + private IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + return tester; + } - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; - final String[] prepDataFiles = {"/dbunit/users.xml"}; - final String[] expectedDataFiles = {"/dbunit/users.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeQuery("select * from CLIENTS where id = 1"); + private IDataSet initDataSet() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } - final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + private DataFileLoader initDataFileLoader() { + return new FlatXmlDataFileLoader(); + } - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("last_name")).isEqualTo("Xavier"); - } + @Test public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeQuery("select * from CLIENTS where id = 1"); - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify - final String[] prepDataFiles = {"/dbunit/users.xml"}; - final String[] expectedDataFiles = {"/dbunit/users_exp_rename.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); + final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("last_name")).isEqualTo("Xavier"); + } - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; - final String[] prepDataFiles = {"/dbunit/users.xml"}; - final String[] expectedDataFiles = {"/dbunit/users_exp_delete.xml"}; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement() - .executeUpdate("delete from CLIENTS where id = 2"); + @Test public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; // define tables to verify + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users_exp_rename.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } + + @Test public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users_exp_delete.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("delete from CLIENTS where id = 2"); + + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } } diff --git a/pom.xml b/pom.xml index 734e2c8ab9..8b09f69252 100644 --- a/pom.xml +++ b/pom.xml @@ -601,7 +601,6 @@ - dbunit parent-boot-1 parent-boot-2 From 064e16251be28928331af940acf6b39fe9258dda Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Wed, 1 Apr 2020 20:02:46 +0200 Subject: [PATCH 18/97] [BAEL-2749] Formats pom --- pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/pom.xml b/pom.xml index 8b09f69252..04a2ce054c 100644 --- a/pom.xml +++ b/pom.xml @@ -601,7 +601,6 @@ - parent-boot-1 parent-boot-2 parent-spring-4 @@ -1289,8 +1288,6 @@ - dbunit - parent-boot-1 parent-boot-2 parent-spring-4 From f06af6499859b3dcd45d14d2060631a4fd1f0241 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Thu, 2 Apr 2020 11:20:34 +0200 Subject: [PATCH 19/97] [BAEL-2749] Indentation and annotations format --- .../baeldung/dbunit/ConnectionSettings.java | 8 +- .../baeldung/dbunit/DataSourceDBUnitTest.java | 162 +++++++------- .../java/com/baeldung/dbunit/DbUnitTest.java | 116 +++++----- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 209 +++++++++--------- .../dbunit/PrepAndExpectedDbUnitTest.java | 96 ++++---- 5 files changed, 310 insertions(+), 281 deletions(-) diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java index b30d636a12..cc29d9c58a 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -1,8 +1,8 @@ package com.baeldung.dbunit; public class ConnectionSettings { - public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); - public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; - public static final String USER = "sa"; - public static final String PASSWORD = ""; + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 1cb7489688..93503277b4 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -26,87 +26,97 @@ import static org.assertj.core.api.Assertions.assertThat; public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { - private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); - @Override protected javax.sql.DataSource getDataSource() { - JdbcDataSource dataSource = new JdbcDataSource(); - dataSource.setURL(JDBC_URL); - dataSource.setUser("sa"); - dataSource.setPassword(""); - return dataSource; + @Override + protected javax.sql.DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(JDBC_URL); + dataSource.setUser("sa"); + dataSource.setPassword(""); + return dataSource; + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(resourceAsStream); } + } - @Override protected IDataSet getDataSet() throws Exception { - try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(resourceAsStream); - } + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testSimpleDataSet() throws SQLException { + final Connection connection = getDataSource().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testEmptySchema() throws Exception { + final IDataSet expectedDataSet = getDataSet(); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void testAssertByQuery() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final Connection conn = getDataSource().getConnection(); + + conn.createStatement().executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection().createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + + Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); } + } - @Override protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; + @Test + public void testMultipleFailures() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } } + } - @Override protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Before public void setUp() throws Exception { - super.setUp(); - } - - @After public void tearDown() throws Exception { - super.tearDown(); - } - - @Test public void testSimpleDataSet() throws SQLException { - final Connection connection = getDataSource().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test public void testEmptySchema() throws Exception { - final IDataSet expectedDataSet = getDataSet(); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - final ITable actualTable = databaseDataSet.getTable("CLIENTS"); - Assertion.assertEquals(expectedTable, actualTable); - } - - @Test public void testAssertByQuery() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final Connection conn = getDataSource().getConnection(); - - conn.createStatement().executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); - final ITable actualData = getConnection().createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); - - Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); - } - } - - @Test public void testMultipleFailures() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("ITEMS"); - final Connection conn = getDataSource().getConnection(); - final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); - - conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); - final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualData, collectingHandler); - if (!collectingHandler.getDiffList().isEmpty()) { - String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); - logger.error(() -> message); - } - } - } - - private static String formatDifference(Difference diff) { - return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); - } + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java index a3a41b9b8d..da4ac54f12 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java @@ -21,65 +21,71 @@ import static org.assertj.core.api.Assertions.assertThat; public class DbUnitTest extends DBTestCase { - public DbUnitTest(String name) { - super(name); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); + public DbUnitTest(String name) { + super(name); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); + System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); } + } - @Override protected IDataSet getDataSet() throws Exception { - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Test + public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); } + } - @Override protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Test public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - - @Test public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualTable); - } + @Test + public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); } + } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index be6023d432..a7821102dc 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -26,119 +26,128 @@ import static org.dbunit.Assertion.assertEquals; public class OldSchoolDbUnitTest { - private static IDatabaseTester tester = null; + private static IDatabaseTester tester = null; - @BeforeClass public static void setUp() throws Exception { - tester = initDatabaseTester(); + @BeforeClass + public static void setUp() throws Exception { + tester = initDatabaseTester(); + } + + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); + return tester; + } + + private static IDataSet initDataSet() throws Exception { + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); } + } - private static IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); - return tester; + @Before + public void setup() throws Exception { + tester.onSetup(); + } + + @After + public void tearDown() throws Exception { + tester.onTearDown(); + } + + @Test + public void testSelect() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void testIgnoringProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = { "id", "produced" }; + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); } + } - private static IDataSet initDataSet() throws Exception { - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } + @Test + public void testDelete() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); } + } - @Before public void setup() throws Exception { - tester.onSetup(); + @Test + public void testDeleteWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); } + } - @After public void tearDown() throws Exception { - tester.onTearDown(); + @Test + public void testUpdate() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); } + } - @Test public void testSelect() throws Exception { - final Connection connection = tester.getConnection().getConnection(); + @Test + public void testUpdateWithExcludedColumns() throws Exception { + final Connection connection = tester.getConnection().getConnection(); - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test public void testIgnoringProduced() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - final String[] excludedColumns = { "id", "produced" }; - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); - - connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - - @Test public void testDelete() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - assertEquals(expectedTable, actualTable); - } - } - - @Test public void testDeleteWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); - - assertEquals(expectedTable, actualTable); - } - } - - @Test public void testUpdate() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - assertEquals(expectedTable, actualTable); - } - } - - @Test public void testUpdateWithExcludedColumns() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { - ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); - - assertEquals(expectedTable, actualTable); - } + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); } + } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java index f797f153a0..039dfd1639 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java @@ -24,60 +24,64 @@ import static org.assertj.core.api.Assertions.assertThat; public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { - @Override public void setUp() throws Exception { - setDatabaseTester(initDatabaseTester()); - setDataFileLoader(initDataFileLoader()); - super.setUp(); + @Override + public void setUp() throws Exception { + setDatabaseTester(initDatabaseTester()); + setDataFileLoader(initDataFileLoader()); + super.setUp(); + } + + private IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + return tester; + } + + private IDataSet initDataSet() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); } + } - private IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - return tester; - } + private DataFileLoader initDataFileLoader() { + return new FlatXmlDataFileLoader(); + } - private IDataSet initDataSet() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } + @Test + public void testSelect() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeQuery("select * from CLIENTS where id = 1"); - private DataFileLoader initDataFileLoader() { - return new FlatXmlDataFileLoader(); - } + final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - @Test public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeQuery("select * from CLIENTS where id = 1"); + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("last_name")).isEqualTo("Xavier"); + } - final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + @Test + public void testUpdate() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; // define tables to verify + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users_exp_rename.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("last_name")).isEqualTo("Xavier"); - } + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } - @Test public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; // define tables to verify - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users_exp_rename.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); + @Test + public void testDelete() throws Exception { + final Connection connection = getConnection().getConnection(); + final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; + final String[] prepDataFiles = { "/dbunit/users.xml" }; + final String[] expectedDataFiles = { "/dbunit/users_exp_delete.xml" }; + final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("delete from CLIENTS where id = 2"); - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } - - @Test public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users_exp_delete.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("delete from CLIENTS where id = 2"); - - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } + super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); + } } From e98323d913d19af96119a9d9220b8eebda64c2fc Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Fri, 3 Apr 2020 08:51:46 +0200 Subject: [PATCH 20/97] [BAEL-2749] Renaming test methods and running them with JUnit4 --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 63 +++++++++++-- .../java/com/baeldung/dbunit/DbUnitTest.java | 91 ------------------- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 26 ++++-- .../dbunit/PrepAndExpectedDbUnitTest.java | 87 ------------------ .../jsonassert/JsonAssertUnitTest.java | 10 +- .../src/test/resources/dbunit/data.xml | 2 +- .../dbunit/items_exp_rename_no_produced.xml | 2 +- .../src/test/resources/dbunit/users.xml | 2 +- .../resources/dbunit/users_exp_delete.xml | 2 +- .../resources/dbunit/users_exp_rename.xml | 2 +- 10 files changed, 80 insertions(+), 207 deletions(-) delete mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java delete mode 100644 libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 93503277b4..20b0337f4d 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -14,6 +14,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.platform.commons.logging.Logger; import org.junit.platform.commons.logging.LoggerFactory; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.InputStream; import java.sql.Connection; @@ -23,7 +25,9 @@ import java.sql.SQLException; import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEqualsIgnoreCols; +@RunWith(JUnit4.class) public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); @@ -65,7 +69,7 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { } @Test - public void testSimpleDataSet() throws SQLException { + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws SQLException { final Connection connection = getDataSource().getConnection(); final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); @@ -75,7 +79,7 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { } @Test - public void testEmptySchema() throws Exception { + public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception { final IDataSet expectedDataSet = getDataSet(); final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); final IDataSet databaseDataSet = getConnection().createDataSet(); @@ -84,33 +88,74 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { } @Test - public void testAssertByQuery() throws Exception { + public void givenDataSet_whenInsert_thenTableHasNewClient() throws Exception { try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); final Connection conn = getDataSource().getConnection(); - conn.createStatement().executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); - final ITable actualData = getConnection().createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + conn.createStatement() + .executeUpdate( + "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection() + .createQueryTable( + "result_name", + "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); - Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); + assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); } } @Test - public void testMultipleFailures() throws Exception { + public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenInsertUnexpectedData_thenFailOnAllUnexpectedValues() throws Exception { try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); final ITable expectedTable = expectedDataSet.getTable("ITEMS"); final Connection conn = getDataSource().getConnection(); final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); - conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + conn.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); Assertion.assertEquals(expectedTable, actualData, collectingHandler); if (!collectingHandler.getDiffList().isEmpty()) { - String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n")); + String message = (String) collectingHandler + .getDiffList() + .stream() + .map(d -> formatDifference((Difference) d)).collect(joining("\n")); logger.error(() -> message); } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java deleted file mode 100644 index da4ac54f12..0000000000 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DbUnitTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.Assertion; -import org.dbunit.DBTestCase; -import org.dbunit.PropertiesBasedJdbcDatabaseTester; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.junit.Test; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; -import static com.baeldung.dbunit.ConnectionSettings.USER; -import static org.assertj.core.api.Assertions.assertThat; - -public class DbUnitTest extends DBTestCase { - - public DbUnitTest(String name) { - super(name); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); - System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); - } - - @Override - protected IDataSet getDataSet() throws Exception { - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } - - @Override - protected DatabaseOperation getSetUpOperation() { - return DatabaseOperation.REFRESH; - } - - @Override - protected DatabaseOperation getTearDownOperation() { - return DatabaseOperation.DELETE_ALL; - } - - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); - } - - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); - - connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { - ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); - - connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - - final IDataSet databaseDataSet = getConnection().createDataSet(); - ITable actualTable = databaseDataSet.getTable("ITEMS"); - - Assertion.assertEquals(expectedTable, actualTable); - } - } - -} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index a7821102dc..6243af9676 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -12,6 +12,8 @@ import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.InputStream; import java.sql.Connection; @@ -24,6 +26,7 @@ import static com.baeldung.dbunit.ConnectionSettings.USER; import static org.assertj.core.api.Assertions.assertThat; import static org.dbunit.Assertion.assertEquals; +@RunWith(JUnit4.class) public class OldSchoolDbUnitTest { private static IDatabaseTester tester = null; @@ -58,7 +61,7 @@ public class OldSchoolDbUnitTest { } @Test - public void testSelect() throws Exception { + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws Exception { final Connection connection = tester.getConnection().getConnection(); final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); @@ -68,24 +71,27 @@ public class OldSchoolDbUnitTest { } @Test - public void testIgnoringProduced() throws Exception { + public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() throws Exception { final Connection connection = tester.getConnection().getConnection(); final String[] excludedColumns = { "id", "produced" }; try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable( + expectedDataSet.getTable("ITEMS"), excludedColumns); - connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + connection.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable( + databaseDataSet.getTable("ITEMS"), excludedColumns); Assertion.assertEquals(expectedTable, actualTable); } } @Test - public void testDelete() throws Exception { + public void givenDataSet_whenDelete_thenItemIsRemoved() throws Exception { final Connection connection = tester.getConnection().getConnection(); try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { @@ -101,7 +107,7 @@ public class OldSchoolDbUnitTest { } @Test - public void testDeleteWithExcludedColumns() throws Exception { + public void givenDataSet_whenDelete_thenItemIsRemovedAndResultsEqualIfProducedIsIgnored() throws Exception { final Connection connection = tester.getConnection().getConnection(); try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { @@ -118,7 +124,7 @@ public class OldSchoolDbUnitTest { } @Test - public void testUpdate() throws Exception { + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { final Connection connection = tester.getConnection().getConnection(); try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { @@ -134,18 +140,18 @@ public class OldSchoolDbUnitTest { } @Test - public void testUpdateWithExcludedColumns() throws Exception { + public void givenDataSet_whenUpdateWithNoProduced_thenItemHasNewName() throws Exception { final Connection connection = tester.getConnection().getConnection(); try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[] { "produced" }); connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); final IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); - assertEquals(expectedTable, actualTable); } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java deleted file mode 100644 index 039dfd1639..0000000000 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/PrepAndExpectedDbUnitTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.dbunit; - -import org.dbunit.DefaultPrepAndExpectedTestCase; -import org.dbunit.IDatabaseTester; -import org.dbunit.JdbcDatabaseTester; -import org.dbunit.PrepAndExpectedTestCaseSteps; -import org.dbunit.VerifyTableDefinition; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; -import org.dbunit.operation.DatabaseOperation; -import org.dbunit.util.fileloader.DataFileLoader; -import org.dbunit.util.fileloader.FlatXmlDataFileLoader; -import org.junit.Test; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; - -import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; -import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; -import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; -import static com.baeldung.dbunit.ConnectionSettings.USER; -import static org.assertj.core.api.Assertions.assertThat; - -public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase { - - @Override - public void setUp() throws Exception { - setDatabaseTester(initDatabaseTester()); - setDataFileLoader(initDataFileLoader()); - super.setUp(); - } - - private IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); - tester.setDataSet(initDataSet()); - tester.setSetUpOperation(DatabaseOperation.REFRESH); - return tester; - } - - private IDataSet initDataSet() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { - return new FlatXmlDataSetBuilder().build(is); - } - } - - private DataFileLoader initDataFileLoader() { - return new FlatXmlDataFileLoader(); - } - - @Test - public void testSelect() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeQuery("select * from CLIENTS where id = 1"); - - final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - - assertThat(rs.next()).isTrue(); - assertThat(rs.getString("last_name")).isEqualTo("Xavier"); - } - - @Test - public void testUpdate() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; // define tables to verify - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users_exp_rename.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("update CLIENTS set first_name = 'new name' where id = 1"); - - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } - - @Test - public void testDelete() throws Exception { - final Connection connection = getConnection().getConnection(); - final VerifyTableDefinition[] verifyTables = { new VerifyTableDefinition("CLIENTS", new String[] {}) }; - final String[] prepDataFiles = { "/dbunit/users.xml" }; - final String[] expectedDataFiles = { "/dbunit/users_exp_delete.xml" }; - final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement().executeUpdate("delete from CLIENTS where id = 2"); - - super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps); - } - -} diff --git a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index ce9638c4af..822468e91f 100644 --- a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -78,10 +78,10 @@ public class JsonAssertUnitTest { @Test public void givenArray_whenComparing_thenOrderMustMatchForStrict() throws JSONException { - String result = "[Alex, Barbera, Charlie, Xavier]"; - JSONAssert.assertEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT); - JSONAssert.assertEquals("[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT); - JSONAssert.assertNotEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT); + String result = "[Alex, Barbera, Charlie, Wolf]"; + JSONAssert.assertEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.LENIENT); + JSONAssert.assertEquals("[Alex, Barbera, Charlie, Wolf]", result, JSONCompareMode.STRICT); + JSONAssert.assertNotEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.STRICT); } @Test @@ -94,7 +94,7 @@ public class JsonAssertUnitTest { @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { - String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; + String names = "{names:[Alex, Barbera, Charlie, Wolf]}"; JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT)); } diff --git a/libraries-testing/src/test/resources/dbunit/data.xml b/libraries-testing/src/test/resources/dbunit/data.xml index 290cc36890..4865dec54c 100644 --- a/libraries-testing/src/test/resources/dbunit/data.xml +++ b/libraries-testing/src/test/resources/dbunit/data.xml @@ -1,6 +1,6 @@ - + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml index b42d3804fa..4f14b17113 100644 --- a/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml @@ -1,6 +1,6 @@ - + diff --git a/libraries-testing/src/test/resources/dbunit/users.xml b/libraries-testing/src/test/resources/dbunit/users.xml index 9ac3909bc5..f04943c4cc 100644 --- a/libraries-testing/src/test/resources/dbunit/users.xml +++ b/libraries-testing/src/test/resources/dbunit/users.xml @@ -1,6 +1,6 @@ - + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml index 2fe97ae6f6..20a2f2f1a7 100644 --- a/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml +++ b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml @@ -1,5 +1,5 @@ - + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml index 95682118bb..1ab6cf53b8 100644 --- a/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml +++ b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml @@ -1,6 +1,6 @@ - + From 902bb5308945cc37b148ee630832071209ce9361 Mon Sep 17 00:00:00 2001 From: Marius Catalin Munteanu Date: Wed, 11 Mar 2020 10:56:13 +0200 Subject: [PATCH 21/97] [BAEL-3011] Accesing Spring MVC Data from Thymeleaf - Code example for https://jira.baeldung.com/browse/BAEL-3012 --- .../thymeleaf/mvcdata/BeanConfig.java | 14 ++++ .../thymeleaf/mvcdata/EmailController.java | 63 ++++++++++++++++ .../mvcdata/repository/EmailData.java | 48 +++++++++++++ .../templates/mvcdata/email-bean-data.html | 14 ++++ .../mvcdata/email-model-attributes.html | 16 +++++ .../mvcdata/email-request-parameters.html | 20 ++++++ .../mvcdata/email-servlet-context.html | 14 ++++ .../mvcdata/email-session-attributes.html | 14 ++++ .../mvcdata/EmailControllerUnitTest.java | 72 +++++++++++++++++++ 9 files changed, 275 insertions(+) create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html create mode 100644 spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java new file mode 100644 index 0000000000..19f0101cf2 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.thymeleaf.mvcdata; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Configuration +public class BeanConfig { + @Bean + public EmailData emailData() { + return new EmailData(); + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java new file mode 100644 index 0000000000..1bfe3f3428 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java @@ -0,0 +1,63 @@ +package com.baeldung.thymeleaf.mvcdata; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Controller +public class EmailController { + private EmailData emailData = new EmailData(); + private ServletContext servletContext; + + public EmailController(ServletContext servletContext) { + this.servletContext = servletContext; + } + + @GetMapping(value = "/email/modelattributes") + public String emailModel(Model model) { + model.addAttribute("emaildata", emailData); + return "mvcdata/email-model-attributes"; + } + + @ModelAttribute("emailModelAttribute") + EmailData emailModelAttribute() { + return emailData; + } + + @GetMapping(value = "/email/requestparameters") + public String emailRequestParameters( + @RequestParam(value = "emailsubject") String emailSubject, + @RequestParam(value = "emailcontent") String emailContent, + @RequestParam(value = "emailaddress") String emailAddress1, + @RequestParam(value = "emailaddress") String emailAddress2, + @RequestParam(value = "emaillocale") String emailLocale) { + return "mvcdata/email-request-parameters"; + } + + @GetMapping("/email/sessionattributes") + public String emailSessionAttributes(HttpSession httpSession) { + httpSession.setAttribute("emaildata", emailData); + return "mvcdata/email-session-attributes"; + } + + @GetMapping("/email/servletcontext") + public String emailServletContext() { + servletContext.setAttribute("emailsubject", emailData.getEmailSubject()); + servletContext.setAttribute("emailcontent", emailData.getEmailBody()); + servletContext.setAttribute("emailaddress", emailData.getEmailAddress1()); + servletContext.setAttribute("emaillocale", emailData.getEmailLocale()); + return "mvcdata/email-servlet-context"; + } + + @GetMapping("/email/beandata") + public String emailBeanData() { + return "mvcdata/email-bean-data"; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java new file mode 100644 index 0000000000..9dc25bdaa7 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.mvcdata.repository; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class EmailData implements Serializable { + private String emailSubject; + private String emailBody; + private String emailLocale; + private String emailAddress1; + private String emailAddress2; + + public EmailData() { + this.emailSubject = "You have received a new message"; + this.emailBody = "Good morning !"; + this.emailLocale = "en-US"; + this.emailAddress1 = "jhon.doe@example.com"; + this.emailAddress2 = "mark.jakob@example.com"; + } + + public String getEmailSubject() { + return this.emailSubject; + } + + public String getEmailBody() { + return this.emailBody; + } + + public String getEmailLocale() { + return this.emailLocale; + } + + public String getEmailAddress1() { + return this.emailAddress1; + } + + public String getEmailAddress2() { + return this.emailAddress2; + } + + public List getEmailAddresses() { + List emailAddresses = new ArrayList<>(); + emailAddresses.add(getEmailAddress1()); + emailAddresses.add(getEmailAddress2()); + return emailAddresses; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html new file mode 100644 index 0000000000..59073b51c6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html @@ -0,0 +1,14 @@ + + + +

Subject

+

Subject

+

Content

+

Body

+

Email address

+

Email address

+

Language

+

Language

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html new file mode 100644 index 0000000000..caf136383a --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html @@ -0,0 +1,16 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html new file mode 100644 index 0000000000..8bcd3e1c62 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html @@ -0,0 +1,20 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Email address 1

+

+

Email address 2

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html new file mode 100644 index 0000000000..b07573047e --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html new file mode 100644 index 0000000000..9227171fc6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java new file mode 100644 index 0000000000..5e1190e174 --- /dev/null +++ b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.thymeleaf.mvcdata; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc(printOnlyOnFailure = false) +public class EmailControllerUnitTest { + + EmailData emailData = new EmailData(); + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenCallModelAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("You have received a new message"))); + } + + @Test + public void whenCallRequestParameters_thenReturnEmailData() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("emailsubject", emailData.getEmailSubject()); + params.add("emailcontent", emailData.getEmailBody()); + params.add("emailaddress", emailData.getEmailAddress1()); + params.add("emailaddress", emailData.getEmailAddress2()); + params.add("emaillocale", emailData.getEmailLocale()); + mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters") + .params(params)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("en-US"))); + } + + @Test + public void whenCallSessionAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/sessionattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Good morning !"))); + } + + @Test + public void whenCallServletContext_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/servletcontext")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + + @Test + public void whenCallBeanData_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + +} From ba65e099896cce714f3616329971d58c47dfa99d Mon Sep 17 00:00:00 2001 From: gindex Date: Sat, 28 Mar 2020 19:01:54 +0100 Subject: [PATCH 22/97] Add blocking and non-blocking mono examples Add article reference Fix url --- reactor-core/README.md | 1 + .../java/com/baeldung/mono/MonoUnitTest.java | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java diff --git a/reactor-core/README.md b/reactor-core/README.md index e3cca35f86..f2dbd77981 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,3 +7,4 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) +- [How To Get String From Mono In Reactive Java](http://baeldung.com/string-from-mono/) \ No newline at end of file diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java new file mode 100644 index 0000000000..b493cd1159 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mono; + +import org.junit.Test; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class MonoUnitTest { + @Test + public void whenMonoProducesString_thenBlockAndConsume() { + String expected = "hello world!"; + + String result1 = Mono.just(expected).block(); + assertEquals(expected, result1); + + String result2 = Mono.just(expected).block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals(expected, result2); + + Optional result3 = Mono.empty().blockOptional(); + assertEquals(Optional.empty(), result3); + } + + @Test + public void whenMonoProducesString_thenConsumeNonBlocking() { + String expected = "hello world!"; + + Mono.just(expected) + .doOnNext(result -> assertEquals(expected, result)) + .subscribe(); + + Mono.just(expected) + .subscribe(result -> assertEquals(expected, result)); + + } +} From a3c69eba43cd3e32dfa6d78532736a7211e2f824 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 22 Mar 2020 18:36:02 +0100 Subject: [PATCH 23/97] [BAEL-2808] Added tests for physical naming strategies --- .../spring-data-jpa-4/create.sql | 2 + .../default-naming-strategy-ddl.sql | 1 + persistence-modules/spring-data-jpa-4/pom.xml | 5 ++ .../com/baeldung/namingstrategy/Person.java | 36 ++++++++ .../namingstrategy/PersonRepository.java | 6 ++ .../QuotedLowerCaseNamingStrategy.java | 12 +++ ...DataJpaTableAndColumnNamesApplication.java | 7 ++ .../UnquotedLowerCaseNamingStrategy.java | 12 +++ ...owerCaseNamingStrategyIntegrationTest.java | 78 +++++++++++++++++ ...PhysicalNamingStrategyIntegrationTest.java | 82 ++++++++++++++++++ ...owerCaseNamingStrategyIntegrationTest.java | 83 +++++++++++++++++++ ...oted-lower-case-naming-strategy.properties | 9 ++ ...spring-physical-naming-strategy.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 9 ++ .../upper-case-naming-strategy-ddl.sql | 1 + 15 files changed, 352 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-4/create.sql create mode 100644 persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql new file mode 100644 index 0000000000..1bbe1640a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/create.sql @@ -0,0 +1,2 @@ +create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) +create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql new file mode 100644 index 0000000000..34d5bd1867 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql @@ -0,0 +1 @@ +create table person (id int8 not null, firstname varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml index 8a476012c7..71fc21527f 100644 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ b/persistence-modules/spring-data-jpa-4/pom.xml @@ -33,6 +33,11 @@ mysql-connector-java + + org.postgresql + postgresql + + com.h2database h2 diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java new file mode 100644 index 0000000000..c3e7f50403 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -0,0 +1,36 @@ +package com.baeldung.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + @Id + private Long id; + + @Column(name = "FIRSTNAME") + private String firstName; + + private String lastName; + + public Person() {} + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long id() { + return id; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java new file mode 100644 index 0000000000..3c7c25bbcb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.namingstrategy; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PersonRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..16b01e50e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java new file mode 100644 index 0000000000..09aaf12b60 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.namingstrategy; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataJpaTableAndColumnNamesApplication { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..69e96aee27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..ffa282da72 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java @@ -0,0 +1,78 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy.properties") +class QuotedLowerCaseNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..8ad59fe2db --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy.properties") +class SpringPhysicalNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndDefaultNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..2d84a17526 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java @@ -0,0 +1,83 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy.properties") +class UnquotedLowerCaseNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..dce43e2da5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties new file mode 100644 index 0000000000..a8ba1a3e4d --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:spring-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..63f400db0b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql new file mode 100644 index 0000000000..b26697ac66 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql @@ -0,0 +1 @@ +create table "PERSON" ("ID" int8 not null, "FIRSTNAME" varchar(255), "LAST_NAME" varchar(255), primary key ("ID")) From aebba04be7812a3ba020cfddfbc38da245dca10b Mon Sep 17 00:00:00 2001 From: dupirefr Date: Tue, 24 Mar 2020 08:09:31 +0100 Subject: [PATCH 24/97] [BAEL-2808] Added a few tests to illustrate my problem --- .../QuotedUpperCaseNamingStrategy.java | 12 +++ .../UnquotedUpperCaseNamingStrategy.java | 12 +++ ...rCaseNamingStrategyH2IntegrationTest.java} | 5 +- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++++++++++++++++++ ...NamingStrategyPostgresIntegrationTest.java | 81 ++++++++++++++++++ ...sicalNamingStrategyH2IntegrationTest.java} | 11 ++- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...rCaseNamingStrategyH2IntegrationTest.java} | 11 ++- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++++++++++++++++++ ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 4 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-upper-case-naming-strategy.properties | 9 ++ ...cal-naming-strategy-on-postgres.properties | 9 ++ ...spring-physical-naming-strategy.properties | 2 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 4 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-upper-case-naming-strategy.properties | 9 ++ 22 files changed, 701 insertions(+), 14 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedLowerCaseNamingStrategyIntegrationTest.java => QuotedLowerCaseNamingStrategyH2IntegrationTest.java} (95%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{SpringPhysicalNamingStrategyIntegrationTest.java => SpringPhysicalNamingStrategyH2IntegrationTest.java} (85%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedLowerCaseNamingStrategyIntegrationTest.java => UnquotedLowerCaseNamingStrategyH2IntegrationTest.java} (91%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..3cb62aa5a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..cb87af10f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 95% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java index ffa282da72..71a4dbda3f 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy.properties") -class QuotedLowerCaseNamingStrategyIntegrationTest { +class QuotedLowerCaseNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -45,6 +45,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } @@ -52,6 +53,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Expected result assertThrows(SQLGrammarException.class, query::getResultStream); } @@ -59,6 +61,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..79c47e86e0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") +class QuotedLowerCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..f819327a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy.properties") +class QuotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..20250a7ecb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") +class QuotedUpperCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java similarity index 85% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java index 8ad59fe2db..1850fea173 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy.properties") -class SpringPhysicalNamingStrategyIntegrationTest { +class SpringPhysicalNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -42,9 +42,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { @ParameterizedTest @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndDefaultNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -53,9 +54,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { } @Test - void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedUpperCase_thenResult() { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Unexpected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -64,9 +66,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { } @Test - void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedLowerCase_thenException() { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..97f2b601b0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") +class SpringPhysicalNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 91% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java index 2d84a17526..6311c42e93 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy.properties") -class UnquotedLowerCaseNamingStrategyIntegrationTest { +class UnquotedLowerCaseNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -43,9 +43,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { @ParameterizedTest @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -54,9 +55,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { } @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Unexpected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -65,9 +67,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { } @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..4e1d69ccdb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") +class UnquotedLowerCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..7af8001854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy.properties") +class UnquotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..0fdb05b0ee --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") +class UnquotedUpperCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..04b29de41f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties index dce43e2da5..6643c12c8a 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -1,8 +1,8 @@ -spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..36898d5b4f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..6d56d58749 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..706b12b1b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties index a8ba1a3e4d..c9a0c6f24c 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -2,7 +2,7 @@ spring.datasource.url=jdbc:h2:mem:spring-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..b22472bd8f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties index 63f400db0b..8083515b4b 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -1,8 +1,8 @@ -spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..da03a0d7b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..d1b63e008c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file From daab2b383ff6059a9a64af89300e3adc2ae1d743 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Wed, 1 Apr 2020 23:10:07 +0200 Subject: [PATCH 25/97] [BAEL-2808] Last fix --- .../spring-data-jpa-4/default-naming-strategy-ddl.sql | 1 - .../src/main/java/com/baeldung/namingstrategy/Person.java | 1 - .../spring-data-jpa-4/upper-case-naming-strategy-ddl.sql | 1 - 3 files changed, 3 deletions(-) delete mode 100644 persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql delete mode 100644 persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql diff --git a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql deleted file mode 100644 index 34d5bd1867..0000000000 --- a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql +++ /dev/null @@ -1 +0,0 @@ -create table person (id int8 not null, firstname varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java index c3e7f50403..cfb6e67c2c 100644 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -9,7 +9,6 @@ public class Person { @Id private Long id; - @Column(name = "FIRSTNAME") private String firstName; private String lastName; diff --git a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql deleted file mode 100644 index b26697ac66..0000000000 --- a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql +++ /dev/null @@ -1 +0,0 @@ -create table "PERSON" ("ID" int8 not null, "FIRSTNAME" varchar(255), "LAST_NAME" varchar(255), primary key ("ID")) From c73b8dbf724d4fe5bc2a3f4b5ffbb424b4747c22 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 5 Apr 2020 16:16:27 +0200 Subject: [PATCH 26/97] [BAEL-2808] Migrated PostgreSQL tests to LiveTest --- ...ation.java => SpringDataJpaNamingConventionApplication.java} | 2 +- ....java => QuotedLowerCaseNamingStrategyPostgresLiveTest.java} | 2 +- ....java => QuotedUpperCaseNamingStrategyPostgresLiveTest.java} | 2 +- ...t.java => SpringPhysicalNamingStrategyPostgresLiveTest.java} | 2 +- ...ava => UnquotedLowerCaseNamingStrategyPostgresLiveTest.java} | 2 +- ...ava => UnquotedUpperCaseNamingStrategyPostgresLiveTest.java} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/{SpringDataJpaTableAndColumnNamesApplication.java => SpringDataJpaNamingConventionApplication.java} (69%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java => QuotedLowerCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java => QuotedUpperCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{SpringPhysicalNamingStrategyPostgresIntegrationTest.java => SpringPhysicalNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java => UnquotedLowerCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java => UnquotedUpperCaseNamingStrategyPostgresLiveTest.java} (97%) diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java similarity index 69% rename from persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java rename to persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java index 09aaf12b60..f223015db8 100644 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java @@ -3,5 +3,5 @@ package com.baeldung.namingstrategy; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class SpringDataJpaTableAndColumnNamesApplication { +public class SpringDataJpaNamingConventionApplication { } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java index 79c47e86e0..6b1c984600 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") -class QuotedLowerCaseNamingStrategyPostgresIntegrationTest { +class QuotedLowerCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java index 20250a7ecb..bd23b81b4b 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") -class QuotedUpperCaseNamingStrategyPostgresIntegrationTest { +class QuotedUpperCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java index 97f2b601b0..e26ebb148d 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") -class SpringPhysicalNamingStrategyPostgresIntegrationTest { +class SpringPhysicalNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java index 4e1d69ccdb..033a213cf5 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") -class UnquotedLowerCaseNamingStrategyPostgresIntegrationTest { +class UnquotedLowerCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java index 0fdb05b0ee..0151e7ece4 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") -class UnquotedUpperCaseNamingStrategyPostgresIntegrationTest { +class UnquotedUpperCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; From c76c811b1cb72b71c8c127c9e3da41a731e4adff Mon Sep 17 00:00:00 2001 From: patkorek Date: Tue, 7 Apr 2020 10:23:15 +0200 Subject: [PATCH 27/97] BAEL-2660 few examples to convert String to Int --- .../strings/ConvertStringToInt.groovy | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy new file mode 100644 index 0000000000..40c53965a5 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -0,0 +1,92 @@ +package com.baeldung.strings + +import org.junit.Test + +import java.text.DecimalFormat + +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertNull + +class ConvertStringToInt { + + @Test + void givenString_thenConvertToIntegerUsingAsInteger() { + def stringNum = "123" + def invalidString = "123a" + Integer expectedInteger = 123 + Integer integerNum = stringNum as Integer + def intNum = invalidString?.isInteger() ? invalidString as Integer : null + + assertNull(null, intNum) + assertEquals(integerNum, expectedInteger) + } + + @Test + void givenString_thenConvertToIntUsingAsInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum as int + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum.toInteger() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingParseInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.parseInt(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingValueOf() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.valueOf(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingIntValue() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum).intValue() + int secondIntNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) + assertEquals(secondIntNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingDecimalFormat() { + def stringNum = "123" + int expectedInt = 123 + DecimalFormat decimalFormat = new DecimalFormat("#") + int intNum = decimalFormat.parse(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test(expected = NumberFormatException.class) + void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def invalidString = "123a" + invalidString as Integer + } + + @Test(expected = NullPointerException.class) + void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def invalidString = null + invalidString.toInteger() + } +} From a59aa144001d35a75c7014eb03f7e0457e67161f Mon Sep 17 00:00:00 2001 From: patkorek Date: Tue, 7 Apr 2020 10:34:38 +0200 Subject: [PATCH 28/97] Renamed methods --- .../com/baeldung/strings/ConvertStringToInt.groovy | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 40c53965a5..3b179ee193 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -10,7 +10,7 @@ import static org.junit.Assert.assertNull class ConvertStringToInt { @Test - void givenString_thenConvertToIntegerUsingAsInteger() { + void givenString_whenUsingAsInteger_thenConvertToInteger() { def stringNum = "123" def invalidString = "123a" Integer expectedInteger = 123 @@ -22,7 +22,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntUsingAsInt() { + void givenString_whenUsingAsInt_thenConvertToInt() { def stringNum = "123" int expectedInt = 123 int intNum = stringNum as int @@ -31,7 +31,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingToInteger() { + void givenString_whenUsingToInteger_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = stringNum.toInteger() @@ -40,7 +40,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingParseInt() { + void givenString_whenUsingParseInt_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = Integer.parseInt(stringNum) @@ -49,7 +49,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingValueOf() { + void givenString_whenUsingValueOf_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = Integer.valueOf(stringNum) @@ -58,7 +58,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingIntValue() { + void givenString_whenUsingIntValue_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = new Integer(stringNum).intValue() @@ -69,7 +69,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingDecimalFormat() { + void givenString_whenUsingDecimalFormat_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 DecimalFormat decimalFormat = new DecimalFormat("#") From 15d4893d2e2742261e2661d3ffabcfca443a6851 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Wed, 8 Apr 2020 08:13:28 +0200 Subject: [PATCH 29/97] [BAEL-2749] Bumps DBUnit to version 2.7.0 --- libraries-testing/pom.xml | 2 +- .../test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index c4d2786441..ad6c81a3d6 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -198,7 +198,7 @@ 3.6.2 2.0.0.0 1.4.200 - 2.6.0 + 2.7.0 3.14.0 1.8 1.8 diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 20b0337f4d..93c7e9a456 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -17,6 +17,7 @@ import org.junit.platform.commons.logging.LoggerFactory; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; @@ -33,7 +34,7 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); @Override - protected javax.sql.DataSource getDataSource() { + protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); From bcf5d50baa5e4b8ce46be437095123a985dcadda Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 9 Apr 2020 23:42:31 +0530 Subject: [PATCH 30/97] JAVA-1188: Removed duplicate entry from README --- core-java-modules/core-java-collections-maps/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md index 828f8992e1..15cb32fbe8 100644 --- a/core-java-modules/core-java-collections-maps/README.md +++ b/core-java-modules/core-java-collections-maps/README.md @@ -4,7 +4,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) - [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) From db789ae6748a944168dda12c507406e748405315 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 9 Apr 2020 20:55:15 +0200 Subject: [PATCH 31/97] JAVA-976: Fix spring-security-mvc-login configuration --- .../src/test/java/com/baeldung/SpringContextTest.java | 2 +- .../security/RedirectionSecurityIntegrationTest.java | 2 +- .../src/test/resources/mvc-servlet.xml | 8 -------- 3 files changed, 2 insertions(+), 10 deletions(-) delete mode 100644 spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java index 4cf3b736ea..dfc83a40b0 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class SpringContextTest { @Test diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java index 1235e2e69f..e2b444de20 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class RedirectionSecurityIntegrationTest { diff --git a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml deleted file mode 100644 index aee837c977..0000000000 --- a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file From 06a4e640bb6da563db64c2d2d949b2ddbf4c73cf Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 10 Apr 2020 03:15:39 +0430 Subject: [PATCH 32/97] Fixed a few cassandra related issues --- persistence-modules/java-cassandra/pom.xml | 6 +++ .../src/test/resources/cassandra.yaml | 51 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 persistence-modules/java-cassandra/src/test/resources/cassandra.yaml diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 54879fb321..091efaeff4 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -18,6 +18,12 @@ cassandra-driver-core ${cassandra-driver-core.version} true + + + com.google.guava + guava + + diff --git a/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml new file mode 100644 index 0000000000..59687444d0 --- /dev/null +++ b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml @@ -0,0 +1,51 @@ +cluster_name: 'Test Cluster' +hinted_handoff_enabled: true +max_hint_window_in_ms: 10800000 +hinted_handoff_throttle_in_kb: 1024 +max_hints_delivery_threads: 2 +hints_directory: target/embeddedCassandra/hints +authenticator: AllowAllAuthenticator +authorizer: AllowAllAuthorizer +permissions_validity_in_ms: 2000 +partitioner: RandomPartitioner +data_file_directories: + - target/embeddedCassandra/data +commitlog_directory: target/embeddedCassandra/commitlog +cdc_raw_directory: target/embeddedCassandra/cdc +disk_failure_policy: stop +key_cache_size_in_mb: +key_cache_save_period: 14400 +row_cache_size_in_mb: 0 +row_cache_save_period: 0 +saved_caches_directory: target/embeddedCassandra/saved_caches +commitlog_sync: periodic +commitlog_sync_period_in_ms: 10000 +commitlog_segment_size_in_mb: 32 +concurrent_reads: 32 +concurrent_writes: 32 +trickle_fsync: false +trickle_fsync_interval_in_kb: 10240 +thrift_framed_transport_size_in_mb: 15 +thrift_max_message_length_in_mb: 16 +incremental_backups: false +snapshot_before_compaction: false +auto_snapshot: false +column_index_size_in_kb: 64 +compaction_throughput_mb_per_sec: 16 +read_request_timeout_in_ms: 5000 +range_request_timeout_in_ms: 10000 +write_request_timeout_in_ms: 2000 +cas_contention_timeout_in_ms: 1000 +truncate_request_timeout_in_ms: 60000 +request_timeout_in_ms: 10000 +cross_node_timeout: false +endpoint_snitch: SimpleSnitch +dynamic_snitch_update_interval_in_ms: 100 +dynamic_snitch_reset_interval_in_ms: 600000 +dynamic_snitch_badness_threshold: 0.1 +request_scheduler: org.apache.cassandra.scheduler.NoScheduler +index_interval: 128 +seed_provider: + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + - seeds: "127.0.0.1" From 7e26a04973e631dcb6ea88cf0e9fbc7b2ad35a34 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 10 Apr 2020 09:24:15 +0200 Subject: [PATCH 33/97] springboot shedlock building fix --- spring-boot-modules/spring-boot-libraries/pom.xml | 4 ++++ .../shedlock/SpringBootShedlockApplication.java} | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) rename spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/{Application.java => scheduling/shedlock/SpringBootShedlockApplication.java} (71%) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 2b1b1b7d12..090967d8a8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -28,6 +28,10 @@ org.springframework.boot spring-boot-starter-tomcat + + org.springframework.boot + spring-boot-starter-data-jpa + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java similarity index 71% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java index 15422e1065..cebb234036 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.scheduling.shedlock; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.boot.SpringApplication; @@ -8,8 +8,8 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") -public class Application { +public class SpringBootShedlockApplication { public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(SpringBootShedlockApplication.class, args); } } From 52ca4fbcd9e8d1d42eafdb1b4b16326fa09eb404 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:29:38 +0800 Subject: [PATCH 34/97] Update README.md --- core-java-modules/core-java-date-operations-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md index 728162ca1a..19c7b98d30 100644 --- a/core-java-modules/core-java-date-operations-2/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -7,4 +7,5 @@ This module contains articles about date operations in Java. - [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) - [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) +- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) - [[<-- Prev]](/core-java-modules/core-java-date-operations-1) From bf764f5f44da4adf16a24d08313c85fecf4a93c2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:31:19 +0800 Subject: [PATCH 35/97] Update README.md --- spring-reactive-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md index 629f7e7f58..d6ce3b7645 100644 --- a/spring-reactive-kotlin/README.md +++ b/spring-reactive-kotlin/README.md @@ -4,3 +4,4 @@ This module contains articles about reactive Kotlin ### Relevant Articles: - [Spring Webflux with Kotlin](https://www.baeldung.com/spring-webflux-kotlin) +- [Kotlin Reactive Microservice With Spring Boot](https://www.baeldung.com/spring-boot-kotlin-reactive-microservice) From e1cf55dc822408210083eff3d52f6502d2c4060f Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:40:36 +0800 Subject: [PATCH 36/97] Update README.md --- core-java-modules/core-java-lang-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index 65d40c6a26..3ade982397 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -10,4 +10,5 @@ This module contains articles about core features in the Java language - [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) - [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) - [The Java Headless Mode](https://www.baeldung.com/java-headless-mode) +- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values) - [[<-- Prev]](/core-java-modules/core-java-lang) From 404f13f940d2f2d7143f5d6bcd9231c27f63059a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:46:47 +0800 Subject: [PATCH 37/97] Update README.md --- spring-security-modules/spring-security-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-modules/spring-security-mvc/README.md b/spring-security-modules/spring-security-mvc/README.md index 7d1a492cd3..bb4cfe1a4f 100644 --- a/spring-security-modules/spring-security-mvc/README.md +++ b/spring-security-modules/spring-security-mvc/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [HttpSessionListener Example – Monitoring](https://www.baeldung.com/httpsessionlistener_with_metrics) - [Control the Session with Spring Security](https://www.baeldung.com/spring-security-session) +- [The Clear-Site-Data Header in Spring Security](https://www.baeldung.com/spring-security-clear-site-data-header) ### Build the Project From 721f339d8c32ba93f908e021a298e90666544ce5 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:50:44 +0800 Subject: [PATCH 38/97] Update README.md --- core-java-modules/core-java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index 4a418db29f..5daae8394a 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -12,3 +12,4 @@ This module contains articles about strings in Java. - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) +- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) From 086d6a9531a5f42f1284ed1809254d22226c688a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:54:59 +0800 Subject: [PATCH 39/97] Update README.md --- persistence-modules/hibernate-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md index d0a253f028..fb48f975bc 100644 --- a/persistence-modules/hibernate-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -13,3 +13,4 @@ This module contains articles specific to use of Hibernate as a JPA implementati - [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) - [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) +- [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) From f88c53eb4921eb6aac480f4524912e8ef5620f10 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:57:27 +0800 Subject: [PATCH 40/97] Update README.md --- core-java-modules/core-java-regex/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md index 21cd7a95a3..6fdea9f2ca 100644 --- a/core-java-modules/core-java-regex/README.md +++ b/core-java-modules/core-java-regex/README.md @@ -9,3 +9,4 @@ - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) - [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) +- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) From 012465bed2504d614c0c694e24c0f023492ba1dc Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:00:00 +0800 Subject: [PATCH 41/97] Create README.md --- persistence-modules/spring-persistence-simple-2/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 persistence-modules/spring-persistence-simple-2/README.md diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md new file mode 100644 index 0000000000..a6408df8f2 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) From 564e7fc0337630a6b7e53a49abbd018dabf3eb06 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:02:20 +0800 Subject: [PATCH 42/97] Create README.md --- algorithms-miscellaneous-6/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 algorithms-miscellaneous-6/README.md diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md new file mode 100644 index 0000000000..d9d6483a39 --- /dev/null +++ b/algorithms-miscellaneous-6/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) From 09b03f875416b14694b3491c46cbcf52e796bb91 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:05:30 +0800 Subject: [PATCH 43/97] Update README.md --- algorithms-miscellaneous-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md index d9d6483a39..99be63d7ca 100644 --- a/algorithms-miscellaneous-6/README.md +++ b/algorithms-miscellaneous-6/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) +- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent) From acdcb5cacab872b1ce9b907483efa67a67e9cc23 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:07:16 +0800 Subject: [PATCH 44/97] Update README.md --- core-java-modules/core-java-concurrency-basic-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index e3f7a94e14..c7143baf36 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) -- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) \ No newline at end of file +- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) +- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) From 88afc279cffb8c58ec7f0e5416a34d2efb5ca282 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:10:17 +0800 Subject: [PATCH 45/97] Update README.md --- core-java-modules/core-java-string-operations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md index 18a2649a6a..c40e56bc46 100644 --- a/core-java-modules/core-java-string-operations/README.md +++ b/core-java-modules/core-java-string-operations/README.md @@ -13,4 +13,5 @@ This module contains articles about string operations. - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[next -->]](../core-java-string-operations-2) From c34f99f42aac0ea22d6afbbbf356568c1afaa24c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:21:07 +0800 Subject: [PATCH 46/97] Update README.md --- libraries-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-3/README.md b/libraries-3/README.md index 62bd3b9f66..ec433960ef 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -16,3 +16,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) From 45abeb493b4d34a3b6502faa632d0bcd160cc3c7 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:22:40 +0800 Subject: [PATCH 47/97] Update README.md --- core-java-modules/core-java-concurrency-advanced-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index 2c554e948b..b11cde5158 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -10,4 +10,5 @@ This module contains articles about advanced topics about multithreading with co - [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler) - [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing) - [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) +- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) From 76d15b81c505e8f82db8f70d786ee09c253622d6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:25:53 +0800 Subject: [PATCH 48/97] Update README.md --- java-numbers-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index 598acfb927..f818bdb675 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -10,4 +10,5 @@ This module contains articles about numbers in Java. - [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range) - [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) - [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci) +- [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class) - More articles: [[<-- prev]](/java-numbers-2) From cb016c1027f8ec8b9bcea4c87f88fd2a5a622fa0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:28:18 +0800 Subject: [PATCH 49/97] Update README.md --- core-java-modules/core-java-security-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index 2eb21fb77e..24a821bd4d 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -8,4 +8,5 @@ This module contains articles about core Java Security - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- [Checksums in Java](https://www.baeldung.com/java-checksums) - More articles: [[<-- prev]](/core-java-modules/core-java-security) From 618916b6ab8753bf6d419031d21e9e1db934e8f1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:31:17 +0800 Subject: [PATCH 50/97] Update README.md --- guava-collections-map/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/guava-collections-map/README.md b/guava-collections-map/README.md index b3ec5e2157..4f8743dcfb 100644 --- a/guava-collections-map/README.md +++ b/guava-collections-map/README.md @@ -9,4 +9,5 @@ This module contains articles about map collections in Guava - [Guide to Guava Multimap](https://www.baeldung.com/guava-multimap) - [Guide to Guava RangeMap](https://www.baeldung.com/guava-rangemap) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) \ No newline at end of file +- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) +- [Using Guava’s MapMaker](https://www.baeldung.com/guava-mapmaker) From 2b27994c13acca8ad0af453eb05c6e82749e6543 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:35:28 +0800 Subject: [PATCH 51/97] Update README.md --- spring-batch/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-batch/README.md b/spring-batch/README.md index d637de269c..3a89459629 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -3,6 +3,7 @@ This module contains articles about Spring Batch ### Relevant Articles: + - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) @@ -10,3 +11,4 @@ This module contains articles about Spring Batch - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) - [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) +- [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) From 44f3912f83a0aa0f7aa4dcdec5a0496d020e7bfa Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:38:35 +0800 Subject: [PATCH 52/97] Update README.md --- core-kotlin-modules/core-kotlin-collections/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index bbea5869af..f0da2b4cfd 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -8,3 +8,4 @@ This module contains articles about core Kotlin collections. - [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) - [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) - [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) +- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) From fba81f5e629ca568d197622b6d32dbe1c653de15 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:40:10 +0800 Subject: [PATCH 53/97] Update README.md --- guava/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guava/README.md b/guava/README.md index c67a3604ea..71f76c1360 100644 --- a/guava/README.md +++ b/guava/README.md @@ -12,4 +12,4 @@ This module contains articles a Google Guava - [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter) - [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter) - +- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) From a70207b99317ff43992f9704b1832de960132d79 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:42:37 +0800 Subject: [PATCH 54/97] Update README.md --- core-java-modules/core-java-14/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 0e8278c4f6..13bb468b30 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -7,3 +7,4 @@ This module contains articles about Java 14. - [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation) - [Java Text Blocks](https://www.baeldung.com/java-text-blocks) - [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) +- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) From 28401da21a1410bd54c2c4be125d68ffc529f933 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:44:41 +0800 Subject: [PATCH 55/97] Create README.md --- libraries-concurrency/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-concurrency/README.md diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From a1b1870921120ac90c7b68fa3a19004f564b801a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:46:53 +0800 Subject: [PATCH 56/97] Update README.md --- core-java-modules/core-java-streams-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index a739245399..05c4b99900 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -9,4 +9,5 @@ This module contains articles about the Stream API in Java. - [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) +- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) - More articles: [[<-- prev>]](/../core-java-streams-2) From 8e1787ffeacc858d72180a8d0919650feb796e2e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:48:28 +0800 Subject: [PATCH 57/97] Update README.md --- spring-5-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index e98012c047..aff8bb227c 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring 5 model-view-controller (MVC) pattern - [Spring Boot and Kotlin](https://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Interface Driven Controllers in Spring](https://www.baeldung.com/spring-interface-driven-controllers) +- [Returning Plain HTML From a Spring MVC Controller](https://www.baeldung.com/spring-mvc-return-html) From 08472ff2e9e2dc28f7d7975a9d01a81d2e330742 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:50:04 +0800 Subject: [PATCH 58/97] Update README.md --- spring-thymeleaf-3/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md index e1ddd727d7..a8e234b067 100644 --- a/spring-thymeleaf-3/README.md +++ b/spring-thymeleaf-3/README.md @@ -2,4 +2,5 @@ This module contains articles about Spring with Thymeleaf -## Relevant Articles: \ No newline at end of file +## Relevant Articles: +- [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) From fd1b953c2760173a9679638862a3ad79216a7e50 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:51:50 +0800 Subject: [PATCH 59/97] Update README.md --- spring-core-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-3/README.md b/spring-core-3/README.md index b2c4f694a8..6c210b23ef 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -10,4 +10,5 @@ This module contains articles about core Spring functionality - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) - [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) - [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) +- [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) - More articles: [[<-- prev]](/spring-core-2) From 76cdbd811ebe8ad93758b22807b8ff4b331a50c5 Mon Sep 17 00:00:00 2001 From: patkorek Date: Fri, 10 Apr 2020 12:49:52 +0200 Subject: [PATCH 60/97] Modified one method --- .../com/baeldung/strings/ConvertStringToInt.groovy | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 3b179ee193..3b73c31596 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -62,10 +62,17 @@ class ConvertStringToInt { def stringNum = "123" int expectedInt = 123 int intNum = new Integer(stringNum).intValue() - int secondIntNum = new Integer(stringNum) assertEquals(intNum, expectedInt) - assertEquals(secondIntNum, expectedInt) + } + + @Test + void givenString_whenUsingNewInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) } @Test From 949881921e6513972cc7143517c94b85b81f5644 Mon Sep 17 00:00:00 2001 From: patkorek Date: Fri, 10 Apr 2020 13:27:27 +0200 Subject: [PATCH 61/97] Added test case with isInteger() method. --- .../com/baeldung/strings/ConvertStringToInt.groovy | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 3b73c31596..7a4be4a957 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -96,4 +96,15 @@ class ConvertStringToInt { def invalidString = null invalidString.toInteger() } + + @Test + void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def invalidString = "123a" + def validString = "123" + def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false + def correctNum = validString?.isInteger() ? validString as Integer : false + + assertEquals(false, invalidNum) + assertEquals(123, correctNum) + } } From 5a1f7ffea8d617a80d38234bb0f097de49747aed Mon Sep 17 00:00:00 2001 From: gindex Date: Fri, 10 Apr 2020 13:36:51 +0200 Subject: [PATCH 62/97] Add blockingHelloWorld() --- .../java/com/baeldung/mono/MonoUnitTest.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java index b493cd1159..f9e67b0a2f 100644 --- a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -12,13 +12,13 @@ import static org.junit.Assert.assertEquals; public class MonoUnitTest { @Test public void whenMonoProducesString_thenBlockAndConsume() { - String expected = "hello world!"; - String result1 = Mono.just(expected).block(); - assertEquals(expected, result1); + String result1 = blockingHelloWorld().block(); + assertEquals("Hello world!", result1); - String result2 = Mono.just(expected).block(Duration.of(1000, ChronoUnit.MILLIS)); - assertEquals(expected, result2); + String result2 = blockingHelloWorld() + .block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals("Hello world!", result2); Optional result3 = Mono.empty().blockOptional(); assertEquals(Optional.empty(), result3); @@ -26,14 +26,18 @@ public class MonoUnitTest { @Test public void whenMonoProducesString_thenConsumeNonBlocking() { - String expected = "hello world!"; - Mono.just(expected) - .doOnNext(result -> assertEquals(expected, result)) + blockingHelloWorld() + .doOnNext(result -> assertEquals("Hello world!", result)) .subscribe(); - Mono.just(expected) - .subscribe(result -> assertEquals(expected, result)); + blockingHelloWorld() + .subscribe(result -> assertEquals("Hello world!", result)); } + + private Mono blockingHelloWorld() { + // blocking + return Mono.just("Hello world!"); + } } From 82e69447a54a650c59953fed9b0fab312fe552e6 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 10 Apr 2020 21:58:48 +0200 Subject: [PATCH 63/97] BAEL-3730: Add example of usage CacheManagerCustomizer in Spring Boot (#9048) --- spring-caching/pom.xml | 4 ++++ .../caching/boot/CacheApplication.java | 14 +++++++++++ .../caching/boot/SimpleCacheCustomizer.java | 24 +++++++++++++++++++ .../SimpleCacheCustomizerIntegrationTest.java | 24 +++++++++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java create mode 100644 spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java create mode 100644 spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index c3ededbd14..d33f24de1f 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -19,6 +19,10 @@ org.springframework spring-context + + org.springframework.boot + spring-boot-starter-cache + org.springframework spring-web diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java new file mode 100644 index 0000000000..714dc443e0 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.caching.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@SpringBootApplication +@EnableCaching +public class CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(CacheApplication.class, args); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java new file mode 100644 index 0000000000..a76a01caae --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.stereotype.Component; + +import static java.util.Arrays.asList; + +@Component +public class SimpleCacheCustomizer implements CacheManagerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCacheCustomizer.class); + + static final String USERS_CACHE = "users"; + static final String TRANSACTIONS_CACHE = "transactions"; + + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + LOGGER.info("Customizing Cache Manager"); + cacheManager.setCacheNames(asList(USERS_CACHE, TRANSACTIONS_CACHE)); + } +} diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java new file mode 100644 index 0000000000..56a4bd4745 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cache.CacheManager; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SimpleCacheCustomizerIntegrationTest { + + @Autowired + private CacheManager cacheManager; + + @Test + public void givenCacheManagerCustomizerWhenBootstrappedThenCacheManagerCustomized() { + assertThat(cacheManager.getCacheNames()) + .containsOnly(SimpleCacheCustomizer.USERS_CACHE, SimpleCacheCustomizer.TRANSACTIONS_CACHE); + } +} \ No newline at end of file From a6e5f78a488bbad61cf592185e9b1981cdd3140d Mon Sep 17 00:00:00 2001 From: mikr Date: Fri, 10 Apr 2020 23:59:34 +0200 Subject: [PATCH 64/97] JAVA-1225 Add dependency to Hibernate Code --- spring-boot-modules/spring-boot-springdoc/pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index c99a9c2b24..375cf06c2c 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -37,6 +37,12 @@ test + + org.hibernate + hibernate-core + ${hibernate.version} + + org.springdoc @@ -61,6 +67,7 @@ 1.8 + 5.2.10.Final 1.2.32 From f154a172398ed6d3b8aa5cda91ad5d3cad08cde6 Mon Sep 17 00:00:00 2001 From: "ramprasad.devarakonda@gmail.com" Date: Tue, 24 Mar 2020 00:55:23 +0000 Subject: [PATCH 65/97] BAEL-3769 | Writing templates for test cases using JUnit 5 --- testing-modules/junit5-annotations/pom.xml | 9 +- .../junit5/templates/UserIdGenerator.java | 5 ++ .../junit5/templates/UserIdGeneratorImpl.java | 15 ++++ .../DisabledOnQAEnvironmentExtension.java | 27 ++++++ .../GenericTypedParameterResolver.java | 26 ++++++ .../UserIdGeneratorImplUnitTest.java | 18 ++++ .../templates/UserIdGeneratorTestCase.java | 37 ++++++++ ...eneratorTestInvocationContextProvider.java | 87 +++++++++++++++++++ .../src/test/resources/application.properties | 1 + 9 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java create mode 100644 testing-modules/junit5-annotations/src/test/resources/application.properties diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index d0fba4d21b..9e51d0ab55 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -46,12 +46,19 @@ ${junit.platform.version} test + + org.assertj + assertj-core + ${assertj-core.version} + test + - 5.6.0 + 5.6.2 1.6.0 2.8.2 + 3.11.1 diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java new file mode 100644 index 0000000000..f19adb13c8 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java @@ -0,0 +1,5 @@ +package com.baeldung.junit5.templates; + +public interface UserIdGenerator { + String generate(String firstName, String lastName); +} diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java new file mode 100644 index 0000000000..b39b07bc4b --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorImpl implements UserIdGenerator { + private boolean isFeatureEnabled; + + public UserIdGeneratorImpl(boolean isFeatureEnabled) { + this.isFeatureEnabled = isFeatureEnabled; + } + + public String generate(String firstName, String lastName) { + String initialAndLastName = firstName.substring(0, 1) + .concat(lastName); + return isFeatureEnabled ? "bael".concat(initialAndLastName) : initialAndLastName; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java new file mode 100644 index 0000000000..cd8b7b677d --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.io.IOException; +import java.util.Properties; + +public class DisabledOnQAEnvironmentExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + Properties properties = new Properties(); + try { + properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader() + .getResourceAsStream("application.properties")); + if ("qa".equalsIgnoreCase(properties.getProperty("env"))) { + String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName()); + System.out.println(reason); + return ConditionEvaluationResult.disabled(reason); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return ConditionEvaluationResult.enabled("Test enabled"); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java new file mode 100644 index 0000000000..76321be101 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java @@ -0,0 +1,26 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class GenericTypedParameterResolver implements ParameterResolver { + T data; + + public GenericTypedParameterResolver(T data) { + this.data = data; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return parameterContext.getParameter() + .getType() + .isInstance(data); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return data; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java new file mode 100644 index 0000000000..a2306154a6 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserIdGeneratorImplUnitTest { + @TestTemplate + @ExtendWith(UserIdGeneratorTestInvocationContextProvider.class) + public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) { + UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled()); + + String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName()); + + assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId()); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java new file mode 100644 index 0000000000..dd41dd5a27 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java @@ -0,0 +1,37 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorTestCase { + private String displayName; + private boolean isFeatureEnabled; + private String firstName; + private String lastName; + private String expectedUserId; + + public UserIdGeneratorTestCase(String displayName, boolean isFeatureEnabled, String firstName, String lastName, String expectedUserId) { + this.displayName = displayName; + this.isFeatureEnabled = isFeatureEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.expectedUserId = expectedUserId; + } + + public String getDisplayName() { + return displayName; + } + + public boolean isFeatureEnabled() { + return isFeatureEnabled; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getExpectedUserId() { + return expectedUserId; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java new file mode 100644 index 0000000000..277ec03f05 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java @@ -0,0 +1,87 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.*; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext extensionContext) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext extensionContext) { + boolean featureDisabled = false; + boolean featureEnabled = true; + return Stream.of( + featureDisabledContext( + new UserIdGeneratorTestCase( + "Given feature switch disabled When user name is John Smith Then generated userid is JSmith", + featureDisabled, "John", "Smith", "JSmith")), + featureEnabledContext( + new UserIdGeneratorTestCase( + "Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith", + featureEnabled, "John", "Smith", "baelJSmith")) + ); + } + + private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new BeforeTestExecutionCallback() { + @Override + public void beforeTestExecution(ExtensionContext extensionContext) { + System.out.println("BeforeTestExecutionCallback:Disabled context"); + } + }, + new AfterTestExecutionCallback() { + @Override + public void afterTestExecution(ExtensionContext extensionContext) { + System.out.println("AfterTestExecutionCallback:Disabled context"); + } + }); + } + }; + } + + private TestTemplateInvocationContext featureEnabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new DisabledOnQAEnvironmentExtension(), + new BeforeEachCallback() { + @Override + public void beforeEach(ExtensionContext extensionContext) { + System.out.println("BeforeEachCallback:Enabled context"); + } + }, + new AfterEachCallback() { + @Override + public void afterEach(ExtensionContext extensionContext) { + System.out.println("AfterEachCallback:Enabled context"); + } + }); + } + }; + } +} diff --git a/testing-modules/junit5-annotations/src/test/resources/application.properties b/testing-modules/junit5-annotations/src/test/resources/application.properties new file mode 100644 index 0000000000..bbfa14d866 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/resources/application.properties @@ -0,0 +1 @@ +env=qa \ No newline at end of file From 552c1d805b281c6c575b269892e58d9b13d84b5b Mon Sep 17 00:00:00 2001 From: patkorek Date: Sat, 11 Apr 2020 14:39:36 +0200 Subject: [PATCH 66/97] Moved to com.baeldung.stringtoint package. --- .../baeldung/{strings => stringtoint}/ConvertStringToInt.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-groovy/src/test/groovy/com/baeldung/{strings => stringtoint}/ConvertStringToInt.groovy (98%) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy similarity index 98% rename from core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy rename to core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy index 7a4be4a957..48cf48fa8a 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -1,4 +1,4 @@ -package com.baeldung.strings +package com.baeldung.stringtoint import org.junit.Test From 3bdfd8f72681b94c3ca21bea00bf039a387d89dd Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 11 Apr 2020 18:16:13 +0200 Subject: [PATCH 67/97] [JAVA-1265] Review build time * Migrate UserMapperUnitTest to UserMapperIntegrationTest as it uses Spring and takes a lot of time to execute --- jhipster-5/bookstore-monolith/pom.xml | 4 ++-- ...UserMapperUnitTest.java => UserMapperIntegrationTest.java} | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/{UserMapperUnitTest.java => UserMapperIntegrationTest.java} (99%) diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 5eaf761921..233765e0f3 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT war Bookstore - + jhipster-5 com.baeldung.jhipster @@ -982,7 +982,7 @@ com.github.eirslett - frontend-maven-plugin + frontend-maven-plugin ${frontend-maven-plugin.version} install-node-and-npm diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java index cd6a326c06..cd49135d63 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserMapperUnitTest { +public class UserMapperIntegrationTest { private static final String DEFAULT_LOGIN = "johndoe"; From bbae9153a8cb2fe1179736acb4fb38ede9e80e78 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 11 Apr 2020 22:39:52 +0530 Subject: [PATCH 68/97] Disabling JWS module --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 8d4632fb3e..b3d949d495 100644 --- a/pom.xml +++ b/pom.xml @@ -803,7 +803,7 @@ jenkins/plugins jhipster - jws + libraries @@ -1296,7 +1296,7 @@ jenkins/plugins jhipster - jws + libraries From 4a83c738350acd32e9c6d2035dce0a91238be503 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Sun, 12 Apr 2020 10:06:34 +0530 Subject: [PATCH 69/97] Adding codebase for the article tracked under BAEL-2046. (#9055) --- atomikos/README.md | 7 ++ atomikos/pom.xml | 119 ++++++++++++++++++ .../baeldung/atomikos/direct/Application.java | 53 ++++++++ .../baeldung/atomikos/spring/Application.java | 41 ++++++ .../atomikos/spring/config/Config.java | 68 ++++++++++ .../atomikos/spring/jpa/Application.java | 48 +++++++ .../atomikos/spring/jpa/config/Config.java | 38 ++++++ .../spring/jpa/inventory/Inventory.java | 31 +++++ .../spring/jpa/inventory/InventoryConfig.java | 53 ++++++++ .../jpa/inventory/InventoryRepository.java | 9 ++ .../atomikos/spring/jpa/order/Order.java | 42 +++++++ .../spring/jpa/order/OrderConfig.java | 53 ++++++++ .../spring/jpa/order/OrderRepository.java | 9 ++ atomikos/src/main/resources/logback.xml | 13 ++ atomikos/src/main/resources/schema.sql | 10 ++ .../main/resources/transactions.properties | 1 + .../atomikos/direct/ApplicationUnitTest.java | 118 +++++++++++++++++ .../atomikos/spring/ApplicationUnitTest.java | 108 ++++++++++++++++ .../spring/jpa/ApplicationUnitTest.java | 80 ++++++++++++ atomikos/src/test/resources/logback.xml | 13 ++ .../test/resources/transactions.properties | 1 + pom.xml | 4 + 22 files changed, 919 insertions(+) create mode 100644 atomikos/README.md create mode 100644 atomikos/pom.xml create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java create mode 100644 atomikos/src/main/resources/logback.xml create mode 100644 atomikos/src/main/resources/schema.sql create mode 100644 atomikos/src/main/resources/transactions.properties create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java create mode 100644 atomikos/src/test/resources/logback.xml create mode 100644 atomikos/src/test/resources/transactions.properties diff --git a/atomikos/README.md b/atomikos/README.md new file mode 100644 index 0000000000..19f2e871d4 --- /dev/null +++ b/atomikos/README.md @@ -0,0 +1,7 @@ +## Atomikos + +This module contains articles about Atomikos + +### Relevant Articles: + +- [Guide Transactions Using Atomikos]() diff --git a/atomikos/pom.xml b/atomikos/pom.xml new file mode 100644 index 0000000000..881adae074 --- /dev/null +++ b/atomikos/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + atomikos + atomikos + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.atomikos + transactions-jdbc + ${atomikos-version} + + + com.atomikos + transactions-jms + ${atomikos-version} + + + com.atomikos + transactions-hibernate4 + ${atomikos-version} + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-tx + ${spring-version} + + + org.springframework.data + spring-data-jpa + 1.11.23.RELEASE + + + org.springframework + spring-test + ${spring-version} + test + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + provided + + + javax.transaction + jta + + + + + org.apache.activemq + activemq-core + 5.7.0 + + + org.apache.derby + derby + 10.8.1.2 + + + junit + junit + 4.12 + test + + + + javax.transaction + jta + 1.1 + + + org.apache.geronimo.specs + geronimo-jta_1.0.1B_spec + 1.0 + + + javax.validation + validation-api + 2.0.1.Final + + + org.hibernate.validator + hibernate-validator + 6.1.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.4 + + + + + 5.0.6 + 5.1.6.RELEASE + 5.4.3.Final + + + \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java new file mode 100644 index 0000000000..c51ce70dde --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.direct; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import com.atomikos.icatch.jta.UserTransactionImp; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + public void placeOrder(String productId, int amount) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + String orderId = UUID.randomUUID() + .toString(); + boolean rollback = false; + try { + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } catch (Exception e) { + System.out.println(e.getMessage()); + rollback = true; + } finally { + if (!rollback) + utx.commit(); + else + utx.rollback(); + } + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java new file mode 100644 index 0000000000..b480e68d8d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java @@ -0,0 +1,41 @@ +package com.baeldung.atomikos.spring; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.springframework.transaction.annotation.Transactional; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java new file mode 100644 index 0000000000..c6ef83c4ca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java @@ -0,0 +1,68 @@ +package com.baeldung.atomikos.spring.config; + +import java.util.Properties; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.atomikos.jdbc.AtomikosDataSourceBean; +import com.baeldung.atomikos.spring.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager jtaTransactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(inventoryDataSource(), orderDataSource()); + } +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java new file mode 100644 index 0000000000..cf1fef2cd8 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java @@ -0,0 +1,48 @@ +package com.baeldung.atomikos.spring.jpa; + +import java.util.Set; +import java.util.UUID; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.Order; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +public class Application { + + @Autowired + private InventoryRepository inventoryRepository; + + @Autowired + private OrderRepository orderRepository; + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Inventory inventory = inventoryRepository.findOne(productId); + inventory.setBalance(inventory.getBalance() - amount); + inventoryRepository.save(inventory); + Order order = new Order(); + order.setOrderId(orderId); + order.setProductId(productId); + order.setAmount(new Long(amount)); + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> violations = validator.validate(order); + if (violations.size() > 0) + throw new Exception("Invalid instance of an order."); + orderRepository.save(order); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java new file mode 100644 index 0000000000..6716f19576 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.atomikos.spring.jpa.config; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.baeldung.atomikos.spring.jpa.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager transactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java new file mode 100644 index 0000000000..999879218c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java @@ -0,0 +1,31 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "INVENTORY") +public class Inventory { + + @Id + private String productId; + private Long balance; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getBalance() { + return balance; + } + + public void setBalance(Long balance) { + this.balance = balance; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java new file mode 100644 index 0000000000..5301ad6ff2 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.inventory", entityManagerFactoryRef = "inventoryEntityManager", transactionManagerRef = "transactionManager") +public class InventoryConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory inventoryEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.inventory"); + factory.setDataSource(inventoryDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java new file mode 100644 index 0000000000..c3868e51bf --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java new file mode 100644 index 0000000000..4b9ae2dd1d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java @@ -0,0 +1,42 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.Max; + +@Entity +@Table(name = "ORDERS") +public class Order { + + @Id + private String orderId; + private String productId; + @Max(5) + private Long amount; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java new file mode 100644 index 0000000000..b4274bb64c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.order", entityManagerFactoryRef = "orderEntityManager", transactionManagerRef = "transactionManager") +public class OrderConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory orderEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order"); + factory.setDataSource(orderDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java new file mode 100644 index 0000000000..2d5610ebca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OrderRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/resources/logback.xml b/atomikos/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/atomikos/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/atomikos/src/main/resources/schema.sql b/atomikos/src/main/resources/schema.sql new file mode 100644 index 0000000000..5136ad1284 --- /dev/null +++ b/atomikos/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE INVENTORY ( + productId VARCHAR PRIMARY KEY, + balance INT +); + +CREATE TABLE ORDERS ( + orderId VARCHAR PRIMARY KEY, + productId VARCHAR, + amount INT NOT NULL CHECK (amount <= 5) +); \ No newline at end of file diff --git a/atomikos/src/main/resources/transactions.properties b/atomikos/src/main/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/main/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java new file mode 100644 index 0000000000..1a467807ba --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.atomikos.direct; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.atomikos.icatch.jta.UserTransactionImp; +import com.atomikos.jdbc.AtomikosDataSourceBean; + +public class ApplicationUnitTest { + + private static DataSource inventoryDataSource; + private static DataSource orderDataSource; + + private static String productId = UUID.randomUUID() + .toString(); + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @BeforeClass + public static void setUp() throws SQLException { + + inventoryDataSource = getDataSource("db1"); + orderDataSource = getDataSource("db2"); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static DataSource getDataSource(String db) { + + DataSource ds; + AtomikosDataSourceBean ads = new AtomikosDataSourceBean(); + ads.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties properties = new Properties(); + properties.put("databaseName", db); + properties.put("createDatabase", "create"); + ads.setXaProperties(properties); + ads.setUniqueResourceName(db); + ads.setPoolSize(10); // optional + ads.setBorrowConnectionTimeout(10); // optional + ds = ads; + return ds; + + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + utx.commit(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java new file mode 100644 index 0000000000..0c9392eac4 --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.atomikos.spring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + DataSource inventoryDataSource; + + @Autowired + DataSource orderDataSource; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java new file mode 100644 index 0000000000..e6a3c1982c --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.atomikos.spring.jpa; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.jpa.config.Config; +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryConfig; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.OrderConfig; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class, InventoryConfig.class, OrderConfig.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + OrderRepository orderRepository; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryRepository, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryRepository, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Inventory inventory = new Inventory(); + inventory.setProductId(productId); + inventory.setBalance(new Long(10000)); + inventoryRepository.save(inventory); + + } + + private static long getBalance(InventoryRepository inventoryRepository, String productId) throws Exception { + + return inventoryRepository.findOne(productId) + .getBalance(); + + } + +} diff --git a/atomikos/src/test/resources/logback.xml b/atomikos/src/test/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/atomikos/src/test/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/atomikos/src/test/resources/transactions.properties b/atomikos/src/test/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/test/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8d4632fb3e..8a8b8e1b55 100644 --- a/pom.xml +++ b/pom.xml @@ -564,6 +564,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos
@@ -1073,6 +1075,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos
From 40f2f2ea8a431fa6e675ce6d31900f515ea55e31 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 26 Mar 2020 12:29:05 +0200 Subject: [PATCH 70/97] BAEL-3926 - Java Map with case-insensitive keys --- .../core-java-collections-maps/pom.xml | 7 ++++ .../map/CaseInsensitiveMapUnitTest.java | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index c0dd705c1c..b459213e17 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,10 +26,17 @@ ${assertj.version} test + + org.springframework + spring-core + ${spring.version} + test + 4.1 3.6.1 + 5.2.5.RELEASE diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..a2171aa326 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.map; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import static org.junit.Assert.*; + +import java.util.TreeMap; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(treeMap.size(), 1); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(commonsHashMap.get("aBc"), (Integer)2); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(linkedHashMap.size(), 0); + } +} From 7d9d3c5f607260be7a466600bb09b9926a252770 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:50:20 +0300 Subject: [PATCH 71/97] new module has been added --- .../core-java-collections-maps/pom.xml | 7 ---- java-collections-maps-3/README.md | 8 ++++ java-collections-maps-3/pom.xml | 39 +++++++++++++++++++ .../CaseInsensitiveMapUnitTest.java | 7 ++-- pom.xml | 10 ++++- 5 files changed, 59 insertions(+), 12 deletions(-) create mode 100644 java-collections-maps-3/README.md create mode 100644 java-collections-maps-3/pom.xml rename {java-collections-maps/src/test/java/com/baeldung/map => java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys}/CaseInsensitiveMapUnitTest.java (84%) diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index b459213e17..c0dd705c1c 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,17 +26,10 @@ ${assertj.version} test - - org.springframework - spring-core - ${spring.version} - test - 4.1 3.6.1 - 5.2.5.RELEASE diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md new file mode 100644 index 0000000000..9df666296b --- /dev/null +++ b/java-collections-maps-3/README.md @@ -0,0 +1,8 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-case-insensitive-keys) +- More articles: [[<-- prev>]](/../java-collections-maps) +- More articles: [[<-- prev>]](/../java-collections-maps-2) diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..0dd915c87b --- /dev/null +++ b/java-collections-maps-3/pom.xml @@ -0,0 +1,39 @@ + + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + 4.0.0 + java-collections-maps-3 + + + + org.springframework + spring-core + ${spring.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + + 4.1 + 3.6.1 + 5.2.5.RELEASE + + \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java similarity index 84% rename from java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java rename to java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index a2171aa326..b12080e368 100644 --- a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,6 +1,7 @@ -package com.baeldung.map; +package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; import static org.junit.Assert.*; @@ -23,7 +24,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); } @Test @@ -32,6 +33,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(linkedHashMap.size(), 0); } } diff --git a/pom.xml b/pom.xml index 8a8b8e1b55..cb0c0cf5d7 100644 --- a/pom.xml +++ b/pom.xml @@ -453,6 +453,9 @@ java-collections-conversions java-collections-conversions-2 + java-collections-maps + java-collections-maps-2 + java-collections-maps-3 javafx @@ -564,7 +567,7 @@ rxjava-libraries rxjava-observables rxjava-operators - + atomikos
@@ -965,6 +968,9 @@ java-collections-conversions java-collections-conversions-2 + java-collections-maps + java-collections-maps-2 + java-collections-maps-3 javafx @@ -1075,7 +1081,7 @@ rxjava-libraries rxjava-observables rxjava-operators - + atomikos
From 5137f8fa209d1a0c2f8847017cb959e0a6db69b1 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:58:34 +0300 Subject: [PATCH 72/97] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b12080e368..b3653a97c2 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,37 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(treeMap.size(), 1); + assertEquals(1, treeMap.size()); + + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, treeMap.get("aBc")); } @Test @@ -24,7 +54,34 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + Assert.assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + Assert.assertEquals(0, commonsHashMap.size()); } @Test @@ -33,6 +90,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(0, linkedHashMap.size()); } } From 9fc999311cdc4fa83b733631a4213b48728cb9d7 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:41:07 +0300 Subject: [PATCH 73/97] tests has been added and split --- java-collections-maps-3/README.md | 2 +- .../CaseInsensitiveMapUnitTest.java | 29 +++++++++---------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index 9df666296b..ab6a37d00c 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -3,6 +3,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: -- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-case-insensitive-keys) +- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys/) - More articles: [[<-- prev>]](/../java-collections-maps) - More articles: [[<-- prev>]](/../java-collections-maps-2) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b3653a97c2..82feef869a 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - +import java.util.Map; import java.util.TreeMap; +import static org.junit.Assert.*; public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); @@ -21,7 +20,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); @@ -41,20 +40,20 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - Assert.assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("aBc")); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("aBc")); } @Test @@ -63,25 +62,25 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("aBc")); } @Test public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 3); treeMap.remove("aBC"); - Assert.assertEquals(0, treeMap.size()); + assertEquals(0, treeMap.size()); } @Test public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 3); commonsHashMap.remove("aBC"); - Assert.assertEquals(0, commonsHashMap.size()); + assertEquals(0, commonsHashMap.size()); } @Test @@ -90,6 +89,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(0, linkedHashMap.size()); + assertEquals(0, linkedHashMap.size()); } } From 640f8ce5d28cc78265d13e2f957895e36c7a719c Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:50:07 +0300 Subject: [PATCH 74/97] varius get cases --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 82feef869a..60dd1da9c0 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -45,6 +45,7 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("ABc")); } @Test @@ -54,6 +55,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("ABc")); } @Test @@ -63,6 +65,7 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("ABc")); } @Test From c2e37ce399ab221298a7914275a146c8ce23fb68 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Mon, 30 Mar 2020 13:28:29 +0300 Subject: [PATCH 75/97] changed README, assert has changed --- java-collections-maps-3/README.md | 2 +- .../CaseInsensitiveMapUnitTest.java | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index ab6a37d00c..ed68eb00a0 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -3,6 +3,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: -- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys/) + - More articles: [[<-- prev>]](/../java-collections-maps) - More articles: [[<-- prev>]](/../java-collections-maps-2) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 60dd1da9c0..37d9af7535 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -25,7 +25,6 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals(1, commonsHashMap.size()); - } @Test @@ -35,7 +34,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals(1, linkedHashMap.size()); - } @Test @@ -44,8 +42,8 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals((Integer)2, treeMap.get("aBc")); - assertEquals((Integer)2, treeMap.get("ABc")); + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); } @Test @@ -54,8 +52,8 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals((Integer)2, commonsHashMap.get("aBc")); - assertEquals((Integer)2, commonsHashMap.get("ABc")); + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); } @Test @@ -64,8 +62,8 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - assertEquals((Integer)2, linkedHashMap.get("aBc")); - assertEquals((Integer)2, linkedHashMap.get("ABc")); + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); } @Test From 46843866bd569096bed78d1d261a82363ada9ff2 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 10:06:43 +0300 Subject: [PATCH 76/97] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 37d9af7535..c64738a266 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -29,7 +29,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -58,7 +58,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -86,7 +86,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); From 73892202d1aacee43417e413ba14a1ba3b90b67b Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 12:18:03 +0300 Subject: [PATCH 77/97] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index c64738a266..833807c692 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,6 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals(1, treeMap.size()); - } @Test From db989e2322d3214326c3b5b316d566e0260175bb Mon Sep 17 00:00:00 2001 From: omerfinger <43134354+omerfinger@users.noreply.github.com> Date: Wed, 8 Apr 2020 12:12:26 +0300 Subject: [PATCH 78/97] Revert to original pom settings --- java-collections-maps-3/pom.xml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index 0dd915c87b..a397eaa033 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -8,9 +8,13 @@ 0.0.1-SNAPSHOT ../parent-java + 4.0.0 java-collections-maps-3 - + 0.1.0-SNAPSHOT + java-collections-maps-3 + jar + org.springframework @@ -36,4 +40,4 @@ 3.6.1 5.2.5.RELEASE - \ No newline at end of file + From 0b2e7e9f7c7089329e783fe3e096fe74cfe4767c Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 26 Mar 2020 12:29:05 +0200 Subject: [PATCH 79/97] BAEL-3926 - Java Map with case-insensitive keys --- .../core-java-collections-maps/pom.xml | 7 ++++ .../map/CaseInsensitiveMapUnitTest.java | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index c0dd705c1c..b459213e17 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,10 +26,17 @@ ${assertj.version} test + + org.springframework + spring-core + ${spring.version} + test + 4.1 3.6.1 + 5.2.5.RELEASE diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..a2171aa326 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.map; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import static org.junit.Assert.*; + +import java.util.TreeMap; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(treeMap.size(), 1); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(commonsHashMap.get("aBc"), (Integer)2); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(linkedHashMap.size(), 0); + } +} From b2bc2dc00408c6d1fd223e73258f03a5aac4d5cf Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:50:20 +0300 Subject: [PATCH 80/97] new module has been added --- .../core-java-collections-maps/pom.xml | 7 -- java-collections-maps-3/pom.xml | 4 +- .../CaseInsensitiveMapUnitTest.java | 74 +++---------------- .../map/CaseInsensitiveMapUnitTest.java | 37 ---------- 4 files changed, 11 insertions(+), 111 deletions(-) delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index b459213e17..c0dd705c1c 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,17 +26,10 @@ ${assertj.version} test - - org.springframework - spring-core - ${spring.version} - test - 4.1 3.6.1 - 5.2.5.RELEASE diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index a397eaa033..3888623a7f 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -8,13 +8,13 @@ 0.0.1-SNAPSHOT ../parent-java - + 4.0.0 java-collections-maps-3 0.1.0-SNAPSHOT java-collections-maps-3 jar - + org.springframework diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 833807c692..b12080e368 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,94 +1,38 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import java.util.Map; -import java.util.TreeMap; import static org.junit.Assert.*; +import java.util.TreeMap; + public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(1, treeMap.size()); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 1); - commonsHashMap.put("ABC", 2); - - assertEquals(1, commonsHashMap.size()); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 1); - linkedHashMap.put("ABC", 2); - - assertEquals(1, linkedHashMap.size()); - } - - @Test - public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 1); - treeMap.put("ABC", 2); - - assertEquals(2, treeMap.get("aBc").intValue()); - assertEquals(2, treeMap.get("ABc").intValue()); + assertEquals(treeMap.size(), 1); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals(2, commonsHashMap.get("aBc").intValue()); - assertEquals(2, commonsHashMap.get("ABc").intValue()); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 1); - linkedHashMap.put("ABC", 2); - - assertEquals(2, linkedHashMap.get("aBc").intValue()); - assertEquals(2, linkedHashMap.get("ABc").intValue()); - } - - @Test - public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 3); - treeMap.remove("aBC"); - - assertEquals(0, treeMap.size()); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 3); - commonsHashMap.remove("aBC"); - - assertEquals(0, commonsHashMap.size()); + Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); } @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - assertEquals(0, linkedHashMap.size()); + Assert.assertEquals(linkedHashMap.size(), 0); } } diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java deleted file mode 100644 index a2171aa326..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.map; - -import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Test; -import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - -import java.util.TreeMap; - -public class CaseInsensitiveMapUnitTest { - @Test - public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 1); - treeMap.put("ABC", 2); - - assertEquals(treeMap.size(), 1); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 1); - commonsHashMap.put("ABC", 2); - - assertEquals(commonsHashMap.get("aBc"), (Integer)2); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 3); - linkedHashMap.remove("aBC"); - - assertEquals(linkedHashMap.size(), 0); - } -} From da97125e2068af38e4e3dd53ba196a644b195aa4 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:58:34 +0300 Subject: [PATCH 81/97] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b12080e368..b3653a97c2 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,37 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(treeMap.size(), 1); + assertEquals(1, treeMap.size()); + + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, treeMap.get("aBc")); } @Test @@ -24,7 +54,34 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + Assert.assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + Assert.assertEquals(0, commonsHashMap.size()); } @Test @@ -33,6 +90,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(0, linkedHashMap.size()); } } From ac21dcc346f1c3debe4b8bd370f937c5aa6f7ba0 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:41:07 +0300 Subject: [PATCH 82/97] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b3653a97c2..82feef869a 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - +import java.util.Map; import java.util.TreeMap; +import static org.junit.Assert.*; public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); @@ -21,7 +20,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); @@ -41,20 +40,20 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - Assert.assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("aBc")); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("aBc")); } @Test @@ -63,25 +62,25 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("aBc")); } @Test public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 3); treeMap.remove("aBC"); - Assert.assertEquals(0, treeMap.size()); + assertEquals(0, treeMap.size()); } @Test public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 3); commonsHashMap.remove("aBC"); - Assert.assertEquals(0, commonsHashMap.size()); + assertEquals(0, commonsHashMap.size()); } @Test @@ -90,6 +89,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(0, linkedHashMap.size()); + assertEquals(0, linkedHashMap.size()); } } From dac08f02db475176443be050cc929b1c40699913 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:50:07 +0300 Subject: [PATCH 83/97] varius get cases --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 82feef869a..60dd1da9c0 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -45,6 +45,7 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("ABc")); } @Test @@ -54,6 +55,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("ABc")); } @Test @@ -63,6 +65,7 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("ABc")); } @Test From 22a94cd61c2b5f936e85aeecf6c52c7a5f9153d7 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Mon, 30 Mar 2020 13:28:29 +0300 Subject: [PATCH 84/97] changed README, assert has changed --- .../CaseInsensitiveMapUnitTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 60dd1da9c0..37d9af7535 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -25,7 +25,6 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals(1, commonsHashMap.size()); - } @Test @@ -35,7 +34,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals(1, linkedHashMap.size()); - } @Test @@ -44,8 +42,8 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals((Integer)2, treeMap.get("aBc")); - assertEquals((Integer)2, treeMap.get("ABc")); + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); } @Test @@ -54,8 +52,8 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals((Integer)2, commonsHashMap.get("aBc")); - assertEquals((Integer)2, commonsHashMap.get("ABc")); + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); } @Test @@ -64,8 +62,8 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - assertEquals((Integer)2, linkedHashMap.get("aBc")); - assertEquals((Integer)2, linkedHashMap.get("ABc")); + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); } @Test From 7848c39d7b634f6b90d3e2832429bfad5be311dd Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 10:06:43 +0300 Subject: [PATCH 85/97] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 37d9af7535..c64738a266 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -29,7 +29,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -58,7 +58,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -86,7 +86,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); From edb8e8b341e45de9c5aec23aedf309c3aeccec96 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 12:18:03 +0300 Subject: [PATCH 86/97] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index c64738a266..833807c692 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,6 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals(1, treeMap.size()); - } @Test From 7930d2c72e6e33d163a475abc7166e02cafb2d89 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sun, 12 Apr 2020 11:48:00 +0300 Subject: [PATCH 87/97] rebase parent pom on upstream --- pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pom.xml b/pom.xml index cb0c0cf5d7..24d9fd1d0b 100644 --- a/pom.xml +++ b/pom.xml @@ -453,8 +453,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 java-collections-maps-3 @@ -968,8 +966,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 java-collections-maps-3 From a0dd4a537db8332ab8790b0ee0dca3e7a42c3e5f Mon Sep 17 00:00:00 2001 From: gindex Date: Sun, 12 Apr 2020 13:01:52 +0200 Subject: [PATCH 88/97] Revert README.md to 1acadab1 --- reactor-core/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/reactor-core/README.md b/reactor-core/README.md index f2dbd77981..e3cca35f86 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,4 +7,3 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) -- [How To Get String From Mono In Reactive Java](http://baeldung.com/string-from-mono/) \ No newline at end of file From 856c0473068fef84d5a68c532bd2ecd28884ea38 Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Sun, 12 Apr 2020 13:53:06 -0500 Subject: [PATCH 89/97] Update terraform/best-practices/k8s-modules/SETUP.md Co-Authored-By: KevinGilmore --- terraform/best-practices/k8s-modules/SETUP.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md index b7e4c2764d..f00247a293 100644 --- a/terraform/best-practices/k8s-modules/SETUP.md +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -4,7 +4,7 @@ This sample deploys two services behind a Kubernetes ingress. # Setup instructions -1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. If you get a list of nodes that contains at least one _ready_ module, you're good to go 2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere in the OS's PATH. @@ -18,4 +18,3 @@ This sample deploys two services behind a Kubernetes ingress. 6. Run _terraform destroy_ to remove the previously creates namespace. - From bf0ff591457cef341514a54764c1b944f87b7cd2 Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Sun, 12 Apr 2020 13:53:19 -0500 Subject: [PATCH 90/97] Update terraform/best-practices/k8s-basic/SETUP.md Co-Authored-By: KevinGilmore --- terraform/best-practices/k8s-basic/SETUP.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md index 479bb75274..35e690d88e 100644 --- a/terraform/best-practices/k8s-basic/SETUP.md +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -1,6 +1,6 @@ # Setup instructions -1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. If you get a list of nodes that contains at least one _ready_ module, you're good to go 2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere in the OS's PATH. @@ -12,4 +12,3 @@ ''' 5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. 6. Run _terraform destroy_ to remove the previously creates namespace. - From a6b0996346beedb9066b1aa0ab334c65ee79080a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 13 Apr 2020 22:34:36 +0530 Subject: [PATCH 91/97] BAEL-3909: Update README to include article in correct module --- core-java-modules/core-java-string-operations-2/README.md | 1 + core-java-modules/core-java-string-operations/README.md | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 5e92738f5c..bc00c6a915 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -11,4 +11,5 @@ This module contains articles about string operations. - [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) - [L-Trim and R-Trim in Java](https://www.baeldung.com/l-trim-and-r-trim-in-java) - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md index c40e56bc46..18a2649a6a 100644 --- a/core-java-modules/core-java-string-operations/README.md +++ b/core-java-modules/core-java-string-operations/README.md @@ -13,5 +13,4 @@ This module contains articles about string operations. - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[next -->]](../core-java-string-operations-2) From 676738e7cbe702b85cf11c84b526d18e5b47b503 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 13 Apr 2020 21:21:19 +0200 Subject: [PATCH 92/97] JAVA-1295: Fix node.left -> node.right --- data-structures/src/main/java/com/baeldung/tree/BinaryTree.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index bb62714006..7469e8ba64 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -142,7 +142,7 @@ public class BinaryTree { nodes.add(node.left); } - if (node.left != null) { + if (node.right != null) { nodes.add(node.right); } } From bc872d37428127eed4088f141205d1583588159c Mon Sep 17 00:00:00 2001 From: Benjamin Caure Date: Tue, 14 Apr 2020 07:08:04 +0200 Subject: [PATCH 93/97] BAEL-3943 Bson to json (#9079) --- persistence-modules/java-mongodb/README.md | 1 + .../com/baeldung/morphia/domain/Book.java | 88 ++++++++--- .../bsontojson/BsonToJsonIntegrationTest.java | 142 ++++++++++++++++++ .../bsontojson/JsonDateTimeConverter.java | 30 ++++ 4 files changed, 243 insertions(+), 18 deletions(-) create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index a8539e644f..5c3c448b03 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -10,3 +10,4 @@ This module contains articles about MongoDB in Java. - [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) +- [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json) diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java index 172c916ad9..4ed2ab8580 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -1,5 +1,7 @@ package com.baeldung.morphia.domain; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; @@ -29,28 +31,13 @@ public class Book { private double cost; @Reference private Set companionBooks; + @Property + private LocalDateTime publishDate; public Book() { } - public String getTitle() { - return title; - } - - public String getAuthor() { - return author; - } - - public double getCost() { - return cost; - } - - public void addCompanionBooks(Book book) { - if (companionBooks != null) - this.companionBooks.add(book); - } - public Book(String isbn, String title, String author, double cost, Publisher publisher) { this.isbn = isbn; this.title = title; @@ -60,6 +47,71 @@ public class Book { this.companionBooks = new HashSet<>(); } + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + @Override public String toString() { return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; @@ -113,4 +165,4 @@ public class Book { return true; } -} \ No newline at end of file +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java new file mode 100644 index 0000000000..e382ea4ab2 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.bsontojson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bson.Document; +import org.bson.json.Converter; +import org.bson.json.JsonMode; +import org.bson.json.JsonWriterSettings; +import org.bson.json.StrictJsonWriter; +import org.bson.types.ObjectId; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; + +public class BsonToJsonIntegrationTest { + + private static final String DB_NAME = "library"; + private static Datastore datastore; + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), DB_NAME); + datastore.ensureIndexes(); + + datastore.save(new Book() + .setIsbn("isbn") + .setTitle("title") + .setAuthor("author") + .setCost(3.95) + .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) + .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .addCompanionBooks(new Book().setIsbn("isbn2"))); + } + + @AfterClass + public static void tearDown() { + datastore.delete(datastore.createQuery(Book.class)); + } + + @Test + public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": 1577898812000}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + + @Test + public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .outputMode(JsonMode.RELAXED) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + @Test + public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .dateTimeConverter(new JsonDateTimeConverter()) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; + + assertEquals(expectedJson, json); + + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java new file mode 100644 index 0000000000..46023e363f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.bsontojson; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; + +import org.bson.json.Converter; +import org.bson.json.StrictJsonWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonDateTimeConverter implements Converter { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class); + static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT + .withZone(ZoneId.of("UTC")); + + @Override + public void convert(Long value, StrictJsonWriter writer) { + try { + Instant instant = new Date(value).toInstant(); + String s = DATE_TIME_FORMATTER.format(instant); + writer.writeString(s); + } catch (Exception e) { + LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e); + } + } +} From 405230e25bf2cf92932b16d6dcc64acff80b9846 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 14 Apr 2020 10:52:05 +0530 Subject: [PATCH 94/97] Testing multithreading (#9088) --- .../core-java-concurrency-testing/.gitignore | 26 --- .../core-java-concurrency-testing/pom.xml | 170 +++++++++--------- 2 files changed, 85 insertions(+), 111 deletions(-) delete mode 100644 core-java-modules/core-java-concurrency-testing/.gitignore diff --git a/core-java-modules/core-java-concurrency-testing/.gitignore b/core-java-modules/core-java-concurrency-testing/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/core-java-modules/core-java-concurrency-testing/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml index bb3e6f5152..51de83f67c 100644 --- a/core-java-modules/core-java-concurrency-testing/pom.xml +++ b/core-java-modules/core-java-concurrency-testing/pom.xml @@ -1,93 +1,93 @@ - 4.0.0 - core-java-concurrency-testing - 0.1.0-SNAPSHOT - core-java-concurrency-testing - jar + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + core-java-concurrency-testing + 0.1.0-SNAPSHOT + core-java-concurrency-testing + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - junit - junit - 4.13 - test - - - com.googlecode.thread-weaver - threadweaver - 0.2 - test - - - com.google.code.tempus-fugit - tempus-fugit - 1.1 - test - - - com.googlecode.multithreadedtc - multithreadedtc - 1.01 - test - - - org.openjdk.jcstress - jcstress-core - 0.5 - - + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${javac.target} - ${javac.target} - ${javac.target} - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + - - org.apache.maven.plugins - maven-shade-plugin - 2.2 - - - main - package - - shade - - - jcstress - - - org.openjdk.jcstress.Main - - - META-INF/TestList - - - - - - - - + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + From 7fdcf68ccb4ef95a7555095e5cccb46b25978f78 Mon Sep 17 00:00:00 2001 From: SippingCode <55111084+SippingCode@users.noreply.github.com> Date: Wed, 15 Apr 2020 07:26:52 +0200 Subject: [PATCH 95/97] BAEL 3970 - Manual logout with Spring Security (#9075) * Manual logout with Spring Security - Basic manual logout - logout with Clear Data Site Header * Add missing annotation for controller. Change mapping URL value. * Add intergration tests for manual logouts. * BAEL-3970 - Add asserts on test. Fix tests names. Remove unused imports. --- .../manuallogout/BasicAuthController.java | 32 +++++++++ .../manuallogout/ClearSiteDataController.java | 29 ++++++++ .../manuallogout/ManualLogoutApplication.java | 11 +++ .../SimpleSecurityConfiguration.java | 39 +++++++++++ .../ManualLogoutIntegrationTest.java | 70 +++++++++++++++++++ 5 files changed, 181 insertions(+) create mode 100644 spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java create mode 100644 spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java create mode 100644 spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java create mode 100644 spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java create mode 100644 spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java new file mode 100644 index 0000000000..8f01940dce --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java @@ -0,0 +1,32 @@ +package com.baeldung.manuallogout; + +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@Controller +public class BasicAuthController { + + @RequestMapping(value = {"/basiclogout"}, method = RequestMethod.POST) + public String logout(HttpServletRequest request, HttpServletResponse response) { + HttpSession session; + SecurityContextHolder.clearContext(); + session = request.getSession(false); + if (session != null) { + session.invalidate(); + } + for (Cookie cookie : request.getCookies()) { + String cookieName = cookie.getName(); + Cookie cookieToDelete = new Cookie(cookieName, null); + cookieToDelete.setMaxAge(0); + response.addCookie(cookieToDelete); + } + return "redirect:/login?logout"; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java new file mode 100644 index 0000000000..7eef397da3 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java @@ -0,0 +1,29 @@ +package com.baeldung.manuallogout; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Controller +public class ClearSiteDataController { + + Directive[] SOURCE = {Directive.COOKIES, Directive.STORAGE, Directive.EXECUTION_CONTEXTS, Directive.CACHE}; + + @RequestMapping(value = {"/csdlogout"}, method = RequestMethod.POST) + public String logout(HttpServletRequest request, HttpServletResponse response) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { + ClearSiteDataHeaderWriter csdHeaderWriter = new ClearSiteDataHeaderWriter(SOURCE); + new HeaderWriterLogoutHandler(csdHeaderWriter).logout(request, response, auth); + } + return "redirect:/login?logout"; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java new file mode 100644 index 0000000000..50ea356f03 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.manuallogout; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ManualLogoutApplication { + public static void main(String[] args) { + SpringApplication.run(ManualLogoutApplication.class, args); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java new file mode 100644 index 0000000000..6f14f6fca2 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.manuallogout; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SimpleSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.formLogin() + .loginProcessingUrl("/login") + .loginPage("/login") + .usernameParameter("username") + .passwordParameter("password") + .defaultSuccessUrl("/") + .failureUrl("/login?error"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password("password") + .roles("USER") + .and() + .withUser("manager") + .password("password") + .credentialsExpired(true) + .accountExpired(true) + .accountLocked(true) + .authorities("WRITE_PRIVILEGES", "READ_PRIVILEGES") + .roles("MANAGER"); + } +} diff --git a/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java new file mode 100644 index 0000000000..a64cb82910 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.manuallogout; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpSession; + +import static org.junit.Assert.assertNull; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest() +public class ManualLogoutIntegrationTest { + + private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; + public static final int EXPIRY = 60 * 10; + public static final String COOKIE_NAME = "customerName"; + public static final String COOKIE_VALUE = "myName"; + public static final String ATTRIBUTE_NAME = "att"; + public static final String ATTRIBUTE_VALUE = "attvalue"; + + @Autowired + private MockMvc mockMvc; + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionCleared() throws Exception { + + MockHttpSession session = new MockHttpSession(); + session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); + + Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); + randomCookie.setMaxAge(EXPIRY); // 10 minutes + + MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/basiclogout").secure(true).with(csrf()).session(session).cookie(randomCookie)) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andExpect(cookie().maxAge(COOKIE_NAME, 0)) + .andReturn() + .getRequest(); + + HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession(); + assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME)); + + + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { + + this.mockMvc.perform(post("/csdlogout").secure(true).with(csrf())) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) + .andReturn(); + } +} \ No newline at end of file From 86c4eea3dd95a0e98e6bb882e482fe0702adbd20 Mon Sep 17 00:00:00 2001 From: Belma Jakupovic Date: Wed, 15 Apr 2020 21:15:59 +0200 Subject: [PATCH 96/97] additional answers mockito change repository method (#9082) --- .../mockito/additionalanswers/BookRepository.java | 15 +++++++++++---- .../mockito/additionalanswers/BookService.java | 4 ++-- .../additionalanswers/BookServiceUnitTest.java | 12 ++++++------ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java index 78187e3f01..677ee502b4 100644 --- a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java @@ -1,5 +1,9 @@ package com.baeldung.mockito.additionalanswers; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + public class BookRepository { public Book getByBookId(Long bookId) { return new Book(bookId, "To Kill a Mocking Bird", "Harper Lee", 256); @@ -9,9 +13,12 @@ public class BookRepository { return new Book(book.getBookId(), book.getTitle(), book.getAuthor(), book.getNumberOfPages()); } - public Book checkIfEquals(Book bookOne, Book bookTwo, Book bookThree) { - if (bookOne.equals(bookTwo) && bookTwo.equals(bookThree) && bookThree.equals(bookOne)) { - return bookOne; - } else return bookTwo; + public Book selectRandomBook(Book bookOne, Book bookTwo, Book bookThree) { + List selection = new ArrayList<>(); + selection.add(bookOne); + selection.add(bookTwo); + selection.add(bookThree); + Random random = new Random(); + return selection.get(random.nextInt(selection.size())); } } diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java index 92c01f8a70..4499a6524b 100644 --- a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java @@ -15,8 +15,8 @@ public class BookService { return bookRepository.save(book); } - public Book checkifEquals(Book book1, Book book2, Book book3) { - return bookRepository.checkIfEquals(book1, book2, book3); + public Book selectRandomBook(Book book1, Book book2, Book book3) { + return bookRepository.selectRandomBook(book1, book2, book3); } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java index c9527ec0ec..ee32bcf70c 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java @@ -34,9 +34,9 @@ public class BookServiceUnitTest { Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); - Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg()); + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg()); - Book secondBook = bookService.checkifEquals(book1, book2, book3); + Book secondBook = bookService.selectRandomBook(book1, book2, book3); assertEquals(secondBook, book2); } @@ -47,9 +47,9 @@ public class BookServiceUnitTest { Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); - Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg()); + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg()); - Book lastBook = bookService.checkifEquals(book1, book2, book3); + Book lastBook = bookService.selectRandomBook(book1, book2, book3); assertEquals(lastBook, book3); } @@ -59,9 +59,9 @@ public class BookServiceUnitTest { Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); - Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1)); + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1)); - Book bookOnIndex = bookService.checkifEquals(book1, book2, book3); + Book bookOnIndex = bookService.selectRandomBook(book1, book2, book3); assertEquals(bookOnIndex, book2); } From 23099cff16320fcd96c677b824c10b3caa723574 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Wed, 15 Apr 2020 21:19:02 +0200 Subject: [PATCH 97/97] BAEL-3994: Add example of chaining methods returning Optionals (#9102) * BAEL-3994: Add example of chaining methods returning Optionals * BAEL-3994: Update --- .../orelseoptional/ItemsProvider.java | 21 +++++++++++++++ .../OrElseOptionalUnitTest.java | 26 +++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java new file mode 100644 index 0000000000..480dc782e4 --- /dev/null +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java @@ -0,0 +1,21 @@ +package com.baeldung.orelseoptional; + +import java.util.Optional; + +public class ItemsProvider { + + Optional getEmptyItem() { + System.out.println("Returning an empty item"); + return Optional.empty(); + } + + Optional getNail() { + System.out.println("Returning a nail"); + return Optional.of("nail"); + } + + Optional getHammer() { + System.out.println("Returning a hammer"); + return Optional.of("hammer"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java index 91aebbeebd..e3bdedcd82 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.orelseoptional; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Optional; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class OrElseOptionalUnitTest { @@ -25,6 +25,28 @@ public class OrElseOptionalUnitTest { assertEquals(fallbackOptionalString, OptionalUtils.or(optionalString, fallbackOptionalString)); } + @Test + public void givenTwoOptionalMethods_whenFirstEmpty_thenSecondEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getEmptyItem() + .map(Optional::of) + .orElseGet(itemsProvider::getNail); + + assertEquals(Optional.of("nail"), item); + } + + @Test + public void givenTwoOptionalMethods_whenFirstNonEmpty_thenSecondNotEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getNail() + .map(Optional::of) + .orElseGet(itemsProvider::getHammer); + + assertEquals(Optional.of("nail"), item); + } + // Uncomment code when code base is compatible with Java 9 // @Test // public void givenOptional_whenEmptyValue_thenCustomMessage() {