├── .gitignore ├── .travis.settings.xml ├── .travis.yml ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── fr │ │ └── juanwolf │ │ └── mysqlbinlogreplicator │ │ ├── DomainClass.java │ │ ├── annotations │ │ ├── MysqlMapping.java │ │ └── NestedMapping.java │ │ ├── component │ │ └── DomainClassAnalyzer.java │ │ ├── nested │ │ ├── NestedRowMapper.java │ │ ├── SQLRelationship.java │ │ └── requester │ │ │ ├── ManyToManyRequester.java │ │ │ ├── ManyToOneRequester.java │ │ │ ├── OneToManyRequester.java │ │ │ ├── OneToOneRequester.java │ │ │ └── SQLRequester.java │ │ └── service │ │ ├── MySQLEventListener.java │ │ └── MysqlBinLogService.java └── resources │ ├── application.properties │ └── logback.xml └── test ├── java ├── fr │ └── juanwolf │ │ └── mysqlbinlogreplicator │ │ ├── component │ │ └── DomainClassAnalyzerTest.java │ │ ├── dao │ │ └── UserRepository.java │ │ ├── domain │ │ ├── Bill.java │ │ ├── Cart.java │ │ └── User.java │ │ ├── nested │ │ ├── NestedRowMapperTest.java │ │ └── requester │ │ │ ├── OneToManyRequesterTest.java │ │ │ ├── OneToOneRequesterTest.java │ │ │ └── SQLRequesterTest.java │ │ └── service │ │ ├── MySQLEventListenerTest.java │ │ └── MysqlBinLogServiceTest.java └── integrationTest │ ├── Replicator.java │ ├── dao │ ├── CartRepository.java │ └── UserRepository.java │ └── domain │ ├── Cart.java │ └── User.java └── resources └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | *.class 4 | 5 | # Mobile Tools for Java (J2ME) 6 | .mtj.tmp/ 7 | 8 | # Package Files # 9 | *.jar 10 | *.war 11 | *.ear 12 | 13 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 14 | hs_err_pid* 15 | 16 | 17 | ### Maven template 18 | target/ 19 | pom.xml.tag 20 | pom.xml.releaseBackup 21 | pom.xml.versionsBackup 22 | pom.xml.next 23 | release.properties 24 | dependency-reduced-pom.xml 25 | buildNumber.properties 26 | .mvn/timing.properties 27 | 28 | LOG_PATH_IS_UNDEFINED 29 | 30 | 31 | -------------------------------------------------------------------------------- /.travis.settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | nexus-releases 14 | ${env.CI_DEPLOY_USERNAME} 15 | ${env.CI_DEPLOY_PASSWORD} 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | 5 | branches: 6 | only: 7 | - master 8 | 9 | script: 10 | - mvn clean test 11 | 12 | after_success: 13 | - mvn clean -DrepoToken=$repoToken cobertura:cobertura coveralls:report 14 | - VERSION=$( grep -oPm1 "(?<=)[^-SNAPSHOT<]+" pom.xml | head -1) 15 | - TAG="mysql-binlog-replicator-$VERSION" 16 | - git config --global user.name "$GIT_NAME" 17 | - git config --global user.email "$GIT_EMAIL" 18 | - git checkout master 19 | - mvn -X -s ./.travis.settings.xml --batch-mode -Dtag=$TAG -DreleaseVersion=$VERSION -Dgh.token=$GH_TOKEN -Dgpg.passphrase=$GPG_PASSPHRASE release:clean release:prepare 20 | - mvn -X -s ./.travis.settings.xml release:perform -Dgpg.passphrase=$GPG_PASSPHRASE -Dgh.token=$GH_TOKEN 21 | 22 | env: 23 | global: 24 | - secure: GkGCYFr7Zf6sKdIySqBLm5HpvsZO9934S4TlArdlfqO+kiMqNCKOcB2qN01daiFFxhPocxaMkCi6Wgxry0N8oaT1x1RS2e7lt69H7fZSYUEQoxDPLEKE+jQKPumq6XR/z9m5NltkidRiOtnq4u8pl23y5+p8OAMk9KMp2MAsRYcnfLQ/nbEsFyF/3XH41CfErCIQ+mgVAVT3ZTOswsfzU1Cc0V9XQ0XuTk3uI8FailJKBSLy3L0pv7LWSSBLl7S4jlJDgO3B6628OXzGgxqaKqngLU7RaezB8lLxp9zdR1ydSEs83vLpJK9S0V5X5h6gVlyjYNrmuijG42lervQaH3+hCrdhZlIMzEo5oJUcqD6ZHupVu9pZQgd03Ce/IPU9bAKWF2YroiFyR8+ghcnmXY5R6Ci7Gr1qQKOtOsThoZXO0I5LRQfDHlC30L/7PSWLIVvhb1pyRWHkYOnQ4WPrW9IGjkFI89ihnoCdxO3Z212oYPi9vcfU5go7nwWumjcE7q3n1D1K0xdWNPtttIHRvPawj3KKM/nIxfEMjuvF/1A74OMfDQWWSpYamrBgUgMWCK7VJd07YOWidC3dhWE5xGhrrdaqBzJveCRxHt2Cyv16P+g/ulu+7qZdOg3refCFtY/Ixq67mT7kw7rutU65fGhvuy8IPGnRiInXxyTF4bc= 25 | - secure: NommQkVC/2c42NN36slMwyceV7AvZLnd9AJ9Rzdu4C1epo0B0M8Z9t+Pz2Y1vE01baqldp9HWXZ7U4YANz3cJNNjP9xjweifdF0AAB44JIFf0wOmOuCcxEc8J57RKroxIxbr2BbxcqeMFzWDlRh48wkJw0RLrLPbD6cz4oHER875mn5oN4I6tyqVJC8g/HQzHTYdDCDOv9Hsej/hPj9Hzm9EKKejL32ZgRXDHPwzVMB0KAfSFwU8wkI2tS8bOrJDlzdueHeF+pdP7IRrvO6FxdjoznKTVDqzT48p1jAPC5UY3awqwaFjKDZ0QQQXteASG44/pr/xWsvjxRGJtqVITZ6eeJ/Dq4xHew6WIobDScNsZqHENXEVx9DKj2ltj87VllCKyyrzO8mG7AzsKoIfpOavhlRnU5frwzZFftS56tbllmhj4rXBj++1VF3JnCJjXUYz3KlGcfUWIjbCINe/qPcp4btGwbSy8+6EOQQvGtfqfgajlR3fLvtRGVhYKXyIsXBkziel2T1YMv4S2ovcy7KDbCXkja/Ki9yA+4SHdLOqQaZ1Ax0DGyBLu8MFO0ohm3ffXQ80j/Pq4SYiaxr90fok2wVWzUl9yGoa2lXsfdTdhaJkL3FTnQBOAFsNztHD3tBBI2dxolVduaLcYRJ6zkjeCFPu0xU2DYNaIqmk2Ro= 26 | - secure: EjGEwrbSrjfntUSLUp7yOFlmEv8cOc+PIorcn8ILOV19XyZH7ixhM0WQD72xeaPj+VncDgDUIqgW2B1ERyOvfxLzY7klstK8seFemnCdcUe3yGORQ1ApjlgACFiIXxMHFrXVz59kSCLCh503+5CfduwnbUgWv266FwU/m/M6FgQ2NNxd2t7788bJo4oku+k2gNnbLxT3wW92aElRp/Q1ReutCvlqqqg+yxRf9Fl9t0u/aMBimOGiWW94rbOKP42jkJTY/MQ70SNBBW9UzTmi13QTOYILAW3yDhI2URC1QrXHlR1ZwoKgRH2MiLj4/BsLGWAXsWAwSmJ5dfDzdSaFrrNA88GpF6oB3TIKFdjq+yjgVtH/5rBLEpkPArahjYfHCmTh7YeiD4TyOuz0zCHydSAebss9NX6ieIaUCT1G4bbFujH7F8Lfc4yNT4tZhnCvlwSQx0tDZ6m4K4rdEuHubkw1WoDQgk7SXg4ZmiHbXhDBIlxvteS46k44reLt34zz3LRQlNmP7+eS9EsAUK+c6yAlGL46oFfUbH8DIKWjL12/fezrcqwMV3EkWbSC0UygUIK7uaG0RwYhv8rVu/VE1C6mcit4DMxX9kGSE8AC8bZ/i1Oy90k+j06y0gQAi+nhMiEb8AYYlktTc8YPkBqRTUdopRVCSGtSig1iQUnntT8=q 27 | - secure: P78g0LDfcOpproY9KGnJDsAB5H5EpZVoM+GNIx+NJlrKIuDQhaVJbhGuHFzMJDJg2PXEf/rKYv1wU8C4wZs9/N3AFi6cyknqt70rzAN2EVld+fcIr2iMg1TUeUY2zVCyPLVMpj/tjPGXOXS13EPFYwvhJnyCPNOnTTcWAff6WGEFf57IvwEGtOJ7+vumRqB346YPdoYXwAbmpU1spQSNVvne4qSg49VVZzes3KtGID0m7yRbS+o44DpbyO9K8/2FRae2fA3uySnjsRo2u0T8EotbxA86bsNM1pMN5m5Uo3Q3y2IdScfG2NBgsrl8j/+RrOgfocBviadDRUYNupLH6++yP0a6OcZ5JNH1j0+E7GeHlCNezUzUFQea7V4pj94BnRl61GeczeVoYm5wFRwqvb4/c1mjNpL/kkUffX3aV0HybbC2Rvh+pMATAoL8jti01kDmxM9M3KwCZMoznHAp4ktOmvENKvTmvdqmC44OROWb6TCXTAoOLgRmmNjuG2RIf2GXv3jnKYRbWQeWKlIWAGo7HSOwQm9067ZWR8qgfenVGQygjxclO4MoNEDZZY97tkAkuVdkYY7wS9i1os8fWLNKoWhsexH9wMnsNrIHdXKAY7Iovo/rqFSaPdEarsFo6+5XyEA3B+Gruvqk1IglGoz1q5LxB55rzwOm6Ct8vQ0= 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MySQL BinLog Replicator [![Build Status](https://travis-ci.org/juanwolf/mysql-binlog-replicator.svg?branch=master)](https://travis-ci.org/juanwolf/mysql-binlog-replicator) [![Coverage Status](https://coveralls.io/repos/juanwolf/mysql-binlog-replicator/badge.svg?branch=master&service=github)](https://coveralls.io/github/juanwolf/mysql-binlog-replicator?branch=master) 2 | 3 | This library will give you the ability to create a real time feeding from a mysql database to an ElasticSearch etc... 4 | (all repository available in spring which extend the CRUDRepository interface in fact) 5 | 6 | ## Install ## 7 | 8 | ### Maven ### 9 | 10 | 11 | fr.juanwolf 12 | mysql-binlog-replicator 13 | 1.0.7 14 | 15 | 16 | ### Setup the MYSQL server ### 17 | 18 | First, configure your server to activate the replication. 19 | 20 | To activate replication on the master, add this configuration to your mysql configuration file : 21 | 22 | [mysqld] 23 | server-id = 1 24 | log_bin = /var/log/mysql/mysql-bin.log 25 | expire_logs_days = 10 26 | max_binlog_size = 100M 27 | binlog-format = row # important to detect write and update event. 28 | 29 | 30 | WARNING : 31 | 32 | As says in [mysql-binlog-connector-java](https://github.com/shyiko/mysql-binlog-connector-java#tapping-into-mysql-replication-stream), 33 | Make sure that the user you're using has the REPLICATION SLAVE and REPLICATION CLIENT privileges. 34 | 35 | ### Setup the mysql-binlog-replicator ### 36 | 37 | Create a mysql-binlog-replicator.properties with the mysql configuration : 38 | 39 | 40 | mysql.host=localhost 41 | mysql.port=3306 42 | # Tables that you want to track changes separated by commas 43 | mysql.schema=user 44 | # The package where you keep all your pojos 45 | mysql.scanmapping=fr.juanwolf.mysqlbinlogreplicator.domain 46 | # The user with replication access 47 | mysql.user=replicator 48 | # The password for the user with replication access 49 | mysql.password=Bernard Lama 50 | 51 | ### Setup modules configuration ### 52 | 53 | #### ElasticSearch configuration #### 54 | 55 | Make sure that you configured this variable to connect the service to your ElasticSearch : 56 | 57 | spring.data.elasticsearch.cluster-nodes=localhost:9300 58 | 59 | 60 | ## Create POJO's ## 61 | 62 | ### Use @MysqlMapping ### 63 | 64 | Make sure you're using the @MysqlMapping annotation. It will bind the pojo to a specific table name and to your dao (repository). 65 | 66 | For example a class for accounts would look like : 67 | 68 | @MysqlMapping(table = "user", repository="userRepository") 69 | public class Account { 70 | @Id 71 | String id; 72 | 73 | @Field(type = FieldType.Long, index = FieldIndex.analyzed) 74 | long identifier; 75 | 76 | @Field(type = FieldType.String, index = FieldIndex.analyzed) 77 | String mail; 78 | 79 | @Field(index = FieldIndex.analyzed, type = FieldType.Date) 80 | Date creationDate; 81 | 82 | @Field(index = FieldIndex.analyzed, type = FieldType.Float) 83 | float cartAmount; 84 | 85 | public Account() {} 86 | 87 | public float getCartAmount() { 88 | return cartAmount; 89 | } 90 | 91 | public Date getCreationDate() { 92 | return creationDate; 93 | } 94 | 95 | public void setMail(String mail) { 96 | this.mail = mail; 97 | } 98 | 99 | public long getIdentifier() { 100 | return identifier; 101 | } 102 | } 103 | 104 | As you can see we keep the spring configuration for the elasticsearch repository AND the mysqlMapping annotation for the service. 105 | 106 | ### Type Mapping ### 107 | 108 | You can convert different SQL types to java types. Only this ones are available : 109 | 110 | | SQL types | Java types | Conditions | 111 | |------------|------------------|----------------------------------------| 112 | | DATE | Date | For yyyy-MM-dd SQL format | 113 | | DATETIME | Date | | 114 | | DATETIME | String | Need date.output format in config file | 115 | | TIMESTAMP | sql.Timestamp | For yyyy-MM-dd hh:mm:ss SQL format | 116 | | TIME | sql.Time | For hh:MM:ss SQL format | 117 | | BIT | boolean | | 118 | | TINY | boolean | | 119 | | INT | int | | 120 | | LONG | long | | 121 | | FLOAT | float | | 122 | | VARCHAR | String | | 123 | | LONGTEXT | String | | 124 | | TINYTEXT | String | | 125 | 126 | If you need any other mapping, please open issue. 127 | 128 | ### Use the annotations for the repositories you'll use on your POJOs### 129 | 130 | #### ElasticSearch #### 131 | 132 | Add to your pojos annotations needed by the ElasticSearch Repository, example for the user class above : 133 | 134 | @Document(indexName = "user") 135 | @Mapping(mappingPath = "user") 136 | @MysqlMapping(table = "user", repository="userRepository") 137 | public class Account { 138 | ... 139 | } 140 | 141 | ### Create your main ### 142 | 143 | - Autowire the mysqlBinLogService 144 | - Create the main which call mysqlBinLogService.startReplication() 145 | - It should work (if not please open an issue or/and contribute :D) 146 | 147 | ## How it works ## 148 | 149 | Thanks to [shykio](https://github.com/shyiko) and his [mysql-binlog-connector-java](https://github.com/shyiko/mysql-binlog-connector-java), the mysql-binlog-replicator will detect every update of the binlog file from your mysqll server and then replicate it to your CRUD repository. 150 | 151 | ### Example ### 152 | 153 | You can find an example of how to use it here : [mysql-binlog-replicator-example](http://github.com/juanwolf/mysql-binlog-replicator-example) 154 | 155 | ## Enhancement ## 156 | 157 | The project does not support nested documents and does not apply indexes (could be a feature in next releases). 158 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | fr.juanwolf 6 | mysql-binlog-replicator 7 | 1.0.9-SNAPSHOT 8 | jar 9 | 10 | Mysql BinLog Replicator 11 | Create the ORM between events received from the mysql-binlog-java library and spring repositories. 12 | 13 | 14 | juanwolf 15 | Jean-Loup ADDE 16 | jean-loup.adde@juanwolf.fr 17 | http://juanwolf.fr 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-parent 23 | 1.2.5.RELEASE 24 | 25 | 26 | 27 | 28 | https://github.com/juanwolf/mysql-binlog-replicator 29 | scm:git:https://juanwolf@github.com/juanwolf/mysql-binlog-replicator.git 30 | scm:git:https://juanwolf@github.com/juanwolf/mysql-binlog-replicator.git 31 | mysql-binlog-replicator-1.0.6 32 | 33 | 34 | 35 | UTF-8 36 | 1.8 37 | 0.2.2 38 | 1.16.4 39 | 0.9.9-RC1 40 | 3.1.0 41 | 2.6 42 | 3.1.0 43 | 2.6 44 | 5.0.3 45 | 2.5.2 46 | 1.6 47 | 2.9.1 48 | 2.2.1 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-data-jpa 60 | compile 61 | 62 | 63 | com.github.shyiko 64 | mysql-binlog-connector-java 65 | ${mysql-binlog-connector-java.version} 66 | 67 | 68 | org.reflections 69 | reflections 70 | ${reflections.version} 71 | 72 | 73 | org.projectlombok 74 | lombok 75 | ${lombok.version} 76 | compile 77 | 78 | 79 | mysql 80 | mysql-connector-java 81 | runtime 82 | 83 | 84 | spring-boot-starter-test 85 | org.springframework.boot 86 | test 87 | 88 | 89 | org.springframework.boot 90 | spring-boot-starter-data-elasticsearch 91 | test 92 | 93 | 94 | org.assertj 95 | assertj-core 96 | ${assertj-core.version} 97 | test 98 | 99 | 100 | 101 | 102 | 103 | nexus-releases 104 | https://oss.sonatype.org/content/repositories/snapshots 105 | 106 | 107 | nexus-releases 108 | Nexus Release Repository 109 | http://oss.sonatype.org/service/local/staging/deploy/maven2/ 110 | 111 | 112 | 113 | 114 | 115 | release 116 | 117 | 118 | gpg.passphrase 119 | 120 | 121 | 122 | 123 | 124 | org.apache.maven.plugins 125 | maven-gpg-plugin 126 | ${maven-gpg-plugin.version} 127 | 128 | 129 | sign-artifacts 130 | verify 131 | 132 | sign 133 | 134 | 135 | 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-jar-plugin 140 | ${maven-jar-plugin.version} 141 | 142 | 143 | org.apache.maven.plugins 144 | maven-source-plugin 145 | ${maven-source-plugin.version} 146 | 147 | 148 | attach-sources 149 | 150 | jar-no-fork 151 | 152 | 153 | 154 | 155 | 156 | org.apache.maven.plugins 157 | maven-javadoc-plugin 158 | ${maven-javadoc-plugin.version} 159 | 160 | 161 | attach-javadocs 162 | 163 | jar 164 | 165 | 166 | 167 | 168 | 169 | org.apache.maven.plugins 170 | maven-release-plugin 171 | ${maven-release-plugin.version} 172 | 173 | true 174 | true 175 | release 176 | deploy 177 | release(): [ci skip] 178 | 179 | 180 | 181 | org.apache.maven.plugins 182 | maven-assembly-plugin 183 | 184 | 185 | jar-with-dependencies 186 | 187 | 188 | 189 | 190 | package 191 | 192 | single 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | src/main/java 204 | src/test/java 205 | 206 | 207 | org.eluder.coveralls 208 | coveralls-maven-plugin 209 | ${coveralls-maven-plugin.version} 210 | 211 | 212 | org.codehaus.mojo 213 | cobertura-maven-plugin 214 | ${cobertura-maven-plugin.version} 215 | 216 | 217 | org.ow2.asm 218 | asm 219 | ${asm.version} 220 | 221 | 222 | 223 | 224 | true 225 | 226 | 227 | fr.juanwolf.mysqlbinlogreplicator.* 228 | 90 229 | 80 230 | 231 | 232 | 233 | 234 | html 235 | xml 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/DomainClass.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.SQLRequester; 4 | import lombok.Data; 5 | import org.springframework.data.repository.CrudRepository; 6 | 7 | import java.lang.reflect.Field; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by juanwolf on 07/08/15. 13 | */ 14 | @Data 15 | public class DomainClass { 16 | 17 | private String table; 18 | 19 | private CrudRepository crudRepository; 20 | 21 | private Class domainClass; 22 | 23 | private Map sqlRequesters; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/annotations/MysqlMapping.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | package fr.juanwolf.mysqlbinlogreplicator.annotations; 19 | 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Retention; 22 | import java.lang.annotation.RetentionPolicy; 23 | import java.lang.annotation.Target; 24 | 25 | @Retention(RetentionPolicy.RUNTIME) 26 | @Target({ElementType.TYPE}) 27 | public @interface MysqlMapping { 28 | String table(); 29 | String repository(); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/annotations/NestedMapping.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.annotations; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * Created by juanwolf on 07/08/15. 12 | */ 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Target({ElementType.FIELD}) 15 | public @interface NestedMapping { 16 | 17 | /** 18 | * tablename for the foreign entity. 19 | */ 20 | String table(); 21 | 22 | /** 23 | * @return The name of the foreign key for the current pojo 24 | */ 25 | String foreignKey(); 26 | 27 | /** 28 | * @return The association between both objects 29 | */ 30 | SQLRelationship sqlAssociaton(); 31 | 32 | /** 33 | * @return The name of the column for the primary key of the nested field. 34 | */ 35 | String primaryKey() default "id"; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/component/DomainClassAnalyzer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | package fr.juanwolf.mysqlbinlogreplicator.component; 19 | 20 | import com.github.shyiko.mysql.binlog.event.deserialization.ColumnType; 21 | import fr.juanwolf.mysqlbinlogreplicator.DomainClass; 22 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 23 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 24 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 25 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.SQLRequester; 26 | import lombok.Getter; 27 | import lombok.Setter; 28 | import lombok.extern.slf4j.Slf4j; 29 | import org.reflections.Reflections; 30 | import org.springframework.beans.BeansException; 31 | import org.springframework.beans.factory.annotation.Autowired; 32 | import org.springframework.beans.factory.annotation.Value; 33 | import org.springframework.context.ApplicationContext; 34 | import org.springframework.core.env.Environment; 35 | import org.springframework.data.repository.CrudRepository; 36 | import org.springframework.jdbc.core.JdbcTemplate; 37 | import org.springframework.stereotype.Component; 38 | 39 | import javax.annotation.PostConstruct; 40 | import java.lang.reflect.Constructor; 41 | import java.lang.reflect.Field; 42 | import java.lang.reflect.InvocationTargetException; 43 | import java.lang.reflect.ParameterizedType; 44 | import java.sql.Time; 45 | import java.sql.Timestamp; 46 | import java.text.DateFormat; 47 | import java.text.ParseException; 48 | import java.text.SimpleDateFormat; 49 | import java.util.*; 50 | 51 | @Slf4j 52 | @Component 53 | public class DomainClassAnalyzer { 54 | 55 | 56 | /** 57 | * Map containing every domainClass mapped by table names 58 | */ 59 | @Getter 60 | @Setter 61 | private Map domainClassMap = new HashMap<>(); 62 | 63 | 64 | /** 65 | * Map containing every domainClass mapped by nested table names 66 | */ 67 | @Getter 68 | @Setter 69 | private Map nestedDomainClassMap = new HashMap<>(); 70 | 71 | @Value("${mysql.schema}") 72 | String databaseName; 73 | 74 | @Autowired 75 | private ApplicationContext applicationContext; 76 | 77 | @Setter 78 | @Value("${mysql.scanmapping}") 79 | private String scanMapping; 80 | 81 | @Getter 82 | private List mappingTablesExpected; 83 | 84 | @Getter 85 | private List nestedTables; 86 | 87 | @Autowired 88 | private Environment environment; 89 | 90 | @Autowired 91 | private JdbcTemplate jdbcTemplate; 92 | 93 | public static final DateFormat BINLOG_DATETIME_FORMATTER = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.UK); 94 | 95 | public static final DateFormat BINLOG_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd", Locale.UK); 96 | 97 | @Getter 98 | public DateFormat binlogOutputDateFormatter; 99 | 100 | @PostConstruct 101 | public void postConstruct() throws BeansException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 102 | mappingTablesExpected = new ArrayList<>(); 103 | nestedTables = new ArrayList<>(); 104 | Reflections reflections = new Reflections(scanMapping); 105 | Set> types = reflections.getTypesAnnotatedWith(MysqlMapping.class); 106 | final Iterator> iterator = types.iterator(); 107 | while (iterator.hasNext()) { 108 | Class classDomain = iterator.next(); 109 | MysqlMapping mysqlMapping = (MysqlMapping) classDomain.getAnnotation(MysqlMapping.class); 110 | DomainClass domainClass = new DomainClass(); 111 | domainClass.setDomainClass(classDomain); 112 | mappingTablesExpected.add(mysqlMapping.table()); 113 | CrudRepository crudRepository = (CrudRepository) applicationContext.getBean(mysqlMapping.repository()); 114 | domainClass.setCrudRepository(crudRepository); 115 | domainClass.setTable(mysqlMapping.table()); 116 | Map nestedClassesMap = new HashMap<>(); 117 | for (Field field : classDomain.getDeclaredFields()) { 118 | NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class); 119 | if (nestedMapping != null) { 120 | Class sqlRequesterClass = nestedMapping.sqlAssociaton().getRequesterClass(); 121 | Constructor sqlRequesterConstructor = sqlRequesterClass.getConstructor(); 122 | SQLRequester sqlRequester = (SQLRequester) sqlRequesterConstructor.newInstance(); 123 | sqlRequester.setDatabaseName(databaseName); 124 | sqlRequester.setEntryTableName(mysqlMapping.table()); 125 | sqlRequester.setExitTableName(nestedMapping.table()); 126 | sqlRequester.setForeignKey(nestedMapping.foreignKey()); 127 | sqlRequester.setPrimaryKeyForeignEntity(nestedMapping.primaryKey()); 128 | sqlRequester.setEntryType(classDomain); 129 | sqlRequester.setAssociatedField(field); 130 | Class foreignType = field.getType(); 131 | if (field.getGenericType() instanceof ParameterizedType) { 132 | ParameterizedType genericType = (ParameterizedType) field.getGenericType(); 133 | Class properType = (Class) genericType.getActualTypeArguments()[0]; 134 | foreignType = properType; 135 | } 136 | sqlRequester.setForeignType(foreignType); 137 | sqlRequester.setJdbcTemplate(jdbcTemplate); 138 | NestedRowMapper currentClassNestedRowMapper = new NestedRowMapper(classDomain, this, mysqlMapping.table()); 139 | NestedRowMapper foreignClassNestedRowMapper = new NestedRowMapper(foreignType, this, mysqlMapping.table()); 140 | sqlRequester.setRowMapper(currentClassNestedRowMapper); 141 | sqlRequester.setForeignRowMapper(foreignClassNestedRowMapper); 142 | nestedClassesMap.put(field.getName(), sqlRequester); 143 | nestedTables.add(nestedMapping.table()); 144 | nestedDomainClassMap.put(nestedMapping.table(), domainClass); 145 | } 146 | } 147 | domainClass.setSqlRequesters(nestedClassesMap); 148 | domainClassMap.put(domainClass.getTable(), domainClass); 149 | } 150 | if (environment.getProperty("date.output") != null) { 151 | binlogOutputDateFormatter = new SimpleDateFormat(environment.getProperty("date.output")); 152 | } 153 | } 154 | 155 | public Object generateInstanceFromName(String name) throws ReflectiveOperationException { 156 | DomainClass domainClass = domainClassMap.get(name); 157 | if (domainClass == null) { 158 | log.error("Class with name {} not found.", name); 159 | throw new ReflectiveOperationException(); 160 | } 161 | Class classAsked = domainClassMap.get(name).getDomainClass(); 162 | try { 163 | Constructor classConstructor = classAsked.getConstructor(); 164 | return classConstructor.newInstance(); 165 | } catch (Exception e) { 166 | log.error("Impossible to instantiate an instance of {}: " 167 | + "no empty constructor found or the constructor is private for class {}", name, name); 168 | } 169 | // Should never happen. 170 | return null; 171 | } 172 | 173 | public void instantiateField(Object object, Field field, Object value, int columnType, String tablename) throws ParseException, IllegalAccessException { 174 | field.setAccessible(true); 175 | if (columnType == ColumnType.DATETIME.getCode() && field.getType() == Date.class) { 176 | Date date = BINLOG_DATETIME_FORMATTER.parse((String) value); 177 | field.set(object, date); 178 | } else if (columnType == ColumnType.DATE.getCode() && field.getType() == Date.class) { 179 | Date date = BINLOG_DATE_FORMATTER.parse((String) value); 180 | field.set(object, date); 181 | } else if (columnType == ColumnType.DATETIME.getCode() && field.getType() == String.class) { 182 | Date date = BINLOG_DATETIME_FORMATTER.parse((String) value); 183 | if (binlogOutputDateFormatter != null) { 184 | field.set(object, binlogOutputDateFormatter.format(date)); 185 | } else { 186 | log.warn("No date.output DateFormat found in your property file. If you want anything else than" + 187 | "the timestamp as output of your date, set this property with a java DateFormat."); 188 | field.set(object, date.toString()); 189 | } 190 | } else if (columnType == ColumnType.TIME.getCode() && field.getType() == Time.class) { 191 | Time time = Time.valueOf((String) value); 192 | field.set(object, time); 193 | } else if (columnType == ColumnType.TIMESTAMP.getCode() || field.getType() == Timestamp.class) { 194 | Timestamp timestamp = Timestamp.valueOf((String) value); 195 | field.set(object, timestamp); 196 | } else if ((columnType == ColumnType.BIT.getCode() || columnType == ColumnType.TINY.getCode()) 197 | && field.getType() == boolean.class) { 198 | boolean booleanField = ((Byte) value) != 0; 199 | field.set(object, booleanField); 200 | } else if (columnType == ColumnType.LONG.getCode() && field.getType() == long.class) { 201 | field.set(object, Long.parseLong((String) value)); 202 | } else if (columnType == ColumnType.LONG.getCode() && isInteger(field)) { 203 | field.set(object, Integer.parseInt((String) value)); 204 | } else if (columnType == ColumnType.FLOAT.getCode() && field.getType() == float.class) { 205 | field.set(object, Float.parseFloat((String) value)); 206 | } else if (field.getType() == String.class){ 207 | field.set(object, value); 208 | } else { 209 | if (mappingTablesExpected.contains(tablename)) { 210 | Object nestedObject = generateNestedField(field, value, tablename); 211 | field.set(object, nestedObject); 212 | } 213 | } 214 | } 215 | 216 | public Object generateNestedField(Field field, Object value, String tablename) { 217 | DomainClass currentDomainClass = domainClassMap.get(tablename); 218 | SQLRequester sqlRequester = currentDomainClass.getSqlRequesters().get(field.getName()); 219 | return sqlRequester.queryForeignEntity(sqlRequester.getForeignKey(), 220 | sqlRequester.getPrimaryKeyForeignEntity(), (String) value); 221 | } 222 | 223 | // TOOLS 224 | static boolean isInteger(Field field) { 225 | return field.getType() == Integer.class || field.getType() == int.class; 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/NestedRowMapper.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.DomainClass; 4 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 5 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 6 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 7 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.OneToManyRequester; 8 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.SQLRequester; 9 | import fr.juanwolf.mysqlbinlogreplicator.service.MySQLEventListener; 10 | import lombok.Setter; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.jdbc.core.RowMapper; 13 | 14 | import java.lang.reflect.Constructor; 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.InvocationTargetException; 17 | import java.sql.ResultSet; 18 | import java.sql.SQLException; 19 | import java.sql.Time; 20 | import java.sql.Timestamp; 21 | import java.util.ArrayList; 22 | import java.util.Date; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | /** 27 | * Created by juanwolf on 11/08/15. 28 | */ 29 | @Slf4j 30 | public class NestedRowMapper implements RowMapper { 31 | 32 | Class nestedObjectClass; 33 | 34 | Field[] fields; 35 | 36 | DomainClassAnalyzer domainClassAnalyzer; 37 | 38 | @Setter 39 | String mainTable; 40 | 41 | public NestedRowMapper(Class nestedObjectClass, DomainClassAnalyzer domainClassAnalyzer, String mainTable) { 42 | this.nestedObjectClass = nestedObjectClass; 43 | fields = this.nestedObjectClass.getDeclaredFields(); 44 | this.domainClassAnalyzer = domainClassAnalyzer; 45 | this.mainTable = mainTable; 46 | } 47 | 48 | @Override 49 | public Object mapRow(ResultSet resultSet, int i) throws SQLException { 50 | try { 51 | Constructor nestedConstructor = nestedObjectClass.getConstructor(); 52 | Object nestedObject = nestedConstructor.newInstance(); 53 | for (Field field : fields) { 54 | field.setAccessible(true); 55 | if (field.getType() == int.class || field.getType() == Integer.class) { 56 | int intValue = resultSet.getInt(field.getName()); 57 | field.set(nestedObject, intValue); 58 | } else if (field.getType() == String.class) { 59 | String resultString = resultSet.getString(field.getName()); 60 | field.set(nestedObject, resultString); 61 | } else if (field.getType() == java.sql.Date.class || field.getType() == java.util.Date.class) { 62 | Date dateValue = resultSet.getDate(field.getName()); 63 | if (field.getType() == java.sql.Date.class) { 64 | field.set(nestedObject, dateValue); 65 | } else { 66 | if (dateValue != null) { 67 | java.util.Date date = new Date(dateValue.getTime()); 68 | field.set(nestedObject, date); 69 | } else { 70 | field.set(nestedObject, null); 71 | } 72 | } 73 | } else if (field.getType() == long.class) { 74 | long longValue = resultSet.getLong(field.getName()); 75 | field.set(nestedObject, longValue); 76 | } else if (field.getType() == boolean.class) { 77 | boolean booleanValue = resultSet.getBoolean(field.getName()); 78 | field.set(nestedObject, booleanValue); 79 | } else if (field.getType() == Time.class) { 80 | Time timeValue = resultSet.getTime(field.getName()); 81 | field.set(nestedObject, timeValue); 82 | } else if (field.getType() == float.class) { 83 | float floatValue = resultSet.getFloat(field.getName()); 84 | field.set(nestedObject, floatValue); 85 | } else if (field.getType() == double.class) { 86 | double doubleValue = resultSet.getDouble(field.getName()); 87 | field.set(nestedObject, doubleValue); 88 | } else if (field.getType() == java.sql.Timestamp.class) { 89 | Timestamp timestampValue = resultSet.getTimestamp(field.getName()); 90 | field.set(nestedObject, timestampValue); 91 | } else { 92 | MysqlMapping mysqlMapping = (MysqlMapping) nestedObjectClass.getAnnotation(MysqlMapping.class); 93 | DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(mysqlMapping.table()); 94 | if (domainClass != null) { 95 | SQLRequester sqlRequester = domainClass.getSqlRequesters().get(field.getName()); 96 | NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class); 97 | if (nestedMapping != null && !nestedMapping.table().equals(mainTable)) { 98 | if (sqlRequester instanceof OneToManyRequester) { 99 | Object nestedTmpObject = sqlRequester.queryForeignEntity(sqlRequester.getForeignKey(), 100 | sqlRequester.getPrimaryKeyForeignEntity(), 101 | resultSet.getString(nestedMapping.primaryKey())); 102 | field.set(nestedObject, nestedTmpObject); 103 | } else { 104 | Object nestedTmpObject = sqlRequester.queryForeignEntity(sqlRequester.getForeignKey(), 105 | sqlRequester.getPrimaryKeyForeignEntity(), 106 | resultSet.getString(nestedMapping.foreignKey())); 107 | field.set(nestedObject, nestedTmpObject); 108 | } 109 | } 110 | } 111 | } 112 | field.setAccessible(false); 113 | } 114 | return nestedObject; 115 | } catch (NoSuchMethodException e) { 116 | log.error("No empty constructor for the class {}. Please, create one to make this object instantiable.", 117 | nestedObjectClass, e); 118 | } catch (Exception exception) { 119 | log.error("An exception occurred: ", exception); 120 | } 121 | return null; 122 | } 123 | 124 | public List getList(List> mapList) { 125 | List res = new ArrayList<>(); 126 | for(Map map : mapList) { 127 | res.add(listEachMapRow(map)); 128 | } 129 | return res; 130 | } 131 | 132 | public Object listEachMapRow(Map mapFields) { 133 | try { 134 | 135 | Constructor nestedConstructor = nestedObjectClass.getConstructor(); 136 | Object nestedObject = nestedConstructor.newInstance(); 137 | for (Field field : fields) { 138 | field.setAccessible(true); 139 | if (field.getType() == int.class || field.getType() == Integer.class) { 140 | int intValue = (int) mapFields.get(field.getName()); 141 | field.set(nestedObject, intValue); 142 | } else if (field.getType() == String.class) { 143 | String resultString = (String) mapFields.get(field.getName()); 144 | field.set(nestedObject, resultString); 145 | } else if (field.getType() == java.sql.Date.class || field.getType() == java.util.Date.class) { 146 | Date dateValue = (Date) mapFields.get(field.getName()); 147 | if (field.getType() == java.sql.Date.class) { 148 | field.set(nestedObject, dateValue); 149 | } else { 150 | if (dateValue != null) { 151 | java.util.Date date = new Date(dateValue.getTime()); 152 | field.set(nestedObject, date); 153 | } else { 154 | field.set(nestedObject, null); 155 | } 156 | } 157 | } else if (field.getType() == long.class) { 158 | long longValue = (long) mapFields.get(field.getName()); 159 | field.set(nestedObject, longValue); 160 | } else if (field.getType() == boolean.class) { 161 | boolean booleanValue = (boolean) mapFields.get(field.getName()); 162 | field.set(nestedObject, booleanValue); 163 | } else if (field.getType() == Time.class) { 164 | Time timeValue = (Time) mapFields.get(field.getName()); 165 | field.set(nestedObject, timeValue); 166 | } else if (field.getType() == float.class) { 167 | float floatValue = (float) mapFields.get(field.getName()); 168 | field.set(nestedObject, floatValue); 169 | } else if (field.getType() == double.class) { 170 | double doubleValue = (double) mapFields.get(field.getName()); 171 | field.set(nestedObject, doubleValue); 172 | } else if (field.getType() == java.sql.Timestamp.class) { 173 | Timestamp timestampValue = (Timestamp) mapFields.get(field.getName()); 174 | field.set(nestedObject, timestampValue); 175 | } else { 176 | MysqlMapping mysqlMapping = (MysqlMapping) nestedObjectClass.getAnnotation(MysqlMapping.class); 177 | DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(mysqlMapping.table()); 178 | if (domainClass != null) { 179 | SQLRequester sqlRequester = domainClass.getSqlRequesters().get(field.getName()); 180 | NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class); 181 | if (nestedMapping != null && !mainTable.equals(nestedMapping.table())) { 182 | Object nestedTmpObject = sqlRequester.queryForeignEntity(sqlRequester.getForeignKey(), 183 | sqlRequester.getPrimaryKeyForeignEntity(), 184 | mapFields.get(nestedMapping.foreignKey()).toString()); 185 | field.set(nestedObject, nestedTmpObject); 186 | } 187 | } 188 | } 189 | field.setAccessible(false); 190 | } 191 | return nestedObject; 192 | } catch (NoSuchMethodException e) { 193 | log.error("No empty constructor for the class {}. Please, create one to make this object instantiable.", 194 | nestedObjectClass, e); 195 | } catch (Exception exception) { 196 | log.error("An exception occurred: ", exception); 197 | } 198 | return null; 199 | } 200 | 201 | @Override 202 | public boolean equals(Object o) { 203 | if (this == o) return true; 204 | 205 | if (o == null || getClass() != o.getClass()) return false; 206 | 207 | NestedRowMapper that = (NestedRowMapper) o; 208 | 209 | return this.nestedObjectClass == that.nestedObjectClass; 210 | } 211 | 212 | @Override 213 | public int hashCode() { 214 | return nestedObjectClass.hashCode() * fields.hashCode() + 4; 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/SQLRelationship.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.*; 4 | 5 | import javax.persistence.OneToMany; 6 | 7 | /** 8 | * Created by juanwolf on 10/08/15. 9 | */ 10 | public enum SQLRelationship { 11 | 12 | ONE_TO_ONE { 13 | @Override 14 | public Class getRequesterClass() { 15 | return OneToOneRequester.class; 16 | } 17 | }, 18 | ONE_TO_MANY { 19 | @Override 20 | public Class getRequesterClass() { 21 | return OneToManyRequester.class; 22 | } 23 | }, 24 | MANY_TO_ONE { 25 | @Override 26 | public Class getRequesterClass() { 27 | return ManyToOneRequester.class; 28 | } 29 | }, 30 | MANY_TO_MANY { 31 | @Override 32 | public Class getRequesterClass() { 33 | return ManyToManyRequester.class; 34 | } 35 | }; 36 | 37 | private SQLRelationship() {} 38 | 39 | public abstract Class getRequesterClass(); 40 | 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/ManyToManyRequester.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 4 | import org.springframework.jdbc.core.RowMapper; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Created by juanwolf on 10/08/15. 10 | */ 11 | public class ManyToManyRequester extends SQLRequester { 12 | 13 | public ManyToManyRequester() { 14 | super(); 15 | } 16 | 17 | public ManyToManyRequester(String entryTableName, String exitTableName, RowMapper rowMapper, 18 | RowMapper foreignMapper) { 19 | super(entryTableName, exitTableName, rowMapper, foreignMapper); 20 | super.sqlRelationship = SQLRelationship.MANY_TO_MANY; 21 | } 22 | 23 | @Override 24 | public List queryForeignEntity(String foreignKey, String primaryKey, String value) { 25 | return (List) jdbcTemplate.queryForList("SELECT" + 26 | " * FROM " + getForeignTablePath() 27 | + "INNER JOIN " + super.getEntryTablePath() + " ON " 28 | + super.getEntryTablePath() + "." + foreignKey + "=" + getForeignTablePath() + "." + primaryKey 29 | + "WHERE " + primaryKey + "=" + value, foreignRowMapper); 30 | } 31 | 32 | @Override 33 | public List reverseQueryEntity(String foreignKey, String primaryKey, String value) { 34 | return (List) jdbcTemplate.queryForList("SELECT * FROM " + getEntryTablePath() 35 | + "INNER JOIN " + super.getEntryTablePath() + " ON " 36 | + getForeignTablePath() + "." + foreignKey + "=" + getEntryTablePath() + "." + primaryKey 37 | + "WHERE " + primaryKey + "=" + value , rowMapper); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/ManyToOneRequester.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 4 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 5 | import org.springframework.jdbc.core.RowMapper; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * Created by juanwolf on 10/08/15. 12 | */ 13 | public class ManyToOneRequester extends SQLRequester { 14 | 15 | public ManyToOneRequester() { 16 | super(); 17 | super.sqlRelationship = SQLRelationship.MANY_TO_ONE; 18 | } 19 | 20 | public ManyToOneRequester(String entryTableName, String exitTableName, RowMapper rowMapper, 21 | RowMapper foreignMapper) { 22 | super(entryTableName, exitTableName, rowMapper, foreignMapper); 23 | super.sqlRelationship = SQLRelationship.MANY_TO_ONE; 24 | } 25 | 26 | @Override 27 | public N queryForeignEntity(String foreignKey, String primaryKey, String value) { 28 | String query = "SELECT * FROM " + getForeignTablePath() + " " 29 | + "WHERE " + getForeignTablePath() + "." + primaryKey + "=" + value; 30 | return (N) jdbcTemplate.queryForObject(query, foreignRowMapper); 31 | } 32 | 33 | @Override 34 | public List reverseQueryEntity(String foreignKey, String primaryKey, String value) { 35 | String sql = "SELECT * FROM " + getEntryTablePath() + " " 36 | + "WHERE " + getEntryTablePath() + "." + foreignKey + "=" + value; 37 | List> rows = jdbcTemplate.queryForList(sql); 38 | NestedRowMapper nestedRowMapper = (NestedRowMapper) rowMapper; 39 | return (List) nestedRowMapper.getList(rows); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/OneToManyRequester.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 4 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 5 | import org.springframework.jdbc.core.RowMapper; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * Created by juanwolf on 10/08/15. 12 | */ 13 | public class OneToManyRequester extends SQLRequester { 14 | 15 | public OneToManyRequester() { 16 | super(); 17 | super.sqlRelationship = SQLRelationship.ONE_TO_MANY; 18 | } 19 | 20 | public OneToManyRequester(String entryTableName, String exitTableName, RowMapper rowMapper, 21 | RowMapper foreignMapper) { 22 | super(entryTableName, exitTableName, rowMapper, foreignMapper); 23 | super.sqlRelationship = SQLRelationship.ONE_TO_MANY; 24 | } 25 | 26 | @Override 27 | public List queryForeignEntity(String foreignKey, String primaryKey, String value) { 28 | final String query = "SELECT * FROM " + getForeignTablePath() + " " 29 | + "WHERE " + super.getForeignTablePath() + "." + foreignKey + "=" + value; 30 | List> rows = jdbcTemplate.queryForList(query); 31 | NestedRowMapper nestedRowMapper = (NestedRowMapper) foreignRowMapper; 32 | return (List) nestedRowMapper.getList(rows); 33 | } 34 | 35 | @Override 36 | public T reverseQueryEntity(String foreignKey, String primaryKey, String value) { 37 | String idValue = jdbcTemplate.queryForObject("SELECT " + foreignKey + " FROM " + getForeignTablePath() + " " 38 | + "WHERE " + getForeignTablePath() + "." + primaryKeyForeignEntity + "=" + value, String.class); 39 | // The value string is equal to the id of the foreign object 40 | String query = "SELECT * FROM " + getEntryTablePath() + " " 41 | + "WHERE " + getEntryTablePath() + "." + primaryKey + "=" + idValue; 42 | Object object = jdbcTemplate.queryForObject(query, rowMapper); 43 | return (T) object; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/OneToOneRequester.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 4 | import org.springframework.jdbc.core.RowMapper; 5 | 6 | /** 7 | * Created by juanwolf on 10/08/15. 8 | */ 9 | public class OneToOneRequester extends SQLRequester { 10 | 11 | public OneToOneRequester() { 12 | super(); 13 | super.sqlRelationship = SQLRelationship.ONE_TO_ONE; 14 | } 15 | 16 | public OneToOneRequester(String entryTableName, String exitTableName, RowMapper rowMapper, 17 | RowMapper foreignRowMapper) { 18 | super(entryTableName, exitTableName, rowMapper, foreignRowMapper); 19 | super.sqlRelationship = SQLRelationship.ONE_TO_ONE; 20 | } 21 | 22 | @Override 23 | public N queryForeignEntity(String foreignKey, String primaryKey, String value) { 24 | return (N) jdbcTemplate.queryForObject("SELECT * FROM " + getForeignTablePath() + " " 25 | + "INNER JOIN " + getEntryTablePath() + " ON " 26 | + getEntryTablePath() + "." + foreignKey + "=" + getForeignTablePath() + "." + primaryKey + " " 27 | + "WHERE " + getForeignTablePath() + "." + primaryKey + "=" + value , foreignRowMapper); 28 | } 29 | 30 | @Override 31 | public T reverseQueryEntity(String foreignKey, String primaryKey, String value) { 32 | final String sql = "SELECT * FROM " + getEntryTablePath() + " " 33 | + "INNER JOIN " + getForeignTablePath() + " ON " 34 | + getEntryTableName() + "." + foreignKey + "=" + getForeignTablePath() + "." + primaryKey + " " 35 | + "WHERE " + getForeignTablePath() + "." + primaryKey + "=" + value; 36 | T mainObject = (T) jdbcTemplate.queryForObject(sql, rowMapper); 37 | return mainObject; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/SQLRequester.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 4 | import lombok.Data; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.jdbc.core.RowMapper; 11 | import org.springframework.stereotype.Component; 12 | 13 | import javax.annotation.PostConstruct; 14 | import java.lang.reflect.Field; 15 | 16 | /** 17 | * Created by juanwolf on 10/08/15. 18 | */ 19 | @Data 20 | @Component 21 | public abstract class SQLRequester { 22 | 23 | @Getter 24 | @Autowired 25 | JdbcTemplate jdbcTemplate; 26 | 27 | @Setter 28 | String databaseName; 29 | 30 | /** 31 | * Main class 32 | */ 33 | Class entryType; 34 | 35 | /** 36 | * Field which link the entryType to the foreignType 37 | */ 38 | Field associatedField; 39 | 40 | /** 41 | * Foreign Class 42 | */ 43 | Class foreignType; 44 | 45 | /** 46 | * TableName for the entry T Class 47 | */ 48 | String entryTableName; 49 | 50 | /** 51 | * Tablename for the N class 52 | */ 53 | String exitTableName; 54 | 55 | public SQLRelationship sqlRelationship; 56 | 57 | /** 58 | * Mapper for the foreign Class 59 | */ 60 | RowMapper foreignRowMapper; 61 | 62 | /** 63 | * Mapper for the main class 64 | */ 65 | RowMapper rowMapper; 66 | 67 | /** 68 | * Foreign key column name in the main class 69 | */ 70 | String foreignKey; 71 | 72 | /** 73 | * Primary key column name in the foreign class 74 | */ 75 | String primaryKeyForeignEntity; 76 | 77 | public SQLRequester() { 78 | } 79 | 80 | public SQLRequester(String entryTableName, String exitTableName, RowMapper rowMapper, 81 | RowMapper foreignRowMapper) { 82 | this.entryTableName = entryTableName; 83 | this.exitTableName = exitTableName; 84 | this.rowMapper = rowMapper; 85 | this.foreignRowMapper = foreignRowMapper; 86 | } 87 | 88 | public String getEntryTablePath() { 89 | return databaseName + "." + entryTableName; 90 | } 91 | 92 | public String getForeignTablePath() { 93 | return databaseName + "." + exitTableName; 94 | } 95 | 96 | public String getForeignKeyPath(String tablePath) { 97 | return tablePath + "." + foreignKey; 98 | } 99 | 100 | public String getPrimaryKey(String tablePath) { 101 | return tablePath + "." + primaryKeyForeignEntity; 102 | } 103 | 104 | public abstract N queryForeignEntity(String foreignKey, String primaryKey, String value); 105 | 106 | public abstract T reverseQueryEntity(String foreignKey, String primaryKey, String value); 107 | 108 | 109 | 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/service/MySQLEventListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | package fr.juanwolf.mysqlbinlogreplicator.service; 19 | 20 | import com.github.shyiko.mysql.binlog.BinaryLogClient; 21 | import com.github.shyiko.mysql.binlog.event.*; 22 | import com.github.shyiko.mysql.binlog.event.deserialization.ColumnType; 23 | import fr.juanwolf.mysqlbinlogreplicator.DomainClass; 24 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 25 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 26 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 27 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.SQLRequester; 28 | import lombok.AccessLevel; 29 | import lombok.Getter; 30 | import lombok.Setter; 31 | import lombok.extern.slf4j.Slf4j; 32 | import org.springframework.data.repository.CrudRepository; 33 | 34 | import java.io.Serializable; 35 | import java.lang.reflect.Field; 36 | import java.text.ParseException; 37 | import java.util.HashMap; 38 | import java.util.List; 39 | import java.util.Map; 40 | 41 | @Slf4j 42 | public class MySQLEventListener implements BinaryLogClient.EventListener { 43 | 44 | //All columnNames for all tables 45 | @Setter 46 | private Map columnMap; 47 | // All the column type for the table 48 | @Getter 49 | @Setter 50 | private Map columnsTypes; 51 | //Current tableName 52 | @Getter 53 | @Setter(AccessLevel.PROTECTED) 54 | private String tableName; 55 | 56 | @Getter 57 | private DomainClassAnalyzer domainClassAnalyzer; 58 | 59 | public MySQLEventListener(Map columnMap, DomainClassAnalyzer domainClassAnalyzer) { 60 | this.columnMap = columnMap; 61 | this.domainClassAnalyzer = domainClassAnalyzer; 62 | this.columnsTypes = new HashMap<>(); 63 | } 64 | 65 | @Override 66 | public void onEvent(Event event) { 67 | try { 68 | this.actionOnEvent(event); 69 | } catch (Exception e) { 70 | log.error("An exception occurred during OnEvent.", e); 71 | } 72 | } 73 | 74 | public void actionOnEvent(Event event) throws Exception { 75 | if (tableName != null && isMappingConcern()) { 76 | DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(tableName); 77 | CrudRepository currentRepository = domainClass.getCrudRepository(); 78 | Class currentClass = domainClass.getDomainClass(); 79 | if (EventType.isDelete(event.getHeader().getEventType())) { 80 | Object domainObject = currentClass.cast(generateDomainObjectForDeleteEvent(event, tableName)); 81 | currentRepository.delete(domainObject); 82 | log.debug("Object deleted : {}", domainObject.toString()); 83 | } else if (EventType.isUpdate(event.getHeader().getEventType())) { 84 | UpdateRowsEventData data = event.getData(); 85 | log.debug("Update event received data = {}", data); 86 | Object domainObject = currentClass.cast(generateDomainObjectForUpdateEvent(event, tableName)); 87 | currentRepository.save(domainObject); 88 | } else if (EventType.isWrite(event.getHeader().getEventType())) { 89 | WriteRowsEventData data = event.getData(); 90 | log.debug("Write event received with data = {}", data); 91 | Object currentClassInstance = currentClass.cast(generateDomainObjectForWriteEvent(event, tableName)); 92 | currentRepository.save(currentClassInstance); 93 | } 94 | } 95 | if (tableName != null && isNestedConcern() && isCrudEvent(event.getHeader().getEventType())) { 96 | DomainClass domainClass = domainClassAnalyzer.getNestedDomainClassMap().get(tableName); 97 | for (SQLRequester sqlRequester : domainClass.getSqlRequesters().values()) { 98 | if (sqlRequester.getExitTableName().equals(tableName)) { 99 | String primaryKeyValue = getPrimaryKeyFromEvent(event, sqlRequester, tableName); 100 | Object mainObject = sqlRequester.reverseQueryEntity(sqlRequester.getForeignKey(), 101 | sqlRequester.getPrimaryKeyForeignEntity(), primaryKeyValue); 102 | CrudRepository crudRepository = domainClass.getCrudRepository(); 103 | if (mainObject instanceof List) { 104 | List mainObjectList = (List) mainObject; 105 | for (Object object : mainObjectList) { 106 | crudRepository.save(object); 107 | } 108 | } else { 109 | crudRepository.save(mainObject); 110 | } 111 | } 112 | } 113 | } 114 | if (event.getHeader().getEventType() == EventType.TABLE_MAP) { 115 | TableMapEventData tableMapEventData = event.getData(); 116 | tableName = tableMapEventData.getTable(); 117 | if (!columnsTypes.containsKey(tableName)) { 118 | columnsTypes.put(tableName, tableMapEventData.getColumnTypes()); 119 | } 120 | } 121 | } 122 | 123 | boolean isMappingConcern() { 124 | return domainClassAnalyzer.getMappingTablesExpected().contains(tableName); 125 | } 126 | 127 | boolean isNestedConcern() { 128 | return domainClassAnalyzer.getNestedTables().contains(tableName); 129 | } 130 | 131 | boolean isCrudEvent(EventType event) { 132 | return EventType.isDelete(event) || EventType.isUpdate(event) || EventType.isWrite(event); 133 | } 134 | 135 | Object generateDomainObjectForUpdateEvent(Event event, String tableName) throws ReflectiveOperationException, ParseException { 136 | UpdateRowsEventData data = event.getData(); 137 | Serializable[] afterValues = data.getRows().get(0).getValue(); 138 | return getObjectFromRows(afterValues, tableName); 139 | } 140 | 141 | Object generateDomainObjectForWriteEvent(Event event, String tableName) throws ReflectiveOperationException, ParseException { 142 | WriteRowsEventData data = event.getData(); 143 | Serializable[] rows = data.getRows().get(0); 144 | return getObjectFromRows(rows, tableName); 145 | } 146 | 147 | Object generateDomainObjectForDeleteEvent(Event event, String tableName) throws ReflectiveOperationException, ParseException { 148 | DeleteRowsEventData data = event.getData(); 149 | Serializable[] rows = data.getRows().get(0); 150 | return getObjectFromRows(rows, tableName); 151 | } 152 | 153 | Object getObjectFromRows(Serializable[] rows, String tableName) throws ReflectiveOperationException, ParseException { 154 | Object[] columns = columnMap.get(tableName); 155 | Object object = domainClassAnalyzer.generateInstanceFromName(tableName); 156 | DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(tableName); 157 | 158 | // Setting up the list of foreign keys 159 | Map foreignKeysSQLRequesterMap = new HashMap(); 160 | for (String nestedField: domainClass.getSqlRequesters().keySet()) { 161 | SQLRequester sqlRequester = domainClass.getSqlRequesters().get(nestedField); 162 | foreignKeysSQLRequesterMap.put(sqlRequester.getForeignKey(), sqlRequester); 163 | } 164 | 165 | String debugLogObject = ""; 166 | byte[] columnsType = columnsTypes.get(tableName); 167 | for (int i = 0; i < rows.length; i++) { 168 | if (rows[i] != null) { 169 | try { 170 | Field field; 171 | if (foreignKeysSQLRequesterMap.keySet().contains(columns[i].toString())) { 172 | String columnsName = columns[i].toString(); 173 | field = foreignKeysSQLRequesterMap.get(columnsName).getAssociatedField(); 174 | } else { 175 | field = object.getClass().getDeclaredField(columns[i].toString()); 176 | } 177 | domainClassAnalyzer.instantiateField(object, field, rows[i].toString(), columnsType[i], tableName); 178 | if (log.isDebugEnabled()) { 179 | debugLogObject += columns[i] + "=" + rows[i].toString() + ", "; 180 | } 181 | } catch (NoSuchFieldException exception) { 182 | log.warn("No field found for {}", columns[i].toString()); 183 | } 184 | } 185 | } 186 | for (Field field : object.getClass().getDeclaredFields()) { 187 | field.setAccessible(true); 188 | Object fieldValue = field.get(object); 189 | if (fieldValue == null) { 190 | if (field.isAnnotationPresent(NestedMapping.class)) { 191 | NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class); 192 | if (nestedMapping.sqlAssociaton() == SQLRelationship.ONE_TO_MANY) { 193 | Field primaryKeyField = object.getClass().getField(nestedMapping.primaryKey()); 194 | primaryKeyField.setAccessible(true); 195 | Object primaryKeyValue = primaryKeyField.get(object); 196 | domainClassAnalyzer.instantiateField(object, field, primaryKeyValue.toString(), 197 | ColumnType.STRING.getCode(), tableName); 198 | primaryKeyField.setAccessible(false); 199 | } 200 | } 201 | } 202 | field.setAccessible(false); 203 | } 204 | log.debug("Object generated : {{}}", debugLogObject); 205 | return object; 206 | } 207 | 208 | String getPrimaryKeyFromEvent(Event event, SQLRequester sqlRequester, String tableName) { 209 | Serializable[] rows = null; 210 | if (EventType.isDelete(event.getHeader().getEventType())) { 211 | DeleteRowsEventData data = event.getData(); 212 | rows = data.getRows().get(0); 213 | } else if (EventType.isUpdate(event.getHeader().getEventType())){ 214 | UpdateRowsEventData data = event.getData(); 215 | rows = data.getRows().get(0).getValue(); 216 | } else if (EventType.isWrite(event.getHeader().getEventType())) { 217 | WriteRowsEventData data = event.getData(); 218 | rows = data.getRows().get(0); 219 | } 220 | return getPrimaryKeyValueFromRows(rows, tableName, sqlRequester); 221 | } 222 | 223 | String getPrimaryKeyValueFromRows(Serializable[] rows, String tableName, SQLRequester sqlRequester) { 224 | Object[] columns = columnMap.get(tableName); 225 | for (int i = 0; i < rows.length; i++) { 226 | if (rows[i] != null) { 227 | if (sqlRequester.getPrimaryKeyForeignEntity().equals(columns[i])) { 228 | return rows[i].toString(); 229 | } 230 | } 231 | 232 | } 233 | return null; 234 | } 235 | 236 | } 237 | -------------------------------------------------------------------------------- /src/main/java/fr/juanwolf/mysqlbinlogreplicator/service/MysqlBinLogService.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | package fr.juanwolf.mysqlbinlogreplicator.service; 19 | 20 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 21 | import com.github.shyiko.mysql.binlog.BinaryLogClient; 22 | import com.github.shyiko.mysql.binlog.jmx.BinaryLogClientStatistics; 23 | import lombok.Setter; 24 | import lombok.extern.slf4j.Slf4j; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.beans.factory.annotation.Value; 27 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 28 | import org.springframework.stereotype.Service; 29 | 30 | import javax.annotation.PostConstruct; 31 | import javax.management.*; 32 | import java.io.IOException; 33 | import java.lang.management.ManagementFactory; 34 | import java.util.*; 35 | 36 | @Service 37 | @Slf4j 38 | public class MysqlBinLogService { 39 | 40 | private static final String SQL = "SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = :tableschema AND table_name = :tablename ORDER BY 'ordinal_position'"; 41 | 42 | @Setter 43 | @Value("${mysql.host}") 44 | private String mysqlHost; 45 | 46 | @Setter 47 | @Value("${mysql.port}") 48 | private Integer mysqlPort; 49 | 50 | @Setter 51 | @Value("${spring.datasource.username}") 52 | private String mysqlUser; 53 | 54 | @Setter 55 | @Value("${spring.datasource.password}") 56 | private String mysqlPassword; 57 | 58 | @Value("${mysql.schema}") 59 | private String schemaExpected; 60 | 61 | @Autowired 62 | private NamedParameterJdbcTemplate namedParameterJdbcTemplate; 63 | 64 | @Autowired 65 | private DomainClassAnalyzer domainClassAnalyzer; 66 | 67 | BinaryLogClient client; 68 | 69 | Map columnMap; 70 | 71 | MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); 72 | 73 | @PostConstruct 74 | public void postConstruct() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException { 75 | 76 | log.debug("Create BinaryLogClient {}@{}:{}", mysqlUser, mysqlHost, mysqlPort); 77 | client = new BinaryLogClient(mysqlHost, mysqlPort, mysqlUser, mysqlPassword); 78 | log.debug("Getting columns names."); 79 | getColumnName(); 80 | log.debug("Activate JMXBean"); 81 | 82 | ObjectName objectName = new ObjectName("mysql.binlog:type=BinaryLogClient"); 83 | mBeanServer.registerMBean(client, objectName); 84 | 85 | BinaryLogClientStatistics stats = new BinaryLogClientStatistics(client); 86 | ObjectName statsObjectName = new ObjectName("mysql.binlog:type=BinaryLogClientStatistics"); 87 | mBeanServer.registerMBean(stats, statsObjectName); 88 | } 89 | 90 | public void startReplication() throws IOException { 91 | log.debug("Register Event listener."); 92 | client.registerEventListener(new MySQLEventListener(columnMap, domainClassAnalyzer)); 93 | log.info("Start Replication."); 94 | client.connect(); 95 | log.debug("Client connected."); 96 | } 97 | 98 | void getColumnName() { 99 | log.info("Retrieving columns informations from the database."); 100 | List tableExpected = new ArrayList<>(domainClassAnalyzer.getMappingTablesExpected()); 101 | tableExpected.addAll(domainClassAnalyzer.getNestedTables()); 102 | columnMap = new HashMap<>(); 103 | for (String tableName : tableExpected) { 104 | Map paramMap = new HashMap<>(); 105 | paramMap.put("tableschema", schemaExpected); 106 | paramMap.put("tablename", tableName); 107 | List> columnsMap = namedParameterJdbcTemplate.queryForList(SQL, paramMap); 108 | ArrayList columnsList = new ArrayList<>(); 109 | for (Map column : columnsMap) { 110 | columnsList.add((String) column.get("COLUMN_NAME")); 111 | } 112 | log.debug("Columns found for {} : {}", tableName, Arrays.toString(columnsList.toArray())); 113 | columnMap.put(tableName, columnsList.toArray()); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #Spring 2 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 3 | spring.datasource.url=jdbc:mysql://${mysql.host}:${mysql.port} 4 | spring.datasource.username=${mysql.user} 5 | spring.datasource.password=${mysql.password} 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/component/DomainClassAnalyzerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package fr.juanwolf.mysqlbinlogreplicator.component; 20 | 21 | 22 | import com.github.shyiko.mysql.binlog.event.deserialization.ColumnType; 23 | import fr.juanwolf.mysqlbinlogreplicator.DomainClass; 24 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 25 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 26 | import fr.juanwolf.mysqlbinlogreplicator.dao.UserRepository; 27 | import fr.juanwolf.mysqlbinlogreplicator.domain.Bill; 28 | import fr.juanwolf.mysqlbinlogreplicator.domain.Cart; 29 | import fr.juanwolf.mysqlbinlogreplicator.domain.User; 30 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 31 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.OneToOneRequester; 32 | import org.junit.Before; 33 | import org.junit.Test; 34 | import org.junit.runner.RunWith; 35 | import org.mockito.InjectMocks; 36 | import org.mockito.Mock; 37 | import org.mockito.runners.MockitoJUnitRunner; 38 | import org.springframework.beans.factory.annotation.Autowired; 39 | import org.springframework.context.ApplicationContext; 40 | import org.springframework.core.env.Environment; 41 | import org.springframework.jdbc.core.JdbcTemplate; 42 | import org.springframework.jdbc.core.RowMapper; 43 | 44 | import java.lang.reflect.Field; 45 | import java.lang.reflect.InvocationTargetException; 46 | import java.sql.Time; 47 | import java.sql.Timestamp; 48 | import java.text.DateFormat; 49 | import java.text.ParseException; 50 | import java.text.SimpleDateFormat; 51 | import java.util.*; 52 | 53 | import static org.assertj.core.api.Assertions.assertThat; 54 | import static org.assertj.core.api.StrictAssertions.fail; 55 | import static org.mockito.Matchers.any; 56 | import static org.mockito.Matchers.anyString; 57 | import static org.mockito.Mockito.when; 58 | 59 | @RunWith(MockitoJUnitRunner.class) 60 | public class DomainClassAnalyzerTest { 61 | 62 | public static final DateFormat BINLOG_DATETIME_FORMATTER = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.UK); 63 | public static final DateFormat BINLOG_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd", Locale.UK); 64 | 65 | @Autowired 66 | @InjectMocks 67 | private DomainClassAnalyzer domainClassAnalyzer; 68 | 69 | private String scanMapping = "fr.juanwolf.mysqlbinlogreplicator.domain"; 70 | 71 | @Mock 72 | private ApplicationContext applicationContext; 73 | 74 | @Mock 75 | private UserRepository userRepository; 76 | 77 | @Mock 78 | private Environment environment; 79 | 80 | @Mock 81 | private JdbcTemplate jdbcTemplate; 82 | 83 | @Before 84 | public void setUp() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 85 | when(applicationContext.getBean("userRepository")).thenReturn(userRepository); 86 | when(environment.getProperty("date.output")).thenReturn(null); 87 | domainClassAnalyzer.setScanMapping(scanMapping); 88 | domainClassAnalyzer.postConstruct(); 89 | } 90 | 91 | @Test 92 | public void constructor_should_initialize_a_map_of_domain_with_proper_fields() { 93 | // given 94 | Class _class = User.class; 95 | // When 96 | // domainClassAnalyzer.postConstruct(); 97 | // Then 98 | assertThat(domainClassAnalyzer.getDomainClassMap().get("user").getDomainClass()).isEqualTo(_class); 99 | } 100 | 101 | @Test 102 | public void postConstruct_should_add_userTable_to_table_expected() { 103 | // given 104 | MysqlMapping mysqlMapping = (MysqlMapping) User.class.getAnnotation(MysqlMapping.class); 105 | String valueExpected = mysqlMapping.table(); 106 | // when 107 | //domainClassAnalyzer.postConstruct(); 108 | // then 109 | assertThat(domainClassAnalyzer.getMappingTablesExpected()).contains(valueExpected); 110 | } 111 | 112 | @Test 113 | public void postContruct_should_set_the_dateOutputFormatter_to_null_if_no_dateoutput_given() { 114 | // given 115 | // when 116 | // then 117 | assertThat(domainClassAnalyzer.getBinlogOutputDateFormatter()).isNull(); 118 | } 119 | 120 | @Test 121 | public void postContruct_should_set_the_dateOutputFormatter_if_a_dateoutput_is_given() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 122 | // given 123 | String dateOutput = "YYYY-MM-dd"; 124 | when(environment.getProperty("date.output")).thenReturn(dateOutput); 125 | // when 126 | domainClassAnalyzer.postConstruct(); 127 | // then 128 | assertThat(domainClassAnalyzer.getBinlogOutputDateFormatter()).isNotNull(); 129 | } 130 | 131 | @Test 132 | public void generateInstance_from_name_should_return_a_serviceRequest() throws ReflectiveOperationException { 133 | // Given 134 | // When 135 | Object user = domainClassAnalyzer.generateInstanceFromName("user"); 136 | // Then 137 | assertThat(user.getClass()).isEqualTo(User.class); 138 | } 139 | 140 | @Test 141 | public void generateInstance_from_name_should_return_an_exception_if_no_class_has_been_found() { 142 | // Given 143 | // When 144 | try { 145 | Object none = domainClassAnalyzer.generateInstanceFromName("none"); 146 | fail("ReflectiveOperationException expected."); 147 | } catch (ReflectiveOperationException e) { 148 | assertThat(true).isTrue(); 149 | } 150 | // Then 151 | } 152 | 153 | @Test 154 | public void generateInstanceFromName_should_return_null_if_no_constructor_exist() throws ReflectiveOperationException { 155 | // Given 156 | class NoConstructorClass {} 157 | Map domainMap = domainClassAnalyzer.getDomainClassMap(); 158 | DomainClass domainClass = new DomainClass(); 159 | domainClass.setDomainClass(NoConstructorClass.class); 160 | domainMap.put("noConstructorClass", domainClass); 161 | domainClassAnalyzer.setDomainClassMap(domainMap); 162 | // When 163 | NoConstructorClass noConstructorObject = (NoConstructorClass) domainClassAnalyzer.generateInstanceFromName("noConstructorClass"); 164 | // Then 165 | assertThat(noConstructorObject).isNull(); 166 | 167 | } 168 | 169 | @Test 170 | public void instantiateField_should_set_mail_with_string_specified() throws ReflectiveOperationException, ParseException { 171 | // Given 172 | String mail = "awesome_identifier"; 173 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 174 | // When 175 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("mail"), mail, 0, "user"); 176 | 177 | // Then 178 | assertThat(user.getMail()).isEqualTo(mail); 179 | } 180 | 181 | @Test 182 | public void instantiateField_should_set_creationDate_with_date_specified() throws ReflectiveOperationException, ParseException { 183 | // Given 184 | String date = "Wed Jul 22 13:00:00 CEST 2015"; 185 | Date dateExpected = BINLOG_DATETIME_FORMATTER.parse(date); 186 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 187 | // When 188 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationDate"), date, ColumnType.DATETIME.getCode(), "user"); 189 | 190 | // Then 191 | assertThat(user.getCreationDate()).isEqualTo(dateExpected); 192 | } 193 | 194 | @Test 195 | public void instantiateField_should_not_set_creationDate_if_date_is_not_parsable() throws ReflectiveOperationException { 196 | // Given 197 | String date = "My nice date"; 198 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 199 | // When 200 | try { 201 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationDate"), date, ColumnType.DATETIME.getCode(), "user"); 202 | fail("ParseException expected."); 203 | } catch (ParseException e) { 204 | assertThat(e).hasMessage("Unparseable date: \"My nice date\""); 205 | } 206 | } 207 | 208 | @Test 209 | public void instantiateField_should_set_identifier_with_long_specified() throws ReflectiveOperationException, ParseException { 210 | // Given 211 | String longValue = "4"; 212 | long valueExpected = 4; 213 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 214 | // When 215 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("identifier"), longValue, ColumnType.LONG.getCode(), "user"); 216 | // Then 217 | assertThat(valueExpected).isEqualTo(user.getIdentifier()); 218 | 219 | } 220 | 221 | @Test 222 | public void instantiateField_should_set_cart_amount_with_float_specified() throws ReflectiveOperationException, ParseException { 223 | // Given 224 | String floatValue = "4.5"; 225 | float valueExpected = 4.5f; 226 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 227 | // When 228 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("cartAmount"), floatValue, ColumnType.FLOAT.getCode(), "user"); 229 | // Then 230 | assertThat(valueExpected).isEqualTo(user.getCartAmount()); 231 | } 232 | 233 | @Test 234 | public void isInteger_should_return_true_for_integer_Type() throws NoSuchFieldException { 235 | // Given 236 | User user = new User(); 237 | user.setId(0); 238 | // When 239 | boolean isInteger = DomainClassAnalyzer.isInteger(user.getClass().getDeclaredField("id")); 240 | // Then 241 | assertThat(isInteger).isTrue(); 242 | } 243 | 244 | @Test 245 | public void instantiateField_should_set_id_for_with_the_specific_value() throws ReflectiveOperationException, ParseException { 246 | // Given 247 | String id = "15"; 248 | int idExpected = Integer.parseInt(id); 249 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 250 | // When 251 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("id"), id, ColumnType.LONG.getCode(), "user"); 252 | 253 | // Then 254 | assertThat(user.getId()).isEqualTo(idExpected); 255 | } 256 | 257 | @Test 258 | public void instantiateField_should_set_boolean_to_true_if_value_is_1_for_byte_type() throws ReflectiveOperationException, ParseException { 259 | // Given 260 | byte isAdmin = 1; 261 | boolean valueExpected = true; 262 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 263 | // When 264 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("isAdmin"), isAdmin, ColumnType.BIT.getCode(), "user"); 265 | 266 | // Then 267 | assertThat(user.isAdmin()).isEqualTo(valueExpected); 268 | } 269 | 270 | @Test 271 | public void instantiateField_should_set_boolean_to_true_if_value_is_1_for_tiny_type() throws ReflectiveOperationException, ParseException { 272 | // Given 273 | byte isAdmin = 1; 274 | boolean valueExpected = true; 275 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 276 | // When 277 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("isAdmin"), isAdmin, ColumnType.TINY.getCode(), "user"); 278 | 279 | // Then 280 | assertThat(user.isAdmin()).isEqualTo(valueExpected); 281 | } 282 | 283 | @Test 284 | public void instantiateField_should_set_boolean_to_false_if_value_is_0_for_tiny_type() throws ReflectiveOperationException, ParseException { 285 | // Given 286 | byte isAdmin = 0; 287 | boolean valueExpected = false; 288 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 289 | // When 290 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("isAdmin"), isAdmin, ColumnType.TINY.getCode(), "user"); 291 | 292 | // Then 293 | assertThat(user.isAdmin()).isEqualTo(valueExpected); 294 | } 295 | 296 | @Test 297 | public void instantiateField_should_set_the_string_with_the_specified_output_of_the_date() throws ReflectiveOperationException, ParseException { 298 | // Given 299 | String outputFormat = "YYYY-MM-dd"; 300 | when(environment.getProperty("date.output")).thenReturn(outputFormat); 301 | // We need to reload the domainClassAnalyzer 302 | String date = "Wed Jul 22 13:00:00 CEST 2015"; 303 | String dateStringExpected = "2015-07-22"; 304 | domainClassAnalyzer.postConstruct(); 305 | // When 306 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 307 | // When 308 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("dateString"), date, ColumnType.DATETIME.getCode(), "user"); 309 | 310 | // Then 311 | assertThat(user.getDateString()).isEqualTo(dateStringExpected); 312 | } 313 | 314 | @Test 315 | public void instantiateField_should_set_the_string_with_the_default_locale_of_the_server_if_no_dateouput_() 316 | throws ReflectiveOperationException, ParseException { 317 | // Given 318 | // We need to reload the domainClassAnalyzer 319 | String date = "Wed Jul 22 13:00:00 CEST 2015"; 320 | Date dateExpected = BINLOG_DATETIME_FORMATTER.parse(date); 321 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.UK); 322 | simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); 323 | domainClassAnalyzer.postConstruct(); 324 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 325 | // When 326 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("dateString"), date, ColumnType.DATETIME.getCode(), "user"); 327 | 328 | // Then 329 | assertThat(BINLOG_DATETIME_FORMATTER.parse(user.getDateString())).isEqualTo(dateExpected); 330 | //assertThat(user.getDateString()).isEqualTo(date); 331 | } 332 | 333 | @Test 334 | public void instantiateField_should_set_the_date_with_the_specific_date_for_date_type() throws ReflectiveOperationException, ParseException { 335 | // Given 336 | // We need to reload the domainClassAnalyzer 337 | String date = "2015-07-09"; 338 | Date dateExpected = BINLOG_DATE_FORMATTER.parse(date); 339 | domainClassAnalyzer.postConstruct(); 340 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 341 | // When 342 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationDate"), date, ColumnType.DATE.getCode(), "user"); 343 | 344 | // Then 345 | assertThat(user.getCreationDate()).isEqualTo(dateExpected); 346 | } 347 | 348 | @Test 349 | public void instantiateField_should_set_the_timestamp_with_the_specific_timestamp() throws ReflectiveOperationException, ParseException { 350 | // Given 351 | String timestampString = "2015-09-26 12:30:15"; 352 | Timestamp timestamp = Timestamp.valueOf(timestampString); 353 | domainClassAnalyzer.postConstruct(); 354 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 355 | // When 356 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationTimestamp"), 357 | timestampString, ColumnType.TIMESTAMP.getCode(), "user"); 358 | // Then 359 | assertThat(user.getCreationTimestamp()).isEqualTo(timestamp); 360 | } 361 | 362 | 363 | @Test 364 | public void instantiateField_should_set_the_time_with_the_specific_time() throws ReflectiveOperationException, ParseException { 365 | // Given 366 | String timeString = "12:30:15"; 367 | Time time = Time.valueOf(timeString); 368 | domainClassAnalyzer.postConstruct(); 369 | User user = (User) domainClassAnalyzer.generateInstanceFromName("user"); 370 | // When 371 | domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationTime"), 372 | timeString, ColumnType.TIME.getCode(), "user"); 373 | // Then 374 | assertThat(user.getCreationTime()).isEqualTo(time); 375 | } 376 | 377 | @Test 378 | public void postConstruct_should_set_the_DomainClass_nested_list_with_annotated_fields() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException { 379 | // Given 380 | NestedRowMapper userRowMapper = new NestedRowMapper(User.class, domainClassAnalyzer, "user"); 381 | NestedRowMapper cartRowMapper = new NestedRowMapper(Cart.class, domainClassAnalyzer, "cart"); 382 | OneToOneRequester userToClassRequester = new OneToOneRequester<>("user", "cart", 383 | userRowMapper , cartRowMapper); 384 | userToClassRequester.setJdbcTemplate(jdbcTemplate); 385 | userToClassRequester.setEntryType(User.class); 386 | userToClassRequester.setForeignType(Cart.class); 387 | userToClassRequester.setForeignKey("cart_id"); 388 | userToClassRequester.setPrimaryKeyForeignEntity("id"); 389 | userToClassRequester.setAssociatedField(User.class.getDeclaredField("cart")); 390 | // When 391 | domainClassAnalyzer.postConstruct(); 392 | // Then 393 | DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get("user"); 394 | assertThat(domainClass.getSqlRequesters()).containsValue(userToClassRequester); 395 | } 396 | 397 | @Test 398 | public void postConstruct_should_add_to_the_tableExpectedList_the_name_of_the_table() throws NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { 399 | // Given 400 | String tableNameExpected = User.class.getDeclaredField("cart").getAnnotation(NestedMapping.class).table(); 401 | // When 402 | domainClassAnalyzer.postConstruct(); 403 | // Then 404 | assertThat(domainClassAnalyzer.getNestedTables()).contains(tableNameExpected); 405 | } 406 | 407 | @Test 408 | public void generateNestedField_should_create_an_instance_of_Cart() throws NoSuchFieldException { 409 | // Given 410 | User user = new User(); 411 | Field field = user.getClass().getDeclaredField("cart"); 412 | Cart cartExpected = new Cart(); 413 | cartExpected.setAmount(1500); 414 | when(jdbcTemplate.queryForObject(anyString(), (RowMapper) any())).thenReturn(cartExpected); 415 | // When 416 | Cart cart = (Cart) domainClassAnalyzer.generateNestedField(field, "1", "user"); 417 | // Then 418 | assertThat(cart).isEqualToComparingFieldByField(cartExpected); 419 | } 420 | 421 | // @Test 422 | // public void generateNestedField_should_create_an_instance_of_list_of_bills() throws NoSuchFieldException { 423 | // // Given 424 | // User user = new User(); 425 | // String requestExpected = "SELECT * FROM bill INNER JOIN user ON user.id=bill.pk_user WHERE user.id=1"; 426 | // Field field = user.getClass().getDeclaredField("bills"); 427 | // List> billMapList = new ArrayMap<>(); 428 | // Map 429 | // when(jdbcTemplate.queryForList(requestExpected, Bill.class)).thenReturn(billList); 430 | // // When 431 | // List bills = (List) domainClassAnalyzer.generateNestedField(field, "1", "user"); 432 | // // Then 433 | // assertThat(bills).isEqualTo(billList); 434 | // } 435 | 436 | } 437 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/dao/UserRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package fr.juanwolf.mysqlbinlogreplicator.dao; 20 | 21 | import integrationTest.domain.User; 22 | import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; 23 | 24 | /** 25 | * Created by juanwolf on 17/07/15. 26 | */ 27 | public interface UserRepository extends ElasticsearchCrudRepository { 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/domain/Bill.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.domain; 2 | 3 | /** 4 | * Created by juanwolf on 17/08/15. 5 | */ 6 | public class Bill { 7 | double amount; 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/domain/Cart.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.domain; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | /** 7 | * Created by juanwolf on 10/08/15. 8 | */ 9 | @Data 10 | @NoArgsConstructor 11 | public class Cart { 12 | public float amount; 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/domain/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package fr.juanwolf.mysqlbinlogreplicator.domain; 20 | 21 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 22 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 23 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 24 | import lombok.Getter; 25 | import lombok.Setter; 26 | import org.springframework.data.annotation.Id; 27 | import org.springframework.data.elasticsearch.annotations.*; 28 | 29 | import java.sql.Time; 30 | import java.sql.Timestamp; 31 | import java.util.Date; 32 | import java.util.List; 33 | 34 | /** 35 | * Created by juanwolf on 17/07/15. 36 | */ 37 | @Document(indexName = "user") 38 | @Mapping(mappingPath = "user") 39 | @MysqlMapping(table = "user", repository="userRepository") 40 | public class User { 41 | @Id 42 | @Setter 43 | @Getter 44 | int id; 45 | 46 | @Getter 47 | @Field(type = FieldType.Long, index = FieldIndex.analyzed) 48 | long identifier; 49 | 50 | @Getter 51 | @Setter 52 | @Field(type = FieldType.String, index = FieldIndex.analyzed) 53 | String mail; 54 | 55 | @Getter 56 | @Field(index = FieldIndex.analyzed, type = FieldType.Date) 57 | Date creationDate; 58 | 59 | @Getter 60 | @Field(index = FieldIndex.analyzed, type = FieldType.Float) 61 | float cartAmount; 62 | 63 | @Getter 64 | @Setter 65 | @Field(index = FieldIndex.analyzed, type = FieldType.Boolean) 66 | boolean isAdmin; 67 | 68 | @Getter 69 | @Field(index = FieldIndex.analyzed, type = FieldType.String) 70 | String dateString; 71 | 72 | @Getter 73 | @Field(index = FieldIndex.analyzed, type = FieldType.String) 74 | Timestamp creationTimestamp; 75 | 76 | @Getter 77 | @Field(index = FieldIndex.analyzed, type = FieldType.String) 78 | Time creationTime; 79 | 80 | @Getter 81 | @NestedMapping(table = "cart", foreignKey="cart_id", sqlAssociaton=SQLRelationship.ONE_TO_ONE) 82 | Cart cart; 83 | 84 | @Getter 85 | double giftCardAmount; 86 | 87 | @Getter 88 | @NestedMapping(table="bill", foreignKey = "pk_user", sqlAssociaton=SQLRelationship.ONE_TO_MANY) 89 | List bills; 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/nested/NestedRowMapperTest.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 4 | import fr.juanwolf.mysqlbinlogreplicator.domain.User; 5 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.Mock; 10 | import org.mockito.runners.MockitoJUnitRunner; 11 | 12 | import java.sql.ResultSet; 13 | import java.sql.SQLException; 14 | import java.util.Calendar; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | import static org.mockito.Mockito.when; 18 | 19 | /** 20 | * Created by juanwolf on 17/08/15. 21 | */ 22 | @RunWith(MockitoJUnitRunner.class) 23 | public class NestedRowMapperTest { 24 | 25 | @Mock 26 | ResultSet resultSet; 27 | 28 | @Mock 29 | DomainClassAnalyzer domainClassAnalyzer; 30 | 31 | NestedRowMapper nestedRowMapper; 32 | 33 | @Before 34 | public void setUp() { 35 | nestedRowMapper = new NestedRowMapper(User.class, domainClassAnalyzer, "user"); 36 | } 37 | 38 | @Test 39 | public void mapRow_should_return_null_if_theres_no_empty_constructor() throws SQLException { 40 | // Given 41 | class emptyClass { 42 | 43 | } 44 | nestedRowMapper = new NestedRowMapper(emptyClass.class, domainClassAnalyzer, "empty"); 45 | // When 46 | Object result = nestedRowMapper.mapRow(null, 0); 47 | // Then 48 | assertThat(result).isNull(); 49 | 50 | } 51 | 52 | @Test 53 | public void mapRow_should_return_a_string_set_with_specific_value_in_resultSet() throws SQLException { 54 | // Given 55 | String email = "HULK@shield.com"; 56 | when(resultSet.getString("mail")).thenReturn(email); 57 | // When 58 | User user = (User) nestedRowMapper.mapRow(resultSet, 0); 59 | // Then 60 | assertThat(user.getMail()).isEqualTo(email); 61 | } 62 | 63 | @Test 64 | public void mapRow_should_return_a_date_set_with_specific_value_in_resultSet() throws SQLException { 65 | // Given 66 | Calendar calendar = Calendar.getInstance(); 67 | java.util.Date currentDate = calendar.getTime(); 68 | java.sql.Date date = new java.sql.Date(currentDate.getTime()); 69 | 70 | when(resultSet.getDate("creationDate")).thenReturn(date); 71 | // When 72 | User user = (User) nestedRowMapper.mapRow(resultSet, 0); 73 | // Then 74 | assertThat(user.getCreationDate()).isEqualTo(date); 75 | } 76 | 77 | @Test 78 | public void mapRow_should_return_a_float_set_with_specific_value_in_resultSet() throws SQLException { 79 | // Given 80 | float cartAmount = 1500; 81 | when(resultSet.getFloat("cartAmount")).thenReturn(cartAmount); 82 | // When 83 | User user = (User) nestedRowMapper.mapRow(resultSet, 0); 84 | // Then 85 | assertThat(user.getCartAmount()).isEqualTo(cartAmount); 86 | } 87 | 88 | @Test 89 | public void mapRow_should_return_a_double_set_with_specific_value_in_resultSet() throws SQLException { 90 | // Given 91 | double giftCardAmount = 1500; 92 | when(resultSet.getDouble("giftCardAmount")).thenReturn(giftCardAmount); 93 | // When 94 | User user = (User) nestedRowMapper.mapRow(resultSet, 0); 95 | // Then 96 | assertThat(user.getGiftCardAmount()).isEqualTo(giftCardAmount); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/OneToManyRequesterTest.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 4 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 5 | import fr.juanwolf.mysqlbinlogreplicator.domain.User; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.mockito.InjectMocks; 9 | import org.mockito.Mock; 10 | import org.mockito.runners.MockitoJUnitRunner; 11 | import org.springframework.jdbc.core.JdbcTemplate; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | import static org.assertj.core.api.StrictAssertions.assertThat; 17 | import static org.mockito.Matchers.any; 18 | import static org.mockito.Mockito.when; 19 | 20 | /** 21 | * Created by juanwolf on 28/08/15. 22 | */ 23 | @RunWith(MockitoJUnitRunner.class) 24 | public class OneToManyRequesterTest { 25 | 26 | @Mock 27 | JdbcTemplate jdbcTemplate; 28 | 29 | @Mock 30 | NestedRowMapper nestedRowMapper; 31 | 32 | 33 | OneToManyRequester oneToManyRequester; 34 | 35 | @Test 36 | public void constructor_should_create_a_sql_relationship_with_one_to_many_type() { 37 | // Given 38 | 39 | // When 40 | OneToManyRequester oneToManyRequester = new OneToManyRequester("", "", null, null); 41 | // Then 42 | assertThat(oneToManyRequester.getSqlRelationship()).isEqualTo(SQLRelationship.ONE_TO_MANY); 43 | } 44 | 45 | @Test 46 | public void queryForeignEntity_should_return_list_of_foreign_objects() { 47 | // Given 48 | when(jdbcTemplate.queryForList(any())).thenReturn(new ArrayList()); 49 | when(nestedRowMapper.getList(any())).thenReturn(new ArrayList()); 50 | oneToManyRequester = new OneToManyRequester("cart", "user", null, null); 51 | oneToManyRequester.setJdbcTemplate(jdbcTemplate); 52 | oneToManyRequester.setForeignRowMapper(nestedRowMapper); 53 | // When 54 | List users = oneToManyRequester.queryForeignEntity("cart_id", "id", "1"); 55 | // Then 56 | assertThat(users).isNotNull(); 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/OneToOneRequesterTest.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | /** 4 | * Created by juanwolf on 28/08/15. 5 | */ 6 | public class OneToOneRequesterTest { 7 | } 8 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/nested/requester/SQLRequesterTest.java: -------------------------------------------------------------------------------- 1 | package fr.juanwolf.mysqlbinlogreplicator.nested.requester; 2 | 3 | /** 4 | * Created by juanwolf on 28/08/15. 5 | */ 6 | public class SQLRequesterTest { 7 | } 8 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/service/MySQLEventListenerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | 20 | package fr.juanwolf.mysqlbinlogreplicator.service; 21 | 22 | import com.github.shyiko.mysql.binlog.event.*; 23 | import com.github.shyiko.mysql.binlog.event.deserialization.ColumnType; 24 | import fr.juanwolf.mysqlbinlogreplicator.DomainClass; 25 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 26 | import fr.juanwolf.mysqlbinlogreplicator.nested.NestedRowMapper; 27 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.OneToManyRequester; 28 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.OneToOneRequester; 29 | import fr.juanwolf.mysqlbinlogreplicator.nested.requester.SQLRequester; 30 | import integrationTest.domain.User; 31 | import lombok.Getter; 32 | import org.junit.Before; 33 | import org.junit.Test; 34 | import org.junit.runner.RunWith; 35 | import org.mockito.InjectMocks; 36 | import org.mockito.Mock; 37 | import org.mockito.Spy; 38 | import org.mockito.runners.MockitoJUnitRunner; 39 | import org.springframework.data.repository.CrudRepository; 40 | 41 | import java.io.Serializable; 42 | import java.text.ParseException; 43 | import java.util.*; 44 | 45 | import static org.assertj.core.api.Assertions.assertThat; 46 | import static org.mockito.Mockito.doReturn; 47 | import static org.mockito.Mockito.when; 48 | 49 | /** 50 | * Created by juanwolf on 22/07/15. 51 | */ 52 | @RunWith(MockitoJUnitRunner.class) 53 | public class MySQLEventListenerTest { 54 | 55 | Map domainClassMap; 56 | 57 | @Spy 58 | DomainClassAnalyzer domainClassAnalyzer; 59 | 60 | @Mock 61 | CrudRepository crudRepository; 62 | 63 | Event tableMapEvent; 64 | 65 | @Mock 66 | DomainClass domainClass; 67 | 68 | @Mock 69 | EventHeader tableMapEventHeader; 70 | 71 | @Mock 72 | EventHeader eventHeader; 73 | 74 | final String tableName = "user"; 75 | 76 | @InjectMocks 77 | MySQLEventListener mySQLEventListener; 78 | 79 | @Before 80 | public void setUp() throws NoSuchFieldException { 81 | domainClassMap = new HashMap<>(); 82 | DomainClass domainClassAccount = new DomainClass(); 83 | domainClassAccount.setDomainClass(User.class); 84 | SQLRequester cartSQLRequester = new OneToOneRequester<>(); 85 | cartSQLRequester.setAssociatedField(User.class.getDeclaredField("cart")); 86 | cartSQLRequester.setPrimaryKeyForeignEntity("id"); 87 | Map cartColumnMap = new HashMap<>(); 88 | Object[] columnarray = {"id", "amount", "user_id"}; 89 | cartColumnMap.put("cart", columnarray); 90 | 91 | Map sqlRequesterMap = new HashMap<>(); 92 | sqlRequesterMap.put("cart", cartSQLRequester); 93 | domainClassAccount.setSqlRequesters(sqlRequesterMap); 94 | List nestedTables = new ArrayList<>(); 95 | nestedTables.add("cart"); 96 | when(domainClassAnalyzer.getNestedTables()).thenReturn(nestedTables); 97 | domainClassMap.put("user", domainClassAccount); 98 | domainClassMap.put("newTable", domainClass); 99 | when(domainClassAnalyzer.getDomainClassMap()).thenReturn(domainClassMap); 100 | when(tableMapEventHeader.getEventType()).thenReturn(EventType.TABLE_MAP); 101 | TableMapEventData tableMapEventData = new TableMapEventData(); 102 | tableMapEventData.setTable(tableName); 103 | this.tableMapEvent = new Event(tableMapEventHeader, tableMapEventData); 104 | mySQLEventListener = new MySQLEventListener(new HashMap<>(), domainClassAnalyzer); 105 | mySQLEventListener.setColumnMap(cartColumnMap); 106 | 107 | } 108 | 109 | @Test 110 | public void constructor_should_initialize_an_empty_columnType_map() { 111 | // given 112 | // when 113 | MySQLEventListener mySQLEventListener = new MySQLEventListener(null, null); 114 | // then 115 | assertThat(mySQLEventListener.getColumnsTypes()).isEmpty(); 116 | } 117 | 118 | @Test 119 | public void actionOnEvent_should_add_entry_to_columnTypes_with_specific_type_array() throws Exception { 120 | // given 121 | Map localDomainClassMap = new HashMap<>(); 122 | when(domainClass.getCrudRepository()).thenReturn(crudRepository); 123 | localDomainClassMap.put(tableName, domainClass); 124 | domainClassAnalyzer.setDomainClassMap(localDomainClassMap); 125 | // when(domainClassAnalyzer.getDomainClassMap()).thenReturn(localDomainClassMap); 126 | MySQLEventListener listener = new MySQLEventListener(new HashMap<>(), domainClassAnalyzer); 127 | // when 128 | listener.actionOnEvent(tableMapEvent); 129 | // then 130 | assertThat(listener.getColumnsTypes()).containsKey(tableName); 131 | } 132 | 133 | @Test 134 | public void actionOnEvent_should_change_the_tableName_when_a_new_TableMapEvent_is_received() throws Exception { 135 | // given 136 | String newTable = "newtable"; 137 | TableMapEventData tableMapEventData = this.tableMapEvent.getData(); 138 | tableMapEventData.setTable(newTable); 139 | Event newtableMapEvent = new Event(tableMapEventHeader, tableMapEventData); 140 | mySQLEventListener.actionOnEvent(this.tableMapEvent); 141 | when(domainClass.getCrudRepository()).thenReturn(crudRepository); 142 | when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(new ArrayList()); 143 | when(domainClassAnalyzer.getNestedTables()).thenReturn(new ArrayList()); 144 | // when 145 | mySQLEventListener.actionOnEvent(newtableMapEvent); 146 | // then 147 | assertThat(mySQLEventListener.getTableName()).isEqualTo(newTable); 148 | } 149 | 150 | @Test 151 | public void getObjectFromRows_should_return_an_object_with_field_equals_to_null_for_empty_array() throws ReflectiveOperationException, ParseException { 152 | // given 153 | Serializable[] rows = {}; 154 | doReturn(new User()).when(mySQLEventListener.getDomainClassAnalyzer()).generateInstanceFromName("user"); 155 | // when 156 | User object = (User) mySQLEventListener.getObjectFromRows(rows, "user"); 157 | // then 158 | assertThat(object).isEqualToComparingFieldByField(new User()); 159 | } 160 | 161 | @Test 162 | public void getObjectFromRows_should_return_an_object_with_fields_set_to_specificValue() throws ReflectiveOperationException, ParseException { 163 | // given 164 | String email = "this.is.my.mail@devel.com"; 165 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 166 | Object[] columns = {"mail"}; 167 | setUpMySqlEventListener(columns, types); 168 | Serializable[] rows = {email}; 169 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 170 | // when 171 | User object = (User) mySQLEventListener.getObjectFromRows(rows, "user"); 172 | // then 173 | assertThat(object.getMail()).isEqualTo(email); 174 | } 175 | 176 | @Test 177 | public void getObjectFromRows_should_return_an_empty_object_if_a_no_such_field_exception_occurred() throws ReflectiveOperationException, ParseException { 178 | // given 179 | String email = "this.is.my.mail@devel.com"; 180 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 181 | Object[] columns = {"no field"}; 182 | setUpMySqlEventListener(columns, types); 183 | Serializable[] rows = {email}; 184 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 185 | // when 186 | User object = (User) mySQLEventListener.getObjectFromRows(rows, "user"); 187 | // then 188 | assertThat(object).isEqualToComparingFieldByField(new User()); 189 | } 190 | 191 | @Test 192 | public void getObjectFromRows_should_not_instanciate_a_field_with_a_null_value_in_rows() throws ReflectiveOperationException, ParseException { 193 | // given 194 | String email = null; 195 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 196 | Object[] columns = {"mail"}; 197 | setUpMySqlEventListener(columns, types); 198 | Serializable[] rows = {email}; 199 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 200 | // when 201 | User object = (User) mySQLEventListener.getObjectFromRows(rows, "user"); 202 | // then 203 | assertThat(object).isEqualToComparingFieldByField(new User()); 204 | } 205 | 206 | @Test 207 | public void isTableConcern_should_return_true_if_the_table_is_contain_in_the_list() { 208 | // Given 209 | List tablesExpected = new ArrayList<>(); 210 | tablesExpected.add("user"); 211 | when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tablesExpected); 212 | mySQLEventListener.setTableName("user"); 213 | // When 214 | boolean isTableConcern = mySQLEventListener.isMappingConcern(); 215 | // Then 216 | assertThat(isTableConcern).isTrue(); 217 | 218 | } 219 | 220 | @Test 221 | public void isTableConcern_should_return_false_if_the_table_is_not_contained_in_the_list() { 222 | // Given 223 | List tablesExpected = new ArrayList<>(); 224 | when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tablesExpected); 225 | mySQLEventListener.setTableName("user"); 226 | // When 227 | boolean isTableConcern = mySQLEventListener.isMappingConcern(); 228 | // Then 229 | assertThat(isTableConcern).isFalse(); 230 | 231 | } 232 | 233 | @Test 234 | public void generateDomainObjectForUpdateEvent_should_return_the_specify_object_for_the_specific_rows() throws ReflectiveOperationException, ParseException { 235 | // Given 236 | Map columnsType = new HashMap<>(); 237 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 238 | columnsType.put("user", types); 239 | Map columnMap = new HashMap<>(); 240 | Object[] columns = {"mail"}; 241 | columnMap.put("user", columns); 242 | mySQLEventListener.setColumnMap(columnMap); 243 | mySQLEventListener.setColumnsTypes(columnsType); 244 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 245 | UpdateRowsEventData updateRowsEventData = new UpdateRowsEventData(); 246 | Map map = new HashMap<>(); 247 | List> datas = new ArrayList(); 248 | Serializable[] serializables = {"john@zen.com"}; 249 | map.put(serializables, serializables); 250 | datas.add(map.entrySet().stream().findFirst().get()); 251 | updateRowsEventData.setRows(datas); 252 | Event event = new Event(tableMapEventHeader, updateRowsEventData); 253 | User userExpected = new User(); 254 | userExpected.setMail("john@zen.com"); 255 | // When 256 | Object updatedObject = mySQLEventListener.generateDomainObjectForUpdateEvent(event, "user"); 257 | // Then 258 | assertThat(updatedObject).isEqualToComparingFieldByField(userExpected); 259 | 260 | } 261 | 262 | @Test 263 | public void generateDomainObjectForDeleteEvent_should_return_the_specify_object_for_the_specific_rows() throws ReflectiveOperationException, ParseException { 264 | // Given 265 | Map columnsType = new HashMap<>(); 266 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 267 | columnsType.put("user", types); 268 | Map columnMap = new HashMap<>(); 269 | Object[] columns = {"mail"}; 270 | columnMap.put("user", columns); 271 | mySQLEventListener.setColumnMap(columnMap); 272 | mySQLEventListener.setColumnsTypes(columnsType); 273 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 274 | DeleteRowsEventData deleteRowsEventData = new DeleteRowsEventData(); 275 | List datas = new ArrayList(); 276 | Serializable[] serializables = {"john@zen.com"}; 277 | datas.add(serializables); 278 | deleteRowsEventData.setRows(datas); 279 | Event event = new Event(tableMapEventHeader, deleteRowsEventData); 280 | User userExpected = new User(); 281 | userExpected.setMail("john@zen.com"); 282 | // When 283 | Object updatedObject = mySQLEventListener.generateDomainObjectForDeleteEvent(event, "user"); 284 | // Then 285 | assertThat(updatedObject).isEqualToComparingFieldByField(userExpected); 286 | 287 | } 288 | 289 | @Test 290 | public void generateDomainObjectForWriteEvent_should_return_the_specify_object_for_the_specific_rows() throws ReflectiveOperationException, ParseException { 291 | // Given 292 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 293 | Object[] columns = {"mail"}; 294 | setUpMySqlEventListener(columns, types); 295 | setUpDomainClassAnalyzer(null, new User()); 296 | WriteRowsEventData updateRowsEventData = new WriteRowsEventData(); 297 | List datas = new ArrayList(); 298 | Serializable[] serializables = {"john@zen.com"}; 299 | datas.add(serializables); 300 | updateRowsEventData.setRows(datas); 301 | Event event = new Event(tableMapEventHeader, updateRowsEventData); 302 | User userExpected = new User(); 303 | userExpected.setMail("john@zen.com"); 304 | // When 305 | Object updatedObject = mySQLEventListener.generateDomainObjectForWriteEvent(event, "user"); 306 | // Then 307 | assertThat(updatedObject).isEqualToComparingFieldByField(userExpected); 308 | 309 | } 310 | 311 | @Test 312 | public void onEvent_should_remove_the_object_from_the_event_received_if_the_table_is_concerned() throws ReflectiveOperationException { 313 | // given 314 | when(eventHeader.getEventType()).thenReturn(EventType.DELETE_ROWS); 315 | StubRepository stubRepository = new StubRepository(); 316 | User userToDelete = new User(); 317 | stubRepository.save(userToDelete); 318 | setUpDomainClassAnalyzer(stubRepository, userToDelete); 319 | byte[] types = {}; 320 | Object[] columns = {}; 321 | setUpMySqlEventListener(columns, types); 322 | DeleteRowsEventData deleteRowsEventData = new DeleteRowsEventData(); 323 | List datas = new ArrayList(); 324 | Serializable[] serializables = {}; 325 | datas.add(serializables); 326 | deleteRowsEventData.setRows(datas); 327 | Event event = new Event(eventHeader, deleteRowsEventData); 328 | // when 329 | mySQLEventListener.onEvent(event); 330 | // then 331 | assertThat(stubRepository.count()).isEqualTo(0); 332 | 333 | } 334 | 335 | @Test 336 | public void onEvent_should_insert_the_object_from_the_event_received_if_the_table_is_concerned() throws ReflectiveOperationException { 337 | // given 338 | when(eventHeader.getEventType()).thenReturn(EventType.WRITE_ROWS); 339 | StubRepository stubRepository = new StubRepository(); 340 | User userToAdd = new User(); 341 | userToAdd.setMail("test@test.com"); 342 | setUpDomainClassAnalyzer(stubRepository, userToAdd); 343 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 344 | Object[] columns = { "mail" }; 345 | setUpMySqlEventListener(columns, types); 346 | WriteRowsEventData writeRowsEventData = new WriteRowsEventData(); 347 | List datas = new ArrayList(); 348 | Serializable[] serializables = {}; 349 | datas.add(serializables); 350 | writeRowsEventData.setRows(datas); 351 | Event event = new Event(eventHeader, writeRowsEventData); 352 | // when 353 | mySQLEventListener.onEvent(event); 354 | // then 355 | assertThat(stubRepository.count()).isEqualTo(1); 356 | } 357 | 358 | @Test 359 | public void onEvent_should_update_the_object_from_the_event_received_if_the_table_is_concerned() throws ReflectiveOperationException { 360 | // given 361 | String emailExpected = "test@test.com"; 362 | when(eventHeader.getEventType()).thenReturn(EventType.UPDATE_ROWS); 363 | StubRepository stubRepository = new StubRepository(); 364 | User userToUpdate = new User(); 365 | setUpDomainClassAnalyzer(stubRepository, userToUpdate); 366 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 367 | Object[] columns = { "mail" }; 368 | setUpMySqlEventListener(columns, types); 369 | UpdateRowsEventData updateRowsEventData = new UpdateRowsEventData(); 370 | List> datas = new ArrayList<>(); 371 | Serializable[] serializables = { emailExpected }; 372 | Serializable[] beforeValues = {}; 373 | datas.add(new AbstractMap.SimpleEntry<>(beforeValues, serializables)); 374 | updateRowsEventData.setRows(datas); 375 | Event event = new Event(eventHeader, updateRowsEventData); 376 | // when 377 | mySQLEventListener.onEvent(event); 378 | // then 379 | String emailOfUpdatedAccount = ((User)stubRepository.getElementList().get(0)).getMail(); 380 | assertThat(emailOfUpdatedAccount).isEqualTo(emailExpected); 381 | } 382 | 383 | // TOOLS ---------------------------------------------------------------------- 384 | 385 | public void setUpMySqlEventListener(Object[] columns, byte[] types) { 386 | mySQLEventListener.setTableName("user"); 387 | Map columnsType = new HashMap<>(); 388 | columnsType.put("user", types); 389 | Map columnMap = new HashMap<>(); 390 | columnMap.put("user", columns); 391 | mySQLEventListener.setColumnMap(columnMap); 392 | mySQLEventListener.setColumnsTypes(columnsType); 393 | } 394 | 395 | public void setUpDomainClassAnalyzer(CrudRepository crudRepository, User user) throws ReflectiveOperationException { 396 | Map domainMap = new HashMap<>(); 397 | List tablesExpected = new ArrayList<>(); 398 | tablesExpected.add("user"); 399 | DomainClass domainClass = new DomainClass(); 400 | domainClass.setDomainClass(User.class); 401 | domainClass.setCrudRepository(crudRepository); 402 | OneToOneRequester cartSQLRequester = new OneToOneRequester(); 403 | cartSQLRequester.setAssociatedField(User.class.getDeclaredField("cart")); 404 | Map sqlRequesterMap = new HashMap<>(); 405 | sqlRequesterMap.put("cart", cartSQLRequester); 406 | domainClass.setSqlRequesters(sqlRequesterMap); 407 | domainMap.put("user", domainClass); 408 | when(domainClassAnalyzer.getDomainClassMap()).thenReturn(domainMap); 409 | when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tablesExpected); 410 | doReturn(user).when(domainClassAnalyzer).generateInstanceFromName("user"); 411 | } 412 | 413 | @Test 414 | public void getPrimaryKeyValueFromRows_should_return_the_value_of_the_primary_key() { 415 | // Given 416 | String primaryKeyExpected = "0"; 417 | String[] rows = {primaryKeyExpected, "", "4"}; 418 | // When 419 | String primaryKey = mySQLEventListener.getPrimaryKeyValueFromRows(rows, 420 | "cart", 421 | domainClassAnalyzer.getDomainClassMap().get("user").getSqlRequesters().get("cart")); 422 | // Then 423 | assertThat(primaryKey).isEqualTo(primaryKeyExpected); 424 | } 425 | 426 | @Test 427 | public void getPrimaryKeyValueFromRows_should_return_null_if_rows_is_empty() { 428 | // Given 429 | String[] rows = {}; 430 | // When 431 | String primaryKey = mySQLEventListener.getPrimaryKeyValueFromRows(rows, 432 | "cart", 433 | domainClassAnalyzer.getDomainClassMap().get("user").getSqlRequesters().get("cart")); 434 | // Then 435 | assertThat(primaryKey).isNull(); 436 | } 437 | 438 | @Test 439 | public void getPrimaryKeyFromEvent_should_return_the_value_of_the_foreign_key_for_an_update_event() throws ReflectiveOperationException { 440 | // Given 441 | String foreignKeyValueExpected = "115"; 442 | Map columnsType = new HashMap<>(); 443 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 444 | columnsType.put("user", types); 445 | Map columnMap = new HashMap<>(); 446 | Object[] columns = {"id"}; 447 | columnMap.put("user", columns); 448 | mySQLEventListener.setColumnMap(columnMap); 449 | mySQLEventListener.setColumnsTypes(columnsType); 450 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 451 | UpdateRowsEventData updateRowsEventData = new UpdateRowsEventData(); 452 | Map map = new HashMap<>(); 453 | List> datas = new ArrayList(); 454 | Serializable[] serializables = { foreignKeyValueExpected }; 455 | map.put(serializables, serializables); 456 | datas.add(map.entrySet().stream().findFirst().get()); 457 | updateRowsEventData.setRows(datas); 458 | when(tableMapEventHeader.getEventType()).thenReturn(EventType.UPDATE_ROWS); 459 | Event event = new Event(tableMapEventHeader, updateRowsEventData); 460 | // When 461 | String value = mySQLEventListener.getPrimaryKeyFromEvent(event, 462 | domainClassAnalyzer.getDomainClassMap().get("user").getSqlRequesters().get("cart"), 463 | "user"); 464 | // Then 465 | assertThat(value).isEqualTo(foreignKeyValueExpected); 466 | 467 | } 468 | 469 | @Test 470 | public void getPrimaryKeyFromEvent_should_return_the_value_of_the_foreign_key_for_a_delete_event() throws ReflectiveOperationException { 471 | // Given 472 | String foreignKeyValueExpected = "115"; 473 | Map columnsType = new HashMap<>(); 474 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 475 | columnsType.put("user", types); 476 | Map columnMap = new HashMap<>(); 477 | Object[] columns = {"id"}; 478 | columnMap.put("user", columns); 479 | mySQLEventListener.setColumnMap(columnMap); 480 | mySQLEventListener.setColumnsTypes(columnsType); 481 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 482 | DeleteRowsEventData updateRowsEventData = new DeleteRowsEventData(); 483 | List datas = new ArrayList(); 484 | Serializable[] serializables = { foreignKeyValueExpected }; 485 | datas.add(serializables); 486 | updateRowsEventData.setRows(datas); 487 | when(tableMapEventHeader.getEventType()).thenReturn(EventType.DELETE_ROWS); 488 | Event event = new Event(tableMapEventHeader, updateRowsEventData); 489 | // When 490 | String value = mySQLEventListener.getPrimaryKeyFromEvent(event, 491 | domainClassAnalyzer.getDomainClassMap().get("user").getSqlRequesters().get("cart"), 492 | "user"); 493 | // Then 494 | assertThat(value).isEqualTo(foreignKeyValueExpected); 495 | 496 | } 497 | 498 | 499 | 500 | @Test 501 | public void getPrimaryKeyFromEvent_should_return_the_value_of_the_foreign_key_for_an_insert_event() throws ReflectiveOperationException { 502 | // Given 503 | String foreignKeyValueExpected = "115"; 504 | Map columnsType = new HashMap<>(); 505 | byte[] types = { (byte) ColumnType.VARCHAR.getCode()}; 506 | columnsType.put("user", types); 507 | Map columnMap = new HashMap<>(); 508 | Object[] columns = {"id"}; 509 | columnMap.put("user", columns); 510 | mySQLEventListener.setColumnMap(columnMap); 511 | mySQLEventListener.setColumnsTypes(columnsType); 512 | doReturn(new User()).when(domainClassAnalyzer).generateInstanceFromName("user"); 513 | WriteRowsEventData updateRowsEventData = new WriteRowsEventData(); 514 | List datas = new ArrayList(); 515 | Serializable[] serializables = { foreignKeyValueExpected }; 516 | datas.add(serializables); 517 | updateRowsEventData.setRows(datas); 518 | when(tableMapEventHeader.getEventType()).thenReturn(EventType.WRITE_ROWS); 519 | Event event = new Event(tableMapEventHeader, updateRowsEventData); 520 | // When 521 | String value = mySQLEventListener.getPrimaryKeyFromEvent(event, 522 | domainClassAnalyzer.getDomainClassMap().get("user").getSqlRequesters().get("cart"), 523 | "user"); 524 | // Then 525 | assertThat(value).isEqualTo(foreignKeyValueExpected); 526 | 527 | } 528 | 529 | 530 | public class StubRepository implements CrudRepository { 531 | @Getter 532 | private List elementList; 533 | 534 | public StubRepository() { 535 | elementList = new ArrayList<>(); 536 | } 537 | 538 | @Override 539 | public Object save(Object o) { 540 | elementList.add(o); 541 | return o; 542 | } 543 | 544 | @Override 545 | public Iterable save(Iterable iterable) { 546 | elementList.add(iterable); 547 | return iterable; 548 | } 549 | 550 | @Override 551 | public Object findOne(Serializable serializable) { 552 | return null; 553 | } 554 | 555 | @Override 556 | public boolean exists(Serializable serializable) { 557 | return true; 558 | } 559 | 560 | @Override 561 | public Iterable findAll() { 562 | return elementList; 563 | } 564 | 565 | @Override 566 | public Iterable findAll(Iterable iterable) { 567 | return null; 568 | } 569 | 570 | @Override 571 | public long count() { 572 | return elementList.size(); 573 | } 574 | 575 | @Override 576 | public void delete(Serializable serializable) { 577 | 578 | } 579 | 580 | @Override 581 | public void delete(Object o) { 582 | elementList.remove(o); 583 | } 584 | 585 | @Override 586 | public void delete(Iterable iterable) { 587 | 588 | } 589 | 590 | @Override 591 | public void deleteAll() { 592 | 593 | } 594 | } 595 | } 596 | -------------------------------------------------------------------------------- /src/test/java/fr/juanwolf/mysqlbinlogreplicator/service/MysqlBinLogServiceTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package fr.juanwolf.mysqlbinlogreplicator.service; 20 | 21 | import com.github.shyiko.mysql.binlog.BinaryLogClient; 22 | import fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | import org.junit.runner.RunWith; 26 | import org.mockito.InjectMocks; 27 | import org.mockito.Mock; 28 | import org.mockito.runners.MockitoJUnitRunner; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 31 | 32 | import javax.management.*; 33 | import java.io.IOException; 34 | import java.util.ArrayList; 35 | import java.util.HashMap; 36 | import java.util.List; 37 | import java.util.Map; 38 | 39 | import static org.assertj.core.api.Assertions.assertThat; 40 | import static org.mockito.Matchers.*; 41 | import static org.mockito.Mockito.verify; 42 | import static org.mockito.Mockito.when; 43 | 44 | /** 45 | * Created by juanwolf on 27/07/15. 46 | */ 47 | @RunWith(MockitoJUnitRunner.class) 48 | public class MysqlBinLogServiceTest { 49 | 50 | @Mock 51 | DomainClassAnalyzer domainClassAnalyzer; 52 | 53 | @Mock 54 | NamedParameterJdbcTemplate namedParameterJdbcTemplate; 55 | 56 | @Mock 57 | BinaryLogClient client; 58 | 59 | @Mock 60 | MBeanServer mBeanServer; 61 | 62 | @Autowired 63 | @InjectMocks 64 | MysqlBinLogService mysqlBinLogService; 65 | 66 | private final static String MYSQL_HOST = "localhost"; 67 | private final static int MYSQL_PORT = 3306; 68 | private final static String MYSQL_USER = "root"; 69 | private final static String MYSQL_PWD = ""; 70 | 71 | 72 | @Before 73 | public void setUp() { 74 | mysqlBinLogService.setMysqlHost(MYSQL_HOST); 75 | mysqlBinLogService.setMysqlPort(MYSQL_PORT); 76 | mysqlBinLogService.setMysqlUser(MYSQL_USER); 77 | mysqlBinLogService.setMysqlPassword(MYSQL_PWD); 78 | 79 | } 80 | 81 | 82 | @Test 83 | public void getColumnName_should_add_columns_name_to_the_columnMap() { 84 | // Given 85 | List tableExpectedList = new ArrayList<>(); 86 | tableExpectedList.add("account"); 87 | when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tableExpectedList); 88 | List> columnsMap = new ArrayList<>(); 89 | Map columnMap = new HashMap<>(); 90 | columnMap.put("COLUMN_NAME", "column_name"); 91 | columnsMap.add(columnMap); 92 | when(namedParameterJdbcTemplate.queryForList(anyString(), anyMap())).thenReturn(columnsMap); 93 | // When 94 | mysqlBinLogService.getColumnName(); 95 | // Then 96 | assertThat(mysqlBinLogService.columnMap.get("account")).contains("column_name"); 97 | } 98 | 99 | @Test 100 | public void postConstruct_should_instanciate_a_new_binlogclientstatisticClient() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException { 101 | // Given 102 | ObjectName statsObjectName = new ObjectName("mysql.binlog:type=BinaryLogClientStatistics"); 103 | // When 104 | mysqlBinLogService.postConstruct(); 105 | // Then 106 | verify(mBeanServer).registerMBean(any(), eq(statsObjectName)); 107 | } 108 | 109 | @Test 110 | public void startReplication_should_instanciate_a_new_listener() throws IOException { 111 | // Given 112 | // When 113 | mysqlBinLogService.startReplication(); 114 | // Then 115 | verify(client).registerEventListener(any()); 116 | } 117 | 118 | @Test 119 | public void startReplication_should_connect_the_client() throws IOException { 120 | // Given 121 | // When 122 | mysqlBinLogService.startReplication(); 123 | // Then 124 | verify(client).connect(); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/test/java/integrationTest/Replicator.java: -------------------------------------------------------------------------------- 1 | package integrationTest; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.service.MysqlBinLogService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.context.annotation.ComponentScan; 9 | 10 | /** 11 | * Created by juanwolf on 27/07/15. 12 | */ 13 | @SpringBootApplication 14 | @ComponentScan("fr.juanwolf.mysqlbinlogreplicator") 15 | public class Replicator implements CommandLineRunner { 16 | 17 | @Autowired 18 | private MysqlBinLogService mysqlBinLogService; 19 | 20 | 21 | public static void main(String[] args) { 22 | SpringApplication.run(Replicator.class, args); 23 | } 24 | 25 | @Override 26 | public void run(String... strings) throws Exception { 27 | mysqlBinLogService.startReplication(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/integrationTest/dao/CartRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package integrationTest.dao; 20 | 21 | import integrationTest.domain.Cart; 22 | import integrationTest.domain.User; 23 | import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; 24 | 25 | /** 26 | * Created by juanwolf on 17/07/15. 27 | */ 28 | public interface CartRepository extends ElasticsearchCrudRepository { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/integrationTest/dao/UserRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package integrationTest.dao; 20 | 21 | import integrationTest.domain.User; 22 | import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; 23 | 24 | /** 25 | * Created by juanwolf on 17/07/15. 26 | */ 27 | public interface UserRepository extends ElasticsearchCrudRepository { 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/integrationTest/domain/Cart.java: -------------------------------------------------------------------------------- 1 | package integrationTest.domain; 2 | 3 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 4 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 5 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import org.springframework.data.annotation.Id; 9 | import org.springframework.data.elasticsearch.annotations.*; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Created by juanwolf on 10/08/15. 15 | */ 16 | @Data 17 | @NoArgsConstructor 18 | @Document(indexName = "cart") 19 | @Mapping(mappingPath = "cart") 20 | @MysqlMapping(table="cart", repository = "cartRepository") 21 | public class Cart { 22 | 23 | @Id 24 | public Integer id; 25 | 26 | @Field(type = FieldType.Float, index = FieldIndex.analyzed) 27 | public float amount; 28 | 29 | @NestedMapping(primaryKey = "id", foreignKey = "cart_id", sqlAssociaton=SQLRelationship.ONE_TO_MANY, table="user") 30 | @Field(type = FieldType.Nested, index=FieldIndex.analyzed) 31 | List users; 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/integrationTest/domain/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2015 Jean-Loup Adde 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | 19 | package integrationTest.domain; 20 | 21 | import fr.juanwolf.mysqlbinlogreplicator.annotations.MysqlMapping; 22 | import fr.juanwolf.mysqlbinlogreplicator.annotations.NestedMapping; 23 | import fr.juanwolf.mysqlbinlogreplicator.nested.SQLRelationship; 24 | import lombok.Getter; 25 | import lombok.Setter; 26 | import org.springframework.data.annotation.Id; 27 | import org.springframework.data.elasticsearch.annotations.*; 28 | 29 | import java.sql.Time; 30 | import java.sql.Timestamp; 31 | import java.util.Date; 32 | import java.util.List; 33 | 34 | /** 35 | * Created by juanwolf on 17/07/15. 36 | */ 37 | @Document(indexName = "user") 38 | @Mapping(mappingPath = "user") 39 | @MysqlMapping(table = "user", repository="userRepository") 40 | public class User { 41 | @Id 42 | @Setter 43 | @Getter 44 | Integer id; 45 | 46 | @Getter 47 | @Field(type = FieldType.Integer, index = FieldIndex.analyzed) 48 | Integer identifier; 49 | 50 | @Getter 51 | @Setter 52 | @Field(type = FieldType.String, index = FieldIndex.analyzed) 53 | String mail; 54 | 55 | @Getter 56 | @Field(index = FieldIndex.analyzed, type = FieldType.Date) 57 | Date creationDate; 58 | 59 | @Getter 60 | @Field(index = FieldIndex.analyzed, type = FieldType.Float) 61 | float cartAmount; 62 | 63 | // @Getter 64 | // @Setter 65 | // @Field(index = FieldIndex.analyzed, type = FieldType.Boolean) 66 | // boolean isAdmin; 67 | 68 | 69 | @Getter 70 | @NestedMapping(table = "cart", foreignKey="cart_id", sqlAssociaton=SQLRelationship.MANY_TO_ONE) 71 | Cart cart; 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | #MYSQL 2 | mysql.host=localhost 3 | mysql.port=3306 4 | 5 | mysql.schema=replication_test 6 | 7 | mysql.scanmapping=integrationTest.domain 8 | 9 | #Spring 10 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 11 | spring.datasource.url=jdbc:mysql://${mysql.host}:${mysql.port} 12 | spring.datasource.username=root 13 | spring.datasource.password= 14 | 15 | #ELASTIC 16 | spring.data.elasticsearch.cluster-nodes=localhost:9300 17 | 18 | 19 | 20 | --------------------------------------------------------------------------------