├── .gitignore ├── .gitlab-ci.yml ├── LICENSE ├── README.md ├── json-view ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── monitorjbl │ │ └── json │ │ ├── JsonView.java │ │ ├── JsonViewModule.java │ │ ├── JsonViewSerializer.java │ │ ├── Match.java │ │ ├── MatcherBehavior.java │ │ └── Memoizer.java │ └── test │ ├── java │ └── com │ │ └── monitorjbl │ │ └── json │ │ ├── JsonViewSerializerPerformanceTest.java │ │ ├── JsonViewSerializerTest.java │ │ ├── WriterTest.java │ │ └── model │ │ ├── CustomType.java │ │ ├── CustomTypeSerializer.java │ │ ├── NonReplacableKeyMap.java │ │ ├── TestAutodetect.java │ │ ├── TestBackreferenceObject.java │ │ ├── TestChildObject.java │ │ ├── TestDuplicateKeys.java │ │ ├── TestInterface.java │ │ ├── TestNonNulls.java │ │ ├── TestNulls.java │ │ ├── TestObject.java │ │ ├── TestSubobject.java │ │ ├── TestSuperinterface.java │ │ └── TestUnrelatedObject.java │ └── resources │ └── log4j.properties ├── pom.xml ├── release.sh ├── shippable.yml └── spring-json-view ├── pom.xml └── src ├── main └── java │ └── com │ └── monitorjbl │ └── json │ ├── DefaultView.java │ ├── JsonResult.java │ ├── JsonResultRetriever.java │ ├── JsonViewHttpEntityMethodProcessor.java │ ├── JsonViewMessageConverter.java │ ├── JsonViewResponseProcessor.java │ ├── JsonViewReturnValueHandler.java │ └── JsonViewSupportFactoryBean.java └── test ├── java └── com │ └── monitorjbl │ └── json │ ├── ConfigTest.java │ ├── JavaConfigurationTest.java │ ├── XmlConfigurationTest.java │ ├── model │ ├── TestChildObject.java │ ├── TestDefaultViewObject.java │ ├── TestDefaultViewSubobject.java │ ├── TestObject.java │ ├── TestSubobject.java │ └── TestUnrelatedObject.java │ └── server │ ├── ConfigServer.java │ ├── Context.java │ ├── DefaultViewFactory.java │ ├── JacksonConfiguration.java │ ├── JavaConfigServer.java │ ├── XmlConfigServer.java │ └── controller │ └── JsonController.java └── resources ├── context.xml └── log4j.properties /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | *.iws 3 | *.ipr 4 | target 5 | .DS_Store 6 | .idea 7 | .java-version -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: maven:3.6.3-openjdk-8-slim 2 | ci_build: 3 | stage: build 4 | before_script: 5 | - mkdir -p ~/.m2 && echo "${MVN_SETTINGS}" > ~/.m2/settings.xml 6 | script: 7 | - mvn clean package 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Run Status](https://gitlab.com/monitorjbl/json-view/badges/master/pipeline.svg) 2 | 3 | # Programmatic JSON Views 4 | 5 | Ever needed to programmatically include or exclude a field when serializing object with Jackson? Well, if you have then you probably know by now that it's very difficult to do. Jackson is by nature very declarative (annotations for everything!), so doing something programmatically gets ugly fast. 6 | 7 | While the declarative style certainly has many benefits (compile-time checking, ease of refactoring, etc.), the inability to simply and programmatically control your inclusions/exclusions is one major downside. Inspired by [VRaptor](http://www.vraptor.org/), this library provides an easy way to alter serialized output on the fly. 8 | 9 | * [JsonView](#jsonview) 10 | * [Usage](#usage) 11 | * [Including](#including) 12 | * [Typical use cases](#typical-use-cases) 13 | * [Excluding](#excluding) 14 | * [Including](#including) 15 | * [Advanced use cases](#advanced-use-cases) 16 | * [Wildcard matchers](#wildcard-matchers) 17 | * [Class matchers](#class-matchers) 18 | * [Custom Serializers](#custom-serializers) 19 | * [Field Transformations](#field-transformations) 20 | * [Rules](#rules) 21 | * [Spring Integration](#spring-integration) 22 | * [Including](#including-1) 23 | * [Configuration](#configuration) 24 | * [Usage](#usage-1) 25 | * [Return value](#return-value) 26 | * [Building from source](#building-from-source) 27 | 28 | # JsonView 29 | 30 | All the functionality of this library really boils down to a custom Jackson serializer. 31 | 32 | ## Usage 33 | 34 | Just initialize a standard Jackson `ObjectMapper` class like so: 35 | 36 | ```java 37 | import com.fasterxml.jackson.databind.ObjectMapper; 38 | import com.fasterxml.jackson.databind.module.SimpleModule; 39 | import com.monitorjbl.json.JsonView; 40 | import com.monitorjbl.json.JsonViewSerializer; 41 | 42 | //initialize jackson 43 | ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule()); 44 | ``` 45 | 46 | ## Including 47 | 48 | To use it, simply add this project to your classpath using your build tool of choice. This project is available on Maven Central, so if you're using Maven you can just add this to your pom.xml: 49 | 50 | ```xml 51 | 52 | com.monitorjbl 53 | json-view 54 | 1.0.1 55 | 56 | ``` 57 | 58 | ## Typical use cases 59 | 60 | The potential use cases for this library are pretty varied, but here are a few to get you started. 61 | 62 | ### Exclusion 63 | 64 | The most common use case for this is when you have an object with an expensive (big) field on it. You may not always want to serialize it. Let's say that you've got this class: 65 | 66 | ```java 67 | public class MyObject{ 68 | private Long id; 69 | private String name; 70 | private MySmallObject smallObj; 71 | private List contains; //expensive list with many entries 72 | 73 | //getters and setters and/or builder 74 | } 75 | ``` 76 | 77 | If you were to return a list of `MyObject`, you may not want to show the `contains` field; with *n* instances of `MyObject` and *m* instances of `MyBigObject` per instance of `MyObject`, you'll be returning n\*m instances. 78 | 79 | The typically suggested pattern suggests using the `@JsonIgnore` annotation on the field. However, this effectively makes this field permanently ignored everywhere in your app. What if you want only don't want to show this field when dealing with a single instance rather than a `List`? 80 | 81 | Using `JsonView` allows you to filter this field out quickly and easily: 82 | 83 | ```java 84 | import com.monitorjbl.json.JsonView; 85 | import static com.monitorjbl.json.Match.match; 86 | 87 | //get a list of the objects 88 | List list = myObjectService.list(); 89 | 90 | //exclude expensive field 91 | String json = mapper.writeValueAsString(JsonView.with(list).onClass(MyObject.class, match().exclude("contains"))); 92 | ``` 93 | 94 | ### Inclusion 95 | 96 | The inverse of this is also possible. For example, let's say this was your class instead: 97 | 98 | ```java 99 | public class MyObject{ 100 | private Long id; 101 | private String name; 102 | private MySmallObject smallObj; 103 | @JsonIgnore 104 | private List contains; //expensive list with many entries 105 | 106 | //getters and setters and/or builder 107 | } 108 | ``` 109 | 110 | You can programmatically include fields that are ignored by default: 111 | 112 | 113 | ```java 114 | import com.monitorjbl.json.JsonView; 115 | import static com.monitorjbl.json.Match.match; 116 | 117 | //get a list of the objects 118 | List list = myObjectService.list(); 119 | 120 | //exclude expensive field 121 | String json = mapper.writeValueAsString(JsonView.with(list).onClass(MyObject.class, match().include("contains"))); 122 | ``` 123 | 124 | ## Advanced use cases 125 | 126 | But wait, there's more! 127 | 128 | ### Wildcard matchers 129 | 130 | This is very handy if you have a limited set of fields you actually want to include. 131 | 132 | ```java 133 | import com.monitorjbl.json.JsonView; 134 | import static com.monitorjbl.json.Match.match; 135 | 136 | //get a list of the objects 137 | List list = myObjectService.list(); 138 | 139 | String json = mapper.writeValueAsString(JsonView.with(list).onClass(MyObject.class, match() 140 | .exclude("*") 141 | .include("name"))); 142 | ``` 143 | 144 | Wildcards are implemented with trenary logic. If you specify a matcher without a wildcard, it will supercede any other matchers with a wildcard. 145 | 146 | ### Class matchers 147 | 148 | You can also ignore fields on classes referenced by a class! Simply reference the field in a dot-path to do this. In the below example, the field `id` on the class `MySmallObject` is ignored: 149 | 150 | ```java 151 | import com.monitorjbl.json.JsonView; 152 | import static com.monitorjbl.json.Match.match; 153 | 154 | List list = myObjectService.list(); 155 | 156 | String json = mapper.writeValueAsString(JsonView.with(list).onClass(MyObject.class, match() 157 | .exclude("smallObj.id") 158 | .exclude("contains"))); 159 | ``` 160 | 161 | Alternatively, you can make a separate matcher for other classes: 162 | 163 | ```java 164 | import com.monitorjbl.json.JsonView; 165 | import static com.monitorjbl.json.Match.match; 166 | 167 | //get a list of the objects 168 | List list = myObjectService.list(); 169 | 170 | String json = mapper.writeValueAsString(JsonView.with(list) 171 | .onClass(MyObject.class, match() 172 | .exclude("contains")) 173 | .onClass(MySmallObject.class, match() 174 | .exclude("id")); 175 | ``` 176 | 177 | ## Custom Serializers 178 | 179 | Due to the way json-view works, it must assume that it can serialize any class (except for certain [special types](json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java#L169). If you want to use another custom serializer alongside `JsonViewSerializer`, you must explicitly register them with the `JsonViewSerializer` instance. This is a little backwards compared to the way normal registration works, but its unfortunately necessary. However, the `JsonViewModule` class provides an easy way to do this: 180 | 181 | ```java 182 | ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule() 183 | .registerSerializer(Date.class, new MyCustomDateSerializer()) 184 | .registerSerializer(URL.class, new MyCustomURLSerializer())); 185 | ``` 186 | 187 | ## Field Transformations 188 | 189 | If you have a field that needs to be transformed in a programatic way, there are ways to do so [inside Jackson](https://stackoverflow.com/a/12046979). These are generally intended to be static transformations, and while they can be used in a dynamic way, they often are simply painful to use. json-view can be used to dynamically perform transforms with lambdas: 190 | 191 | ```java 192 | JsonView.with(ref) 193 | .onClass(TestObject.class, match() 194 | .exclude("*") 195 | .include("str1") 196 | .transform("str1", (TestObject t, String f) -> f.toUpperCase())) 197 | ``` 198 | 199 | ## Rules 200 | 201 | The `JsonView` object is built to make it simple to include/exclude fields from your POJOs. However, when parsing your specified config, you should be aware of the following rules: 202 | 203 | 1. Matching logic is trenary and wildcard matches are "less true" than specific matches. 204 | 2. `includes()` supercedes `excludes()` on equivalent level of matches. 205 | 3. Class inheritance is respected. If you `match()` on a parent class's field, it will be respected without needing a separate `match()` for the parent class. 206 | 4. Higher class specificity in `Match.match()` overrides lower and it is *not* field-based; use of a matcher is an all-or-nothing affair based on the class for which you declare it to be used. Here are a couple of examples where this is important to keep in mind: 207 | 1. If you provide matchers for both your class *and* its parent class, the parent's matcher will be used. 208 | 2. If you provide matchers for Class A and Class B, and Class A has a field typed Class B, the following will occur 209 | 1. If the matcher for Class A references the field in Class A, Class A's matcher will be respected 210 | 2. If the matcher for Class A references fields in Class B with a path, Class B's matcher will be respected 211 | 5. `@JsonIgnore` on fields (not methods) and `@JsonIgnoreProperties` are respected, unless overridden by `include()`. 212 | 6. All serialization is done via fields only. There is no current support for method-based serialization. 213 | 214 | # Spring Integration 215 | 216 | The Spring integration is really a `ThreadLocal` wrapper around the `JsonView` object. 217 | 218 | ## Including 219 | 220 | To use it, simply add this project to your classpath using your build tool of choice. This project is available on Maven Central, so if you're using Maven you can just add this to your pom.xml: 221 | 222 | ```xml 223 | 224 | com.monitorjbl 225 | spring-json-view 226 | 1.0.1 227 | 228 | ``` 229 | 230 | ## Configuration 231 | 232 | A word of warning: this project was built for Spring 4+, integration with Spring 3 is not supported yet. Make sure you're using the correct version. If you are, just add it to your context as a bean: 233 | 234 | **Java config** 235 | ```java 236 | @EnableWebMvc 237 | @Configuration 238 | public class Context extends WebMvcConfigurerAdapter { 239 | @Bean 240 | public JsonViewSupportFactoryBean views() { 241 | return new JsonViewSupportFactoryBean(); 242 | } 243 | } 244 | ``` 245 | 246 | **XML config** 247 | ```xml 248 | 249 | ``` 250 | 251 | ## Usage 252 | 253 | Using it is very simple: 254 | 255 | ```java 256 | import com.monitorjbl.json.JsonResult; 257 | import com.monitorjbl.json.JsonView; 258 | import com.monitorjbl.json.Match; 259 | import com.monitorjbl.json.model.TestObject; 260 | import org.springframework.stereotype.Controller; 261 | import org.springframework.web.bind.annotation.RequestMapping; 262 | import org.springframework.web.bind.annotation.RequestMethod; 263 | import org.springframework.web.bind.annotation.ResponseBody; 264 | 265 | import java.util.List; 266 | 267 | @Controller 268 | public class JsonController { 269 | private JsonResult json = JsonResult.instance(); 270 | @Autowired 271 | private TestObjectService service; 272 | 273 | @RequestMapping(method = RequestMethod.GET, value = "/bean") 274 | @ResponseBody 275 | public void getTestObject() { 276 | List list = service.list(); 277 | 278 | json.use(JsonView.with(list) 279 | .onClass(TestObject.class, Match.match() 280 | .exclude("int1") 281 | .include("ignoredDirect"))); 282 | } 283 | } 284 | ``` 285 | 286 | ## Return value 287 | 288 | While the return value of the method isn't actually used with this library, documentation libraries like Swagger may depend on it being present. To make life simpler, you can simply tack on a `.returnValue()` to the end to grab the object you're manipulating: 289 | 290 | ```java 291 | import com.monitorjbl.json.JsonResult; 292 | import com.monitorjbl.json.JsonView; 293 | import com.monitorjbl.json.Match; 294 | import com.monitorjbl.json.model.TestObject; 295 | import org.springframework.stereotype.Controller; 296 | import org.springframework.web.bind.annotation.RequestMapping; 297 | import org.springframework.web.bind.annotation.RequestMethod; 298 | import org.springframework.web.bind.annotation.ResponseBody; 299 | 300 | import java.util.List; 301 | 302 | @Controller 303 | public class JsonController { 304 | private JsonResult json = JsonResult.instance(); 305 | @Autowired 306 | private TestObjectService service; 307 | 308 | @RequestMapping(method = RequestMethod.GET, value = "/bean") 309 | @ResponseBody 310 | public List getTestObject() { 311 | List list = service.list(); 312 | 313 | return json.use(JsonView.with(list) 314 | .onClass(TestObject.class, Match.match() 315 | .exclude("int1") 316 | .include("ignoredDirect"))) 317 | .returnValue(); 318 | } 319 | } 320 | ``` 321 | 322 | ## Default views 323 | 324 | If you would like to set common views for specific classes, simply include a `DefaultView` instance in the `JsonViewSupportFactoryBean`. 325 | 326 | **Java config** 327 | ```java 328 | @EnableWebMvc 329 | @Configuration 330 | public class Context extends WebMvcConfigurerAdapter { 331 | @Bean 332 | public JsonViewSupportFactoryBean views() { 333 | return new JsonViewSupportFactoryBean(DefaultView.create() 334 | .onClass(TestObject.class, Match.match() 335 | .exclude("int1") 336 | .include("ignoredDirect"))); 337 | } 338 | } 339 | ``` 340 | 341 | **XML config** 342 | 343 | For a real example, look at the following test files: 344 | 345 | * [DefaultViewFactory](spring-json-view/src/test/java/com/monitorjbl/json/server/DefaultViewFactory.java) 346 | * [XML configuration](spring-json-view/src/test/resources/context.xml) 347 | 348 | ```xml 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | ``` 357 | 358 | # Building from source 359 | 360 | To build, all you need is Java 8+, Maven 3+, and git: 361 | 362 | ``` 363 | # Checkout code from GitHub 364 | git clone https://github.com/monitorjbl/json-view.git 365 | cd json-view 366 | 367 | # Build and install to local Maven repo 368 | mvn clean install 369 | ``` 370 | 371 | Once you've done this, you can refer to the latest version of the library in your POM, like so: 372 | 373 | ``` 374 | 375 | com.monitorjbl 376 | json-view 377 | 1.0.1 378 | 379 | ``` 380 | -------------------------------------------------------------------------------- /json-view/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.monitorjbl 8 | json-view 9 | 1.1.0 10 | json-view 11 | Provides programmatic exclusion/inclusion for Jackson JSON serialization 12 | https://github.com/monitorjbl/json-view 13 | 14 | 15 | UTF-8 16 | 2.10.5 17 | 2.10.5.1 18 | 19 | 20 | 21 | 22 | monitorjbl 23 | Taylor Jones 24 | monitorjbl@gmail.com 25 | 26 | 27 | 28 | 29 | 30 | GPLv3 31 | https://raw.githubusercontent.com/monitorjbl/json-view/master/LICENSE 32 | repo 33 | 34 | 35 | 36 | 37 | https://github.com/monitorjbl/json-view.git 38 | 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-compiler-plugin 45 | 3.2 46 | 47 | 1.8 48 | 1.8 49 | 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-javadoc-plugin 54 | 2.10.1 55 | 56 | 57 | attach-sources 58 | 59 | jar 60 | 61 | 62 | 63 | 64 | 65 | org.apache.maven.plugins 66 | maven-source-plugin 67 | 2.2.1 68 | 69 | 70 | attach-sources 71 | 72 | jar 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | default 83 | 84 | true 85 | 86 | 87 | 88 | 89 | org.apache.maven.plugins 90 | maven-surefire-plugin 91 | 2.19.1 92 | 93 | 94 | JsonViewSerializerPerformanceTest.java 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | release 103 | 104 | false 105 | 106 | 107 | 108 | 109 | org.apache.maven.plugins 110 | maven-gpg-plugin 111 | 1.6 112 | 113 | 114 | sign-artifacts 115 | verify 116 | 117 | sign 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | ossrh 130 | https://oss.sonatype.org/content/repositories/snapshots 131 | 132 | 133 | ossrh 134 | https://oss.sonatype.org/service/local/staging/deploy/maven2 135 | 136 | 137 | 138 | 139 | 140 | com.fasterxml.jackson.core 141 | jackson-core 142 | ${jackson.version} 143 | provided 144 | 145 | 146 | com.fasterxml.jackson.core 147 | jackson-databind 148 | ${jackson.databind.version} 149 | provided 150 | 151 | 152 | 153 | 154 | junit 155 | junit 156 | 4.11 157 | test 158 | 159 | 160 | com.google.guava 161 | guava 162 | 18.0 163 | test 164 | 165 | 166 | org.apache.commons 167 | commons-math3 168 | 3.5 169 | test 170 | 171 | 172 | org.apache.commons 173 | commons-lang3 174 | 3.4 175 | test 176 | 177 | 178 | org.mockito 179 | mockito-all 180 | 1.10.19 181 | test 182 | 183 | 184 | org.powermock 185 | powermock-api-mockito 186 | 1.6.2 187 | test 188 | 189 | 190 | org.powermock 191 | powermock-module-junit4 192 | 1.6.2 193 | test 194 | 195 | 196 | org.slf4j 197 | slf4j-api 198 | 1.7.21 199 | test 200 | 201 | 202 | org.slf4j 203 | slf4j-log4j12 204 | 1.7.21 205 | test 206 | 207 | 208 | com.fasterxml.jackson.module 209 | jackson-module-parameter-names 210 | ${jackson.version} 211 | test 212 | 213 | 214 | com.fasterxml.jackson.datatype 215 | jackson-datatype-jdk8 216 | ${jackson.version} 217 | test 218 | 219 | 220 | com.fasterxml.jackson.datatype 221 | jackson-datatype-jsr310 222 | ${jackson.version} 223 | test 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/JsonView.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Objects; 6 | 7 | /** 8 | * Allows runtime alteration of JSON responses 9 | */ 10 | public class JsonView { 11 | protected final T value; 12 | protected final Map, Match> matches = new HashMap<>(); 13 | protected MatcherBehavior matcherBehavior; 14 | 15 | protected JsonView(T value) { 16 | this.value = value; 17 | } 18 | 19 | T getValue() { 20 | return value; 21 | } 22 | 23 | Match getMatch(Class cls) { 24 | return matches.get(cls); 25 | } 26 | 27 | public JsonView onClass(Class cls, Match match) { 28 | matches.put(cls, match); 29 | return this; 30 | } 31 | 32 | public JsonView withMatcherBehavior(MatcherBehavior matcherBehavior) { 33 | this.matcherBehavior = matcherBehavior; 34 | return this; 35 | } 36 | 37 | @Override 38 | public boolean equals(Object o) { 39 | if(this == o) return true; 40 | if(o == null || getClass() != o.getClass()) return false; 41 | JsonView jsonView = (JsonView) o; 42 | return Objects.equals(matches, jsonView.matches) && 43 | matcherBehavior == jsonView.matcherBehavior; 44 | } 45 | 46 | @Override 47 | public int hashCode() { 48 | return Objects.hash(matches, matcherBehavior); 49 | } 50 | 51 | public static JsonView with(E value) { 52 | return new JsonView<>(value); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/JsonViewModule.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.core.Version; 4 | import com.fasterxml.jackson.databind.JsonSerializer; 5 | import com.fasterxml.jackson.databind.module.SimpleModule; 6 | 7 | public class JsonViewModule extends SimpleModule { 8 | 9 | private final JsonViewSerializer jsonView; 10 | 11 | public JsonViewModule() { 12 | this(new JsonViewSerializer()); 13 | } 14 | 15 | public JsonViewModule(JsonViewSerializer jsonView) { 16 | super(new Version(0, 16, 0, "", "com.monitorjbl", "json-view")); 17 | addSerializer(JsonView.class, jsonView); 18 | this.jsonView = jsonView; 19 | } 20 | 21 | public JsonViewModule withDefaultMatcherBehavior(MatcherBehavior matcherBehavior){ 22 | this.jsonView.setDefaultMatcherBehavior(matcherBehavior); 23 | return this; 24 | } 25 | 26 | public JsonViewModule registerSerializer(Class cls, JsonSerializer serializer) { 27 | jsonView.registerCustomSerializer(cls, serializer); 28 | return this; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.JsonBackReference; 5 | import com.fasterxml.jackson.annotation.JsonIgnore; 6 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 7 | import com.fasterxml.jackson.annotation.JsonInclude; 8 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 9 | import com.fasterxml.jackson.annotation.JsonManagedReference; 10 | import com.fasterxml.jackson.annotation.JsonProperty; 11 | import com.fasterxml.jackson.core.JsonGenerator; 12 | import com.fasterxml.jackson.databind.JsonNode; 13 | import com.fasterxml.jackson.databind.JsonSerializer; 14 | import com.fasterxml.jackson.databind.SerializerProvider; 15 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 16 | import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; 17 | 18 | import java.io.IOException; 19 | import java.lang.annotation.Annotation; 20 | import java.lang.reflect.Field; 21 | import java.lang.reflect.InvocationTargetException; 22 | import java.lang.reflect.Method; 23 | import java.lang.reflect.Modifier; 24 | import java.math.BigDecimal; 25 | import java.net.URI; 26 | import java.net.URL; 27 | import java.time.temporal.Temporal; 28 | import java.util.ArrayList; 29 | import java.util.Date; 30 | import java.util.HashMap; 31 | import java.util.HashSet; 32 | import java.util.LinkedHashMap; 33 | import java.util.List; 34 | import java.util.Map; 35 | import java.util.Objects; 36 | import java.util.Optional; 37 | import java.util.Set; 38 | import java.util.Stack; 39 | import java.util.UUID; 40 | import java.util.function.Function; 41 | import java.util.function.Predicate; 42 | import java.util.regex.Pattern; 43 | import java.util.stream.Collectors; 44 | import java.util.stream.Stream; 45 | 46 | import static com.monitorjbl.json.MatcherBehavior.CLASS_FIRST; 47 | import static com.monitorjbl.json.MatcherBehavior.PATH_FIRST; 48 | import static java.util.Arrays.asList; 49 | 50 | public class JsonViewSerializer extends JsonSerializer { 51 | public static boolean log = false; 52 | /** 53 | * Cached results from expensive (pure) methods 54 | */ 55 | private final Memoizer memoizer; 56 | 57 | /** 58 | * Map of custom serializers to take into account when serializing fields. 59 | */ 60 | private Map, JsonSerializer> customSerializersMap = null; 61 | 62 | private MatcherBehavior defaultMatcherBehavior = CLASS_FIRST; 63 | 64 | public JsonViewSerializer() { 65 | this(1024); 66 | } 67 | 68 | public JsonViewSerializer(int maxCacheSize) { 69 | this.memoizer = new Memoizer(maxCacheSize); 70 | } 71 | 72 | /** 73 | * Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.
74 | * This way you could register for instance a JODA serialization as a DateTimeSerializer.
75 | * Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.
76 | * Example:
77 | * 78 | * JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); 79 | * bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); 80 | * 81 | * 82 | * @param Type class of the serializer 83 | * @param cls {@link Class} The class type you want to add a custom serializer 84 | * @param forType {@link JsonSerializer} The serializer you want to apply for that type 85 | */ 86 | @SuppressWarnings("unchecked") 87 | public void registerCustomSerializer(Class cls, JsonSerializer forType) { 88 | if(customSerializersMap == null) { 89 | customSerializersMap = new HashMap<>(); 90 | } 91 | 92 | if(cls == null) { 93 | throw new IllegalArgumentException("Class must not be null"); 94 | } else if(cls.equals(JsonView.class)) { 95 | throw new IllegalArgumentException("Class cannot be " + JsonView.class); 96 | } else if(customSerializersMap.containsKey(cls)) { 97 | throw new IllegalArgumentException("Class " + cls + " already has a serializer registered (" + customSerializersMap.get(cls) + ")"); 98 | } 99 | 100 | customSerializersMap.put(cls, (JsonSerializer) forType); 101 | } 102 | 103 | /** 104 | * Unregister a previously registered serializer. @see registerCustomSerializer 105 | * 106 | * @param cls The class type the serializer was registered for 107 | */ 108 | public void unregisterCustomSerializer(Class cls) { 109 | if(customSerializersMap != null) { 110 | customSerializersMap.remove(cls); 111 | } 112 | } 113 | 114 | /** 115 | * Set the default matcher behavior to be used if the {@link JsonView} object to 116 | * be serialized does not specify one. 117 | * 118 | * @param defaultMatcherBehavior The default behavior to use 119 | */ 120 | public void setDefaultMatcherBehavior(MatcherBehavior defaultMatcherBehavior) { 121 | this.defaultMatcherBehavior = defaultMatcherBehavior; 122 | } 123 | 124 | @Override 125 | public void serialize(JsonView result, JsonGenerator jgen, SerializerProvider serializers) throws IOException { 126 | new JsonWriter(serializers, jgen, result).write(null, result.getValue()); 127 | } 128 | 129 | class JsonWriter { 130 | Stack path = new Stack<>(); 131 | String currentPath = ""; 132 | Match currentMatch = null; 133 | AccessibleProperty referringField = null; 134 | 135 | final SerializerProvider serializerProvider; 136 | final JsonGenerator jgen; 137 | final JsonView result; 138 | 139 | JsonWriter(SerializerProvider serializerProvider, JsonGenerator jgen, JsonView result) { 140 | this.serializerProvider = serializerProvider; 141 | this.jgen = jgen; 142 | this.result = result; 143 | } 144 | 145 | //internal use only to encapsulate what the current state was 146 | private JsonWriter(JsonGenerator jgen, JsonView result, Match currentMatch, SerializerProvider serializerProvider) { 147 | this.jgen = jgen; 148 | this.result = result; 149 | this.currentMatch = currentMatch; 150 | this.serializerProvider = serializerProvider; 151 | } 152 | 153 | //internal use only to encapsulate what the current state was 154 | private JsonWriter(JsonGenerator jgen, JsonView result, Match currentMatch, 155 | String currentPath, Stack path, AccessibleProperty referringField, SerializerProvider serializerProvider) { 156 | this.jgen = jgen; 157 | this.result = result; 158 | this.currentMatch = currentMatch; 159 | this.currentPath = currentPath; 160 | this.referringField = referringField; 161 | this.path = path; 162 | this.serializerProvider = serializerProvider; 163 | } 164 | 165 | boolean writePrimitive(Object obj) throws IOException { 166 | if(obj instanceof String) { 167 | jgen.writeString((String) obj); 168 | } else if(obj instanceof Integer) { 169 | jgen.writeNumber((Integer) obj); 170 | } else if(obj instanceof Long) { 171 | jgen.writeNumber((Long) obj); 172 | } else if(obj instanceof Short) { 173 | jgen.writeNumber((Short) obj); 174 | } else if(obj instanceof Double) { 175 | jgen.writeNumber((Double) obj); 176 | } else if(obj instanceof Float) { 177 | jgen.writeNumber((Float) obj); 178 | } else if(obj instanceof Character) { 179 | jgen.writeNumber((Character) obj); 180 | } else if(obj instanceof Byte) { 181 | jgen.writeNumber((Byte) obj); 182 | } else if(obj instanceof Boolean) { 183 | jgen.writeBoolean((Boolean) obj); 184 | } else if(obj == null) { 185 | jgen.writeNull(); 186 | } else if(obj instanceof BigDecimal) { 187 | jgen.writeNumber((BigDecimal) obj); 188 | } else { 189 | return false; 190 | } 191 | return true; 192 | } 193 | 194 | boolean writeSpecial(Object obj) throws IOException { 195 | if(obj instanceof Date) { 196 | serializerProvider.defaultSerializeDateValue((Date) obj, jgen); 197 | } else if(obj instanceof Temporal) { 198 | serializerProvider.defaultSerializeValue(obj, jgen); 199 | } else if(obj instanceof URL) { 200 | jgen.writeString(obj.toString()); 201 | } else if(obj instanceof URI) { 202 | jgen.writeString(obj.toString()); 203 | } else if(obj instanceof UUID) { 204 | jgen.writeString(obj.toString()); 205 | } else if(obj instanceof Class) { 206 | jgen.writeString(((Class) obj).getCanonicalName()); 207 | } else { 208 | return false; 209 | } 210 | return true; 211 | } 212 | 213 | boolean writeEnum(Object obj) throws IOException { 214 | if(obj.getClass().isEnum()) { 215 | jgen.writeString(((Enum) obj).name()); 216 | } else { 217 | return false; 218 | } 219 | return true; 220 | } 221 | 222 | @SuppressWarnings("unchecked") 223 | boolean writeList(Object obj) throws IOException { 224 | if(obj instanceof List || obj instanceof Set || obj.getClass().isArray()) { 225 | Iterable iter; 226 | if(obj.getClass().isArray()) { 227 | if(obj instanceof byte[]) { 228 | jgen.writeBinary((byte[]) obj); 229 | return true; 230 | } else { 231 | iter = convertArray(obj); 232 | } 233 | } else { 234 | iter = (Iterable) obj; 235 | } 236 | 237 | jgen.writeStartArray(); 238 | for(Object o : iter) { 239 | new JsonWriter(jgen, result, currentMatch, currentPath, path, referringField, serializerProvider).write(null, o); 240 | } 241 | jgen.writeEndArray(); 242 | } else { 243 | return false; 244 | } 245 | return true; 246 | } 247 | 248 | @SuppressWarnings("unchecked") 249 | Iterable convertArray(Object obj) { 250 | Iterable iter; 251 | if(obj instanceof int[]) { 252 | int[] arr = (int[]) obj; 253 | iter = new ArrayList<>(); 254 | for(int v : arr) { 255 | ((List) iter).add(v); 256 | } 257 | } else if(obj instanceof double[]) { 258 | double[] arr = (double[]) obj; 259 | iter = new ArrayList<>(); 260 | for(double v : arr) { 261 | ((List) iter).add(v); 262 | } 263 | } else if(obj instanceof float[]) { 264 | float[] arr = (float[]) obj; 265 | iter = new ArrayList<>(); 266 | for(float v : arr) { 267 | ((List) iter).add(v); 268 | } 269 | } else if(obj instanceof long[]) { 270 | long[] arr = (long[]) obj; 271 | iter = new ArrayList<>(); 272 | for(long v : arr) { 273 | ((List) iter).add(v); 274 | } 275 | } else if(obj instanceof short[]) { 276 | short[] arr = (short[]) obj; 277 | iter = new ArrayList<>(); 278 | for(short v : arr) { 279 | ((List) iter).add(v); 280 | } 281 | } else if(obj instanceof char[]) { 282 | char[] arr = (char[]) obj; 283 | iter = new ArrayList<>(); 284 | for(char v : arr) { 285 | ((List) iter).add(v); 286 | } 287 | } else if(obj instanceof boolean[]) { 288 | boolean[] arr = (boolean[]) obj; 289 | iter = new ArrayList<>(); 290 | for(boolean v : arr) { 291 | ((List) iter).add(v); 292 | } 293 | } else { 294 | iter = asList((Object[]) obj); 295 | } 296 | return iter; 297 | } 298 | 299 | @SuppressWarnings("unchecked") 300 | boolean writeMap(Object obj) throws IOException { 301 | if(obj instanceof Map) { 302 | Map map = (Map) obj; 303 | 304 | jgen.writeStartObject(); 305 | for(Object key : map.keySet()) { 306 | jgen.writeFieldName(key.toString()); 307 | new JsonWriter(jgen, result, currentMatch, serializerProvider).write(null, map.get(key)); 308 | } 309 | jgen.writeEndObject(); 310 | } else { 311 | return false; 312 | } 313 | return true; 314 | } 315 | 316 | @SuppressWarnings("unchecked") 317 | void writeObject(Object obj) throws IOException { 318 | jgen.writeStartObject(); 319 | 320 | List fields = getAccessibleProperties(obj.getClass()); 321 | 322 | for(AccessibleProperty property : fields) { 323 | try { 324 | //if the field has a serializer annotation on it, serialize with it 325 | if(fieldAllowed(property, obj.getClass())) { 326 | Object val = readField(obj, property); 327 | if(!valueAllowed(property, val, obj.getClass())) { 328 | continue; 329 | } 330 | 331 | String name = getFieldName(property); 332 | jgen.writeFieldName(name); 333 | 334 | JsonSerializer fieldSerializer = annotatedWithJsonSerialize(property); 335 | if(fieldSerializer != null) { 336 | fieldSerializer.serialize(val, jgen, serializerProvider); 337 | } else if(customSerializersMap != null && val != null) { 338 | JsonSerializer serializer = customSerializersMap.get(val.getClass()); 339 | if(serializer != null) { 340 | serializer.serialize(val, jgen, serializerProvider); 341 | } else { 342 | new JsonWriter(jgen, result, currentMatch, currentPath, path, property, serializerProvider).write(name, val); 343 | } 344 | } else if(val instanceof JsonNode) { 345 | // Let Jackson deal with these, they're special 346 | serializerProvider.defaultSerializeValue(val, jgen); 347 | } else { 348 | new JsonWriter(jgen, result, currentMatch, currentPath, path, property, serializerProvider).write(name, val); 349 | } 350 | } 351 | } catch(IllegalArgumentException | IllegalAccessException e) { 352 | throw new RuntimeException(e); 353 | } 354 | } 355 | 356 | jgen.writeEndObject(); 357 | } 358 | 359 | boolean valueAllowed(AccessibleProperty property, Object value, Class cls) { 360 | Include defaultInclude = serializerProvider.getConfig() == null ? Include.ALWAYS : serializerProvider.getConfig().getSerializationInclusion(); 361 | JsonInclude jsonInclude = getAnnotation(property, JsonInclude.class); 362 | JsonSerialize jsonSerialize = getAnnotation(cls, JsonSerialize.class); 363 | 364 | // Make sure local annotations win over global ones 365 | if(jsonInclude != null && jsonInclude.value() == Include.NON_NULL && value == null) { 366 | return false; 367 | } 368 | 369 | return value != null 370 | || (defaultInclude == Include.ALWAYS && jsonSerialize == null) 371 | || (jsonSerialize != null && jsonSerialize.include() == Inclusion.ALWAYS); 372 | } 373 | 374 | /** 375 | * Do a search for *all* matchers for a class. This takes into account all relevant 376 | * parents in the class hierarchy. If multiple matches are found, the matches will 377 | * be unioned together. 378 | */ 379 | @SuppressWarnings("unchecked") 380 | private Optional classMatchSearch(Class declaringClass) { 381 | // return memoizer.classMatches(result, declaringClass, () -> { 382 | List matches = new ArrayList<>(); 383 | Stack classes = new Stack<>(); 384 | classes.push(declaringClass); 385 | while(!classes.isEmpty()) { 386 | Class cls = classes.pop(); 387 | Match match = result.getMatch(cls); 388 | 389 | if(match != null) { 390 | matches.add(match); 391 | } 392 | if(cls.getInterfaces() != null) { 393 | Stream.of(cls.getInterfaces()).forEach(c -> classes.push(c)); 394 | } 395 | if(cls.getSuperclass() != null && !cls.getSuperclass().equals(Object.class)) { 396 | classes.push(cls.getSuperclass()); 397 | } 398 | } 399 | 400 | if(matches.size() == 1) { 401 | return Optional.of(matches.get(0)); 402 | } else if(matches.size() > 1) { 403 | // Join all the includes and excludes 404 | Match unionMatch = new Match(); 405 | matches.forEach(m -> { 406 | unionMatch.getExcludes().addAll(m.getExcludes()); 407 | unionMatch.getIncludes().addAll(m.getIncludes()); 408 | unionMatch.getTransforms().putAll(m.getTransforms()); 409 | }); 410 | return Optional.of(unionMatch); 411 | } else { 412 | return Optional.empty(); 413 | } 414 | // }); 415 | } 416 | 417 | @SuppressWarnings("unchecked") 418 | boolean fieldAllowed(AccessibleProperty property, Class declaringClass) { 419 | String name = property.name; 420 | if(Modifier.isStatic(property.modifiers)) { 421 | return false; 422 | } 423 | 424 | MatchPrefixTuple tuple = getMatchPrefix(declaringClass); 425 | String prefix = tuple.prefix; 426 | Match match = tuple.match; 427 | 428 | //if there is a match, respect it 429 | if(match != null) { 430 | 431 | if(currentMatch == null) { 432 | currentMatch = match; 433 | } 434 | 435 | int included = containsMatchingPattern(match.getIncludes(), prefix + name, true); 436 | int excluded = containsMatchingPattern(match.getExcludes(), prefix + name, false); 437 | 438 | /* 439 | The logic for this is a little complex. We're dealing with ternary logic to 440 | properly handle wildcard matches. We want matches made with wildcards to be 441 | overruled by matches without them. 442 | */ 443 | if(included == 1) { 444 | return true; 445 | } else if(excluded == 1) { 446 | return false; 447 | } else if(included == 0) { 448 | return true; 449 | } else if(excluded == 0) { 450 | return false; 451 | } else { 452 | return !annotatedWithIgnore(property); 453 | } 454 | } else { 455 | //else, respect JsonIgnore only 456 | return !annotatedWithIgnore(property); 457 | } 458 | } 459 | 460 | MatchPrefixTuple getMatchPrefix(Class declaringClass) { 461 | String prefix = currentPath.length() > 0 ? currentPath + "." : ""; 462 | 463 | // Determine matcher behavior 464 | MatcherBehavior currentBehavior = result.matcherBehavior; 465 | if(currentBehavior == null) { 466 | currentBehavior = JsonViewSerializer.this.defaultMatcherBehavior; 467 | } 468 | 469 | //search for matching class 470 | Match match = null; 471 | if(currentBehavior == CLASS_FIRST) { 472 | match = classMatchSearch(declaringClass).orElse(null); 473 | if(match == null) { 474 | match = currentMatch; 475 | } else { 476 | prefix = ""; 477 | } 478 | } else if(currentBehavior == PATH_FIRST) { 479 | if(currentMatch != null) { 480 | match = currentMatch; 481 | } else { 482 | match = classMatchSearch(declaringClass).orElse(null); 483 | prefix = ""; 484 | } 485 | } 486 | 487 | return new MatchPrefixTuple(match, prefix); 488 | } 489 | 490 | Object readField(Object obj, AccessibleProperty field) throws IllegalAccessException { 491 | MatchPrefixTuple tuple = getMatchPrefix(obj.getClass()); 492 | if(tuple.match != null && tuple.match.getTransforms().containsKey(tuple.prefix + field.name)) { 493 | return tuple.match.getTransforms().get(tuple.prefix + field.name).apply(obj, field.get(obj)); 494 | } else { 495 | return field.get(obj); 496 | } 497 | } 498 | 499 | void write(String fieldName, Object value) throws IOException { 500 | if(fieldName != null) { 501 | path.push(fieldName); 502 | updateCurrentPath(); 503 | } 504 | 505 | //try to handle all primitives/special cases before treating this as json object 506 | if(!writePrimitive(value) && !writeSpecial(value) && !writeEnum(value) && !writeList(value) && !writeMap(value)) { 507 | writeObject(value); 508 | } 509 | 510 | if(fieldName != null) { 511 | path.pop(); 512 | updateCurrentPath(); 513 | } 514 | } 515 | 516 | void updateCurrentPath() { 517 | StringBuilder builder = new StringBuilder(); 518 | for(String s : path) { 519 | builder.append("."); 520 | builder.append(s); 521 | } 522 | currentPath = builder.length() > 0 ? builder.toString().substring(1) : ""; 523 | } 524 | 525 | @SuppressWarnings("unchecked") 526 | E readClassAnnotation(Class cls, Class annotationType, String methodName) { 527 | try { 528 | for(Annotation an : getAnnotations(cls)) { 529 | Class type = an.annotationType(); 530 | if(an.annotationType().equals(annotationType)) { 531 | for(Method method : type.getDeclaredMethods()) { 532 | if(method.getName().equals(methodName)) { 533 | return (E) method.invoke(an, (Object[]) null); 534 | } 535 | } 536 | throw new IllegalArgumentException("Method " + methodName + " not found on annotation " + annotationType); 537 | } 538 | } 539 | throw new IllegalArgumentException("Annotation " + annotationType + " not found on class " + cls); 540 | } catch(InvocationTargetException | IllegalAccessException e) { 541 | throw new RuntimeException(e); 542 | } 543 | } 544 | 545 | /** 546 | * Returns one of the following values: 547 | *
548 |      * -1: No match found
549 |      *  0: Wildcard-based match
550 |      *  1: Non-wildcard match
551 |      * 
552 | *

553 | * This method is memoized to speed up execution time 554 | */ 555 | int containsMatchingPattern(Set values, String pattern, boolean matchPrefix) { 556 | return memoizer.matches(values, pattern, matchPrefix, () -> { 557 | int match = -1; 558 | for(String val : values) { 559 | String replaced = val.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"); 560 | if(Pattern.compile(replaced).matcher(pattern).matches() || (matchPrefix && val.startsWith(pattern + "."))) { 561 | match = replaced.contains("*") ? 0 : 1; 562 | break; 563 | } 564 | } 565 | return match; 566 | }); 567 | } 568 | 569 | /** 570 | * Returns a boolean indicating whether the provided field is annotated with 571 | * some form of ignore. This method is memoized to speed up execution time 572 | */ 573 | boolean annotatedWithIgnore(AccessibleProperty f) { 574 | return memoizer.annotatedWithIgnore(f, () -> { 575 | JsonIgnore jsonIgnore = getAnnotation(f, JsonIgnore.class); 576 | JsonIgnoreProperties classIgnoreProperties = getAnnotation(f.declaringClass, JsonIgnoreProperties.class); 577 | JsonIgnoreProperties fieldIgnoreProperties = null; 578 | boolean backReferenced = false; 579 | 580 | //make sure the referring field didn't specify properties to ignore 581 | if(referringField != null) { 582 | fieldIgnoreProperties = getAnnotation(referringField, JsonIgnoreProperties.class); 583 | } 584 | 585 | //make sure the referring field didn't specify a backreference annotation 586 | if(getAnnotation(f, JsonBackReference.class) != null && referringField != null) { 587 | for(AccessibleProperty lastField : getAccessibleProperties(referringField.declaringClass)) { 588 | JsonManagedReference fieldManagedReference = getAnnotation(lastField, JsonManagedReference.class); 589 | if(fieldManagedReference != null && lastField.type.equals(f.declaringClass)) { 590 | backReferenced = true; 591 | break; 592 | } 593 | } 594 | } 595 | 596 | return (jsonIgnore != null && jsonIgnore.value()) || 597 | (classIgnoreProperties != null && asList(classIgnoreProperties.value()).contains(f.name)) || 598 | (fieldIgnoreProperties != null && asList(fieldIgnoreProperties.value()).contains(f.name)) || 599 | backReferenced; 600 | }); 601 | } 602 | 603 | JsonSerializer annotatedWithJsonSerialize(AccessibleProperty property) { 604 | JsonSerialize jsonSerialize = getAnnotation(property, JsonSerialize.class); 605 | if(jsonSerialize != null) { 606 | if(!jsonSerialize.using().equals(JsonSerializer.None.class)) { 607 | try { 608 | return jsonSerialize.using().newInstance(); 609 | } catch(InstantiationException | IllegalAccessException e) { 610 | throw new RuntimeException(e); 611 | } 612 | } 613 | } 614 | return null; 615 | } 616 | 617 | private Class[] getInterfaces(Class cls) { 618 | return cls.getInterfaces(); 619 | } 620 | 621 | private List getAccessibleProperties(Class cls) { 622 | return memoizer.accessibleProperty(cls, () -> { 623 | // Gather all fields and methods 624 | Map accessibleProperties = new LinkedHashMap<>(); 625 | Predicate shouldProcessField = fieldVisibilityAllowed(cls); 626 | Predicate shouldProcessMethod = getterVisibilityAllowed(cls); 627 | Predicate visible = (o) -> { 628 | if(o instanceof Field) { 629 | return shouldProcessField.test((Field) o); 630 | } else if(o instanceof Method) { 631 | return shouldProcessMethod.test((Method) o); 632 | } else { 633 | throw new RuntimeException("Could not process property of type " + o.getClass()); 634 | } 635 | }; 636 | 637 | getDeclaredFields(cls).stream() 638 | .map(f -> new AccessibleProperty(f.getName(), f.getAnnotations(), f)) 639 | .forEach(p -> accessibleProperties.put(p.name, p)); 640 | getDeclaredMethods(cls).stream() 641 | .filter(m -> m.getName().startsWith("get") && !m.getReturnType().equals(Void.class) && m.getParameters().length == 0) 642 | .map(m -> new AccessibleProperty(getFieldNameFromGetter(m), m.getAnnotations(), m)) 643 | .forEach(p -> { 644 | AccessibleProperty field = accessibleProperties.get(p.name); 645 | 646 | // Combine annotations from the getter and the field 647 | if(field != null) { 648 | Set annotations = new HashSet(asList(field.annotations)); 649 | annotations.addAll(asList(p.annotations)); 650 | p = new AccessibleProperty(p.name, annotations.toArray(new Annotation[0]), p.property); 651 | } 652 | 653 | // TODO: Makes sure combined annotations are applied to the field when method visibility is disallowed 654 | if(shouldProcessMethod.test((Method) p.property)) { 655 | accessibleProperties.put(p.name, p); 656 | } 657 | }); 658 | 659 | return accessibleProperties.values().stream() 660 | .filter(p -> visible.test(p.property)) 661 | .collect(Collectors.toList()); 662 | }); 663 | } 664 | 665 | private List getDeclaredFields(Class cls) { 666 | List fields = new ArrayList<>(); 667 | Stack parents = new Stack<>(); 668 | parents.push(cls); 669 | 670 | while(!parents.isEmpty()) { 671 | Class c = parents.pop(); 672 | 673 | Stream.of(c.getDeclaredFields()).forEach(f -> fields.add(f)); 674 | 675 | if(c.getSuperclass() != null && !c.getSuperclass().equals(Object.class)) { 676 | parents.push(c.getSuperclass()); 677 | } 678 | } 679 | 680 | return fields; 681 | } 682 | 683 | private List getDeclaredMethods(Class cls) { 684 | List methods = new ArrayList<>(); 685 | Stack parents = new Stack<>(); 686 | parents.push(cls); 687 | 688 | while(!parents.isEmpty()) { 689 | Class c = parents.pop(); 690 | 691 | Stream.of(c.getDeclaredMethods()).forEach(m -> methods.add(m)); 692 | 693 | if(c.getSuperclass() != null && !c.getSuperclass().equals(Object.class)) { 694 | parents.push(c.getSuperclass()); 695 | } 696 | 697 | if(c.getInterfaces() != null) { 698 | Stream.of(c.getInterfaces()).forEach(i -> parents.push(i)); 699 | } 700 | } 701 | 702 | return methods; 703 | } 704 | 705 | private Annotation[] getAnnotations(Class cls) { 706 | return memoizer.annotations(cls, () -> { 707 | return cls.getAnnotations(); 708 | }); 709 | } 710 | 711 | @SuppressWarnings("unchecked") 712 | private T getAnnotation(Class cls, Class annotation) { 713 | Annotation[] annotations = getAnnotations(cls); 714 | if(annotations != null) { 715 | for(Annotation a : annotations) { 716 | if(a.annotationType().equals(annotation)) { 717 | return (T) a; 718 | } 719 | } 720 | } 721 | return null; 722 | } 723 | 724 | @SuppressWarnings("unchecked") 725 | private T getAnnotation(AccessibleProperty property, Class annotation) { 726 | if(property.annotations != null) { 727 | for(Annotation a : property.annotations) { 728 | if(a.annotationType().equals(annotation)) { 729 | return (T) a; 730 | } 731 | } 732 | } 733 | return null; 734 | } 735 | 736 | private Predicate fieldVisibilityAllowed(Class cls) { 737 | JsonAutoDetect autoDetect = getAnnotation(cls, JsonAutoDetect.class); 738 | 739 | if(autoDetect == null) { 740 | return f -> false; 741 | } else { 742 | switch(autoDetect.fieldVisibility()) { 743 | case ANY: 744 | return f -> true; 745 | case PUBLIC_ONLY: 746 | return f -> Modifier.isPublic(f.getModifiers()); 747 | case PROTECTED_AND_PUBLIC: 748 | return f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()); 749 | case NON_PRIVATE: 750 | return f -> !Modifier.isPrivate(f.getModifiers()); 751 | case DEFAULT: 752 | case NONE: 753 | return f -> false; 754 | default: 755 | throw new RuntimeException("No support for field visibility " + autoDetect.fieldVisibility()); 756 | } 757 | } 758 | } 759 | 760 | private Predicate getterVisibilityAllowed(Class cls) { 761 | JsonAutoDetect autoDetect = getAnnotation(cls, JsonAutoDetect.class); 762 | 763 | if(autoDetect == null) { 764 | return m -> true; 765 | } else { 766 | switch(autoDetect.getterVisibility()) { 767 | case DEFAULT: 768 | case ANY: 769 | return m -> true; 770 | case PUBLIC_ONLY: 771 | return m -> Modifier.isPublic(m.getModifiers()); 772 | case PROTECTED_AND_PUBLIC: 773 | return m -> Modifier.isPublic(m.getModifiers()) || Modifier.isProtected(m.getModifiers()); 774 | case NON_PRIVATE: 775 | return m -> !Modifier.isPrivate(m.getModifiers()); 776 | case NONE: 777 | return m -> false; 778 | default: 779 | throw new RuntimeException("No support for field visibility " + autoDetect.fieldVisibility()); 780 | } 781 | } 782 | } 783 | 784 | private String getFieldName(AccessibleProperty property) { 785 | JsonProperty jsonProperty = getAnnotation(property, JsonProperty.class); 786 | if(jsonProperty != null && jsonProperty.value().length() > 0) { 787 | return jsonProperty.value(); 788 | } else { 789 | return property.name; 790 | } 791 | } 792 | 793 | private String getFieldNameFromGetter(Method method) { 794 | if (method.getName().equals("get")) { 795 | return method.getName(); 796 | } 797 | String name = method.getName().replaceFirst("get", ""); 798 | return name.substring(0, 1).toLowerCase() + name.substring(1); 799 | } 800 | 801 | } 802 | 803 | private static class MatchPrefixTuple { 804 | private final Match match; 805 | private final String prefix; 806 | 807 | public MatchPrefixTuple(Match match, String prefix) { 808 | this.match = match; 809 | this.prefix = prefix; 810 | } 811 | } 812 | 813 | static class AccessibleProperty { 814 | public final Class declaringClass; 815 | public final String name; 816 | public final Class type; 817 | public final Annotation[] annotations; 818 | public final int modifiers; 819 | public final Object property; 820 | private final Function getter; 821 | 822 | public AccessibleProperty(String name, Annotation[] annotations, Object property) { 823 | this.name = name; 824 | this.annotations = annotations; 825 | this.property = property; 826 | 827 | if(property instanceof Field) { 828 | this.declaringClass = ((Field) property).getDeclaringClass(); 829 | this.type = ((Field) property).getType(); 830 | this.modifiers = ((Field) property).getModifiers(); 831 | this.getter = this::getFromField; 832 | } else if(property instanceof Method) { 833 | this.declaringClass = ((Method) property).getDeclaringClass(); 834 | this.type = ((Method) property).getReturnType(); 835 | this.modifiers = ((Method) property).getModifiers(); 836 | this.getter = this::getFromMethod; 837 | } else { 838 | throw new RuntimeException("Unable to access property from " + property); 839 | } 840 | } 841 | 842 | public Object get(Object obj) { 843 | return getter.apply(obj); 844 | } 845 | 846 | private Object getFromField(Object obj) { 847 | try { 848 | ((Field) property).setAccessible(true); 849 | return ((Field) property).get(obj); 850 | } catch(IllegalAccessException e) { 851 | throw new RuntimeException(e); 852 | } 853 | } 854 | 855 | private Object getFromMethod(Object obj) { 856 | try { 857 | ((Method) property).setAccessible(true); 858 | return ((Method) property).invoke(obj); 859 | } catch(IllegalAccessException | InvocationTargetException e) { 860 | throw new RuntimeException(e); 861 | } 862 | } 863 | 864 | @Override 865 | public boolean equals(Object o) { 866 | if(this == o) return true; 867 | if(o == null || getClass() != o.getClass()) return false; 868 | AccessibleProperty that = (AccessibleProperty) o; 869 | return Objects.equals(declaringClass, that.declaringClass) && 870 | Objects.equals(name, that.name); 871 | } 872 | 873 | @Override 874 | public int hashCode() { 875 | 876 | return Objects.hash(declaringClass, name); 877 | } 878 | } 879 | } 880 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/Match.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.function.BiFunction; 9 | 10 | public class Match { 11 | private final Set includes = new HashSet<>(); 12 | private final Set excludes = new HashSet<>(); 13 | private final Map> transforms = new HashMap<>(); 14 | 15 | Match() { 16 | 17 | } 18 | 19 | /** 20 | * Mark fields for inclusion during serialization. 21 | * 22 | * @param fields The fields to include 23 | * @return Match 24 | */ 25 | public Match include(String... fields) { 26 | if(fields != null) { 27 | includes.addAll(Arrays.asList(fields)); 28 | } 29 | return this; 30 | } 31 | 32 | /** 33 | * Mark fields for exclusion during serialization. 34 | * 35 | * @param fields The fields to exclude 36 | * @return Match 37 | */ 38 | public Match exclude(String... fields) { 39 | if(fields != null) { 40 | excludes.addAll(Arrays.asList(fields)); 41 | } 42 | return this; 43 | } 44 | 45 | /** 46 | * Mark a field for transformation during serialization. 47 | * 48 | * @param field The fields to include 49 | * @param transformer The function to transform the field. Will be provided with the whole object and the field. 50 | * @param The object being serialized 51 | * @param The field being serialized 52 | * @param The value of the field to serialize 53 | * @return Match 54 | */ 55 | @SuppressWarnings("unchecked") 56 | public Match transform(String field, BiFunction transformer) { 57 | transforms.put(field, (BiFunction) transformer); 58 | return this; 59 | } 60 | 61 | Set getIncludes() { 62 | return includes; 63 | } 64 | 65 | Set getExcludes() { 66 | return excludes; 67 | } 68 | 69 | Map> getTransforms() { 70 | return transforms; 71 | } 72 | 73 | public static Match match() { 74 | return new Match(); 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "Match{" + 80 | "includes=" + includes + 81 | ", excludes=" + excludes + 82 | ", transforms=" + transforms + 83 | '}'; 84 | } 85 | 86 | @Override 87 | public boolean equals(Object o) { 88 | if(this == o) return true; 89 | if(o == null || getClass() != o.getClass()) return false; 90 | 91 | Match match = (Match) o; 92 | 93 | if(includes != null ? !includes.equals(match.includes) : match.includes != null) return false; 94 | if(excludes != null ? !excludes.equals(match.excludes) : match.excludes != null) return false; 95 | return transforms != null ? transforms.equals(match.transforms) : match.transforms == null; 96 | } 97 | 98 | @Override 99 | public int hashCode() { 100 | int result = includes != null ? includes.hashCode() : 0; 101 | result = 31 * result + (excludes != null ? excludes.hashCode() : 0); 102 | result = 31 * result + (transforms != null ? transforms.hashCode() : 0); 103 | return result; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/MatcherBehavior.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | /** 4 | * Dictates the order in which to search for matches when serializing objects. 5 | */ 6 | public enum MatcherBehavior { 7 | /** 8 | * Check for matches on an class first before using the 9 | * current path matcher 10 | */ 11 | CLASS_FIRST, 12 | 13 | /** 14 | * Check for matches against the current path first before 15 | * looking for a matcher on the class 16 | */ 17 | PATH_FIRST 18 | } 19 | -------------------------------------------------------------------------------- /json-view/src/main/java/com/monitorjbl/json/Memoizer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.monitorjbl.json.JsonViewSerializer.AccessibleProperty; 4 | 5 | import java.util.EnumMap; 6 | import java.util.Map; 7 | import java.util.Objects; 8 | import java.util.Set; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | import java.util.function.Supplier; 11 | 12 | import static com.monitorjbl.json.Memoizer.FunctionCache.ACCESSIBLE_PROPERTY; 13 | import static com.monitorjbl.json.Memoizer.FunctionCache.ANNOTATIONS; 14 | import static com.monitorjbl.json.Memoizer.FunctionCache.CLASS_MATCHES; 15 | import static com.monitorjbl.json.Memoizer.FunctionCache.IGNORE_ANNOTATIONS; 16 | import static com.monitorjbl.json.Memoizer.FunctionCache.MATCHES; 17 | 18 | @SuppressWarnings("unchecked") 19 | class Memoizer { 20 | private final int maxCacheSize; 21 | private final Map> cache = new EnumMap<>(FunctionCache.class); 22 | 23 | public Memoizer(int maxCacheSize) { 24 | this.maxCacheSize = maxCacheSize; 25 | for(FunctionCache key : FunctionCache.class.getEnumConstants()) { 26 | cache.put(key, new ConcurrentHashMap<>()); 27 | } 28 | } 29 | 30 | public T matches(Set values, String pattern, boolean matchPrefix, Supplier compute) { 31 | return computeIfAbsent(MATCHES, new TriArg(values, pattern, matchPrefix), compute); 32 | } 33 | 34 | public T classMatches(JsonView jsonView, Class cls, Supplier compute) { 35 | return computeIfAbsent(CLASS_MATCHES, new BiArg(jsonView, cls), compute); 36 | } 37 | 38 | public T annotations(Class cls, Supplier compute) { 39 | return computeIfAbsent(ANNOTATIONS, new MonoArg(cls), compute); 40 | } 41 | 42 | public T annotatedWithIgnore(AccessibleProperty property, Supplier compute) { 43 | return computeIfAbsent(IGNORE_ANNOTATIONS, new MonoArg(property), compute); 44 | } 45 | 46 | public T accessibleProperty(Class cls, Supplier compute) { 47 | return computeIfAbsent(ACCESSIBLE_PROPERTY, new MonoArg(cls), compute); 48 | } 49 | 50 | public T computeIfAbsent(FunctionCache cacheName, Arg arg, Supplier compute) { 51 | Map map = fitToMaxSize(cacheName); 52 | if(!map.containsKey(arg)) { 53 | map.put(arg, compute.get()); 54 | } 55 | return (T) map.get(arg); 56 | } 57 | 58 | private Map fitToMaxSize(FunctionCache key) { 59 | Map map = cache.get(key); 60 | if(map.size() > maxCacheSize) { 61 | map.remove(map.keySet().iterator().next()); 62 | } 63 | return map; 64 | } 65 | 66 | enum FunctionCache { 67 | IGNORE_ANNOTATIONS, MATCHES, ANNOTATIONS, ACCESSIBLE_PROPERTY, CLASS_MATCHES 68 | } 69 | 70 | private interface Arg {} 71 | 72 | private class MonoArg implements Arg { 73 | private final Object arg1; 74 | 75 | public MonoArg(Object arg1) { 76 | this.arg1 = arg1; 77 | } 78 | 79 | @Override 80 | public boolean equals(Object o) { 81 | MonoArg monoArg = (MonoArg) o; 82 | 83 | return arg1 != null ? arg1.equals(monoArg.arg1) : monoArg.arg1 == null; 84 | } 85 | 86 | @Override 87 | public int hashCode() { 88 | return arg1 != null ? arg1.hashCode() : 0; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return "MonoArg{" + 94 | "arg1=" + arg1 + 95 | '}'; 96 | } 97 | } 98 | 99 | private class BiArg implements Arg { 100 | private final Object arg1; 101 | private final Object arg2; 102 | 103 | public BiArg(Object arg1, Object arg2) { 104 | this.arg1 = arg1; 105 | this.arg2 = arg2; 106 | } 107 | 108 | @Override 109 | public boolean equals(Object o) { 110 | if(this == o) return true; 111 | if(o == null || getClass() != o.getClass()) return false; 112 | BiArg biArg = (BiArg) o; 113 | return Objects.equals(arg1, biArg.arg1) && 114 | Objects.equals(arg2, biArg.arg2); 115 | } 116 | 117 | @Override 118 | public int hashCode() { 119 | return Objects.hash(arg1, arg2); 120 | } 121 | 122 | @Override 123 | public String toString() { 124 | return "BiArg{" + 125 | "arg1=" + arg1 + 126 | ", arg2=" + arg2 + 127 | '}'; 128 | } 129 | } 130 | 131 | private class TriArg implements Arg { 132 | private final Object arg1; 133 | private final Object arg2; 134 | private final Object arg3; 135 | 136 | public TriArg(Object arg1, Object arg2, Object arg3) { 137 | this.arg1 = arg1; 138 | this.arg2 = arg2; 139 | this.arg3 = arg3; 140 | } 141 | 142 | @Override 143 | public boolean equals(Object o) { 144 | TriArg triArg = (TriArg) o; 145 | 146 | if(arg1 != null ? !arg1.equals(triArg.arg1) : triArg.arg1 != null) return false; 147 | if(arg2 != null ? !arg2.equals(triArg.arg2) : triArg.arg2 != null) return false; 148 | return arg3 != null ? arg3.equals(triArg.arg3) : triArg.arg3 == null; 149 | } 150 | 151 | @Override 152 | public int hashCode() { 153 | int result = arg1 != null ? arg1.hashCode() : 0; 154 | result = 31 * result + (arg2 != null ? arg2.hashCode() : 0); 155 | result = 31 * result + (arg3 != null ? arg3.hashCode() : 0); 156 | return result; 157 | } 158 | 159 | @Override 160 | public String toString() { 161 | return "TriArg{" + 162 | "arg1=" + arg1 + 163 | ", arg2=" + arg2 + 164 | ", arg3=" + arg3 + 165 | '}'; 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/JsonViewSerializerPerformanceTest.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.module.SimpleModule; 5 | import com.google.common.collect.ImmutableMap; 6 | import com.monitorjbl.json.model.TestObject; 7 | import com.monitorjbl.json.model.TestSubobject; 8 | import org.apache.commons.lang3.RandomStringUtils; 9 | import org.apache.commons.lang3.RandomUtils; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | import org.junit.runners.Parameterized; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | import java.math.RoundingMode; 18 | import java.text.DecimalFormat; 19 | import java.util.Arrays; 20 | import java.util.Collection; 21 | 22 | import static com.google.common.collect.Lists.newArrayList; 23 | import static com.monitorjbl.json.Match.match; 24 | import static org.junit.Assert.fail; 25 | 26 | @RunWith(Parameterized.class) 27 | public class JsonViewSerializerPerformanceTest { 28 | private static final Logger log = LoggerFactory.getLogger(JsonViewSerializerPerformanceTest.class); 29 | private int repetitions; 30 | private JsonViewSerializer serializer = new JsonViewSerializer(); 31 | private ObjectMapper sut; 32 | private ObjectMapper compare = new ObjectMapper(); 33 | 34 | @Parameterized.Parameters 35 | public static Collection data() { 36 | return Arrays.asList(new Object[][]{ 37 | {100}, 38 | {1_000}, 39 | {10_000}, 40 | {100_000}, 41 | }); 42 | } 43 | 44 | public JsonViewSerializerPerformanceTest(int repetitions) { 45 | this.repetitions = repetitions; 46 | } 47 | 48 | @Before 49 | public void setup() { 50 | sut = new ObjectMapper(); 51 | SimpleModule module = new SimpleModule(); 52 | module.addSerializer(JsonView.class, serializer); 53 | sut.registerModule(module); 54 | } 55 | 56 | @Test 57 | public void comparePerformance() throws Exception { 58 | long baselineTimes = randomSingleObjectPerformance(() -> { 59 | // Include this because we're testing the serializer. It's not apples-to-apples if we don't 60 | // include the same pre-work. 61 | JsonView.with(testObject()).onClass(TestObject.class, match().exclude("int1")); 62 | compare.writeValueAsString(testObject()); 63 | }); 64 | long jsonViewTimes = randomSingleObjectPerformance(() -> 65 | sut.writeValueAsString(JsonView.with(testObject()).onClass(TestObject.class, match().exclude("int1")))); 66 | String difference = divide(jsonViewTimes * 100L, baselineTimes); 67 | 68 | System.out.printf("[%-8s]: | Baseline: %-8s | JsonView: %-8s | Difference: %-6s |\n", 69 | repetitions, divide(baselineTimes, 1000000L) + "ms", divide(jsonViewTimes, 1000000L) + "ms", difference + "%"); 70 | 71 | if(((double) jsonViewTimes / (double) baselineTimes) > 10) { 72 | fail("Performance delta is greater than 10x slower than basic Jackson (" + difference + "% slower)"); 73 | } 74 | } 75 | 76 | public long randomSingleObjectPerformance(UncheckedRunnable mapper) throws Exception { 77 | long totalTime = 0; 78 | long chunkTime = 0; 79 | for(int i = 1; i <= repetitions; i++) { 80 | long time = System.nanoTime(); 81 | mapper.run(); 82 | time = System.nanoTime() - time; 83 | 84 | totalTime += time; 85 | chunkTime += time; 86 | if(i % 100000 == 0) { 87 | log.trace("Time per 100k entries: " + ((double) chunkTime / 1000000.0) + "ms"); 88 | chunkTime = 0; 89 | } 90 | } 91 | 92 | return totalTime; 93 | } 94 | 95 | TestObject testObject() { 96 | TestObject ref = new TestObject(); 97 | ref.setInt1(RandomUtils.nextInt(0, 100000000)); 98 | ref.setIgnoredDirect(RandomStringUtils.random(16)); 99 | ref.setStr2(RandomStringUtils.random(4)); 100 | ref.setStringArray(new String[]{RandomStringUtils.random(7), RandomStringUtils.random(5)}); 101 | ref.setList(newArrayList(RandomStringUtils.random(3), RandomStringUtils.random(14))); 102 | ref.setMapOfObjects(ImmutableMap.of(RandomStringUtils.random(14), new TestSubobject())); 103 | TestSubobject sub = new TestSubobject(); 104 | sub.setVal("wer"); 105 | ref.setListOfObjects(newArrayList(sub)); 106 | return ref; 107 | } 108 | 109 | String divide(long numerator, long denominator) { 110 | DecimalFormat df = new DecimalFormat("#.###"); 111 | df.setRoundingMode(RoundingMode.CEILING); 112 | return df.format((double) numerator / (double) denominator); 113 | } 114 | 115 | interface UncheckedRunnable { 116 | public void run() throws Exception; 117 | } 118 | 119 | } -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/WriterTest.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.databind.SerializerProvider; 5 | import com.monitorjbl.json.JsonViewSerializer.JsonWriter; 6 | import com.monitorjbl.json.model.TestObject; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.mockito.Mock; 11 | import org.mockito.MockitoAnnotations; 12 | import org.powermock.api.mockito.PowerMockito; 13 | import org.powermock.core.classloader.annotations.PrepareForTest; 14 | import org.powermock.modules.junit4.PowerMockRunner; 15 | 16 | import java.net.URI; 17 | import java.net.URL; 18 | import java.util.Date; 19 | import java.util.List; 20 | import java.util.Set; 21 | 22 | import static com.google.common.collect.Lists.newArrayList; 23 | import static com.google.common.collect.Sets.newHashSet; 24 | import static org.junit.Assert.assertEquals; 25 | import static org.junit.Assert.assertFalse; 26 | import static org.junit.Assert.assertTrue; 27 | import static org.mockito.Mockito.times; 28 | import static org.mockito.Mockito.verify; 29 | 30 | @RunWith(PowerMockRunner.class) 31 | @PrepareForTest(SerializerProvider.class) 32 | public class WriterTest { 33 | @Mock 34 | JsonGenerator jgen; 35 | @Mock 36 | JsonView result; 37 | SerializerProvider serializerProvider; 38 | 39 | // has to be mocked with powermock due to final methods 40 | JsonWriter sut; 41 | 42 | @Before 43 | public void setup() { 44 | MockitoAnnotations.initMocks(this); 45 | serializerProvider = PowerMockito.mock(SerializerProvider.class); 46 | sut = new JsonViewSerializer().new JsonWriter(serializerProvider, jgen, result); 47 | } 48 | 49 | @Test 50 | public void testContainsMatchingPattern_basic() { 51 | Set patterns = newHashSet("field1", "field2"); 52 | assertEquals(1, sut.containsMatchingPattern(patterns, "field1", true)); 53 | assertEquals(1, sut.containsMatchingPattern(patterns, "field2", true)); 54 | assertEquals(-1, sut.containsMatchingPattern(patterns, "field3", true)); 55 | } 56 | 57 | @Test 58 | public void testContainsMatchingPattern_wildcard() { 59 | Set patterns = newHashSet("field*"); 60 | assertEquals(0, sut.containsMatchingPattern(patterns, "field1", true)); 61 | assertEquals(0, sut.containsMatchingPattern(patterns, "field2", true)); 62 | assertEquals(-1, sut.containsMatchingPattern(patterns, "val1", true)); 63 | } 64 | 65 | @Test 66 | public void testContainsMatchingPattern_wildcardAll() { 67 | Set patterns = newHashSet("*"); 68 | assertEquals(0, sut.containsMatchingPattern(patterns, "field1", true)); 69 | assertEquals(0, sut.containsMatchingPattern(patterns, "field2", true)); 70 | assertEquals(0, sut.containsMatchingPattern(patterns, "val1", true)); 71 | } 72 | 73 | @Test 74 | public void testContainsMatchingPattern_wildcardInChildPath() { 75 | Set patterns = newHashSet("*.green"); 76 | assertEquals(0, sut.containsMatchingPattern(patterns, "field1.green", true)); 77 | assertEquals(-1, sut.containsMatchingPattern(patterns, "field2.blue", true)); 78 | } 79 | 80 | @Test 81 | public void testContainsMatchingPattern_wildcardInComplexPath() { 82 | Set patterns = newHashSet("*.green.*"); 83 | assertEquals(-1, sut.containsMatchingPattern(patterns, "field1.green", true)); 84 | assertEquals(-1, sut.containsMatchingPattern(patterns, "field2.blue", true)); 85 | assertEquals(0, sut.containsMatchingPattern(patterns, "field1.green.id", true)); 86 | assertEquals(-1, sut.containsMatchingPattern(patterns, "field1.blue.id", true)); 87 | assertEquals(0, sut.containsMatchingPattern(patterns, "field2.green.name", true)); 88 | } 89 | 90 | // @Test 91 | // public void testAnnotatedWithIgnore() throws Exception { 92 | // assertTrue(sut.annotatedWithIgnore(TestObject.class.getDeclaredField("ignoredDirect"))); 93 | // assertTrue(sut.annotatedWithIgnore(TestObject.class.getDeclaredField("ignoredIndirect"))); 94 | // assertFalse(sut.annotatedWithIgnore(TestObject.class.getDeclaredField("str1"))); 95 | // } 96 | 97 | @Test 98 | public void testWritePrimitive_object() throws Exception { 99 | assertFalse(sut.writePrimitive(new TestObject())); 100 | } 101 | 102 | @Test 103 | public void testWritePrimitive_string() throws Exception { 104 | sut.writePrimitive("test"); 105 | verify(jgen, times(1)).writeString("test"); 106 | } 107 | 108 | @Test 109 | public void testWritePrimitive_int() throws Exception { 110 | int primitive = 1; 111 | Integer obj = 2; 112 | assertTrue(sut.writePrimitive(primitive)); 113 | assertTrue(sut.writePrimitive(obj)); 114 | verify(jgen, times(1)).writeNumber(1); 115 | verify(jgen, times(1)).writeNumber(2); 116 | } 117 | 118 | @Test 119 | public void testWritePrimitive_long() throws Exception { 120 | long primitive = 1L; 121 | Long obj = 2L; 122 | assertTrue(sut.writePrimitive(primitive)); 123 | assertTrue(sut.writePrimitive(obj)); 124 | verify(jgen, times(1)).writeNumber(1L); 125 | verify(jgen, times(1)).writeNumber(2L); 126 | } 127 | 128 | @Test 129 | public void testWritePrimitive_short() throws Exception { 130 | short primitive = 1; 131 | Short obj = 2; 132 | assertTrue(sut.writePrimitive(primitive)); 133 | assertTrue(sut.writePrimitive(obj)); 134 | verify(jgen, times(1)).writeNumber((short) 1); 135 | verify(jgen, times(1)).writeNumber((short) 2); 136 | } 137 | 138 | @Test 139 | public void testWritePrimitive_char() throws Exception { 140 | char primitive = 'a'; 141 | Character obj = 'b'; 142 | assertTrue(sut.writePrimitive(primitive)); 143 | assertTrue(sut.writePrimitive(obj)); 144 | verify(jgen, times(1)).writeNumber('a'); 145 | verify(jgen, times(1)).writeNumber('b'); 146 | } 147 | 148 | @Test 149 | public void testWritePrimitive_double() throws Exception { 150 | double primitive = 1.0; 151 | Double obj = 2.0; 152 | assertTrue(sut.writePrimitive(primitive)); 153 | assertTrue(sut.writePrimitive(obj)); 154 | verify(jgen, times(1)).writeNumber(1.0); 155 | verify(jgen, times(1)).writeNumber(2.0); 156 | } 157 | 158 | @Test 159 | public void testWritePrimitive_float() throws Exception { 160 | float primitive = 1.0f; 161 | Float obj = 2.0f; 162 | assertTrue(sut.writePrimitive(primitive)); 163 | assertTrue(sut.writePrimitive(obj)); 164 | verify(jgen, times(1)).writeNumber(1.0f); 165 | verify(jgen, times(1)).writeNumber(2.0f); 166 | } 167 | 168 | @Test 169 | public void testWritePrimitive_byte() throws Exception { 170 | byte primitive = 1; 171 | Byte obj = 2; 172 | assertTrue(sut.writePrimitive(primitive)); 173 | assertTrue(sut.writePrimitive(obj)); 174 | verify(jgen, times(1)).writeNumber((byte) 1); 175 | verify(jgen, times(1)).writeNumber((byte) 2); 176 | } 177 | 178 | @Test 179 | public void testWritePrimitive_boolean() throws Exception { 180 | boolean primitive = true; 181 | Boolean obj = false; 182 | sut.writePrimitive(primitive); 183 | sut.writePrimitive(obj); 184 | verify(jgen, times(1)).writeBoolean(true); 185 | verify(jgen, times(1)).writeBoolean(false); 186 | } 187 | 188 | @Test 189 | public void testWriteSpecial_date() throws Exception { 190 | Date dt = new Date(); 191 | sut.writeSpecial(dt); 192 | verify(serializerProvider, times(1)).defaultSerializeDateValue(dt, jgen); 193 | } 194 | 195 | @Test 196 | public void testWriteSpecial_url() throws Exception { 197 | URL url = new URL("http://google.com"); 198 | sut.writeSpecial(url); 199 | verify(jgen, times(1)).writeString(url.toString()); 200 | } 201 | 202 | @Test 203 | public void testWriteSpecial_uri() throws Exception { 204 | URI uri = new URI("http://google.com"); 205 | sut.writeSpecial(uri); 206 | verify(jgen, times(1)).writeString(uri.toString()); 207 | } 208 | 209 | @Test 210 | public void testWriteSpecial_class() throws Exception { 211 | Class cls = TestObject.class; 212 | sut.writeSpecial(cls); 213 | verify(jgen, times(1)).writeString(cls.getCanonicalName()); 214 | } 215 | 216 | 217 | @Test 218 | public void testWriteList_stringList() throws Exception { 219 | assertTrue(sut.writeList(newArrayList("val1", "val2"))); 220 | verify(jgen, times(1)).writeStartArray(); 221 | verify(jgen, times(1)).writeEndArray(); 222 | } 223 | 224 | @Test 225 | public void testWriteList_objectList() throws Exception { 226 | assertTrue(sut.writeList(newArrayList(new TestObject(), new TestObject()))); 227 | verify(jgen, times(1)).writeStartArray(); 228 | verify(jgen, times(1)).writeEndArray(); 229 | } 230 | 231 | @Test 232 | public void testWriteList_mixedList() throws Exception { 233 | assertTrue(sut.writeList(newArrayList(new TestObject(), "val2"))); 234 | verify(jgen, times(1)).writeStartArray(); 235 | verify(jgen, times(1)).writeEndArray(); 236 | } 237 | 238 | @Test 239 | public void testWriteList_stringArray() throws Exception { 240 | assertTrue(sut.writeList(new String[]{"val1", "val2"})); 241 | verify(jgen, times(1)).writeStartArray(); 242 | verify(jgen, times(1)).writeEndArray(); 243 | } 244 | 245 | @Test 246 | public void testWriteList_objectArray() throws Exception { 247 | assertTrue(sut.writeList(new TestObject[]{new TestObject(), new TestObject()})); 248 | verify(jgen, times(1)).writeStartArray(); 249 | verify(jgen, times(1)).writeEndArray(); 250 | } 251 | 252 | @Test 253 | public void testWriteList_intArray() throws Exception { 254 | assertTrue(sut.writeList(new int[]{1, 2})); 255 | verify(jgen, times(1)).writeStartArray(); 256 | verify(jgen, times(1)).writeEndArray(); 257 | verify(jgen, times(1)).writeNumber(1); 258 | verify(jgen, times(1)).writeNumber(2); 259 | } 260 | 261 | @Test 262 | public void testWriteList_longArray() throws Exception { 263 | assertTrue(sut.writeList(new long[]{1L, 2L})); 264 | verify(jgen, times(1)).writeStartArray(); 265 | verify(jgen, times(1)).writeEndArray(); 266 | verify(jgen, times(1)).writeNumber(1L); 267 | verify(jgen, times(1)).writeNumber(2L); 268 | } 269 | 270 | @Test 271 | public void testWriteList_shortArray() throws Exception { 272 | assertTrue(sut.writeList(new short[]{1, 2})); 273 | verify(jgen, times(1)).writeStartArray(); 274 | verify(jgen, times(1)).writeEndArray(); 275 | verify(jgen, times(1)).writeNumber((short) 1); 276 | verify(jgen, times(1)).writeNumber((short) 2); 277 | } 278 | 279 | @Test 280 | public void testWriteList_doubleArray() throws Exception { 281 | assertTrue(sut.writeList(new double[]{1.0, 2.0})); 282 | verify(jgen, times(1)).writeStartArray(); 283 | verify(jgen, times(1)).writeEndArray(); 284 | verify(jgen, times(1)).writeNumber(1.0); 285 | verify(jgen, times(1)).writeNumber(2.0); 286 | } 287 | 288 | @Test 289 | public void testWriteList_floatArray() throws Exception { 290 | assertTrue(sut.writeList(new float[]{1f, 2f})); 291 | verify(jgen, times(1)).writeStartArray(); 292 | verify(jgen, times(1)).writeEndArray(); 293 | verify(jgen, times(1)).writeNumber(1f); 294 | verify(jgen, times(1)).writeNumber(2f); 295 | } 296 | 297 | @Test 298 | public void testWriteList_booleanArray() throws Exception { 299 | assertTrue(sut.writeList(new boolean[]{true, false})); 300 | verify(jgen, times(1)).writeStartArray(); 301 | verify(jgen, times(1)).writeEndArray(); 302 | verify(jgen, times(1)).writeBoolean(true); 303 | verify(jgen, times(1)).writeBoolean(false); 304 | } 305 | 306 | @Test 307 | public void testWriteList_byteArray() throws Exception { 308 | String val = "asdf"; 309 | assertTrue(sut.writeList(val.getBytes())); 310 | verify(jgen, times(1)).writeBinary(val.getBytes()); 311 | } 312 | 313 | } 314 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/CustomType.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class CustomType 4 | { 5 | private long sid=0l; 6 | private String name="name"; 7 | 8 | 9 | public CustomType(long sid,String name){ 10 | this.setSid( sid ); 11 | this.setName( name ); 12 | } 13 | 14 | public long getSid() 15 | { 16 | return sid; 17 | } 18 | 19 | public void setSid( long sid ) 20 | { 21 | this.sid = sid; 22 | } 23 | 24 | public String getName() 25 | { 26 | return name; 27 | } 28 | 29 | public void setName( String name ) 30 | { 31 | this.name = name; 32 | } 33 | 34 | 35 | public boolean equals(Object obj){ 36 | if(obj instanceof CustomType){ 37 | CustomType c=(CustomType)obj; 38 | return c.name.equals( name ) && c.sid==sid; 39 | }else{ 40 | return false; 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/CustomTypeSerializer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.databind.SerializerProvider; 5 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 6 | 7 | import java.io.IOException; 8 | 9 | public class CustomTypeSerializer 10 | extends StdSerializer { 11 | private static final long serialVersionUID = 5275226323866715671L; 12 | 13 | public CustomTypeSerializer() { 14 | super(CustomType.class, true); 15 | } 16 | 17 | @Override 18 | public void serialize(CustomType value, JsonGenerator jgen, SerializerProvider provider) throws IOException { 19 | if(value == null) { 20 | jgen.writeNull(); 21 | } else { 22 | jgen.writeString(value.getSid() + "[" + value.getName() + "]"); 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/NonReplacableKeyMap.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import java.util.LinkedHashMap; 4 | 5 | /** 6 | * Acts as a map but prevents keys from being overwritten 7 | */ 8 | public class NonReplacableKeyMap extends LinkedHashMap { 9 | @Override 10 | public V put(K key, V value) { 11 | if(containsKey(key)) { 12 | throw new IllegalStateException(); 13 | } 14 | return super.put(key, value); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestAutodetect.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; 5 | 6 | public class TestAutodetect { 7 | 8 | public static class AutodetectNotPresent { 9 | private String id; 10 | 11 | public String getId() { 12 | return "valid"; 13 | } 14 | 15 | public void setId(String id) { 16 | this.id = id; 17 | } 18 | } 19 | 20 | @JsonAutoDetect 21 | public static class AutodetectDefault { 22 | private String id; 23 | 24 | public String getId() { 25 | return "valid"; 26 | } 27 | 28 | public void setId(String id) { 29 | this.id = id; 30 | } 31 | } 32 | 33 | @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE) 34 | public static class AutodetectFields { 35 | private String id; 36 | 37 | public void setId(String id) { 38 | this.id = id; 39 | } 40 | 41 | private String getId() { 42 | return "not_valid"; 43 | } 44 | } 45 | 46 | @JsonAutoDetect(fieldVisibility = Visibility.NONE, getterVisibility = Visibility.ANY) 47 | public static class AutodetectGetters { 48 | private String id; 49 | 50 | public void setId(String id) { 51 | this.id = id; 52 | } 53 | 54 | private String getId() { 55 | return "valid"; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestBackreferenceObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; 5 | import com.fasterxml.jackson.annotation.JsonBackReference; 6 | import com.fasterxml.jackson.annotation.JsonManagedReference; 7 | 8 | import java.util.List; 9 | 10 | @JsonAutoDetect(fieldVisibility = Visibility.ANY) 11 | public class TestBackreferenceObject { 12 | 13 | private String id; 14 | @JsonBackReference 15 | private List children; 16 | 17 | 18 | public String getId() { 19 | return id; 20 | } 21 | 22 | public void setId(String id) { 23 | this.id = id; 24 | } 25 | 26 | public List getChildren() { 27 | return children; 28 | } 29 | 30 | public void setChildren(List children) { 31 | this.children = children; 32 | } 33 | 34 | @JsonAutoDetect(fieldVisibility = Visibility.ANY) 35 | public static class TestForwardReferenceObject{ 36 | private String id; 37 | @JsonManagedReference 38 | private TestBackreferenceObject parent; 39 | 40 | public String getId() { 41 | return id; 42 | } 43 | 44 | public void setId(String id) { 45 | this.id = id; 46 | } 47 | 48 | public TestBackreferenceObject getParent() { 49 | return parent; 50 | } 51 | 52 | public void setParent(TestBackreferenceObject parent) { 53 | this.parent = parent; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestChildObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestChildObject extends TestObject { 4 | private String childField; 5 | 6 | public String getChildField() { 7 | return childField; 8 | } 9 | 10 | public void setChildField(String childField) { 11 | this.childField = childField; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestDuplicateKeys.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import java.util.LinkedHashMap; 4 | 5 | public interface TestDuplicateKeys { 6 | static class ClassA { 7 | private int id; 8 | 9 | public int getId() { 10 | return this.id; 11 | } 12 | } 13 | 14 | static class ClassB extends ClassA {} 15 | 16 | static class ClassC extends ClassB {} 17 | 18 | } 19 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestInterface.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import java.util.Date; 4 | 5 | public interface TestInterface { 6 | Date getDate(); 7 | } 8 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestNonNulls.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; 5 | 6 | @JsonSerialize(include = Inclusion.NON_NULL) 7 | public class TestNonNulls { 8 | private String val; 9 | private String otherVal; 10 | private TestNonNulls sub; 11 | 12 | public TestNonNulls(String val) { 13 | this.val = val; 14 | } 15 | 16 | public TestNonNulls(String val, TestNonNulls sub) { 17 | this.val = val; 18 | this.sub = sub; 19 | } 20 | 21 | public TestNonNulls() { 22 | } 23 | 24 | public String getVal() { 25 | return val; 26 | } 27 | 28 | public void setVal(String val) { 29 | this.val = val; 30 | } 31 | 32 | public String getOtherVal() { 33 | return otherVal; 34 | } 35 | 36 | public void setOtherVal(String otherVal) { 37 | this.otherVal = otherVal; 38 | } 39 | 40 | public TestNonNulls getSub() { 41 | return sub; 42 | } 43 | 44 | public void setSub(TestNonNulls sub) { 45 | this.sub = sub; 46 | } 47 | } -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestNulls.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 4 | import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; 5 | 6 | @JsonSerialize(include = Inclusion.ALWAYS) 7 | public class TestNulls { 8 | private String val; 9 | private String otherVal; 10 | private TestNulls sub; 11 | 12 | public TestNulls(String val) { 13 | this.val = val; 14 | } 15 | 16 | public TestNulls(String val, TestNulls sub) { 17 | this.val = val; 18 | this.sub = sub; 19 | } 20 | 21 | public TestNulls() { 22 | } 23 | 24 | public String getVal() { 25 | return val; 26 | } 27 | 28 | public void setVal(String val) { 29 | this.val = val; 30 | } 31 | 32 | public String getOtherVal() { 33 | return otherVal; 34 | } 35 | 36 | public void setOtherVal(String otherVal) { 37 | this.otherVal = otherVal; 38 | } 39 | 40 | public TestNulls getSub() { 41 | return sub; 42 | } 43 | 44 | public void setSub(TestNulls sub) { 45 | this.sub = sub; 46 | } 47 | } -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import com.fasterxml.jackson.annotation.JsonInclude; 7 | import com.fasterxml.jackson.annotation.JsonProperty; 8 | import com.fasterxml.jackson.databind.JsonNode; 9 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 10 | 11 | import java.math.BigDecimal; 12 | import java.net.URI; 13 | import java.net.URL; 14 | import java.time.ZonedDateTime; 15 | import java.util.Date; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.UUID; 19 | 20 | @JsonIgnoreProperties({"ignoredIndirect"}) 21 | public class TestObject implements TestInterface { 22 | public enum TestEnum {VALUE_A, VALUE_B} 23 | 24 | public static final String PUBLIC_FIELD = "public"; 25 | private static final String PRIVATE_FIELD = "private"; 26 | 27 | private TestSubobject sub; 28 | @JsonIgnoreProperties({"val"}) 29 | private TestSubobject subWithIgnores; 30 | private String str1; 31 | @JsonInclude(value = JsonInclude.Include.NON_NULL) 32 | private String str2; 33 | @JsonIgnore 34 | private String ignoredDirect; 35 | private String targetObject; 36 | private String ignoredIndirect; 37 | private Date date; 38 | private int int1; 39 | private List list; 40 | private Map mapOfStrings; 41 | private Map mapWithIntKeys; 42 | private String[] stringArray; 43 | private byte[] byteArray; 44 | private int[] intArray; 45 | private TestObject[] objArray; 46 | private List listOfObjects; 47 | private Map mapOfObjects; 48 | private TestEnum testEnum; 49 | private URL url; 50 | private URI uri; 51 | private Class cls; 52 | private BigDecimal bigDecimal; 53 | private CustomType custom; 54 | @JsonSerialize(using = CustomTypeSerializer.class) 55 | private CustomType customFieldSerializer; 56 | private ZonedDateTime zonedDateTime; 57 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "UTC") 58 | private ZonedDateTime formattedZonedDateTime; 59 | @JsonProperty("totallyJsonProp") 60 | private String jsonProp; 61 | @JsonProperty 62 | private String jsonPropNoValue; 63 | private UUID uuid; 64 | private TestObject recursion; 65 | private JsonNode jsonNode; 66 | private String widgetName; 67 | 68 | public String getStr1() { 69 | return str1; 70 | } 71 | 72 | public void setStr1(String str1) { 73 | this.str1 = str1; 74 | } 75 | 76 | public String getStr2() { 77 | return str2; 78 | } 79 | 80 | public void setStr2(String str2) { 81 | this.str2 = str2; 82 | } 83 | 84 | public String getIgnoredDirect() { 85 | return ignoredDirect; 86 | } 87 | 88 | public void setIgnoredDirect(String ignoredDirect) { 89 | this.ignoredDirect = ignoredDirect; 90 | } 91 | 92 | public String getIgnoredIndirect() { 93 | return ignoredIndirect; 94 | } 95 | 96 | public void setIgnoredIndirect(String ignoredIndirect) { 97 | this.ignoredIndirect = ignoredIndirect; 98 | } 99 | 100 | public String getTargetObject() { 101 | return targetObject; 102 | } 103 | 104 | public void setTargetObject(String targetObject) { 105 | this.targetObject = targetObject; 106 | } 107 | 108 | public Date getDate() { 109 | return date; 110 | } 111 | 112 | public void setDate(Date date) { 113 | this.date = date; 114 | } 115 | 116 | public int getInt1() { 117 | return int1; 118 | } 119 | 120 | public void setInt1(int int1) { 121 | this.int1 = int1; 122 | } 123 | 124 | public TestSubobject getSub() { 125 | return sub; 126 | } 127 | 128 | public void setSub(TestSubobject sub) { 129 | this.sub = sub; 130 | } 131 | 132 | public List getList() { 133 | return list; 134 | } 135 | 136 | public void setList(List list) { 137 | this.list = list; 138 | } 139 | 140 | public Map getMapOfStrings() { 141 | return mapOfStrings; 142 | } 143 | 144 | public void setMapOfStrings(Map mapOfStrings) { 145 | this.mapOfStrings = mapOfStrings; 146 | } 147 | 148 | public Map getMapWithIntKeys() { 149 | return mapWithIntKeys; 150 | } 151 | 152 | public void setMapWithIntKeys(Map mapWithIntKeys) { 153 | this.mapWithIntKeys = mapWithIntKeys; 154 | } 155 | 156 | public String[] getStringArray() { 157 | return stringArray; 158 | } 159 | 160 | public void setStringArray(String[] stringArray) { 161 | this.stringArray = stringArray; 162 | } 163 | 164 | public byte[] getByteArray() { 165 | return byteArray; 166 | } 167 | 168 | public void setByteArray(byte[] byteArray) { 169 | this.byteArray = byteArray; 170 | } 171 | 172 | public int[] getIntArray() { 173 | return intArray; 174 | } 175 | 176 | public void setIntArray(int[] intArray) { 177 | this.intArray = intArray; 178 | } 179 | 180 | public TestObject[] getObjArray() { 181 | return objArray; 182 | } 183 | 184 | public void setObjArray(TestObject[] objArray) { 185 | this.objArray = objArray; 186 | } 187 | 188 | public List getListOfObjects() { 189 | return listOfObjects; 190 | } 191 | 192 | public void setListOfObjects(List listOfObjects) { 193 | this.listOfObjects = listOfObjects; 194 | } 195 | 196 | public Map getMapOfObjects() { 197 | return mapOfObjects; 198 | } 199 | 200 | public void setMapOfObjects(Map mapOfObjects) { 201 | this.mapOfObjects = mapOfObjects; 202 | } 203 | 204 | public TestEnum getTestEnum() { 205 | return testEnum; 206 | } 207 | 208 | public void setTestEnum(TestEnum testEnum) { 209 | this.testEnum = testEnum; 210 | } 211 | 212 | public URL getUrl() { 213 | return url; 214 | } 215 | 216 | public void setUrl(URL url) { 217 | this.url = url; 218 | } 219 | 220 | public URI getUri() { 221 | return uri; 222 | } 223 | 224 | public void setUri(URI uri) { 225 | this.uri = uri; 226 | } 227 | 228 | public Class getCls() { 229 | return cls; 230 | } 231 | 232 | public void setCls(Class cls) { 233 | this.cls = cls; 234 | } 235 | 236 | public TestSubobject getSubWithIgnores() { 237 | return subWithIgnores; 238 | } 239 | 240 | public void setSubWithIgnores(TestSubobject subWithIgnores) { 241 | this.subWithIgnores = subWithIgnores; 242 | } 243 | 244 | public BigDecimal getBigDecimal() { 245 | return bigDecimal; 246 | } 247 | 248 | public void setBigDecimal(BigDecimal bigDecimal) { 249 | this.bigDecimal = bigDecimal; 250 | } 251 | 252 | public CustomType getCustom() { 253 | return custom; 254 | } 255 | 256 | public void setCustom(CustomType custom) { 257 | this.custom = custom; 258 | } 259 | 260 | public ZonedDateTime getZonedDateTime() { 261 | return zonedDateTime; 262 | } 263 | 264 | public void setZonedDateTime(ZonedDateTime zonedDateTime) { 265 | this.zonedDateTime = zonedDateTime; 266 | } 267 | 268 | public ZonedDateTime getFormattedZonedDateTime() { 269 | return formattedZonedDateTime; 270 | } 271 | 272 | public void setFormattedZonedDateTime(ZonedDateTime formattedZonedDateTime) { 273 | this.formattedZonedDateTime = formattedZonedDateTime; 274 | } 275 | 276 | public CustomType getCustomFieldSerializer() { 277 | return customFieldSerializer; 278 | } 279 | 280 | public void setCustomFieldSerializer(CustomType customFieldSerializer) { 281 | this.customFieldSerializer = customFieldSerializer; 282 | } 283 | 284 | public String getJsonProp() { 285 | return jsonProp; 286 | } 287 | 288 | public void setJsonProp(String jsonProp) { 289 | this.jsonProp = jsonProp; 290 | } 291 | 292 | public String getJsonPropNoValue() { 293 | return jsonPropNoValue; 294 | } 295 | 296 | public void setJsonPropNoValue(String jsonPropNoValue) { 297 | this.jsonPropNoValue = jsonPropNoValue; 298 | } 299 | 300 | public UUID getUuid() { 301 | return uuid; 302 | } 303 | 304 | public void setUuid(UUID uuid) { 305 | this.uuid = uuid; 306 | } 307 | 308 | public TestObject getRecursion() { 309 | return recursion; 310 | } 311 | 312 | public void setRecursion(TestObject recursion) { 313 | this.recursion = recursion; 314 | } 315 | 316 | public JsonNode getJsonNode() { 317 | return jsonNode; 318 | } 319 | 320 | public void setJsonNode(JsonNode jsonNode) { 321 | this.jsonNode = jsonNode; 322 | } 323 | 324 | public String getStaticValue() { 325 | return "TEST"; 326 | } 327 | 328 | @JsonIgnore 329 | public String getIgnoredValue() { 330 | return "not_valid"; 331 | } 332 | 333 | public String getWidgetName() { 334 | return widgetName; 335 | } 336 | 337 | public void setWidgetName(String widgetName) { 338 | this.widgetName = widgetName; 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestSubobject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestSubobject { 4 | private String val; 5 | private String otherVal; 6 | private TestSubobject sub; 7 | 8 | public TestSubobject(String val) { 9 | this.val = val; 10 | } 11 | 12 | public TestSubobject(String val, TestSubobject sub) { 13 | this.val = val; 14 | this.sub = sub; 15 | } 16 | 17 | public TestSubobject() { 18 | } 19 | 20 | public String getVal() { 21 | return val; 22 | } 23 | 24 | public void setVal(String val) { 25 | this.val = val; 26 | } 27 | 28 | public String getOtherVal() { 29 | return otherVal; 30 | } 31 | 32 | public void setOtherVal(String otherVal) { 33 | this.otherVal = otherVal; 34 | } 35 | 36 | public TestSubobject getSub() { 37 | return sub; 38 | } 39 | 40 | public void setSub(TestSubobject sub) { 41 | this.sub = sub; 42 | } 43 | } -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestSuperinterface.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public interface TestSuperinterface { 4 | 5 | default String getId() { 6 | return "ID"; 7 | } 8 | 9 | public static interface TestChildInterface extends TestSuperinterface { 10 | default String getName() { 11 | return "NAME"; 12 | } 13 | } 14 | 15 | public static class TestInterfaceObject implements TestChildInterface { 16 | private String description; 17 | 18 | public String getDescription() { 19 | return description; 20 | } 21 | 22 | public void setDescription(String description) { 23 | this.description = description; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /json-view/src/test/java/com/monitorjbl/json/model/TestUnrelatedObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestUnrelatedObject { 4 | private Long id; 5 | private String name; 6 | 7 | public Long getId() { 8 | return id; 9 | } 10 | 11 | public void setId(Long id) { 12 | this.id = id; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public void setName(String name) { 20 | this.name = name; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /json-view/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Root logger option 2 | log4j.rootLogger=DEBUG, stdout 3 | 4 | # Direct log messages to stdout 5 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 | log4j.appender.stdout.Target=System.out 7 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 8 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.monitorjbl 8 | json-view-aggregator 9 | 1.0 10 | pom 11 | 12 | 13 | 14 | 15 | org.apache.maven.plugins 16 | maven-deploy-plugin 17 | 2.8.2 18 | 19 | true 20 | 21 | 22 | 23 | 24 | 25 | 26 | spring-json-view 27 | json-view 28 | 29 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd json-view 4 | mvn versions:set -DnewVersion=$1 -DgenerateBackupPoms=false && cd .. 5 | cd spring-json-view 6 | mvn versions:set -DnewVersion=$1 -DgenerateBackupPoms=false && cd .. 7 | 8 | if [[ $1 == *"-SNAPSHOT" ]]; then 9 | git commit -a -m "incrementing snapshot version" 10 | fi 11 | -------------------------------------------------------------------------------- /shippable.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | cache: true 3 | jdk: 4 | - oraclejdk8 5 | 6 | install: 7 | - mvn clean install -DskipTests -B 8 | script: 9 | - mvn clean package -B 10 | -------------------------------------------------------------------------------- /spring-json-view/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.monitorjbl 8 | spring-json-view 9 | 1.1.0 10 | spring-json-view 11 | Provides programmatic JSON response manipulation for Spring MVC 12 | https://github.com/monitorjbl/spring-json-view 13 | 14 | 15 | UTF-8 16 | 2.9.8 17 | 18 | 19 | 20 | 21 | monitorjbl 22 | Taylor Jones 23 | monitorjbl@gmail.com 24 | 25 | 26 | 27 | 28 | 29 | GPLv3 30 | https://raw.githubusercontent.com/monitorjbl/spring-json-view/master/LICENSE 31 | repo 32 | 33 | 34 | 35 | 36 | https://github.com/monitorjbl/spring-json-view.git 37 | 38 | 39 | 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-compiler-plugin 44 | 3.2 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | org.apache.maven.plugins 52 | maven-javadoc-plugin 53 | 2.10.1 54 | 55 | 56 | attach-sources 57 | 58 | jar 59 | 60 | 61 | 62 | 63 | 64 | org.apache.maven.plugins 65 | maven-source-plugin 66 | 2.2.1 67 | 68 | 69 | attach-sources 70 | 71 | jar 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | release 82 | 83 | false 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-gpg-plugin 90 | 1.6 91 | 92 | 93 | sign-artifacts 94 | verify 95 | 96 | sign 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | ossrh 109 | https://oss.sonatype.org/content/repositories/snapshots 110 | 111 | 112 | ossrh 113 | https://oss.sonatype.org/service/local/staging/deploy/maven2 114 | 115 | 116 | 117 | 118 | 119 | org.springframework 120 | spring-webmvc 121 | 4.1.4.RELEASE 122 | provided 123 | 124 | 125 | javax.servlet 126 | javax.servlet-api 127 | 3.1.0 128 | provided 129 | 130 | 131 | com.fasterxml.jackson.core 132 | jackson-core 133 | ${jackson.version} 134 | provided 135 | 136 | 137 | com.fasterxml.jackson.core 138 | jackson-databind 139 | ${jackson.version} 140 | provided 141 | 142 | 143 | 144 | ${project.groupId} 145 | json-view 146 | ${project.version} 147 | 148 | 149 | 150 | org.slf4j 151 | slf4j-api 152 | 1.7.7 153 | 154 | 155 | org.slf4j 156 | slf4j-log4j12 157 | 1.7.7 158 | 159 | 160 | org.apache.httpcomponents 161 | fluent-hc 162 | 4.3.6 163 | test 164 | 165 | 166 | junit 167 | junit 168 | 4.13.2 169 | test 170 | 171 | 172 | com.google.guava 173 | guava 174 | 30.1.1-jre 175 | test 176 | 177 | 178 | 179 | org.eclipse.jetty 180 | jetty-webapp 181 | 9.4.41.v20210516 182 | test 183 | 184 | 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/DefaultView.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | 8 | /** 9 | * Configures default serializer settings in a Spring environment. This is configured 10 | * identically to a JsonView instance, simply use the onClass() method to set matchers. 11 | */ 12 | public class DefaultView { 13 | private final Map matches; 14 | 15 | private DefaultView() { 16 | this.matches = new HashMap<>(); 17 | } 18 | 19 | @SuppressWarnings("unchecked") 20 | public JsonView getMatch(Object obj) { 21 | if(obj == null) { 22 | return null; 23 | } 24 | 25 | JsonView view = JsonView.with(obj); 26 | boolean found = false; 27 | if(obj instanceof Collection) { 28 | for(Object o : (Collection) obj) { 29 | Match m = contains(o.getClass()); 30 | if(m != null) { 31 | view = view.onClass(o.getClass(), m); 32 | found = true; 33 | } 34 | } 35 | } else if(obj instanceof Map) { 36 | Map map = (Map) obj; 37 | for(Entry e : map.entrySet()) { 38 | Match k = contains(e.getKey().getClass()); 39 | Match v = contains(e.getValue().getClass()); 40 | if(k != null) { 41 | view = view.onClass(e.getKey().getClass(), k); 42 | found = true; 43 | } 44 | if(v != null) { 45 | view = view.onClass(e.getValue().getClass(), v); 46 | found = true; 47 | } 48 | } 49 | } else { 50 | Match m = contains(obj.getClass()); 51 | if(m != null) { 52 | view = view.onClass(obj.getClass(), m); 53 | found = true; 54 | } 55 | } 56 | 57 | if(found) { 58 | return view; 59 | } else { 60 | return null; 61 | } 62 | } 63 | 64 | public DefaultView onClass(Class cls, Match match) { 65 | matches.put(cls, match); 66 | return this; 67 | } 68 | 69 | private Match contains(Class cls) { 70 | if(cls == null) { 71 | return null; 72 | } 73 | 74 | Class current = cls; 75 | while(!current.equals(Object.class)) { 76 | //does current class exist in the map? 77 | if(matches.containsKey(current)) { 78 | return matches.get(current); 79 | } 80 | 81 | //does interface exist in the map? 82 | for(Class iface : cls.getInterfaces()) { 83 | if(matches.containsKey(iface)) { 84 | return matches.get(iface); 85 | } 86 | } 87 | current = current.getSuperclass(); 88 | } 89 | return null; 90 | } 91 | 92 | public static DefaultView create() { 93 | return new DefaultView(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonResult.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | public class JsonResult { 4 | private static final JsonResult instance = new JsonResult(); 5 | private static final ThreadLocal current = new ThreadLocal<>(); 6 | 7 | private JsonResult() { 8 | } 9 | 10 | /** 11 | * Use the provided {@code JsonView} object to serialize 12 | * the return value. 13 | * 14 | * @param view JsonView used to render JSON 15 | * @param Type of object being rendered 16 | * @return ResultWrapper to provide return value 17 | */ 18 | @SuppressWarnings("unchecked") 19 | public ResultWrapper use(JsonView view) { 20 | current.set(view); 21 | return new ResultWrapper<>(view); 22 | } 23 | 24 | public static JsonResult instance() { 25 | return instance; 26 | } 27 | 28 | static JsonView get() { 29 | return current.get(); 30 | } 31 | 32 | static void unset(){ 33 | current.remove(); 34 | } 35 | 36 | public static class ResultWrapper { 37 | private JsonView obj; 38 | 39 | private ResultWrapper(JsonView obj) { 40 | this.obj = obj; 41 | } 42 | 43 | /** 44 | * Returns the object being serialized 45 | * 46 | * @return the object 47 | */ 48 | public T returnValue() { 49 | return obj.getValue(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonResultRetriever.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | public class JsonResultRetriever { 7 | private static final Logger log = LoggerFactory.getLogger(JsonResultRetriever.class); 8 | 9 | static boolean hasValue() { 10 | return JsonResult.get() != null; 11 | } 12 | 13 | static JsonView retrieve() { 14 | JsonView val = JsonResult.get(); 15 | JsonResult.unset(); 16 | return val; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonViewHttpEntityMethodProcessor.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.http.converter.HttpMessageConverter; 6 | import org.springframework.web.context.request.NativeWebRequest; 7 | import org.springframework.web.method.support.ModelAndViewContainer; 8 | import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; 9 | 10 | import java.util.List; 11 | 12 | public class JsonViewHttpEntityMethodProcessor extends HttpEntityMethodProcessor { 13 | 14 | public JsonViewHttpEntityMethodProcessor(List> converters) { 15 | super(converters); 16 | } 17 | 18 | @Override 19 | public void handleReturnValue(Object returnValue, MethodParameter returnType, 20 | 21 | ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 22 | if(returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) { 23 | JsonView json = JsonResultRetriever.retrieve(); 24 | ResponseEntity re = (ResponseEntity) returnValue; 25 | returnValue = ResponseEntity.status(re.getStatusCode()) 26 | .headers(re.getHeaders()) 27 | .body(json); 28 | } 29 | 30 | super.handleReturnValue(returnValue, returnType, mavContainer, webRequest); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonViewMessageConverter.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.databind.JsonSerializer; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.databind.module.SimpleModule; 6 | import org.springframework.http.HttpOutputMessage; 7 | import org.springframework.http.converter.HttpMessageNotWritableException; 8 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 9 | 10 | import java.io.IOException; 11 | 12 | public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverter { 13 | 14 | private JsonViewSerializer serializer = new JsonViewSerializer(); 15 | 16 | public JsonViewMessageConverter() { 17 | super(); 18 | ObjectMapper defaultMapper = new ObjectMapper(); 19 | SimpleModule module = new SimpleModule(); 20 | module.addSerializer(JsonView.class, this.serializer); 21 | defaultMapper.registerModule(module); 22 | setObjectMapper(defaultMapper); 23 | } 24 | 25 | public JsonViewMessageConverter(ObjectMapper mapper) { 26 | super(); 27 | SimpleModule module = new SimpleModule(); 28 | module.addSerializer(JsonView.class, this.serializer); 29 | mapper.registerModule(module); 30 | setObjectMapper(mapper); 31 | } 32 | 33 | /** 34 | * Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.
35 | * This way you could register for instance a JODA serialization as a DateTimeSerializer.
36 | * Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.
37 | * Example:
38 | * 39 | * JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); 40 | * bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); 41 | * 42 | * 43 | * @param Type class of the serializer 44 | * @param class1 {@link Class} the class type you want to add a custom serializer 45 | * @param forType {@link JsonSerializer} the serializer you want to apply for that type 46 | */ 47 | public void registerCustomSerializer(Class class1, JsonSerializer forType) { 48 | this.serializer.registerCustomSerializer(class1, forType); 49 | } 50 | 51 | /** 52 | * Unregister a previously registtered serializer. @see registerCustomSerializer 53 | * 54 | * @param Type class of the serializer 55 | * @param class1 {@link Class} the class type for which you want to remove a custom serializer 56 | */ 57 | public void unregisterCustomSerializer(Class class1) { 58 | this.serializer.unregisterCustomSerializer(class1); 59 | } 60 | 61 | @Override 62 | protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { 63 | super.writeInternal(object, outputMessage); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonViewResponseProcessor.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import org.springframework.http.converter.HttpMessageConverter; 4 | import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; 5 | 6 | import java.util.List; 7 | 8 | public class JsonViewResponseProcessor extends RequestResponseBodyMethodProcessor { 9 | public JsonViewResponseProcessor(List> messageConverters) { 10 | super(messageConverters); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonViewReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.http.converter.HttpMessageConverter; 7 | import org.springframework.web.context.request.NativeWebRequest; 8 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 9 | import org.springframework.web.method.support.ModelAndViewContainer; 10 | 11 | import java.util.List; 12 | 13 | public class JsonViewReturnValueHandler implements HandlerMethodReturnValueHandler { 14 | private static final Logger log = LoggerFactory.getLogger(JsonViewReturnValueHandler.class); 15 | 16 | private final HandlerMethodReturnValueHandler delegate; 17 | private final DefaultView defaultView; 18 | 19 | public JsonViewReturnValueHandler(List> converters, DefaultView defaultView) { 20 | this.delegate = new JsonViewResponseProcessor(converters); 21 | this.defaultView = defaultView; 22 | } 23 | 24 | @Override 25 | public boolean supportsReturnType(MethodParameter returnType) { 26 | return delegate.supportsReturnType(returnType); 27 | } 28 | 29 | @Override 30 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 31 | Object val = returnValue; 32 | if(JsonResultRetriever.hasValue()) { 33 | val = JsonResultRetriever.retrieve(); 34 | log.debug("Found [" + ((JsonView) val).getValue().getClass() + "] to serialize"); 35 | } else { 36 | JsonView view = defaultView.getMatch(val); 37 | if(view != null) { 38 | val = view; 39 | log.debug("Default view found for " + val.getClass().getCanonicalName() + ", applied before serialization"); 40 | } else { 41 | log.debug("No JsonView found for thread, using returned value"); 42 | } 43 | } 44 | 45 | delegate.handleReturnValue(val, returnType, mavContainer, webRequest); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /spring-json-view/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.InitializingBean; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.converter.HttpMessageConverter; 12 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 13 | import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; 14 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; 15 | import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; 16 | 17 | import com.fasterxml.jackson.databind.JsonSerializer; 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | 20 | public class JsonViewSupportFactoryBean implements InitializingBean { 21 | protected static final Logger log = LoggerFactory.getLogger(JsonViewSupportFactoryBean.class); 22 | 23 | @Autowired 24 | protected RequestMappingHandlerAdapter adapter; 25 | 26 | protected final JsonViewMessageConverter converter; 27 | protected final DefaultView defaultView; 28 | 29 | public JsonViewSupportFactoryBean() { 30 | this(new ObjectMapper()); 31 | } 32 | 33 | public JsonViewSupportFactoryBean(ObjectMapper mapper) { 34 | this(new JsonViewMessageConverter(mapper.copy()), DefaultView.create()); 35 | } 36 | 37 | public JsonViewSupportFactoryBean(DefaultView defaultView) { 38 | this(new JsonViewMessageConverter(new ObjectMapper()), defaultView); 39 | } 40 | 41 | public JsonViewSupportFactoryBean(ObjectMapper mapper, DefaultView defaultView) { 42 | this(new JsonViewMessageConverter(mapper.copy()), defaultView); 43 | } 44 | 45 | private JsonViewSupportFactoryBean(JsonViewMessageConverter converter, DefaultView defaultView) { 46 | this.converter = converter; 47 | this.defaultView = defaultView; 48 | } 49 | 50 | @Override 51 | public void afterPropertiesSet() throws Exception { 52 | List handlers = new ArrayList<>(adapter.getReturnValueHandlers()); 53 | 54 | List> converters = removeJacksonConverters(adapter.getMessageConverters()); 55 | converters.add(converter); 56 | adapter.setMessageConverters(converters); 57 | 58 | decorateHandlers(handlers); 59 | adapter.setReturnValueHandlers(handlers); 60 | } 61 | 62 | protected List> removeJacksonConverters(List> converters) { 63 | List> copy = new ArrayList<>(converters); 64 | Iterator> iter = copy.iterator(); 65 | while(iter.hasNext()) { 66 | HttpMessageConverter next = iter.next(); 67 | if (next.getClass().getSimpleName().startsWith("MappingJackson2")) { 68 | log.debug("Removing {} as it interferes with us", next.getClass().getName()); 69 | iter.remove(); 70 | } 71 | } 72 | return copy; 73 | } 74 | 75 | protected void decorateHandlers(List handlers) { 76 | List> converters = new ArrayList<>(adapter.getMessageConverters()); 77 | converters.add(converter); 78 | for(HandlerMethodReturnValueHandler handler : handlers) { 79 | int index = handlers.indexOf(handler); 80 | if(handler instanceof HttpEntityMethodProcessor) { 81 | handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters)); 82 | } else if(handler instanceof RequestResponseBodyMethodProcessor) { 83 | handlers.set(index, new JsonViewReturnValueHandler(converters, defaultView)); 84 | break; 85 | } 86 | } 87 | } 88 | 89 | 90 | /** 91 | * Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.
92 | * This way you could register for instance a JODA serialization as a DateTimeSerializer.
93 | * Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.
94 | * Example:
95 | * 96 | * JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); 97 | * bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); 98 | * 99 | * @param Type class of the serializer 100 | * @param cls {@link Class} the class type you want to add a custom serializer 101 | * @param forType {@link JsonSerializer} the serializer you want to apply for that type 102 | */ 103 | public void registerCustomSerializer( Class cls, JsonSerializer forType ) 104 | { 105 | this.converter.registerCustomSerializer( cls, forType ); 106 | } 107 | 108 | 109 | /** 110 | * Unregister a previously registtered serializer. @see registerCustomSerializer 111 | * @param cls The class type the serializer was registered for 112 | */ 113 | public void unregisterCustomSerializer( Class cls ) 114 | { 115 | this.converter.unregisterCustomSerializer(cls); 116 | } 117 | 118 | } -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/ConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.monitorjbl.json.server.ConfigServer; 5 | import org.apache.http.HttpResponse; 6 | import org.apache.http.client.fluent.Request; 7 | import org.apache.http.entity.ContentType; 8 | import org.junit.AfterClass; 9 | import org.junit.Test; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import java.io.IOException; 14 | import java.net.ServerSocket; 15 | import java.net.URL; 16 | import java.util.ArrayList; 17 | import java.util.HashMap; 18 | import java.util.HashSet; 19 | import java.util.List; 20 | import java.util.Map; 21 | import java.util.Set; 22 | import java.util.concurrent.ExecutorService; 23 | import java.util.concurrent.Executors; 24 | import java.util.concurrent.TimeUnit; 25 | import java.util.concurrent.atomic.AtomicInteger; 26 | 27 | import static org.junit.Assert.assertEquals; 28 | import static org.junit.Assert.assertNotNull; 29 | import static org.junit.Assert.assertNull; 30 | 31 | public abstract class ConfigTest { 32 | 33 | protected static final Logger log = LoggerFactory.getLogger(XmlConfigurationTest.class); 34 | protected static ConfigServer server; 35 | protected static int port = -1; 36 | 37 | public static void start() throws Exception { 38 | //get random port 39 | ServerSocket sock = new ServerSocket(0); 40 | port = sock.getLocalPort(); 41 | sock.close(); 42 | 43 | //start server 44 | server.start(port); 45 | boolean ready = false; 46 | while(!ready) { 47 | try { 48 | new URL("http://localhost:" + port + "/ready").openStream(); 49 | ready = true; 50 | } catch(Exception e) { 51 | Thread.sleep(500); 52 | } 53 | } 54 | } 55 | 56 | @Test 57 | @SuppressWarnings("unchecked") 58 | public void testSimple() throws IOException { 59 | Map map = new ObjectMapper().readValue(Request.Get("http://localhost:" + port + "/bean").execute().returnContent().asStream(), HashMap.class); 60 | assertEquals("ignored", map.get("ignoredDirect")); 61 | assertNull(map.get("int1")); 62 | } 63 | 64 | @Test 65 | @SuppressWarnings("unchecked") 66 | public void testSimpleWithReturnValue() throws IOException { 67 | String json = Request.Get("http://localhost:" + port + "/bean/withReturnValue").execute().returnContent().asString(); 68 | Map map = new ObjectMapper().readValue(json, HashMap.class); 69 | assertEquals("ignored", map.get("ignoredDirect")); 70 | assertNull(map.get("int1")); 71 | } 72 | 73 | @Test 74 | @SuppressWarnings("unchecked") 75 | public void testList() throws IOException { 76 | List> list = new ObjectMapper().readValue(Request.Get("http://localhost:" + port + "/list").execute().returnContent().asStream(), ArrayList.class); 77 | 78 | assertEquals(2, list.size()); 79 | for(Map map : list) { 80 | assertEquals("ignored", map.get("ignoredDirect")); 81 | assertNull(map.get("int1")); 82 | } 83 | } 84 | 85 | @Test 86 | @SuppressWarnings("unchecked") 87 | public void testMultithreading() throws Exception { 88 | ExecutorService executorService = Executors.newFixedThreadPool(10); 89 | final AtomicInteger counter = new AtomicInteger(0); 90 | final AtomicInteger errors = new AtomicInteger(0); 91 | 92 | log.info("Multithreading test starting"); 93 | for(int i = 0; i < 100; i++) { 94 | executorService.submit(new Runnable() { 95 | public void run() { 96 | int c = counter.addAndGet(1); 97 | try { 98 | log.debug("testNoninterference() " + c + " started"); 99 | testNoninterference(); 100 | log.debug("testNoninterference() " + c + " passed"); 101 | } catch(Throwable e) { 102 | log.error("testNoninterference() " + c + " failed"); 103 | errors.addAndGet(1); 104 | } 105 | } 106 | }); 107 | executorService.submit(new Runnable() { 108 | public void run() { 109 | int c = counter.addAndGet(1); 110 | try { 111 | log.debug("testList() " + c + " started"); 112 | testList(); 113 | log.debug("testList() " + c + " passed"); 114 | } catch(Throwable e) { 115 | log.error("testList() " + c + " failed"); 116 | errors.addAndGet(1); 117 | } 118 | } 119 | }); 120 | } 121 | 122 | executorService.shutdown(); 123 | executorService.awaitTermination(120L, TimeUnit.SECONDS); 124 | log.info("Multithreading test finished"); 125 | assertEquals(200, counter.get()); 126 | assertEquals(0, errors.get()); 127 | } 128 | 129 | @Test 130 | public void testNoninterference() throws Exception { 131 | String ret = Request.Post("http://localhost:" + port + "/bean").bodyString( 132 | "{\"date\":\"1433214360187\",\"str1\":\"test\",\"notReal\":\"asdfas\"}", ContentType.APPLICATION_JSON) 133 | .execute().returnContent().asString(); 134 | assertEquals(5, ret.split("\n").length); 135 | } 136 | 137 | @Test 138 | @SuppressWarnings("unchecked") 139 | public void testCircularDependency() throws Exception { 140 | String ret = Request.Get("http://localhost:" + port + "/circularReference").execute().returnContent().asString(); 141 | Map map = new ObjectMapper().readValue(ret, HashMap.class); 142 | assertNotNull(map.get("val")); 143 | assertEquals("parent", map.get("val")); 144 | assertNull(map.get("subs")); 145 | } 146 | 147 | @Test 148 | @SuppressWarnings("unchecked") 149 | public void testResponseEntitySupport() throws Exception { 150 | HttpResponse response = Request.Get("http://localhost:" + port + "/responseEntity").execute().returnResponse(); 151 | Map map = new ObjectMapper().readValue(response.getEntity().getContent(), HashMap.class); 152 | 153 | assertEquals(202, response.getStatusLine().getStatusCode()); 154 | assertEquals("asdfasdf", response.getFirstHeader("TEST").getValue()); 155 | assertEquals("qwerqwer", map.get("str2")); 156 | assertEquals("ignored", map.get("ignoredDirect")); 157 | assertNull(map.get("int1")); 158 | } 159 | 160 | @Test 161 | @SuppressWarnings("unchecked") 162 | public void testDefaultViewSupport() throws Exception { 163 | HttpResponse response = Request.Get("http://localhost:" + port + "/defaultView").execute().returnResponse(); 164 | Map map = new ObjectMapper().readValue(response.getEntity().getContent(), HashMap.class); 165 | 166 | assertEquals(4, map.get("id")); 167 | assertEquals("someName", map.get("name")); 168 | assertNull(map.get("ignoredString")); 169 | } 170 | 171 | @Test 172 | @SuppressWarnings("unchecked") 173 | public void testDefaultViewSupportWithInheritance() throws Exception { 174 | HttpResponse response = Request.Get("http://localhost:" + port + "/defaultViewInheritance").execute().returnResponse(); 175 | Map map = new ObjectMapper().readValue(response.getEntity().getContent(), HashMap.class); 176 | 177 | assertEquals(4, map.get("id")); 178 | assertEquals("someName", map.get("name")); 179 | assertEquals("asdf", map.get("notIgnored")); 180 | assertNull(map.get("ignoredString")); 181 | } 182 | 183 | @Test 184 | @SuppressWarnings("unchecked") 185 | public void testDefaultViewSupportWithLists() throws Exception { 186 | HttpResponse response = Request.Get("http://localhost:" + port + "/defaultViewList").execute().returnResponse(); 187 | List> list = new ObjectMapper().readValue(response.getEntity().getContent(), ArrayList.class); 188 | 189 | assertEquals(1, list.size()); 190 | Map map = list.get(0); 191 | assertEquals(4, map.get("id")); 192 | assertEquals("someName", map.get("name")); 193 | assertNull(map.get("ignoredString")); 194 | } 195 | 196 | @Test 197 | @SuppressWarnings("unchecked") 198 | public void testDefaultViewSupportWithSets() throws Exception { 199 | HttpResponse response = Request.Get("http://localhost:" + port + "/defaultViewSet").execute().returnResponse(); 200 | Set> set = new ObjectMapper().readValue(response.getEntity().getContent(), HashSet.class); 201 | 202 | assertEquals(1, set.size()); 203 | Map map = set.iterator().next(); 204 | assertEquals(4, map.get("id")); 205 | assertEquals("someName", map.get("name")); 206 | assertNull(map.get("ignoredString")); 207 | } 208 | 209 | @Test 210 | @SuppressWarnings("unchecked") 211 | public void testDefaultViewSupportWithMaps() throws Exception { 212 | HttpResponse response = Request.Get("http://localhost:" + port + "/defaultViewMap").execute().returnResponse(); 213 | Map> map = new ObjectMapper().readValue(response.getEntity().getContent(), HashMap.class); 214 | 215 | assertNotNull(map.get("myobj")); 216 | assertEquals(4, map.get("myobj").get("id")); 217 | assertEquals("someName", map.get("myobj").get("name")); 218 | assertNull(map.get("myobj").get("ignoredString")); 219 | } 220 | 221 | @AfterClass 222 | public static void stop() { 223 | server.stop(); 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/JavaConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.monitorjbl.json.server.JavaConfigServer; 4 | import org.junit.BeforeClass; 5 | 6 | public class JavaConfigurationTest extends ConfigTest { 7 | 8 | @BeforeClass() 9 | public static void init() throws Exception { 10 | server = new JavaConfigServer(); 11 | ConfigTest.start(); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/XmlConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json; 2 | 3 | import com.monitorjbl.json.server.XmlConfigServer; 4 | import org.junit.BeforeClass; 5 | 6 | public class XmlConfigurationTest extends ConfigTest { 7 | 8 | @BeforeClass() 9 | public static void init() throws Exception { 10 | server = new XmlConfigServer(); 11 | ConfigTest.start(); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestChildObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestChildObject extends TestObject { 4 | private String childField; 5 | 6 | public String getChildField() { 7 | return childField; 8 | } 9 | 10 | public void setChildField(String childField) { 11 | this.childField = childField; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestDefaultViewObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestDefaultViewObject { 4 | private Long id; 5 | private String name; 6 | private String ignoredString; 7 | 8 | public Long getId() { 9 | return id; 10 | } 11 | 12 | public void setId(Long id) { 13 | this.id = id; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public String getIgnoredString() { 25 | return ignoredString; 26 | } 27 | 28 | public void setIgnoredString(String ignoredString) { 29 | this.ignoredString = ignoredString; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestDefaultViewSubobject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestDefaultViewSubobject extends TestDefaultViewObject { 4 | private String notIgnored; 5 | 6 | public String getNotIgnored() { 7 | return notIgnored; 8 | } 9 | 10 | public void setNotIgnored(String notIgnored) { 11 | this.notIgnored = notIgnored; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | 6 | import java.util.Arrays; 7 | import java.util.Date; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | @JsonIgnoreProperties({"ignoredIndirect"}) 12 | public class TestObject { 13 | private String str1; 14 | private String str2; 15 | @JsonIgnore 16 | private String ignoredDirect; 17 | private String ignoredIndirect; 18 | private Date date; 19 | private int int1; 20 | private TestSubobject sub; 21 | private List list; 22 | private Map mapOfStrings; 23 | private Map mapWithIntKeys; 24 | private String[] stringArray; 25 | private byte[] byteArray; 26 | private int[] intArray; 27 | private TestObject[] objArray; 28 | private List listOfObjects; 29 | private Map mapOfObjects; 30 | 31 | public String getStr1() { 32 | return str1; 33 | } 34 | 35 | public void setStr1(String str1) { 36 | this.str1 = str1; 37 | } 38 | 39 | public String getStr2() { 40 | return str2; 41 | } 42 | 43 | public void setStr2(String str2) { 44 | this.str2 = str2; 45 | } 46 | 47 | public String getIgnoredDirect() { 48 | return ignoredDirect; 49 | } 50 | 51 | public void setIgnoredDirect(String ignoredDirect) { 52 | this.ignoredDirect = ignoredDirect; 53 | } 54 | 55 | public String getIgnoredIndirect() { 56 | return ignoredIndirect; 57 | } 58 | 59 | public void setIgnoredIndirect(String ignoredIndirect) { 60 | this.ignoredIndirect = ignoredIndirect; 61 | } 62 | 63 | public Date getDate() { 64 | return date; 65 | } 66 | 67 | public void setDate(Date date) { 68 | this.date = date; 69 | } 70 | 71 | public int getInt1() { 72 | return int1; 73 | } 74 | 75 | public void setInt1(int int1) { 76 | this.int1 = int1; 77 | } 78 | 79 | public TestSubobject getSub() { 80 | return sub; 81 | } 82 | 83 | public void setSub(TestSubobject sub) { 84 | this.sub = sub; 85 | } 86 | 87 | public List getList() { 88 | return list; 89 | } 90 | 91 | public void setList(List list) { 92 | this.list = list; 93 | } 94 | 95 | public Map getMapOfStrings() { 96 | return mapOfStrings; 97 | } 98 | 99 | public void setMapOfStrings(Map mapOfStrings) { 100 | this.mapOfStrings = mapOfStrings; 101 | } 102 | 103 | public Map getMapWithIntKeys() { 104 | return mapWithIntKeys; 105 | } 106 | 107 | public void setMapWithIntKeys(Map mapWithIntKeys) { 108 | this.mapWithIntKeys = mapWithIntKeys; 109 | } 110 | 111 | public String[] getStringArray() { 112 | return stringArray; 113 | } 114 | 115 | public void setStringArray(String[] stringArray) { 116 | this.stringArray = stringArray; 117 | } 118 | 119 | public byte[] getByteArray() { 120 | return byteArray; 121 | } 122 | 123 | public void setByteArray(byte[] byteArray) { 124 | this.byteArray = byteArray; 125 | } 126 | 127 | public int[] getIntArray() { 128 | return intArray; 129 | } 130 | 131 | public void setIntArray(int[] intArray) { 132 | this.intArray = intArray; 133 | } 134 | 135 | public TestObject[] getObjArray() { 136 | return objArray; 137 | } 138 | 139 | public void setObjArray(TestObject[] objArray) { 140 | this.objArray = objArray; 141 | } 142 | 143 | public List getListOfObjects() { 144 | return listOfObjects; 145 | } 146 | 147 | public void setListOfObjects(List listOfObjects) { 148 | this.listOfObjects = listOfObjects; 149 | } 150 | 151 | public Map getMapOfObjects() { 152 | return mapOfObjects; 153 | } 154 | 155 | public void setMapOfObjects(Map mapOfObjects) { 156 | this.mapOfObjects = mapOfObjects; 157 | } 158 | 159 | @Override 160 | public String toString() { 161 | return "TestObject{" + 162 | "str1='" + str1 + '\'' + 163 | ", str2='" + str2 + '\'' + 164 | ", ignoredDirect='" + ignoredDirect + '\'' + 165 | ", ignoredIndirect='" + ignoredIndirect + '\'' + 166 | ", date=" + date + 167 | ", int1=" + int1 + 168 | ", sub=" + sub + 169 | ", list=" + list + 170 | ", mapOfStrings=" + mapOfStrings + 171 | ", mapWithIntKeys=" + mapWithIntKeys + 172 | ", stringArray=" + Arrays.toString(stringArray) + 173 | ", byteArray=" + Arrays.toString(byteArray) + 174 | ", intArray=" + Arrays.toString(intArray) + 175 | ", objArray=" + Arrays.toString(objArray) + 176 | ", listOfObjects=" + listOfObjects + 177 | ", mapOfObjects=" + mapOfObjects + 178 | '}'; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestSubobject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | import java.util.List; 4 | 5 | public class TestSubobject { 6 | private String val; 7 | private TestSubobject sub; 8 | private List subs; 9 | 10 | public TestSubobject(String val) { 11 | this.val = val; 12 | } 13 | 14 | public TestSubobject(String val, TestSubobject sub) { 15 | this.val = val; 16 | this.sub = sub; 17 | } 18 | 19 | public TestSubobject() { 20 | } 21 | 22 | public String getVal() { 23 | return val; 24 | } 25 | 26 | public void setVal(String val) { 27 | this.val = val; 28 | } 29 | 30 | public TestSubobject getSub() { 31 | return sub; 32 | } 33 | 34 | public void setSub(TestSubobject sub) { 35 | this.sub = sub; 36 | } 37 | 38 | public List getSubs() { 39 | return subs; 40 | } 41 | 42 | public void setSubs(List subs) { 43 | this.subs = subs; 44 | } 45 | } -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/model/TestUnrelatedObject.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.model; 2 | 3 | public class TestUnrelatedObject { 4 | private Long id; 5 | private String name; 6 | 7 | public Long getId() { 8 | return id; 9 | } 10 | 11 | public void setId(Long id) { 12 | this.id = id; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public void setName(String name) { 20 | this.name = name; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/ConfigServer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | public interface ConfigServer { 4 | public void start(int port); 5 | 6 | public void stop(); 7 | } 8 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/Context.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.monitorjbl.json.JsonViewSupportFactoryBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 10 | 11 | @EnableWebMvc 12 | @Configuration 13 | @ComponentScan({"com.monitorjbl.json.server"}) 14 | public class Context extends WebMvcConfigurerAdapter { 15 | @Bean 16 | public JsonViewSupportFactoryBean views() { 17 | return new JsonViewSupportFactoryBean(JacksonConfiguration.configureJackson(new ObjectMapper()), DefaultViewFactory.instance()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/DefaultViewFactory.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | import com.monitorjbl.json.DefaultView; 4 | import com.monitorjbl.json.model.TestDefaultViewObject; 5 | 6 | import static com.monitorjbl.json.Match.match; 7 | 8 | public class DefaultViewFactory { 9 | private static final DefaultView defaultView = DefaultView.create().onClass(TestDefaultViewObject.class, match().exclude("ignoredString")); 10 | 11 | public static DefaultView instance() { 12 | return defaultView; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/JacksonConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | 8 | /** 9 | * Configures Jackson mapper for unit tests. Works with XML-based configuration 10 | * if it is included as a bean. 11 | */ 12 | public class JacksonConfiguration { 13 | private final ObjectMapper mapper; 14 | 15 | public JacksonConfiguration(ObjectMapper mapper) { 16 | this.mapper = mapper; 17 | configureJackson(mapper); 18 | } 19 | 20 | public static ObjectMapper configureJackson(ObjectMapper mapper) { 21 | mapper.enable(SerializationFeature.INDENT_OUTPUT); 22 | mapper.setSerializationInclusion(Include.NON_NULL); 23 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 24 | return mapper; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/JavaConfigServer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | import org.eclipse.jetty.server.Server; 4 | import org.eclipse.jetty.servlet.ServletContextHandler; 5 | import org.eclipse.jetty.servlet.ServletHolder; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; 9 | import org.springframework.web.servlet.DispatcherServlet; 10 | 11 | public class JavaConfigServer implements ConfigServer{ 12 | public static final Logger log = LoggerFactory.getLogger(JavaConfigServer.class); 13 | private boolean running; 14 | private Thread thread; 15 | 16 | public synchronized void start(final int port) { 17 | if(thread != null) { 18 | throw new IllegalStateException("Server is already running"); 19 | } 20 | 21 | thread = new Thread(new Runnable() { 22 | @Override 23 | public void run() { 24 | try { 25 | Server server = new Server(port); 26 | 27 | final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); 28 | applicationContext.register(Context.class); 29 | 30 | final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext)); 31 | final ServletContextHandler context = new ServletContextHandler(); 32 | context.setContextPath("/"); 33 | context.addServlet(servletHolder, "/*"); 34 | 35 | server.setHandler(context); 36 | 37 | running = true; 38 | server.start(); 39 | log.info("Server started"); 40 | 41 | while(running) { 42 | Thread.sleep(1); 43 | } 44 | 45 | server.stop(); 46 | log.info("Server stopped"); 47 | } catch(Exception e) { 48 | log.error("Server exception", e); 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | }); 53 | thread.start(); 54 | } 55 | 56 | public void stop() { 57 | running = false; 58 | try { 59 | thread.join(); 60 | } catch(InterruptedException e) { 61 | e.printStackTrace(); 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | new JavaConfigServer().start(9090); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/XmlConfigServer.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server; 2 | 3 | import org.eclipse.jetty.server.Server; 4 | import org.eclipse.jetty.servlet.ServletContextHandler; 5 | import org.eclipse.jetty.servlet.ServletHolder; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.context.support.XmlWebApplicationContext; 9 | import org.springframework.web.servlet.DispatcherServlet; 10 | 11 | public class XmlConfigServer implements ConfigServer { 12 | public static final Logger log = LoggerFactory.getLogger(XmlConfigServer.class); 13 | private boolean running; 14 | private Thread thread; 15 | 16 | public synchronized void start(final int port) { 17 | if(thread != null) { 18 | throw new IllegalStateException("Server is already running"); 19 | } 20 | 21 | thread = new Thread(new Runnable() { 22 | @Override 23 | public void run() { 24 | try { 25 | Server server = new Server(port); 26 | 27 | final XmlWebApplicationContext xmlBasedContext = new XmlWebApplicationContext(); 28 | //System.out.println(xmlBasedContext.getEnvironment().getClass()); 29 | xmlBasedContext.setConfigLocation("classpath:context.xml"); 30 | 31 | final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(xmlBasedContext)); 32 | final ServletContextHandler context = new ServletContextHandler(); 33 | context.setContextPath("/"); 34 | context.addServlet(servletHolder, "/*"); 35 | server.setHandler(context); 36 | 37 | running = true; 38 | server.start(); 39 | log.info("Server started"); 40 | 41 | while(running) { 42 | Thread.sleep(1); 43 | } 44 | 45 | server.stop(); 46 | log.info("Server stopped"); 47 | } catch(Exception e) { 48 | log.error("Server exception", e); 49 | throw new RuntimeException(e); 50 | } 51 | } 52 | }); 53 | thread.start(); 54 | } 55 | 56 | public void stop() { 57 | running = false; 58 | try { 59 | thread.join(); 60 | } catch(InterruptedException e) { 61 | e.printStackTrace(); 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | new XmlConfigServer().start(9090); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /spring-json-view/src/test/java/com/monitorjbl/json/server/controller/JsonController.java: -------------------------------------------------------------------------------- 1 | package com.monitorjbl.json.server.controller; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import com.monitorjbl.json.JsonResult; 5 | import com.monitorjbl.json.JsonView; 6 | import com.monitorjbl.json.Match; 7 | import com.monitorjbl.json.model.TestDefaultViewObject; 8 | import com.monitorjbl.json.model.TestDefaultViewSubobject; 9 | import com.monitorjbl.json.model.TestObject; 10 | import com.monitorjbl.json.model.TestSubobject; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.stereotype.Controller; 15 | import org.springframework.web.bind.annotation.RequestBody; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.RequestMethod; 18 | import org.springframework.web.bind.annotation.ResponseBody; 19 | 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.Set; 24 | 25 | import static java.util.Arrays.asList; 26 | import static java.util.Collections.singleton; 27 | import static java.util.Collections.singletonList; 28 | import static java.util.Collections.singletonMap; 29 | 30 | @Controller 31 | public class JsonController { 32 | private static final Logger log = LoggerFactory.getLogger(JsonController.class); 33 | private final JsonResult json = JsonResult.instance(); 34 | 35 | @RequestMapping(method = RequestMethod.GET, value = "/ready") 36 | @ResponseBody 37 | public String ready() { 38 | return "readys"; 39 | } 40 | 41 | @RequestMapping(method = RequestMethod.GET, value = "/blank") 42 | @ResponseBody 43 | public void blank() { 44 | //do nothing 45 | } 46 | 47 | @RequestMapping(method = RequestMethod.GET, value = "/bean") 48 | @ResponseBody 49 | public void bean() { 50 | TestObject obj = new TestObject(); 51 | obj.setInt1(1); 52 | obj.setIgnoredDirect("ignored"); 53 | obj.setStr2("asdf"); 54 | obj.setList(asList("red", "blue", "green")); 55 | obj.setSub(new TestSubobject("qwerqwerqwerqw")); 56 | 57 | json.use(JsonView.with(obj) 58 | .onClass(TestObject.class, Match.match() 59 | .exclude("int1") 60 | .include("ignoredDirect"))); 61 | } 62 | 63 | @RequestMapping(method = RequestMethod.GET, value = "/bean/withReturnValue") 64 | @ResponseBody 65 | public TestObject beanWithReturn() { 66 | TestObject obj = new TestObject(); 67 | obj.setInt1(1); 68 | obj.setIgnoredDirect("ignored"); 69 | obj.setStr2("asdf"); 70 | obj.setList(asList("red", "blue", "green")); 71 | obj.setSub(new TestSubobject("qwerqwerqwerqw")); 72 | 73 | return json.use(JsonView.with(obj) 74 | .onClass(TestObject.class, Match.match() 75 | .exclude("int1") 76 | .include("ignoredDirect"))) 77 | .returnValue(); 78 | } 79 | 80 | @RequestMapping(method = RequestMethod.GET, value = "/list") 81 | @ResponseBody 82 | public void list() { 83 | List list = new ArrayList<>(); 84 | TestObject obj = new TestObject(); 85 | obj.setInt1(1); 86 | obj.setIgnoredDirect("ignored"); 87 | obj.setStr2("asdf"); 88 | list.add(obj); 89 | obj = new TestObject(); 90 | obj.setInt1(2); 91 | obj.setIgnoredDirect("ignored"); 92 | obj.setStr2("asdf"); 93 | list.add(obj); 94 | 95 | log.debug("GET testList()"); 96 | 97 | json.use(JsonView.with(list) 98 | .onClass(TestObject.class, Match.match() 99 | .exclude("int1") 100 | .include("ignoredDirect"))); 101 | } 102 | 103 | @RequestMapping(method = RequestMethod.POST, value = "/bean") 104 | @ResponseBody 105 | public TestObject acceptData(@RequestBody TestObject object) { 106 | if(object.getDate().getTime() != 1433214360187L) { 107 | throw new RuntimeException("field not set properly"); 108 | } 109 | log.debug("POST testNoninterference()"); 110 | return object; 111 | } 112 | 113 | @RequestMapping(method = RequestMethod.GET, value = "/map") 114 | @ResponseBody 115 | public Map map() { 116 | return ImmutableMap.of( 117 | "red", "herring", 118 | "blue", "fish"); 119 | } 120 | 121 | @RequestMapping(method = RequestMethod.GET, value = "/circularReference") 122 | @ResponseBody 123 | public ResponseEntity circular() { 124 | TestSubobject parent = new TestSubobject(); 125 | TestSubobject child = new TestSubobject(); 126 | 127 | child.setVal("child"); 128 | child.setSubs(asList(parent)); 129 | 130 | parent.setVal("parent"); 131 | parent.setSubs(asList(child)); 132 | 133 | parent = json.use(JsonView.with(parent) 134 | .onClass(TestSubobject.class, Match.match() 135 | .exclude("subs"))) 136 | .returnValue(); 137 | 138 | return ResponseEntity.ok(parent); 139 | } 140 | 141 | @RequestMapping(method = RequestMethod.GET, value = "/responseEntity") 142 | @ResponseBody 143 | public ResponseEntity responseEntity() { 144 | TestObject obj = new TestObject(); 145 | obj.setInt1(4); 146 | obj.setIgnoredDirect("ignored"); 147 | obj.setStr2("qwerqwer"); 148 | return ResponseEntity.accepted() 149 | .header("TEST", "asdfasdf") 150 | .body(json.use(JsonView.with(obj) 151 | .onClass(TestObject.class, Match.match() 152 | .exclude("int1") 153 | .include("ignoredDirect"))) 154 | .returnValue()); 155 | } 156 | 157 | @RequestMapping(method = RequestMethod.GET, value = "/defaultView") 158 | @ResponseBody 159 | public TestDefaultViewObject defaultView() { 160 | TestDefaultViewObject obj = new TestDefaultViewObject(); 161 | obj.setId(4L); 162 | obj.setName("someName"); 163 | obj.setIgnoredString("oeisjfs"); 164 | return obj; 165 | } 166 | 167 | @RequestMapping(method = RequestMethod.GET, value = "/defaultViewInheritance") 168 | @ResponseBody 169 | public TestDefaultViewObject defaultViewInheritance() { 170 | TestDefaultViewSubobject obj = new TestDefaultViewSubobject(); 171 | obj.setId(4L); 172 | obj.setName("someName"); 173 | obj.setNotIgnored("asdf"); 174 | obj.setIgnoredString("oeisjfs"); 175 | return obj; 176 | } 177 | 178 | @RequestMapping(method = RequestMethod.GET, value = "/defaultViewList") 179 | @ResponseBody 180 | public List defaultViewList() { 181 | TestDefaultViewObject obj = new TestDefaultViewObject(); 182 | obj.setId(4L); 183 | obj.setName("someName"); 184 | obj.setIgnoredString("oeisjfs"); 185 | return singletonList(obj); 186 | } 187 | 188 | @RequestMapping(method = RequestMethod.GET, value = "/defaultViewSet") 189 | @ResponseBody 190 | public Set defaultViewSet() { 191 | TestDefaultViewObject obj = new TestDefaultViewObject(); 192 | obj.setId(4L); 193 | obj.setName("someName"); 194 | obj.setIgnoredString("oeisjfs"); 195 | return singleton(obj); 196 | } 197 | 198 | @RequestMapping(method = RequestMethod.GET, value = "/defaultViewMap") 199 | @ResponseBody 200 | public Map defaultViewMap() { 201 | TestDefaultViewObject obj = new TestDefaultViewObject(); 202 | obj.setId(4L); 203 | obj.setName("someName"); 204 | obj.setIgnoredString("oeisjfs"); 205 | return singletonMap("myobj", obj); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /spring-json-view/src/test/resources/context.xml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-json-view/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=WARN, stdout 2 | 3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 | log4j.appender.stdout.layout.ConversionPattern=%p (%t) [%c] %m%n 6 | 7 | #log4j.logger.org.apache.http=DEBUG 8 | #log4j.logger.org.apache.http.wire=ERROR 9 | log4j.logger.com.monitorjbl=INFO 10 | log4j.logger.com.monitorjbl.json.JsonViewResponseProcessor=INFO 11 | #log4j.logger.org.springframework=WARN --------------------------------------------------------------------------------