libhibernate3-java-3.6.10.Final/0000755000175000017500000000000012143273450015614 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/lgpl.txt0000644000175000017500000006347411714611271017331 0ustar ebourgebourg GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libhibernate3-java-3.6.10.Final/changelog.txt0000644000175000017500000071345311714611271020321 0ustar ebourgebourgHibernate Changelog =================== Note: Newer entries are automatically generated and the description might not match the actual issue resolution (i.e. a bug might not be a bug). Please refer to the particular case on JIRA using the issue tracking number to learn more about each case. Changes in version 3.6.10 (2012.02.08) ------------------------------------------- https://hibernate.onjira.com/browse/HHH/fixforversion/11851 ** Bug * [HHH-3218] - ManyToOne Persisting Cascade in Embeddable as part of ElementCollection * [HHH-5299] - Multi-Level cascading of unsaved instances with bidirectional associations fails with TransientObjectException (Carl-Eric Menzel) * [HHH-5755] - javax.persistence.criteria.Expression.as() is broken * [HHH-6580] - Discriminator value used as ID when inserting entity to PosgtreSQL * [HHH-6984] - some statistics are incremented even when stats are disabled * [HHH-6986] - BACKPORT: EntityManagerImpl.close() and EntityManagerImpl.isOpen() should check if the session factory is closed * [HHH-6987] - BACKPORT: Create typed query in EntityManager throws NullPointerException when filters are present * [HHH-6988] - BACKPORT: Criteria.setLockMode does not work correctly * [HHH-6989] - BACKPORT: Removing an entity and persisting it again fails * [HHH-6990] - BACKPORT: Improper handling of primitive arrays in AbstractQueryImpl.registerParameterBinding * [HHH-6991] - BACKPORT: SequenceStyleGenerator should force use of TableStructure when the optimizer is PooledLo * [HHH-7008] - HEM leaks bean info ** New Feature * [HHH-7005] - BACKPORT: Ability (easier) to run bits of code in a timeout protected way Changes in version 3.6.9 (2011.12.14) ------------------------------------------- https://hibernate.onjira.com/browse/HHH/fixforversion/11752 ** Bug * [HHH-6714] - Parentheses dissapear in HQL query where they should stay * [HHH-6784] - The REVINFO table is always added to Hibernate's configuration, even if there are no audit tables * [HHH-6793] - SessionCacheCleaner doesn't accomodate for closed sessions * [HHH-6806] - Auto scan for JPA entities does not work in exploded packages in JBoss AS < 7 Changes in version 3.6.8 (2011.10.26) ------------------------------------------- https://hibernate.onjira.com/browse/HHH/fixforversion/11354 ** Bug * [HHH-2304] - Wrong type detection for sql type char(x) columns * [HHH-3434] - hql insert doesn't work when inserting into a table with composite-id * [HHH-4838] - 2L-Querycache ImmutableNaturalKeyLookup not properly recognized as hasImmutableNaturalId() is called on wrong EntityMetamodel * [HHH-4982] - JPA OneToOne(optional=true) not supported with @PrimaryKeyJoinColumn * [HHH-5789] - Hibernate 3.5.4 doesn't build with OpenJDK 6b18-1.8.2 or greater * [HHH-5801] - ColumnNameCache.columnNameToIndexCache map should be synchronized * [HHH-5917] - Envers doesnt track all columns anymore * [HHH-6121] - Hibernate statistics should log at DEBUG level instead of INFO * [HHH-6177] - Envers - problem with mapping relation when using mixed inheritance strategy * [HHH-6599] - Hibernate mark as rollback even for no transaction requests * [HHH-6614] - Bad performance: audited entity updates (lots of them) with no EntityManager clear * [HHH-6647] - ValidityAuditStrategy breaks in case of concurrent updates to the same entity ** Improvement * [HHH-6723] - Remove extra join from eager @OneToOne * [HHH-6745] - Sybase ASE dialect improvement ** New Feature * [HHH-5580] - tracking entity names in a revision ** Patch * [HHH-4596] - Bulk insertion with assigned identifiers * [HHH-6577] - CUBRID Database Dialect ** Task * [HHH-5930] - Remove hibernate-tools dependency from runtime scope if it's not needed * [HHH-6591] - Port changes for HHH-5348 to 3.6 branch Changes in version 3.6.7 (2011.08.17) ------------------------------------------- https://hibernate.onjira.com/browse/HHH/fixforversion/11250 ** Bug * [HHH-1780] - negation of EXISTS in hql query does not work ** Patch * [HHH-6370] - HSQLDB dialect - fixes reported issues and adds minor enhancement (Fred Toussi) Changes in version 3.6.6 (2011.07.20) ------------------------------------------- https://hibernate.onjira.com/browse/HHH/fixforversion/11232 ** Bug * [HHH-2614] - Blob Length Set to 255 By Default With Derby DB * [HHH-6381] - using @SecondaryTable with optional=true not handled for joined subclasses (@Inheritance(strategy = InheritanceType.JOINED) * [HHH-6386] - sybase improvement * [HHH-6442] - JarVisitorFactory is reconstructing URLs without the URLStreamHandler association * [HHH-6456] - Test failure in CachedPropertyRefCollectionTest behind a proxy ** Improvement * [HHH-5478] - Update Ehcache capabilities in the section [21.2. The Second Level Cache] of the documentation * [HHH-6083] - Upgrade to latest Ehcache & add org.hibernate 3.3 SPI wrappers * [HHH-6421] - Reduce log level of LazyInitializationException from ERROR to TRACE ** Patch * [HHH-4630] - Criteria join on composite identifier generates wrong alias, SQL error ** Task * [HHH-6322] - upgrade to hibernate-jpa-2.0-api-1.0.1.Final * [HHH-6420] - SQL Server dialect is broken (Tomaz Cerar) * [HHH-6455] - Update Hibernate-ehcache to Ehcache 2.4.3 Changes in version 3.6.5 (2011.06.08) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11226 ** Bug * [HHH-2225] - NPE when eager fetching joined component with native SQL query * [HHH-4760] - NotAuditedException occurs when auditReader.getRevisions() is called for javassist proxies * [HHH-5572] - clean up Sybase job failures * [HHH-5808] - ObjectNotFoundException for an audited optional association. Envers is creating a proxy even when the association is null. * [HHH-5967] - Envers Fetching Indexed Collection - Duplicate Row Exception * [HHH-6119] - NullPointerException in AbstractPathImpl without source path * [HHH-6176] - Envers ignores custom comparators for SortedSets * [HHH-6219] - Memory leak with Infinispan cache * [HHH-6223] - connection leak in entitymanager and annotation's testsuite * [HHH-6231] - Upgrade ehcache version * [HHH-6242] - no Types.BINARY type mapping in PostgresqlDialect * [HHH-6243] - JBPAPP-3312 org.hibernate.test.legacy.CustomSQLTest fails ** Improvement * [HHH-5025] - Support caching audit queries using ehcache's DiskStore. * [HHH-5598] - sybase integration improvement * [HHH-5790] - method BasicBinder#bind() and BasicExtractor#extract missing guards for trace logging * [HHH-6248] - Ominous-sounding WARN message from SessionFactoryObjectFactory ** Task * [HHH-6203] - Make necessary updates to pass nexus artifact validation * [HHH-6224] - update mysql jdbc driver version for testing Changes in version 3.6.4 (2011.05.04) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11220 ** Bug * [HHH-2049] - LEFT OUTER JOIN subcriteria filters children * [HHH-4073] - discriminator formula creates problem in hibernate envers * [HHH-4787] - AuditProperty.isNull() doesn't generate "tab.col is null" SQL clause as expected * [HHH-5276] - Table REVINFO created in the default schema even if the property is otherwise set * [HHH-5887] - Document typo hibernate.hbm2ddl.import_files * [HHH-6069] - Escape entity fields name when required * [HHH-6095] - Improve the way AbstractEntityManagerImpl.flush checks for an active transaction, should apply to other AbstractEntityManagerImpl methods that also check for an active tx * [HHH-6099] - Documentation poms have wrong parent declaration * [HHH-6120] - Configuration addCacheableFile doesn't close input and output streams * [HHH-6197] - Blank line at top of configuration.xml for en_US manual causes breaks documentation build ** Improvement * [HHH-6096] - H2Dialect should use CACHED option for temporary table creation ** New Feature * [HHH-6170] - Offer ability to customize the default TransactionFactory and TransactionManagerLookup implementation used if none is specifically specified Changes in version 3.6.3 (2011.04.06) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11211 ** Bug * [HHH-4999] - createSQLQuery(query).list() result screw up when when columns in different tables have same name * [HHH-5803] - Better handling of implicit literal numeric expression typing * [HHH-5940] - @MapKeyJoinColumns always throws an exception * [HHH-5974] - unnecessary import which crashes the system in OSGi environement * [HHH-5978] - TS: Postgresql 8.x - CustomSQLTest fails because UPPER()'s result is not converted to number. * [HHH-6057] - hibernate.cfg.xml references wrong hbm.xml files and doesn't include reference to DTD file * [HHH-6058] - Error in mapping file in Event.hbm.xml file for documentation in download ** Improvement * [HHH-5993] - Expose SessionFactoryObserver to Hibernate EntityManager configuration * [HHH-6022] - Harden the JBossTSStandaloneTransactionManagerLookup implementation to better support JBoss TS version changes ** New Feature * [HHH-6084] - Provide an identifier generator strategy provider component for EntityManager ** Patch * [HHH-5348] - support for TypedQuery jpaql/hql "scalar" queries ** Task * [HHH-6009] - Rename module directories on 3.6 branch to match master Changes in version 3.6.2 (2011.03.09) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11206 ** Bug * [HHH-5590] - Don't log and rethrow exceptions in AbstractFlushingEventListener * [HHH-5842] - Types.Binary column type should be registered as "binary($l) for HSQLDialect (Fred Toussi) * [HHH-5890] - Parent POM: License comment in points to 404 * [HHH-5892] - changelog.txt shows 3.6.1-Final release date in 2010; should be 2011 * [HHH-5893] - Tests fail for dialects that return null for empty LOBs * [HHH-5907] - derby does not support materialize a LOB locator outside the transaction in which it was created * [HHH-5952] - BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING binder does not unwrap value before binding ** Deprecation * [HHH-5968] - Deprecate nullSafeGet()/nullSafeSet() methods with no SessionImplementor argument from UserType and AbstractSingleColumnStandardBasicType ** Improvement * [HHH-5906] - Expose AbstractEntityPersister.getPropertyUniqueness() as public for OGM to use * [HHH-5977] - Add tests for @JoinColumn using secondary table * [HHH-5993] - Expose SessionFactoryObserver to Hibernate EntityManager configuration ** New Feature * [HHH-5916] - Add support for a programmatic way to define a default EntityPersister and CollectionPersister class implementation Changes in version 3.6.1 (2011.02.02) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11170 ** Bug * [HHH-3873] - DB2Dialect.getLimitString raise DB2 error message when called with limit=0 * [HHH-4617] - Using materialized blobs with Postgresql causes error * [HHH-4646] - Inconsistent behavior with Audited and MappedSuperclass annotations * [HHH-5126] - JPA Query with InExpression and Collection_valued_input_parameter Complains About Bad Syntax * [HHH-5136] - map-key-column is broken * [HHH-5168] - DB2Dialect generates CROSS JOINs which aren't supported * [HHH-5177] - auditing a child of a mapped superclass forces auditing on siblings * [HHH-5280] - Exception on unidirectional collection whose elements are owned by several collection: "java.lang.IllegalArgumentException: object is not an instance of declaring class" * [HHH-5359] - Derived entity usecase fails when the association is bidirectional * [HHH-5403] - Update to hsqldb 2.0.0 for testing * [HHH-5534] - Regression in 3.5.5: Cascade on merge for Sets fails with transient entities * [HHH-5550] - Hibernate.createBlob() fails when used in current_session_context_class=thread mode * [HHH-5599] - NPE occurs when using Infinispan as L2 Cache * [HHH-5657] - Assembly needs to exclude .git * [HHH-5659] - Problem using Hibernate3.6.0.Final with BLOB and CLOB fields in Oracle. * [HHH-5681] - Packaged JAR file shouldn't contain files with an absolute path * [HHH-5686] - Collections should be loaded by default using "lazy collection fetch" instead of "extra lazy collection" fetch * [HHH-5704] - New getSubString() handling in ClobProxy is incompatible with MySQL JDBC PS.setClob(int, Clob) for empty CLOB * [HHH-5706] - Incorrect accounting for 1-based LOB offsets * [HHH-5709] - JPA Metamodel: EntityType.getName != @Entity.name * [HHH-5710] - incorrect test logic of org.hibernate.test.readonly.ReadOnlyCriteriaQueryTest * [HHH-5715] - Using row_number with the SQLServerDialect makes select distinct useless * [HHH-5717] - LockOptions not being set correctly * [HHH-5725] - SqlServerDialect should support SQL 2000 which does not support the row_number function * [HHH-5727] - Collection member declaration not handling optional AS in HQL. * [HHH-5729] - Only one check constraint is generated when @Min and @Max annotation is used on a single field * [HHH-5736] - Problem with "not" function of CriteriaBuilder * [HHH-5750] - Envers unset session on proxy * [HHH-5756] - Envers creates new revisions when only collection changed for entity * [HHH-5776] - Hibernate documentation: images missing due to links pointing to file:/NotBackedUp/gbadner * [HHH-5791] - NullPointerException merging a transient entity with non-nullable properties that are null if insert is delayed and check_nullability is false * [HHH-5793] - Query and timestamp caches to use cluster cache loader to avoid behaving like sync repl caches * [HHH-5800] - Implement missing element-collection related xml in JPAOverridenAnnotationReader * [HHH-5806] - mapping static inner class causes hsqldb tests fails * [HHH-5817] - Passing char[] or byte[] to equal function of CriteriaBuilder throws java.lang.ClassCastException (Vyacheslav Dimitrov) * [HHH-5821] - JPA EntityType's (or ManagedType's) getSingularAttributes() returns the version attribute with isVersion set to false. * [HHH-5826] - org.hibernate.util.SerializationHelper#resolveClass never tries loader3 * [HHH-5830] - Improve LOB Type handling * [HHH-5838] - Proxool connection pool should only close pools it opened * [HHH-5853] - Problem loading cachable collections defined with a property-ref key with a versioned owner * [HHH-5883] - @Lob annotated field throws MappingException ** Improvement * [HHH-3965] - Expose the ability to use varchar(max) or nvarchar(max) * [HHH-4539] - Make UPPER and LOWER work on MS SQL Server text and ntext columns * [HHH-4878] - Update documentation about "text" type and new "image", "materialized_blob", and "materialized_clob" types * [HHH-5325] - Minor issues in test suite and suggestions for improvements (fixes HSQDB 2.0 failures) * [HHH-5588] - Improve support for entityNames - determine the entityName for a retrieved object vía envers * [HHH-5631] - Fix warnings reported by Maven 3 * [HHH-5701] - Add .metadata/* to .gitignore * [HHH-5724] - Improve the error message on Bean Validation exception by showing the constraint violation data * [HHH-5726] - SqlServer2005Dialect should support variable limit * [HHH-5761] - Update source repository links in Envers documentation * [HHH-5794] - Add support for additional orm.xml elements for Map handling and element collections * [HHH-5816] - Expose list of modified properties in PostUpdateEvent * [HHH-5823] - Poor multithread performance in UpdateTimestampsCache class * [HHH-5824] - Poor multithread performance in SessionFactoryImpl.getQueryCache method * [HHH-5859] - Upgrade to Infinispan 4.2.1.CR1 ** New Feature * [HHH-2655] - SQLServer2005Dialect (ROW_NUMBER for Paging) * [HHH-5371] - Add support for REVEND_TSTMP which will enable SQL table partitioning by time * [HHH-5879] - Expose state from AbstractEntityPersister / Type / SessionFactoryImplementor for OGM usage **Task * [HHH-5625] - Update Envers manual to reflect 'experimental' status of ValidityAuditStrategy and 'Revision-end-timestamp' * [HHH-5768] - upgrade H2 version to 1.2.145 (was 1.2.140) Changes in version 3.6.0.CR2 (2010.09.29) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11131 ** Bug * [HHH-892] - HQL parser does not resolve alias in ORDER BY clause * [HHH-2917] - Using subselects as operands for arithmetic operations causes NullPointerException * [HHH-4510] - Add column-level read/write support (HHH-4440) to annotations * [HHH-5490] - dirty data be inserted into 2L cache * [HHH-5552] - Infinispan listener implementations need to load entities and keys using application classloader. * [HHH-5563] - JndiInfinispanRegionFactory creates region with a stopped cache, if region previously existed * [HHH-5568] - correct wrong format in document * [HHH-5573] - Change TestCase to rebuildSessionFactory() whenever sessions var is accessed * [HHH-5590] - Don't log and rethrow exceptions in AbstractFlushingEventListener * [HHH-5591] - ConcurrentStatisticsImpl#queryExecuted() does not update queryExecutionMaxTimeQueryString * [HHH-5592] - org.hibernate.test.hql.ASTParserLoadingOrderByTest hangs on postgresql * [HHH-5593] - org.hibernate.test.legacy.FooBarTest.testCollectionWhere fails on hsqldb * [HHH-5594] - org.hibernate.test.jpa.lock.JPALockTest fails on hsqldb * [HHH-5595] - postgresql jdbc driver does not implement the setQueryTimeout method * [HHH-5596] - org.hibernate.test.annotations.onetoone.OneToOneTest.testPkOneToOneSelectStatementDoesNotGenerateExtraJoin() fails on postgresql * [HHH-5597] - org.hibernate.test.criteria.LikeTest.testLike fails on postgresql because of the default escape charactor ** Improvement * [HHH-5560] - Envers ValidAuditTimeStrategy needs a better name * [HHH-5589] - mysql does not support column check ** New Feature * [HHH-5190] - Provide annotation support for 's force and insert * [HHH-5205] - Add support for source="db" for timestamp versions ** Patch * [HHH-5581] - Improve InformixDialect sequence support Changes in version 3.6.0.CR1 (2010.09.15) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11141 ** Sub-task * [HHH-3766] - Modify the queries executed to use the "end-revision" column, when available * [HHH-5446] - Write an envers tutorial guide * [HHH-5499] - Extend AuditReader interface with findRevisions() method ** Bug * [HHH-5310] - orm_2_0.xsd compliant mapping files break in JEE use cases * [HHH-5356] - Sybase 15 does not support cross join * [HHH-5484] - org.hibernate.type.UUIDCharType incorrectly mapped to char and causes test fail due to the padding space * [HHH-5542] - Infinispan region factory uses same cache instance for all timestamp regions * [HHH-5545] - Resolve query cache results not up to date testsuite failures ** Improvement * [HHH-3709] - Add StartRevision/EndRevison fileds to audit tables * [HHH-5372] - Improve envers query performance by using new REVEND column * [HHH-5441] - Create "Getting Started Guide" * [HHH-5543] - JEE bootstrapping should only parse and validate mapping files once * [HHH-5557] - Sybase supports alias length upto 30 characters * [HHH-5564] - Upgrade to Infinispan 4.2.x ** Task * [HHH-5524] - Move tagRelease.sh into svn Changes in version 3.6.0.Beta4 (2010.09.01) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11140 ** Sub-task * [HHH-5442] - Write native tutorial chapter * [HHH-5444] - Write annotations tutorial chapter * [HHH-5445] - Write a jpa/entitymanager tutorial guide * [HHH-5462] - Write preface * [HHH-5463] - Write a community chapter ** Bug * [HHH-817] - Projection aliases should not be applied to where-clause (Milosz Tylenda) * [HHH-1189] - interfaces for Proxies are not regonized as interfaces * [HHH-3334] - Cascade-save breaks if parent ID is assigned (delays insert) and child has identity ID (early insert) (Wallace Wadge) * [HHH-5142] - Exception when initializing lazy @ManyToMany indexed collection containing not audited entities * [HHH-5225] - Cannot parse order-by fragment if it contains a registered function without parentheses * [HHH-5440] - Joined collection expressions not properly "rendered" in JPA Criteria queries * [HHH-5511] - Infinispan Region.destroy() impl should call cache.stop() * [HHH-5512] - JndiInfinispanRegionFactory shouldn't try to stop CacheManager * [HHH-5517] - Switch uuid generation in SessionFactory to org.hibernate.id.UUIDGenerator instead * [HHH-5519] - VersionedItem should not extend Item, otherwise query cache results are confusing * [HHH-5520] - Per org.hibernate.cache.RegionFactory javadocs, implementors should be allowed to use no-arg constructor ** Deprecation * [HHH-5489] - Deprecate jbosscache as a second level cache provider, in favor of infinispan ** Improvement * [HHH-5427] - derby 10.6.1.0 native sequence support broken * [HHH-5507] - Add @MapKeyType annotation * [HHH-5509] - Leverage StandardBasicTypes internaly * [HHH-5515] - Upgrade to Infinispan 4.1.0.CR3 ** Patch * [HHH-5197] - Envers documentation doesn't include the correct configuration when using Hibernate directly * [HHH-5453] - ByteCodeHelper.readByteCode won't load classes bigger than a constant size ** Task * [HHH-5502] - Upgrade to maven-jdocbook-plugin 2.3.2 * [HHH-5505] - enable Sybase 15.5 in the test db profile * [HHH-5506] - rollback maven-jdocbook-plugin to 2.3.0 * [HHH-5510] - Upgrade to maven-jdocbook-plugin 2.3.3 Changes in version 3.6.0.Beta3 (2010.08.18) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11133 ** Sub-task * [HHH-5464] - Write a chapter about obtaining Hibernate ** Bug * [HHH-1643] - Sub-query as function parameter - either sub-query is missed from SQL or NullPointerException raised * [HHH-5180] - StandardQueryCache.get() does not handle EntityNotFoundException for natural key lookups * [HHH-5426] - HQL update/delete does not invalidate the query cache * [HHH-5449] - Versioned HQL update might issue incorrect SQL * [HHH-5469] - HHH-3659 is only half done, due to HHH-4989 (i.e. no HQL performance log when running Java 5) * [HHH-5473] - Default for CHECK_NULLABILITY does not allow merge retries ** Improvement * [HHH-5438] - Skip deployment of "irrelevant" modules * [HHH-5439] - Deployment of site.xml * [HHH-5474] - Clean up usages of now deprecated ExtendedMappings * [HHH-5477] - Introduce StandardBasicTypes for standard basic type constants ** Patch * [HHH-5300] - Configurable QueryPlanCache reference counts (Manuel Dominguez Sarmiento) ** Task * [HHH-5451] - deprecate cglib as bytecode provider * [HHH-5479] - Upgrade jDocBook plugin to 2.3.0 * [HHH-5485] - Move hiberante dtd files from http://hibernate.sourceforge.net to http://www.hibernate.org/dtd Changes in version 3.6.0.Beta2 (2010.08.04) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11132 ** Bug * [HHH-2350] - 2nd level cache broken for non-inverse bidirectional one-to-many relation * [HHH-4011] - ChainedPropertyAccessor is not serializable, which breaks caching to disk and replicated caches. * [HHH-5097] - Bug in ParameterizedFunctionExpression with two or more parameters: IllegalArgumentException * [HHH-5296] - AbstractFromImpl::getJoin() shall return empty set, not null * [HHH-5355] - org.hibernate.test.id.uuid.sqlrep.sqlchar.UUIDCharTest errors with IngresDialect * [HHH-5400] - Binding BLOB values via byte[] (MaterializedBlobType) fails in 3.6 on MySQL * [HHH-5408] - Revise JPA compliance wording used in documentation according to Oracle policies * [HHH-5415] - org.hibernate.type.descriptor.java.DataHelper dumping "NClob not found" exception to stderr * [HHH-5425] - PropertyAccessException when caching results from a Query with a ResultTransformer that as 1 value per row * [HHH-5431] - Infinispan's CacheAdapterImpl.putAllowingTimeout not using silent flag ** Improvement * [HHH-2510] - override equals() and fix hashCode() in AliasToBeanResultTransformer * [HHH-5212] - Alter SQLFunction contract to be more flexible * [HHH-5283] - Add BasicType handling of java.net.URL * [HHH-5295] - Rendered JPAQL query shall be the same all the times, aliases shall not have random indexes * [HHH-5331] - Remove reflection calls on SessionFactory for JDK 1.5 detection in relation to Statistics * [HHH-5375] - Merge AnnotationConfiguration into Configuration * [HHH-5418] - Have Configuration delay parsing/binding of mappings until buildMappings() is called * [HHH-5420] - introducing new dialect for ms sql server 2008 with jdbc 3.0 and above * [HHH-5424] - ResultTransformer should only be set in the QueryKey if putting/getting data that is actually transformed ** New Feature * [HHH-3908] - Expose way to fully control fetching and result mapping on SQLQuery * [HHH-5423] - Provide a JBoss TS TransactionManagerLookup implementation for standalone (non JNDI) usage ** Patch * [HHH-5246] - Addition of withClause for DetachedCriteria (Shawn Clowater) * [HHH-5349] - CriteriaHQLAlignmentTest fails with an error running with the Ingres dialect * [HHH-5401] - Update to HHH-5381 HSQLDB new dialect (Fred Toussi) * [HHH-5435] - Add identity column support to the Ingres10Dialect ** Task * [HHH-5259] - Invalid reflection optimization configuration property name in Hibernate documentation. * [HHH-5416] - upgrade to h2 1.2.140 Changes in version 3.6.0.Beta1 (2010.07.21) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/10941 ** Sub-task * [HHH-3764] - Add the "end-revision" column when generating metadata * [HHH-3765] - Fill the "end revision" column with appropriate data in add/mod/del/collection work units * [HHH-5115] - Migrate Annotations documentation system to jdocbook's maven plugin (like core) * [HHH-5149] - Update "Basic O/R Mapping" (chapter 5) and "Collection Mapping" (chapter 6) of Core manual to use annotations * [HHH-5150] - Update settings section to reflect merge from Annotations and Core documentation * [HHH-5153] - Update Filters chapter to also show annotation configuration * [HHH-5155] - Move Additional modules chapter from Annotations to Core probably in Appendix * [HHH-5366] - Move annotations module tests into testsuite module * [HHH-5367] - Move annotations module sources into core module * [HHH-5379] - Update "Transitive persistence" (10.11) section to incorporate annotations * [HHH-5380] - Update "Cache mappings" (20.2.1) section to incorporate annotations * [HHH-5388] - Add @NamedQuery, @NamedNativeQuery, @SqlResultSetMapping, @Tuplizers and @FetchProfile to Core documentation * [HHH-5389] - Update custom CRUD chapter ** Bug * [HHH-2269] - Many-to-one cascade fails with TransientObjectException if the inverse collection is marked CascadeType.DELETE_ORPHAN * [HHH-2277] - bidirectional both lazy=false fetch=join lead to infinite loop * [HHH-3001] - The NoopOptimizer is not thread safe * [HHH-3005] - DTD: map-key should allow nested type rather than attribute. * [HHH-3096] - COUNT DISTINCT operator with idenfication variable w/ composite primary key produces bad sql * [HHH-3377] - Update H2Dialect to use DECIMAL SQL type instead of NUMERIC * [HHH-3694] - ResultTransformer not used when scroll() is used on a named SQLQuery * [HHH-4036] - EntityMetamodel entityNameByInheritenceClassNameMap field used inconsistently * [HHH-4147] - Eager Bidirectional association with @ManyToOne in PK lead to infinite loop * [HHH-4156] - c3p0 is not used when only specific hibernate.c3p0.* properties * [HHH-4240] - SecondaryTables not recognized when using JOINED inheritance * [HHH-4250] - @ManyToOne - @OneToMany doesn't work with @Inheritance(strategy= InheritanceType.JOINED) * [HHH-4568] - Sybase - Test "BatchTest" fails due to "unexpected row count from update" * [HHH-4647] - Problems with @JoinColumn referencedColumnName and quoted column and table names * [HHH-4716] - NotAuditedException using the entity name concept of hibernate. * [HHH-4773] - @CollectionId does not force the id column to not-null * [HHH-4957] - Criteria Projections.countDistinct() function broken * [HHH-4966] - Entity Manager bug with ParameterExpressionImpl * [HHH-4968] - Cannot deactivate default BeanValidationListener independently of DDL constraints generation (Vladimir Klyushnikov) * [HHH-4991] - ManyToMany table not joined due to max_fetch_depth parameter, results to SQL exceptions * [HHH-5006] - hibernate.globally_quoted_identifiers=true and Annotations tests * [HHH-5032] - Setting LockModeType.OPTIMISTIC_FORCE_INCREMENT defaults to only OPTIMISTIC * [HHH-5042] - TableGenerator does not increment hibernate_sequences.next_hi_value anymore after having exhausted the current lo-range * [HHH-5063] - Projections that have aliases same as the property name result in invalid sql * [HHH-5069] - Fix annotation documentation wrt setup * [HHH-5094] - PersistenceUtilHelper cannot access non-public fields/methods (it should be able to) * [HHH-5098] - AssertionFailure thrown when collection contains a parameterized type * [HHH-5109] - @OneToOne - too many joins * [HHH-5125] - The annotations @Entity and @MappedSuperclass used in one class produce a nullpointerexception * [HHH-5131] - SchemaExport drop fails if constraint names change * [HHH-5135] - "Ambiguous column" exception thrown with columns having the same name as a function registered with the dialect (e.g. to_date, floor) * [HHH-5173] - hql - average returns double but looses the decimal part * [HHH-5178] - Unit tests in org.hibernate.test.immutable fail on mssql and sybase due to keyword used for table and column name * [HHH-5191] - CollectionMetadataGenerator fails to obtain mappedBy attribute when is defined on superclasses * [HHH-5195] - FilterImpl.validate() throws NullPointerExeption on deserialization * [HHH-5204] - Introduce @RequiresDialectFeature annotation * [HHH-5207] - Unexpected exception occurs during refresh of a transient immutable business object. * [HHH-5208] - Oracle 11g R2 RAC - Test SequenceIdentityTest fails because first value of sequence is "2" * [HHH-5210] - Query Cache effective only after closing the session that created the cache * [HHH-5211] - no need to create a schema first when run this test org.hibernate.test.sql.hand.custom.db2.DB2CustomSQLTest * [HHH-5220] - Unit tests related to HHH-5063 and HHH-5135 fail on some dialects * [HHH-5230] - Regresion! @SequenceGenerator with allocationSize=1 fails Other allocationSizes appear to be decremented by 1 * [HHH-5231] - Unit test failures lock up when they run on DB2 and PostgreSQL * [HHH-5233] - @FetchProfile fails to take more than one @FetchProfile.FetchOverride * [HHH-5253] - TableHiLoGenerator does not increment hi-value any more when lo-range es exhausted * [HHH-5258] - Persistence.isLoaded(Object, String) fails if the annotated property does not have a public getter or field * [HHH-5272] - Typo in tutorial at web site * [HHH-5286] - Jar Scanner instances cannot be passed to EntityManagerFactory creation method * [HHH-5288] - Envers auditReader.find() returns wrong data for embedded components using fields with default values * [HHH-5298] - @AuditMappedBy doesn't work on an inherited relation * [HHH-5315] - AuditJoinTable rows are no longer flushed to the database * [HHH-5318] - Wrong logic for RequiresDialectFeature in org.hibernate.test.annotations.HibernateTestCase * [HHH-5319] - Clean up data created in org.hibernate.test.annotations.onetomany.OneToManyTest#testUnidirectionalExplicit * [HHH-5322] - Regression in PersistenceUtilHelper * [HHH-5323] - correct jdbc driver version for testing * [HHH-5324] - Tests fail on mysql * [HHH-5329] - NoClassDefFoundError when using Hibernate 3.5 with J2SE 1.4 because of a wrong catch block * [HHH-5332] - JndiInfinispanRegionFactory cannot be instantiated * [HHH-5334] - PersistenceUtilHelpe.findMember(Class, String) private method doesn't work with members of a superclass * [HHH-5340] - Typo in tutorial at web site * [HHH-5370] - Building IN condition with CriteriaBuilder providing collection of values not working. * [HHH-5384] - HEM should not register its own Synchronization * [HHH-5395] - Fix the failing Lobs test ** Improvement * [HHH-3050] - Convert usage of Hibernate's FastHashMap to ConcurrentHashMap (Java 1.5) * [HHH-4945] - Replace all usages of EJB3TestCase with org.hibernate.ejb.test.TestCase * [HHH-5138] - Redesign types + introduce TypeRegistry & TypeResolver * [HHH-5144] - Dont restrict on jdk5 in hibernate core development * [HHH-5162] - Deprecate @Entity.mutable in favor of @Immutable * [HHH-5171] - Allow usage of standalone @JoinFormula annotation * [HHH-5182] - Inject SessionFactory into "non-basic" Types * [HHH-5217] - Minimize double sequence value reads in PooledOptimizer * [HHH-5218] - Provide a new "pooled value" based optimizer which interprets the database value as the low boundary instead of upper boundary * [HHH-5245] - Introduce LobHelper * [HHH-5248] - Introduce CompositeType interface (to replace AbstractComponentType interface) * [HHH-5251] - NativeSQLQueryReturn impls pre-cache a final hashcode based on non-final fields * [HHH-5252] - AttributeFactory needs more info in AssertionFailure * [HHH-5262] - Allow UserType and CompositeUserType to be registered with BasicTypeRegistry * [HHH-5268] - Support for java.util.UUID properties/generators * [HHH-5285] - Add support for CompositeUserType to implement org.hibernate.usertype.LoggableUserType * [HHH-5362] - Upgrade trunk to latest Infinispan 4.1 * [HHH-5373] - Better account for SQLWarnings in temp table creation ** New Feature * [HHH-3579] - Support for PostgreSQL UUID data type * [HHH-3659] - statistics: Execution time of a query * [HHH-5260] - Allow query region name specific eviction settings * [HHH-5337] - Allow customization of "import.sql" file name and multi files import ** Patch * [HHH-1574] - AbstractEntityPersister.getNaturalIdentifierSnapshot doesn't work with many-to-one ids (Alex Burgel) * [HHH-2268] - Skip bridge methods during getter determination (JDK Bug 5062759) * [HHH-3220] - Patch to prevent "org.hibernate.AssertionFailure: possible non-threadsafe access to the session" error caused by stateless sessions * [HHH-5064] - OrderBy string getting dumped to console on session factory creation (Shawn Clowater) * [HHH-5078] - JPA criteria query numeric expressions produce wrong result (due to wrong bracketing) * [HHH-5147] - EnumType speed up in initEnumValues() * [HHH-5213] - Add native SQL Boolean type to Ingres10Dialect * [HHH-5336] - a few typo fixes * [HHH-5381] - HSQLDB new dialect (Fred Toussi) ** Task * [HHH-4868] - Upgrade to Javassist 3.12.0.GA * [HHH-5139] - Increase minimum language level from 1.4 to 1.5 * [HHH-5145] - Update pom to use the new distributationManagement information * [HHH-5148] - Merge Hibernate Annotations reference documentation into Core * [HHH-5181] - Merge hibernate-annotations module code into hibernate-core * [HHH-5186] - update db profiles id and jdbc properties' name to use dballocator * [HHH-5200] - Prepare to use H2 as the default testing datbase * [HHH-5254] - Present document on Types as a separate chapter * [HHH-5281] - TypeSafeActivator should also generate constraints for @Length * [HHH-5294] - declare source files encoding to utf-8 to avoid maven warning * [HHH-5317] - Update Annotations and EM to use latest version of Hibernate Validator * [HHH-5357] - Rename hibernate-testing packages * [HHH-5358] - Merge jmx module back into core * [HHH-5365] - merge annotations module into core module * [HHH-5374] - Upgrade to H2 version 1.2.139 * [HHH-5382] - Upgrade to slf4j 1.6 * [HHH-5397] - Odds and ends from documentation merge Changes in version 3.5.1 (2010.04.14) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11021 ** Bug * [HHH-2809] - dialect changes: limit string * [HHH-3543] - method org.hibernate.transaction.JDBCTransaction.notifyLocalSynchsBeforeTransactionCompletion "swallows" all exceptions occured inside it * [HHH-4077] - Misuse of NamingStrategy and logical column names in HbmBinder * [HHH-4721] - Error in AuditSync.beforeCompletion() does not result in faillure of JDBCTransaction * [HHH-4912] - testManyToManyWithFormula induces error with Ingres dialect * [HHH-4938] - Multiple errors reported during legacy FooBarTest with Ingres * [HHH-4961] - org.hibernate.test.hql.ASTParserLoadingTest error running testPaginationWithPolymorphicQuery with Ingres * [HHH-4965] - Implicit parameters abusively use TypeFactory.heuristicType losing UserType and XToOneType info * [HHH-4970] - org.hibernate.test.hql.ASTParserLoadingTest error running testComponentParameterBinding with Ingres * [HHH-4973] - org.hibernate.test.hql.ASTParserLoadingTest error running testSelectClauseSubselect with Ingres * [HHH-4976] - org.hibernate.test.hql.ASTParserLoadingTest error running testImplicitPolymorphism with Ingres * [HHH-4977] - org.hibernate.test.hql.ASTParserLoadingTest error running testOneToManyFilter with Ingres * [HHH-5045] - org.hibernate.test.hql.HQLTest failure running testConcatenation with Ingres * [HHH-5059] - callouts and programlistings with highlighting * [HHH-5082] - QueryException thrown when grouping by component * [HHH-5096] - FetchingScrollableResultsImpl.last() does not move to the last result if cursor is after the last result * [HHH-5102] - Instances of a subclass can't be loaded * [HHH-5103] - Specifying the referencedColumnName in a @JoinColumn in backtics like `uid` fails * [HHH-5104] - EntityType.isEqual() test x equals x but should test x equals y (Thierry-Dimitri Roy) * [HHH-5106] - UnsupportedOperationException on SQL named native queries when using the type-safe API ** Improvement * [HHH-3962] - Ingres Hibernate dialect for EAP 4.3.0 GA CP04 ** Patch * [HHH-2470] - Use of session.createSQLQuery causes memory leak (Harry Mark and Michael Stevens) * [HHH-5003] - IngresDialect requires query substitutions for boolean values * [HHH-5076] - Multiple failures reported during ReadOnlyProxyTest with Ingres ** Task * [HHH-3997] - Build aggregated javadocs * [HHH-5083] - Align javadoc styles better with docbook / website * [HHH-5084] - Improve overview for aggregated javadocs * [HHH-5116] - Remove copyrighted fonts from annotations Changes in version 3.5.0-Final (2010.03.31) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11022 ** Sub-task * [HHH-4599] - An embeddable class may contain ToOne or ToMany associations * [HHH-4666] - Implement the clarified rules for resource discovery (esp for and co) * [HHH-4691] - Validate all new concepts are supported in orm.xml ** Bug * [HHH-2088] - TypeMismatchException on object equality expression from one-to-one relationship * [HHH-2997] - LikeExpression case sensitive not working properly * [HHH-4784] - JDBCTransaction -> commit() -> notifyLocalSynchsBeforeTransactionCompletion() * [HHH-4870] - Cannot determine java-type from given member [null] * [HHH-4919] - DefaultMergeEventListener does not call Interceptor.instantiate() for a new persistent entity (Francesco Degrassi) * [HHH-4931] - two tests in org.hibernate.test.legacy.MultiTableTest fail on Ingres * [HHH-4946] - org.hibernate.test.legacy.FooBarTests testLimit failure with Ingres * [HHH-4958] - Immutable entity snapshot is retained after insert * [HHH-4972] - javax.persistence.query.timeout and javax.persistence.lock.timeout can be passed when creating an EMF * [HHH-4993] - Updates to read-only entity associations made while in persistent state are ignored by flush * [HHH-4998] - org.hibernate.test.hql.ASTParserLoadingTest failure running testStr with Ingres * [HHH-5000] - duplicate words in the documents * [HHH-5010] - org.hibernate.test.hql.CriteriaHQLAlignmentTest.testCriteriaAggregationReturnType() needs call flush before do the query * [HHH-5013] - the previous select query should not to hold locks in TypeParameterTest#testSave ** Improvement * [HHH-1088] - Add support for projections using composite keys and components * [HHH-4374] - @Subselect * [HHH-4907] - Support for tuple syntax in HQL/Criteria on databases which do not support tuple syntax * [HHH-4940] - Document immutable/read-only entity and immutable collection functionality * [HHH-4989] - Make Statistics concurrent safe when Java 5 is present (Alex Snaps) * [HHH-5008] - Log query lock mode in EntityLoader constructor * [HHH-5022] - Small documentation improvements in chapter 6 ** New Feature * [HHH-4812] - Add fetch profile support in annotations * [HHH-4994] - find(Class entityClass, Object primaryKey, Map properties) and refresh(Object entity, Map properties) do not honor properties * [HHH-5026] - Ability to customize Scanner strategies ** Patch * [HHH-4419] - is missed using annotations * [HHH-5049] - org.hibernate.test.legacy.ParentChildTest error running testLoadAfterNonExists with Ingres ** Task * [HHH-4933] - Write documentation on JPA 2 * [HHH-4990] - Move to commons-annotations 3.2.0.Final * [HHH-4995] - Update dependency versions for JPA 2 and Metamodel Generator * [HHH-4996] - Use monospace fonts in docbook programlistings * [HHH-5035] - upgrade to jdocbook 2.2.3 * [HHH-5047] - Remove column coordinates from areaspecs * [HHH-5058] - Include hibernate-jpa-2.0-api (JPA 2 API) in release bundle Changes in version 3.5.0-CR-2 (2010.02.24) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11011 ** Sub-task * [HHH-4605] - Add support for @OneToMany @JoinColumn in XML * [HHH-4606] - Add support for @*ToOne @JoinTable in XML * [HHH-4662] - Implement javax.persistence.query.timeout * [HHH-4676] - Any interceptor exception (RTE) should mark the tx for rollback * [HHH-4765] - Enhance Dialect support for JPA-2 locking ** Bug * [HHH-3817] - JBC second level cache integration can cache stale collection data * [HHH-4583] - Incorrect handling of empty conjunction and disjunction * [HHH-4613] - KEY, VALUE and ENTRY should not be strict keywords * [HHH-4693] - MapProxy - problems during marshalling/demarchalling * [HHH-4809] - Immutable entities added to a session have Status.MANAGED unless loaded by the Session * [HHH-4810] - Persistent immutable and read-only entities are updated before being deleted * [HHH-4825] - mapping order impacting behavior leading to bug * [HHH-4836] - Infinispan: 2L QueryCache don't considers cached queries which belong to current transaction * [HHH-4845] - Investigate why entitymanager test cannot be run in forkMode once * [HHH-4899] - Type not supported: org.hibernate.type.TimestampType * [HHH-4917] - Keyword TYPE not supported * [HHH-4926] - Upgrade to jDocBook 2.2.1 * [HHH-4928] - Non-Audited Entity with @ManyToOne in PK causes error in Envers 1.2.2 * [HHH-4932] - Upgrade EM to use the latest metamodel generator (CR-1) * [HHH-4944] - putFromLoad calls could store stale data * [HHH-4948] - Session.flush() does not always cascade save or update to read-only or immutable entities ** Improvement * [HHH-4905] - Allow consistent handling of numeric primary key values by any integral data type * [HHH-4911] - Make referencedColumnName case insensitive * [HHH-4930] - Drop org. prefix on hibernate.cache.default_cache_concurrency_strategy and hibernate.id.new_generator_mappings for consistency * [HHH-4934] - Improve logging in MetadataContext and AttributeFactory * [HHH-4942] - Refactor PackagedEntityManagerTest and JarVisitorTest to use ShrinkWrap ** New Feature * [HHH-3841] - Add support for lock timeouts ** Patch * [HHH-4908] - Multiple failures reported during ReadOnlyProxyTest with Ingres ** Task * [HHH-4640] - Add test with JNDI bound JBoss Transactions Transaction Manager * [HHH-4936] - Document JPA criteria queries * [HHH-4949] - Document JPA 2 metamodel * [HHH-4951] - Correct DTD entities for injecting version and date into docs Changes in version 3.5.0-CR-1 (2010.02.10) ------------------------------------------- http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11014 ** Sub-task * [HHH-4661] - Properly propagate Query.setLockMode to Hibernate Core * [HHH-4664] - Implement EntityManagerFactory#getProperties() * [HHH-4848] - Derived identities: Derived entities using @IdClass and mapping a @XToOne are not supported ** Bug * [HHH-4317] - Memory leak in EnumType class. * [HHH-4824] - localpath appeared in the doc xml * [HHH-4841] - Read-only proxies in NonFlushedChanges are not read-only when applied to a new session * [HHH-4861] - Allow lookup by the "simple" pk type of "parent entity" in "derived identities" cases * [HHH-4877] - "Check Nullability" logging incorrectness in SettingsFactory * [HHH-4880] - EntityManager.refresh does not throw EntityNotFoundException for removed entity * [HHH-4883] - Unable to join across a component * [HHH-4884] - Fix binding of @TableGenerator#initialValue into org.hibernate.id.enhanced.TableGenerator * [HHH-4889] - @IdClass containing an associated entity reference (instead of the pk of this associated entity) should still work * [HHH-4895] - property mappings incorrect for composite ids with many-to-one * [HHH-4896] - Read-only proxy targets initialized from second-level cache are not read-only * [HHH-4898] - Results from read-only Criteria and Query obtained from query cache are not read-only * [HHH-4900] - Wrong immutable type check in IdMetadataGenerator * [HHH-4902] - Handle JPA 2 requirement of setting id attribute to non-null with its equivalent of foreign-generator ** Improvement * [HHH-4578] - Criteria is missing read-only flag * [HHH-4704] - Pass session into EntityTuplizer#setIdentifier * [HHH-4879] - Support HQL index-refering functions for many-to-many, indexed collections * [HHH-4894] - Process composite-id sub-generators PersistentIdentifierGenerator contract(s) ** New Feature * [HHH-4731] - Public API to know if an entity class is audited ** Patch * [HHH-4886] - Merge minor change from IngresDialect.java from 3.3.2 for Ingres 9.2 compatibility ** Task * [HHH-4892] - Simplify testing of persistence packages Changes in version 3.5.0-Beta-4 (2010.01.28) ------------------------------------------- - http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/11012 ** Sub-task * [HHH-4529] - Partial support for derived identity (including @MapsId) * [HHH-4651] - Add support for EntityManager properties * [HHH-4659] - Add support for standard declarative cache (@Cacheable) * [HHH-4660] - Support Cache Retrieve Mode and Cache Store Mode Properties * [HHH-4669] - Implement JDBC driver properties support * [HHH-4677] - implement PersistenceUnitInfo#getPersistenceXMLSchemaVersion(); and the same in PersistenceMetadata * [HHH-4678] - Apply PersistenceUnitInfo#getSharedCacheMode and #getValidationMode * [HHH-4690] - Consider adding a flag for legacy/new generators * [HHH-4725] - implement orphanRemoval for OneToOne * [HHH-4849] - Derived Identity: default @JoinColumn is not honored for properties linked to @MapsId ** Bug * [HHH-3828] - Criteria: Restriction whith class does not work * [HHH-4736] - Cannot pass ValidatorFactory into PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map) * [HHH-4781] - When a read-only entity is refreshed it is changed to modifiable * [HHH-4789] - Check annotations and entitymanager poms for consistent plugin configuration * [HHH-4796] - NullPointerException when an @AssociationOverride joinColumn is set but no @AssociationOverride joinTable is on a given property * [HHH-4797] - Backref properties should be ignored when building the JPA 2 metamodel (leading atm to java.lang.IllegalArgumentException: Cannot determine java-type from given member [null]) * [HHH-4804] - Entities in non-lazy associations loaded by a read-only HQL Query are not read-only * [HHH-4805] - JPA 2 metamodel impl ignores nested generics * [HHH-4806] - em.getTransaction.commit() does not always wrap in a RollbackException * [HHH-4807] - not-null checking no longer applied even if Bean Validation is not present * [HHH-4828] - Entities returned by Query...setReadOnly(true)...iterate() should be read-only * [HHH-4834] - Exception in the metamodel population when raw types are used in collections * [HHH-4843] - org.hibernate.ejb.util.LogHelper assumes javax.persistence.spi.PersistenceUnitInfo#getProperties is never null * [HHH-4846] - NPE in AbstractIdentifiableType.checkDeclaredVersion * [HHH-4847] - In nested id generators, use the context aka idObject for set operation and the raw entity as input for generation * [HHH-4850] - Transaction commit throws RollbackException instead of PessimisticLockException * [HHH-4851] - OneToOneSecondPass Metadata is mistakenly interpreted * [HHH-4853] - 3.4.4.3 Lock Mode Properties and Uses, "Vendor-specific hints must be ignored if they are not understood. " * [HHH-4855] - Incorrectly tries to search a secondary table when globally quoted identifiers are used * [HHH-4858] - Implicitly add a cascade PERSIST when @MapsId is used * [HHH-4859] - NPE when the entity uses a core-style "embedded" id (ie not an @IdClass nor an explicit @EmbeddedId) * [HHH-4862] - quoted column/alias names not properly handled in org.hibernate.loader.EntityAliases ** Improvement * [HHH-4552] - Support generated value within composite keys * [HHH-4813] - annotation and entitymanager module should use the maven-injection-plugin to generate version string * [HHH-4816] - Cleanup JPA setting name constants ** New Feature * [HHH-2501] - Add capability to set a default read-only/modifiable setting for a session * [HHH-2762] - SessionImplementor.getNonFlushedChanges()/applyNonFlushedChanges() API and initial implementation * [HHH-4616] - Configure global/cache level JMX statistics from Hibernate configuration file * [HHH-4726] - Add support for delete-orphan cascading to * [HHH-4840] - Support embedded id properties like core ** Task * [HHH-4792] - Validate fix for HHH-4791 * [HHH-4793] - Revert disabling of VersionsJoinTableRangeComponentNamingTest and fix underlying issue * [HHH-4799] - Create a *unit* test that asserts SerializationHelper's ability to deser a class using an "isolated classloader" (aka a TCCL) * [HHH-4822] - Add @FailureExpected annotation to annotations and entitymananger modules to allow the skipping of tests * [HHH-4823] - Reorder modules in top level pom so that testsuite runs directly after core * [HHH-4856] - Upgrade dependency to jpa metamodel generator Changes in version 3.5.0-Beta-3 (2010.01.13) ------------------------------------------- - http://opensource.atlassian.com/projects/hibernate/browse/HHH/fixforversion/10981 ** Sub-task * [HHH-4203] - Implement JPA 2.0 criteria apis (compiling) * [HHH-4352] - implement @AttributeOverride for Map (key, value) * [HHH-4353] - implement default column naming strategy for Collections and Map of basic types * [HHH-4527] - Implement @j.p.Access support * [HHH-4536] - Fix the mismatch between JPA 2's logical model and mapping.* physical model wrt t*toOne and *ToMany * [HHH-4546] - add JPA 2.0 locking * [HHH-4553] - Hibernate doesn't support official JPA2 escape char for table name * [HHH-4584] - Query Language needs to support joins on embedded values * [HHH-4598] - An embeddable class may contains collection of basic types or embeddable objects * [HHH-4600] - Implements full support for JPA 2 Maps * [HHH-4601] - implement orphanRemoval for *ToMany * [HHH-4649] - support for in ORM.xml files * [HHH-4654] - Criteria quries must support referencing parameters by name * [HHH-4657] - support CascadeType.DETACH and em.detach() * [HHH-4663] - Make sure CriteriaQuery is serializable * [HHH-4665] - Implement emf.getPersistentUnitUtil().getIdentifier(Object) * [HHH-4667] - Properly parse the new orm.xml xsd and persistence.xml xsd * [HHH-4675] - Bean Validation ConstraintViolationException should trigger a tx rollback as per JPA's spec * [HHH-4679] - Make sure @AssociationOverride support the dot notation (section 11.1.2) * [HHH-4680] - Implement @AssociationOverride .value for Map value overriding (section 11.1.2) * [HHH-4681] - Implement @AttributeOverride "key." or "value." for Maps * [HHH-4682] - Check that @CollectionTable (or its absence) defaults to the right table/column names * [HHH-4684] - Make sure @Lob works with @ElementCollection * [HHH-4685] - Make sure bidirectional @*To* works from an embedded object to another entity * [HHH-4686] - Implement @MapKeyEnumerated * [HHH-4687] - implement @MapKeyTemporal * [HHH-4688] - Make sure @OrderBy works for @ElementCollection * [HHH-4689] - Make sure @OrderBy supports dotted notation to point to embedded properties * [HHH-4692] - add the new orm_2_0.xsd file * [HHH-4696] - Add persistence.xsd version 2 * [HHH-4724] - query.multiselect() on a CriteriaQuery returns List instead of List * [HHH-4752] - @AttributeOverride for column name should use no prefix for @ElementCollection (legacy uses "element") * [HHH-4753] - Default table name for @CollectionTable is not inferred correctly according to spec requirement * [HHH-4756] - javax.persistence.criteria.Path#get should result in *delayed* join rendering * [HHH-4758] - Rename org.hibernate.ejb.criteria.AbstractNode#queryBuilder to #criteriaBuilder * [HHH-4766] - Properly support criteria notion of SUM aggregation return types * [HHH-4771] - @ElementCollection fk column should default to entityName_columnNameOfOwningId * [HHH-4782] - Implement @AssociationOverride.joinTable ** Bug * [HHH-1352] - Session.setReadOnly(Object, boolean) fails for proxies * [HHH-1575] - Expression.in on component object gives parameters til SQL in wrong order * [HHH-2166] - Long "in" lists in queries results in a Java stack overflow exception. * [HHH-2990] - Fix SerializationHelper$CustomObjectInputStream to use Class.forName and better classloader * [HHH-3164] - "id in ..." with EmbeddedId and criteria API * [HHH-3240] - In Derby field type 'text' is converted to CLOB(255) * [HHH-3338] - Order of attributes in generated SQL query is dependent on Java version * [HHH-3529] - ConnectionWrapper is not visible from class loader * [HHH-4041] - Null Pointer Exception when using @NotAudited on an entity with discriminator column, inherited from base entity with InheritanceType.SINGLE_TABLE * [HHH-4063] - NPE reading metadata from an mapped interface * [HHH-4065] - Incorrect SQL is used for HQL if the number of values for a filter collection parameter is changed * [HHH-4090] - RelationTargetAuditMode.NOT_AUDITED not working with many-to-many relations * [HHH-4257] - map key type no longer inferred correctly, throws exception at runtime * [HHH-4283] - Bidirectional indexed collection mapped incorrectly for IndexedCollectionTest * [HHH-4457] - SchemaUpdate fails on Sybase ASE 15 when a new column is added without a default value * [HHH-4519] - Hibernate/Infinispan integration doesn't property handle Entity/CollectionRegionAccessStrategy evictAll * [HHH-4520] - Infinispan second level cache integration can cache stale collection data * [HHH-4531] - Derby dialect should not support comments * [HHH-4542] - Annotation processor does not handle "bag" mappings correctly * [HHH-4560] - JDBC4 support inadvertently missed 1.4 compatibility * [HHH-4565] - Maven deps: HSQLDB shouldn't be a dependency in compile scope. * [HHH-4566] - Maven deps: JAXB API and JAXB RI shouldn't be dependencies of Hibernate Annotations. * [HHH-4567] - EntiytManager's QueryImpl mishandles ordinal position of HQL-style positional parameters * [HHH-4571] - Infinispan not properly being built into distribution bundle * [HHH-4572] - check if the connection supports jdbc4 before looking for the createClob method * [HHH-4574] - ConnectionProviderFactory.getConnectionProperties() includes extra properties * [HHH-4581] - Embedded objects in criteria API does not work * [HHH-4586] - Parameterized functions built throught CriteriaBuilder missing parameters when rendered * [HHH-4588] - Seam 2.x depends on ReaderInputStream which it shouldn't. Deprecate the current Hibernate ReaderInputStream class * [HHH-4590] - CASTs from CriteriaBuilder.toXXX methods still need to be fleshed out * [HHH-4604] - IllegalArgumentException should be raised when an ordinal parameter is not present in the query * [HHH-4611] - When the revision number in the revision entity uses a @Column(columnDefinition=), the sql-type is not properly set on the REV property of audit entities * [HHH-4614] - (javassist) Instrumented model with abstract MappedSuperclass and field access doesn't work * [HHH-4625] - Use of maven-injection-plugin intermittently leads to build failures * [HHH-4631] - Infinispan integration module is causing build problems * [HHH-4633] - Using same table for multiple relations doesn't work * [HHH-4634] - A many-to-many relation owned by both sides causes a mapping exception * [HHH-4641] - @PrimaryKeyJoinColumn on an inherited entity doesn't affect the column name * [HHH-4644] - When using join-inheritance and a custom revision entity, the child mapping uses incorrect revision number column sql type * [HHH-4645] - Rename properties used to configure Envers from camel case to _ * [HHH-4650] - Removing an item from a persistent collection, flushing, and adding the same item again fails * [HHH-4653] - Setting the "referencedColumnName" in @JoinColumnOrFormula throws an NPE * [HHH-4670] - Incorrect revision types when in a add-flush-mod-flush sequence * [HHH-4698] - Better handling of JPA criteria expressions * [HHH-4702] - org.hibernate.ejb.metamodel.AttributeFactory should use member for javaType, et al * [HHH-4707] - Currently no support for modulus operator * [HHH-4708] - Make CompoundSelectionImpl implement ExpressionImplementor * [HHH-4709] - registered length functions should return Integer * [HHH-4711] - persistence.xml is not validated during parsing * [HHH-4715] - Unexpected results when an updated entity that is already modifiable is set to modifiable again * [HHH-4720] - Improve javax.persistence.metamodel.Attribute support * [HHH-4735] - Proxy can be associated with a new session when it is already connected to a different one * [HHH-4741] - org.hibernate.test.filter.DynamicFilterTest.testSqlSyntaxOfFiltersWithUnions fails on MySQL * [HHH-4743] - Bug in BooleanLiteralNode with CustomType * [HHH-4764] - org.hibernate.test.pagination.PaginationTest.testLimitOffset() fails on oracle and db2 due to * [HHH-4767] - Bug in how Criteria Subquery selections are handled * [HHH-4768] - Bug in how Criteria Subquery correlations are handled * [HHH-4769] - In HQL, function ROUND always returns an Integer, it truncate the decimal part of Double number. * [HHH-4772] - Empty conjunction/disjunction in criteria does not follow spec rules * [HHH-4774] - Do not handle literals using parameters in JPA criteria select * [HHH-4775] - CriteriaBuilder#notEqual being interpreted oppositely * [HHH-4776] - Add a NullLiteralExpression for CriteriaBuilder#nullLiteral * [HHH-4777] - org.hibernate.ejb.test.PackagedEntityManagerTest.testOverridenPar() hard code hsqldb connection info * [HHH-4778] - Need better handling of criteria expression casting * [HHH-4780] - Allow BigDecimal and BigInteger to be specified as numeric literal types * [HHH-4785] - BinaryArithmeticOperation reverses incoming arguments * [HHH-4786] - SerializableType + custom Serializable class + L2 cache causes problems * [HHH-4788] - antrun plugin version is not explicitly specified in the parent pom * [HHH-4790] - Envers test failing, disabling for beta-3 release * [HHH-4791] - Invalid assumption made in org.hibernate.envers.tools.Tools#getTargetFromProxy ** Deprecation * [HHH-4561] - Deprecate openConnection()/closeConnection() methods on Batcher interface ** Improvement * [HHH-2576] - Allow native-sql to have placeholders for default schema and catalog * [HHH-4000] - Utlize jhighlight hooks for rendered syntax coloration of XML and Java based programlisting docbook elements * [HHH-4540] - Allow the revision timestamp to be a Date * [HHH-4545] - Allow o.h.action.Executable to register for either (or both) before or after transaction completion callbacks * [HHH-4548] - Alter poms to not use javax.* artifacts under Sun proprietary license * [HHH-4550] - Document that update-timestamps cache region should not be configured for expiry. * [HHH-4569] - Split focus of ConfigurationPerformanceTest * [HHH-4573] - Minor typo, formatting and cleanup fixes * [HHH-4575] - When Infinispan is configured for INVALIDATION don't send cluster message on entity insert * [HHH-4671] - Derby is one of those dialects that should not support "cross join" * [HHH-4697] - Add means to get HibernateEntityManagerFactory from HibernateEntityManagerImplementor * [HHH-4705] - Derby does now in fact support the full ANSI SQL TRIM function * [HHH-4719] - Support modulo operator * [HHH-4737] - Cache the EntityKey in EntityEntry when id is non-null * [HHH-4763] - Change antrun plugin configuration in entitymanager module to allow metamodel generation without processing all life cycles ** New Feature * [HHH-2308] - Adding predicates to the join condition using Criteria Query * [HHH-4608] - Add new properties that will allow to specify the default schema and catalog that should be used for audit tables * [HHH-4694] - Support "fake" many-to-one bidirectional relations * [HHH-4749] - Don't block calls to getListeners on SessionImplementor when using thread scoped sessions ** Patch * [HHH-1918] - enable non-hilo identity generation in DerbyDialect * [HHH-2347] - Improvement to DerbyDialect default identy generation mode * [HHH-2584] - PersistentMap.remove() incorrect on uninitialized, non-extra-lazy map * [HHH-3860] - Cascading performance problems when session contains many entities ** Task * [HHH-4006] - Document fetch profiles * [HHH-4498] - Move the xml configuration files in the annotations module into the default resource directory /src/test/resources * [HHH-4655] - Upgrade jpamodelgen dependency in entitymanager to use 1.0.0.Beta1 * [HHH-4672] - Upgrade JPA dependency to hibernate-jpa-2.0-api-1.0.0-CR-1 * [HHH-4673] - Upgrade JPA Static Metamodel Generator dependency to 1.0.0.Beta1 * [HHH-4674] - JBoss has renamed its JACC artifact * [HHH-4783] - Remove obsolete changelog.txt files in annotations and entitymanager modules Changes in version 3.5.0-Beta-2 (2009.11.02) ------------------------------------------- ** Sub-task * [HHH-4047] - Phase 1 - API & implement join-strategy * [HHH-4196] - Implement JPA 2.0 criteria apis (building) * [HHH-4202] - Implement JPA 2.0 metamodel APIs * [HHH-4528] - Read mapping annotations from entity properties rather than the composite pk * [HHH-4533] - Support for @MappedSuperclass such that we can build javax.persistence.metamodel.MappedSuperclassType * [HHH-4537] - Expose Members for MappedSuperclass properties ** Bug * [HHH-1724] - Critieria needs to be aligned with new aggreation type rules * [HHH-3817] - JBC second level cache integration can cache stale collection data * [HHH-3818] - Hibernate/JBC integration doesn't property handle Entity/CollectionRegionAccessStrategy evictAll * [HHH-4095] - bug in org.hibernate.Hibernate.createBlob( InputStream in ) * [HHH-4100] - Problems with Envers docbook sources * [HHH-4105] - SessionFactory mispells method to obtain fetch profile definition * [HHH-4114] - ASTParserLoadingTest fails due to missing "bit_length" function * [HHH-4115] - FooBarTest - "operator does not exist: character varying = integer" * [HHH-4435] - DataVersionAdapter.newerThan incorrect when comparing to self * [HHH-4437] - ToOneDelegateSessionImplementor breaks Hibernate.getClass(auditedEntity.proxyOfnotAuditedEntity) * [HHH-4441] - SessionImpl serialization violates java serialization spec * [HHH-4447] - Envers proxy.getId() returns null if proxy was not initialized yet * [HHH-4449] - NPE during inserting new audited entity with reference to another proxy entity if proxy.lazyInitializer.session is null * [HHH-4463] - Native queries should not be automatically paginated in getSingleResult() as it fails for some DB and or queries * [HHH-4475] - Constants point to non-existing default JBC/JGroups config file locations * [HHH-4486] - Account for MySQL's statement * [HHH-4494] - cglib log warning says BytecodeProvider impl is considered deprecated * [HHH-4500] - MSSQL, Oracle - Mapping inconsistency * [HHH-4503] - Sybase - Annotations - unit tests using LOBs fail * [HHH-4507] - Persistence units in entitymanager's testsuite are using fixed hsqldb configuration * [HHH-4513] - AnotationConfiguration does not honor hibernate.validator.apply_to_ddl property in case Hibernate Validator 4 is activated * [HHH-4522] - CallbackAndDirtyTest throws exception when run against PostgreSQL * [HHH-4525] - Trunk is not including the newly added modules to the distribution bundle * [HHH-4532] - Unit Tests in test/idgen/enhanced/forcedtable need update ** Improvement * [HHH-3461] - Enhance DialectFactory to support Sybase Adaptive Server Anywhere * [HHH-4364] - Support @NamedQuery on a @MappedSuperclass (Sharath Reddy) * [HHH-4382] - @ManyToOne not working wth @Formula * [HHH-4397] - Split test involving database specific features (like sequence / identity) * [HHH-4405] - Integrate new long string and binary property types in core with annotations * [HHH-4415] - TestCase could check for superclass of Dialect before skipping it * [HHH-4442] - Change StandardDialectResolver to use SybaseASE15Dialect over deprecated SybaseDialect * [HHH-4443] - Allow generic handling of any Hibernate type for post-insert generated identifiers * [HHH-4476] - Move cache-jbosscache to JBoss Cache 3.2.1 * [HHH-4484] - When JBoss Cache is configured for INVALIDATION don't send cluster message on entity insert * [HHH-4502] - Update database profiles in pom.xml * [HHH-4508] - Typo in DialectFactory - avalable should be available * [HHH-4523] - Some of the tests in the entitymanager have hard coded connection settings - these tests should use filtered connection settings * [HHH-4526] - Add better metainf information tot he hibernate all jar gennerated for dist ** New Feature * [HHH-1012] - Index not created by SchemaUpdate * [HHH-1480] - JOIN precendence rules per SQL-99 * [HHH-3000] - Allow a TypeDef to be associated with a class (Sharath Reddy) * [HHH-4103] - Implement an Infinispan 2nd level cache provider * [HHH-4232] - TypeDef support on @Embeddable or @MappedSuperClass classes (Sharath Reddy) * [HHH-4332] - Filters for MappedSuperClass * [HHH-4473] - Create documentation to explain the usage of the new 'defaultForType' attribute of the TypeDef annotation * [HHH-4479] - We should be able to implement Joins using formulas with Annotations * [HHH-4512] - TypeDef annotation should support both 'name' and 'defaultForType' attributes ** Patch * [HHH-3972] - Adding FETCH FIRST and OFFSET support to DerbyDialect * [HHH-4440] - Support for column-level read/write fragments (Rob Hasselbaum) * [HHH-4488] - ListProxy, MapProxy etc. - problems during marshalling/demarchalling ** Task * [HHH-2412] - Support for JDBC4 * [HHH-3580] - import entitymanager into core as a module * [HHH-3849] - Disable lock striping in JBoss Cache configs * [HHH-4355] - Allow running tests against different databases by using a simple switch * [HHH-4485] - Replace the JBoss Cache integration configuration properties with "jbc2"-less versions * [HHH-4487] - Restore versions of the old public API jbc2 package classes * [HHH-4499] - Account for modules needing JDK 1.6 * [HHH-4501] - Use Maven wagon-scm provider for release deployments * [HHH-4530] - Change the docbook style for Annotations and EntityManager to the latest styles used in the other Core modules * [HHH-4538] - Update to Bean Validation 1.0.0 and Hibernate Validator 4.0.0 Changes in version 3.5.0.Beta-1 (2009.08.18) ------------------------------------------- ** Sub-task * [HHH-3801] - Create a cache-jbosscache-legacy module * [HHH-3802] - Move the up-to-date JBC integration into cache-jbosscache * [HHH-3803] - Repackage JBC integration to org.hibernate.cache.jbc * [HHH-4027] - Remove current cache-jbosscache module content * [HHH-4028] - Move current cache-jbosscache2 module content to cache-jbosscache * [HHH-4029] - Remove cache-jbosscache2 module ** Bug * [HHH-1930] - QuerySyntaxException "with-clause expressions did not reference from-clause element to which the with-clause was associated" * [HHH-2146] - NullpointerException in DefaultDeleteEventListener.deleteTransientEntity * [HHH-2694] - create-drop with c3p0 causes SQLException * [HHH-2745] - NullPointerException when eager fetching joined many-to-many with native SQL query * [HHH-3046] - Merge fails on complicated data structure because of cycle references * [HHH-3216] - Incorrect parse result in ParameterParser * [HHH-3231] - org.hibernate.id.enhanced.TableGenerator throws "IllegalArgumentException: alias not found: tbl" under Oracle * [HHH-3351] - Dynamic entity model and inheritance - exception when trying to persist * [HHH-3392] - Query Cache entries are not distributable * [HHH-3472] - JTASessionContext broken for WebSphere * [HHH-3481] - JTATransactionFactory bug when Transaction cannot be found in JNDI * [HHH-3506] - enabled filters should apply to HQL update/delete statements * [HHH-3508] - Sybase Dialect - Override supportsCascadeDelete to return "false" * [HHH-3519] - account for parameters in select clause of INSERT-SELECT for DB2 * [HHH-3528] - FETCH JOIN query doesn't work in a StatelessSession * [HHH-3573] - Incorrect support for columns which aren't insertable * [HHH-3575] - Empty versions-query (both types) will cause a runtime exception * [HHH-3584] - Generate SQL when Dynamic Update is true is including version field even when marked as updateable=false * [HHH-3594] - Hibernate collection listener throw exception when adding entity to the collection * [HHH-3600] - exception while saving bidirectional association * [HHH-3602] - Inheritence issue * [HHH-3621] - Assertion failure in MigrationTest * [HHH-3623] - Make at least ListProxy serializable * [HHH-3633] - Envers ignores empty discriminator classes * [HHH-3636] - Attempt to read invalid column when loading collection of subclasses mapped with table-per-subclass with discriminator * [HHH-3640] - Some standard SQL functions are not implemented in Sybase * [HHH-3647] - instance not of expected entity type: java.util.HashMap is not a: smx3.schema3.Party_AUD * [HHH-3652] - CompositeIdWithGeneratorTest needs a standard way to compare timestamps * [HHH-3662] - Merging read-only entities causes AssertionError("Merged entity does not have status set to MANAGED...") * [HHH-3668] - Sybase does not support implicit conversion from character types to numeric types causes failing unit tests * [HHH-3670] - Invalid test for str() for SQL Server and Sybase * [HHH-3671] - The revision type field is not persisted when setting a custom revision type field name throught the properties * [HHH-3672] - Sybase - second(), minute(), hour(), and extract() cause GenericJDBCException * [HHH-3675] - Limitations on Sybase ResultSet implementation cause unit test failures * [HHH-3679] - Sybase conversion of Java byte to tinyint fails with 8-bit values causing unit test failures * [HHH-3680] - Sybase - composite primary key in unit test exceeds maximum for index causing failure * [HHH-3686] - Sybase - QueryCacheTest.testQueryCacheInvalidation fails * [HHH-3693] - Implicit Polymorphic query + pagination returning zero result * [HHH-3696] - Sybase - unit tests fail when numeric values overflow in precision or scale on insert * [HHH-3698] - Problem with HQL parameter bindings as indexed collection selectors * [HHH-3699] - Problem with HQL parameter bindings for parameters in WITH join clause * [HHH-3701] - SQL function "trim" is not available in Sybase Dialect * [HHH-3703] - RevisionEntity with compound primary key fails * [HHH-3705] - NPE encountered on using AnnotationConfiguration * [HHH-3706] - Audit Table Schema not generated using * [HHH-3729] - @AuditJoinTable annotation has no effect for embedded concrete subclasses of a MappedSuperClass * [HHH-3736] - Envers EntityInstantiator does not support private constructors for immutable entities * [HHH-3740] - Unable to build EntityManagerFactory when using a non-audited ManyToOne in Audited components * [HHH-3741] - Join tables are not audited if the join is defined in an abstract * [HHH-3773] - NPE when generating schema containing OneToMany relations * [HHH-3779] - "org.hibernate.MappingException: An audited relation to a non-audited entity" during schema-export ant task * [HHH-3782] - Saving a one-to-many relationship results in unsaved transient instance exception * [HHH-3794] - Issue when method return type is Interface * [HHH-3810] - Transient entities can be inserted twice on merge * [HHH-3830] - Problem with inheritance and @ManyToMany relation * [HHH-3847] - java.lang.NullPointerException on onPreRemoveCollection on replicate of persistent class * [HHH-3871] - unnecessary proxy initialization on audit record save * [HHH-3878] - Exception when querying historical data for deleted Entites * [HHH-3880] - org.hibernate.id.enhanced.TableStructure missing "as" keyword in select statment column renames; required for PostgreSQL * [HHH-3888] - Envers schema generation (ant) ignoring columnDefinition ( atribute of @Column, JPA ) * [HHH-3912] - Change for HHH-3159 causes InstantiationException * [HHH-3918] - Use standard JDK exception nesting * [HHH-3923] - Enver throws Nullpointer exception with a self reference entities * [HHH-3939] - @NotAudited association requires and joins to the associated table * [HHH-3957] - Audited Null Embeddable objects not returned as null * [HHH-3980] - Fix for HHH-2980 introduced bug that allows the same bag collection role to be fetched multiple times * [HHH-4003] - many-to-many loaders should use inner joins from the collection table to element table * [HHH-4034] - Update org.hibernate.action.BulkOperationCleanupAction to use new Region cache APIs * [HHH-4088] - Session.getSession should always return sessions from parent (or root) session * [HHH-4091] - HQLTest#testDuplicateImplicitJoinInSelect * [HHH-4099] - Doc build error (http://jira.codehaus.org/browse/MNG-1323) ** Improvement * [HHH-1234] - allow tuplizers the opportunity to influence getSubclassEntityPersister() processing * [HHH-2592] - force hibernate to generate use offset qeury when offset is zero * [HHH-2686] - Include a primary key in the sequence table used by id.enhanced.TableGenerator * [HHH-2802] - Support HQL style order by (JPA @OrderBy) * [HHH-2980] - Error "org.hibernate.HibernateException: cannot simultaneously fetch multiple bags" not specific enough * [HHH-3159] - Oracle 11g - desupport of oracle.jdbc.driver * [HHH-3249] - Make o.h.id.enhanced.TableGenerator more extension-friendly * [HHH-3275] - Allow pluggable tuplizers for composite elements * [HHH-3357] - improve performance of session.clear() * [HHH-3383] - QueryKey is storing references to entities instead of identifiers * [HHH-3424] - concat() with param binding fails function on derby * [HHH-3439] - Change o.h.cfg.Mappings to not require constructor * [HHH-3454] - Allow enhanced.TableGenerator to segment itself per entity as default * [HHH-3456] - Make o.h.id.enhanced.SequenceStyleGenerator more extension-friendly * [HHH-3471] - Provide true-false type that maps to int values * [HHH-3515] - Introduce EntityNameResolver interface * [HHH-3517] - Allow definition of the default tuplizer class to use * [HHH-3518] - Remove Suite classes from testsuite module * [HHH-3525] - Clean up reflection code trying to determine JDK 1.4 capabilities * [HHH-3532] - schema update task should look for foreign key signature * [HHH-3708] - Suboptimal exception on m:n relations with an unaudited entity * [HHH-3712] - Reorganize the Sybase dialect class hierarchy, add SybaseASE15Dialect, and mark SybaseDialect as deprecated * [HHH-3737] - Support Hibernate 3.3 branch in Envers until 3.4.0GA is out * [HHH-3750] - Allow dialects to handle difference in how Query.setFirstResult() should be interpreted * [HHH-3753] - Upgrade to SLF4J version 1.5.8 * [HHH-3832] - Upgrade to cglib-2.2.jar * [HHH-3842] - Update maven profiles to use the databases in QA Lab * [HHH-3886] - Update database credentials for QA Lab * [HHH-3892] - Improve support for mapping SQL LONGVARCHAR and CLOB to Java String, SQL LONGVARBINARY and BLOB to Java byte[] * [HHH-3944] - Document known database portability strategies * [HHH-3978] - Expose Hibernate version via non-compile-time constant expression * [HHH-3982] - Apply build version to org.hibernate.Version * [HHH-3998] - Fix spurious failures in ConfigurationPerformanceTest * [HHH-3999] - Change mysql hostname in pom.xml * [HHH-4016] - SAPDialect should not use oracle style outer joins, ANSI style is prefered by MaxDB * [HHH-4022] - Add an actual API contract for querying/managing cache regions (from app code) ** New Feature * [HHH-3343] - Postgres Plus Dialect * [HHH-3512] - Registration of IdentifierGenerators (short naming) * [HHH-3559] - Possibility to do versioning and non-versioning commits as required * [HHH-3560] - Assume entities relationships as unversioned by default * [HHH-3563] - Support relations in components * [HHH-3564] - Support for the three types of inheritance * [HHH-3565] - Direct property access * [HHH-3568] - In the hibernate mapping of versions entities, mark them as not updateable * [HHH-3570] - Move from "Versioning" to "Auditing" * [HHH-3588] - RevisionType available via public API * [HHH-3598] - Add the possibility to specify restrictions on RevisionType, using RevisionTypeProperty * [HHH-3611] - Extend revision restrictions in the query system * [HHH-3663] - Request to add Joined inheritance strategy supported for versioning * [HHH-3697] - Turn on/turn off versioning in runtime * [HHH-3723] - Publish sources to maven (snapshot) repository * [HHH-3781] - Echo version information to the console in main() * [HHH-3819] - Deleted entries with non null properties * [HHH-3823] - Obtain current revision entity by AuditReader * [HHH-3898] - Add a flag to disable Nullability.checkNullability() and the exception raised in this case * [HHH-3906] - Move to JPA 2 API as a dependency * [HHH-4010] - support auditing of entity having reference (many-to-one relation) to not audited entity * [HHH-4081] - Support for JPA 2.0 "qualified identification variables" (KEY, VALUE and ENTRY) ** Patch * [HHH-530] - Allow application of filters on subqueries * [HHH-2933] - allow custom resolution of Dialect (Tomoto Shimizu Washio) * [HHH-3401] - H2 Database Dialect Fixes * [HHH-3450] - Include SingletonEhCacheProvider as an additional caching provider (Greg Luck) * [HHH-3639] - Sybase keywords - rename columns * [HHH-3649] - DB2Dialect inherits supportsPooledSequences() as false, but it does support * [HHH-3650] - TableGenerator doesn't marks the "primary key" as not null, causing errors in some RDBMS's which expects the PK to be not-null * [HHH-3742] - Documentation corrections * [HHH-3744] - Improved support for persistence of subclasses * [HHH-4037] - Fixing build errors in documentation/manual ** Task * [HHH-3214] - Update unit tests and config files to use non-depracated Oracle dialects * [HHH-3474] - Upgrade to use slf4j 1.5 (1.5.2) * [HHH-3547] - import Envers into Hibernate core as a module * [HHH-3549] - import commons-annotations back into core as a module * [HHH-3550] - import annotations into core as a module * [HHH-3556] - Convert documentation to docbook * [HHH-3585] - Upgrade to JBoss Cache 3 * [HHH-3760] - Document EntityNameResolver * [HHH-3761] - Document DialectResolver * [HHH-3879] - Envers documentation: configuration of event listeners is incomplete for JPA: @PostPersist, @PostUpdate @PostRemove no longer work * [HHH-3953] - Update tutorial chapter * [HHH-3979] - Upgrade to javassist 3.9.0 * [HHH-3981] - Upgrade to jDocBook 2.2.0 Changes in version 3.3.0.GA (2008.08.13) ------------------------------------------- ** Bug * [HHH-3430] - distribution bundles cglib directly instead of the hibernate repackaging Changes in version 3.3.0.CR2 (2008.07.31) ------------------------------------------- ** Bug * [HHH-1697] - OracleDialect fails to recognize sequence accessible through syonyms when validating schema * [HHH-2604] - Isolator.JdbcDelegate masks the exception if it isn't possible to open a connection. * [HHH-2683] - "datediff" is declared as NoArgSQLFunction in H2Dialect, but actually accepts 3 arguments. * [HHH-3006] - ConcurrentModificationException in AbstractBatcher results in infinite loop * [HHH-3229] - Merge can fail when there is a transient entity reachable by multiple paths and at least one path does not cascade on merge * [HHH-3257] - Content images not displayed * [HHH-3260] - Hibernate wraps a listener init or destroy exception into an AssertionFailure * [HHH-3261] - Do not wrap exceptions raised by event listeners (at init or destroy time) * [HHH-3265] - change license url in pom to http://www.gnu.org/licenses/lgpl-2.1.html * [HHH-3266] - distribution bundle missing jta dependency * [HHH-3272] - using of Integer.valueOf(int), which is not available in JDK 1.4 * [HHH-3282] - DB2Dialect should report supportsLobValueChangePropogation() == false * [HHH-3309] - Serialize/Deserialize problem in AbstractLazyInitializer with entitymode.MAP. * [HHH-3409] - ResultTransformers need smarter equals() and hashCode() impls ** Improvement * [HHH-1786] - JTASessionContext.CleanupSynch does not remove sessions from currentSessionMap * [HHH-2060] - To be able to use with * [HHH-2506] - Make javassist the default ByteCodeProvider * [HHH-2875] - repackage cglib/asm under org.hibernate namespace * [HHH-3269] - upgrade to jDocBook plugin version 2.1.1 * [HHH-3283] - protect BulkManipulationTest#testInsertWithGeneratedTimestampVersion where Dialect#supportsParametersInInsertSelect == false * [HHH-3358] - Enable JTATransactionFactory and JTATransaction factory to work without JNDI * [HHH-3390] - Use READ_COMMITTED for JBC 2 cache ** Patch * [HHH-3294] - Version incorrectly incremented for unchanged persistent entity that is parent of a one to many relationship ** Task * [HHH-3270] - follow up on documentation license questions Changes in version 3.3.0.CR1 (2008.04.28) ------------------------------------------- ** Bug * [HHH-1312] - Unclosed ResultSet when using Identity * [HHH-1396] - Table.validateColumns fails on valid column * [HHH-1569] - Immutable Natural Id check fails with ArrayIndexOutOfBounds in some cases * [HHH-1593] - Infinite loop/StackOverflow when calling configuration.setListener(null) * [HHH-1753] - DB2Dialect.getCurrentTimestampSQLFunctionName() uses Oracle syntax * [HHH-1916] - param values in generator element should be trimmed during HbmBinding * [HHH-1920] - Incorrect documentation regarding XML manipulation in Hibernate reference manual (chapter 18.3). * [HHH-1956] - Interceptor.afterTransactionCompletion not called with JTATransaction (CacheSynchronization.hibernateTransaction not set) * [HHH-2159] - NullPointerException in FromElement#findIntendedAliasedFromElementBasedOnCrazyJPARequirements with 'hibernate.query.jpaql_strict_compliance' enabled * [HHH-2164] - Minor bug in section "20.1.1. Customizing the schema" * [HHH-2200] - Memory leak in AbstractBatcher with Generated Properties * [HHH-2320] - Regression: optional properties under a tag no longer update properly * [HHH-2503] - AbstractEntityPersister swallows JDBCExceptions in processGeneratedProperties * [HHH-2513] - Abusive WARN logged during deserialization of replicated SessionFactory * [HHH-2542] - NullPointerException in TypeFactory.replaceAssociations for ComponentType * [HHH-2553] - New LoadContexts Implementation causing possible performance degradation * [HHH-2593] - Keyword UNION is prefixed with "this_." in filter conditions * [HHH-2616] - No event is fired on Collection recreate/remove/update action * [HHH-2627] - Generated properties leak prepared statements in Hibernate 3.2.3 and higher. * [HHH-2631] - Leaking PreparedStatement and ResultSet via CollectionLoadContext instances maintained in Map collectionLoadContexts in LoadContexts * [HHH-2711] - PropertyAccessException with backref and * [HHH-2726] - spelling o your CLASSPATH * [HHH-2728] - Calling session.clear() while retrieving objects via an iterator will cause a "LazyInitializationException - No Session" by the CGLIBLazyInitializer * [HHH-2788] - Oracl8iDialect No Dialect mapping for JDBC type 91 * [HHH-2795] - CollectionLoadContexts for empy collections are not removed until PersistenceContext.clear() * [HHH-2816] - DefaultFlushEntityEventListener.checkNaturalId() causes extra SELECTs on read-only entities * [HHH-2833] - insert-select query fails with NPE when select includes join * [HHH-2857] - schemaSupport for HSQLDialect remote connections doesn't work * [HHH-2861] - cascade="delete-orphan,all" is ignored * [HHH-2863] - testsuite fix-ups for maven and/or directory changes * [HHH-2864] - Merging a detached instance with a new child in a unidirectional one-to-many association fails if the parent was previously loaded as a proxy * [HHH-2892] - skip up-to-date checks of query cache for natural-id only if immutable * [HHH-2928] - optimizers for enhanced id generators should be synchronized against multi-threaded access * [HHH-2948] - QueryStatistics.executionMinTime always = 0 * [HHH-3111] - WebSphereExtendedJTATransactionLookup$TransactionManagerAdapter.getStatus() implemented incorrect * [HHH-3140] - Region prefix ignored for entities and collections ** Deprecation * [HHH-2755] - Wrong "jsdk.jar" referenced in the tutorial ** Improvement * [HHH-1786] - JTASessionContext.CleanupSynch does not remove sessions from currentSessionMap * [HHH-2048] - Incomplete MappingException at org.hibernate.mapping.SimpleValue * [HHH-2156] - Section 19.3, "Managing the caches" doesn't document CacheMode.IGNORE * [HHH-2533] - redesign Cache/CacheProviders * [HHH-2662] - Workaround PostgreSQL issues in testsuite * [HHH-2663] - Map java.sql.Types.REAL to Hibernate FloatType for auto-discovery stuff * [HHH-2665] - Split Oracle9Dialect into Oracle9iDialect and Oracle10gDialect * [HHH-2669] - Unequivocally map MySQL LOB types to the LONG variant * [HHH-2682] - support for auto-discovery of H2 dialect * [HHH-2696] - Consider migrating to slf4j * [HHH-2761] - Handle null and empty string consistently in PropertiesHelper * [HHH-2778] - TransactionManagerLookup implementation for Bitronix Transaction Manager * [HHH-2789] - Section 19.2 of the documentation does not show OSCache as supporting clusters. It does. * [HHH-2822] - timestamp extraction functions for SAPDBDialect * [HHH-2826] - IS [NOT] NULL checks with component values * [HHH-2859] - Introduce a 'Work' API for user to perform JDBC work * [HHH-3131] - Add a method to ActionQueue to tell whether there are currently entries in the executions collection ** New Feature * [HHH-1] - Optimize Hibernate for the bulk insertion of related entities * [HHH-2555] - Create new RegionFactory for JBossCache * [HHH-2884] - Provide a sessionFactory close event or hook for the event listeners ** Patch * [HHH-952] - Patch to allow subqueries with joins using Criteria API and Subqueries with DetachedCriteria * [HHH-2070] - Expand DB2Dialect auto-discovery support (Martin Renner) * [HHH-2519] - Schema dropping not documented with hibernate.hbm2ddl.auto=create * [HHH-2630] - Hibernate Dialect is not auto-detected for Sybase ASE and DB2 (Shelley McGowan) * [HHH-2758] - Patch IngresDialect based on certification * [HHH-2839] - Don't use dummy dual table for hsqldb (David Bala?ic) * [HHH-2849] - Better error logging in IdentifierGeneratorFactory (Antony Stubbs) * [HHH-2957] - ActionQueue Insertion sort performance degrades exponentially (Jay Erb) * [HHH-3084] - DialectFactory detection of Ingres metadata (Michael Leo) ** Task * [HHH-2702] - Officially move to JDK 1.4 * [HHH-2704] - Migrate to Maven2 for build Changes in version 3.2.6 (2008.02.07) ------------------------------------------- ** Bug * [HHH-925] - DetachedCriteria.createCriteria not working with alias * [HHH-1312] - Unclosed ResultSet when using Identity * [HHH-1329] - SchemaValidator fail when views are involved * [HHH-1593] - Infinite loop/StackOverflow when calling configuration.setListener(null) * [HHH-1685] - DetachedCriteria doesn't create alias on subcriteria * [HHH-1753] - DB2Dialect.getCurrentTimestampSQLFunctionName() uses Oracle syntax * [HHH-1916] - param values in generator element should be trimmed during HbmBinding * [HHH-1956] - Interceptor.afterTransactionCompletion not called with JTATransaction (CacheSynchronization.hibernateTransaction not set) * [HHH-2016] - Oracle9Dialect registers last_day() function as "lastday" * [HHH-2159] - NullPointerException in FromElement#findIntendedAliasedFromElementBasedOnCrazyJPARequirements with 'hibernate.query.jpaql_strict_compliance' enabled * [HHH-2200] - Memory leak in AbstractBatcher with Generated Properties * [HHH-2261] - Setting hibernate.hbm2ddl.auto=validate causes problems on mySQL with numeric fields * [HHH-2320] - Regression: optional properties under a tag no longer update properly * [HHH-2503] - AbstractEntityPersister swallows JDBCExceptions in processGeneratedProperties * [HHH-2542] - NullPointerException in TypeFactory.replaceAssociations for ComponentType * [HHH-2593] - Keyword UNION is prefixed with "this_." in filter conditions * [HHH-2598] - Mapping a collection of entities from two different classes with the same collection name results in duplicate backref property exception if collection keys are not null * [HHH-2616] - No event is fired on Collection recreate/remove/update action * [HHH-2627] - Generated properties leak prepared statements in Hibernate 3.2.3 and higher. * [HHH-2728] - Calling session.clear() while retrieving objects via an iterator will cause a "LazyInitializationException - No Session" by the CGLIBLazyInitializer * [HHH-2788] - Oracl8iDialect No Dialect mapping for JDBC type 91 * [HHH-2795] - CollectionLoadContexts for empy collections are not removed until PersistenceContext.clear() * [HHH-2816] - DefaultFlushEntityEventListener.checkNaturalId() causes extra SELECTs on read-only entities * [HHH-2833] - insert-select query fails with NPE when select includes join * [HHH-2857] - schemaSupport for HSQLDialect remote connections doesn't work * [HHH-2861] - cascade="delete-orphan,all" is ignored * [HHH-2864] - Merging a detached instance with a new child in a unidirectional one-to-many association fails if the parent was previously loaded as a proxy * [HHH-2892] - skip up-to-date checks of query cache for natural-id only if immutable * [HHH-2928] - optimizers for enhanced id generators should be synchronized against multi-threaded access * [HHH-2948] - QueryStatistics.executionMinTime always = 0 ** Improvement * [HHH-1630] - duplicate property mapping - more details * [HHH-1696] - Add outer join support for aliases on DetachedCriteria * [HHH-2048] - Incomplete MappingException at org.hibernate.mapping.SimpleValue * [HHH-2682] - support for auto-discovery of H2 dialect * [HHH-2761] - Handle null and empty string consistently in PropertiesHelper * [HHH-2822] - timestamp extraction functions for SAPDBDialect * [HHH-2826] - IS [NOT] NULL checks with component values * [HHH-2852] - Better error messages when schema validation fails ** Patch * [HHH-952] - Patch to allow subqueries with joins using Criteria API and Subqueries with DetachedCriteria * [HHH-2070] - Expand DB2Dialect auto-discovery support (Martin Renner) * [HHH-2839] - Don't use dummy dual table for hsqldb (David Bala?ic) * [HHH-2849] - Better error logging in IdentifierGeneratorFactory (Antony Stubbs) * [HHH-2957] - ActionQueue Insertion sort performance degrades exponentially (Jay Erb) * [HHH-3084] - DialectFactory detection of Ingres metadata (Michael Leo) ** Task * [HHH-2559] - http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd needs to be updated * [HHH-3085] - Remove connector.jar (unnecessary library) * [HHH-3086] - Remove jdbc2_0-stdext.jar (unnecessary library) Changes in version 3.2.5 (2007.07.31) ------------------------------------------- ** Bug * [HHH-1116] - batch-size typo * [HHH-1561] - Missing " in Documentation for H3, Chapter 15.8 * [HHH-1569] - Immutable Natural Id check fails with ArrayIndexOutOfBounds in some cases * [HHH-1694] - Documentation Outdated: "10.4.4. Queries in native SQL" * [HHH-2180] - minordocumentation error in hbm xml * [HHH-2201] - session.iterate() does not exist * [HHH-2267] - A copy/paste mistake in the documentation for ant task * [HHH-2334] - Documentation error in section 5.1.3 * [HHH-2420] - Error in 2.5. Contextual Sessions * [HHH-2502] - The second level caching documentation states that ehcache is not distributed. * [HHH-2631] - Leaking PreparedStatement and ResultSet via CollectionLoadContext instances maintained in Map collectionLoadContexts in LoadContexts * [HHH-2649] - Batcher configuration parameter incorrectly documented * [HHH-2711] - PropertyAccessException with backref and * [HHH-2713] - duplicated phrase in docs "of the of the" * [HHH-2714] - Three typos in code examples * [HHH-2719] - adddress --> address * [HHH-2720] - Monetory --> Monetary ** Improvement * [HHH-1022] - incomplete documentation in _README.txt in the lib directory * [HHH-1682] - Improve the description of differences between save() and persist() * [HHH-2048] - Incomplete MappingException at org.hibernate.mapping.SimpleValue * [HHH-2417] - Update book on Hibernate reference * [HHH-2418] - Refer HSQL DB website in chapter 1.2.3 * [HHH-2487] - Typo in "5.1.7. version (optional)" * [HHH-2550] - Update API Class in 10.4.3. Criteria queries * [HHH-2662] - Workaround PostgreSQL issues in testsuite * [HHH-2663] - Map java.sql.Types.REAL to Hibernate FloatType for auto-discovery stuff * [HHH-2665] - Split Oracle9Dialect into Oracle9iDialect and Oracle10gDialect ** Patch * [HHH-2520] - Miscellaneous config doc spelling fixes * [HHH-2630] - Hibernate Dialect is not auto-detected for Sybase ASE and DB2 (Shelley McGowan) * [HHH-2758] - Patch IngresDialect based on certification ** Task * [HHH-2551] - Deprecate org.hibernate.criterion.Expression * [HHH-2566] - Replace usages of FlushMode.NEVER with FlushMode.MANUAL * [HHH-2567] - Update reference to use FlushMode.MANUAL * [HHH-2568] - Hibernate javadoc overview refering wrong classes and packages Changes in version 3.2.4.sp1 (2007.05.18) ------------------------------------------- ** Bug * [HHH-2605] - Since 3.2.4 no value specified for row id * [HHH-2613] - LockMode.FORCE on non versioned entity leads to NPE Changes in version 3.2.4 (2007.05.09) ------------------------------------------- ** Bug * [HHH-511] - reattach object from same session * [HHH-2316] - org.hibernate.cache.CacheKey.equals() can cause PropertyAccessException to be thrown * [HHH-2553] - New LoadContexts Implementation causing possible performance degradation * [HHH-2602] - instrumented many-to-one problem with aggressive release ** Deprecation * [HHH-2603] - Deprecate the Session.connection() method ** Improvement * [HHH-2549] - Warn users explicitly about schemaexport and schemaupdate does not support annotations ** New Feature * [HHH-1] - Optimize Hibernate for the bulk insertion of related entities ** Patch * [HHH-2301] - Identity generator with custom insert SQL broken in 3.2 (Scott Rankin and Gail Badner) * [HHH-2336] - paremeterizable and typedef-able UserCollectionType (Holger Brands) * [HHH-2580] - Performace: Too many lookups of WAS extended transaction support (Jesper Udby) Changes in version 3.2.3 (2007.04.02) ------------------------------------------- ** Bug * [HHH-2376] - Query with fully qualified entity class fails * [HHH-2392] - LockModes referencing non-root joined-subclass class in HQL/Criteria * [HHH-2393] - Generated properties leave open ResultSet on Batcher to be closed on transaction completion * [HHH-2397] - hilo generator can generate negative numbers because of arithmetic overflow * [HHH-2469] - ArrayIndexOutOfBoundsException during update by rowid * [HHH-2476] - PersistentMap.put() incorrect on uninitialized, non-extra-lazy map * [HHH-2481] - Big memory leak in the use of CGLIB * [HHH-2499] - incorrect assertion failure relating to generated property values * [HHH-2513] - Abusive WARN logged during deserialization of replicated SessionFactory * [HHH-2521] - Fix cascading of merge across component properties * [HHH-2532] - update/delete executeUpdate() causes problems with JBossCache (at least in opt-locking setups) ** Improvement * [HHH-2495] - encapsulate the notion of state pertaining to processing a result set * [HHH-2534] - better error message for illegal 'collection dereference' in HQL query * [HHH-2535] - Change Cache' Cache71Dialect so that sequence support returns false ** New Feature * [HHH-2471] - create a set of "enhanced" generators * [HHH-2500] - apply Terradata certification results ** Patch * [HHH-2367] - InformixDialect uses wrong data type * [HHH-2489] - SQL comments for HQL bulk operations Changes in version 3.2.2 (2007.01.24) ------------------------------------------- ** Bug * [HHH-1471] - If the 'generated' attribute is set to 'insert' or 'always' on the property of a component it is ignored and the value is not read from the database. * [HHH-1646] - Bad code in FastClass.equals * [HHH-1889] - LockMode.UPGRADE not applied in all cases for SQL Server / Sybase * [HHH-2112] - ClassCastException in StatefulPersistenceContext.getCachedDatabaseSnapshot(...) * [HHH-2221] - MySQL temp table DDL and isolation * [HHH-2238] - SQLQuery executeUpdate doesn't respect Query.setFlushMode() * [HHH-2251] - Settings build unnecessary in schemaupdate/schemavalidate * [HHH-2257] - Query.iterate() results differ from Query.list() 2 * [HHH-2259] - autoflush and autoclose not longer occur in JTA environment with hibernate 3.2 * [HHH-2264] - NPE when NamedQuery contains space before variable name * [HHH-2274] - Collection ordering when many to many order by is used is not respected * [HHH-2275] - Mapping a composite element as a map key using formulas can lead to AOOBE * [HHH-2284] - HQL: selecting components inside components doesn't work * [HHH-2291] - collection based on property-ref not handled correctly during reattch * [HHH-2292] - merge detached instance fails to persist collection changes in case of bare collection reference * [HHH-2356] - NullableType.toString(Object) should account for nulls * [HHH-2366] - Changing a component's value does not trigger an update during flush * [HHH-2378] - replicate() of non-versioned entiy can result in wrong value for version in entity cache ** Improvement * [HHH-1851] - relax special handling of 'id' property * [HHH-2130] - SQLQuery does not autoflush all entities used in the query * [HHH-2193] - Introduce a flag to avoid checking NamedQuery at startup * [HHH-2242] - Consider Allowing Optimistic Lock Strategies other than 'Version' with joined-subclass * [HHH-2250] - Create an appropriate error message if Query.setEntity is passed a NULL value * [HHH-2282] - PersistentClass property lookups do not properly account for embedded composite identifiers * [HHH-2286] - dialect informational metadata * [HHH-2372] - Allow tooling to create Settings via SettingsFactory without contacting the db ** New Feature * [HHH-2246] - No way to specify CACHE_PROVIDER_CONFIG in HibernateServiceMBean ** Patch * [HHH-2300] - Updated dialect for H2 database engine * [HHH-2371] - enhancements to C3P0ConnectionProvider ** Task * [HHH-2032] - update c3p0 to 0.9.1 Changes in version 3.2.1 (2006.11.16) ------------------------------------------- ** Bug * [HHH-939] - 'class' property in HQL results in incorrect SQL for joined-subclass * [HHH-1401] - session.merge() executes unnecessary updates when one-to-many relationship is defined. * [HHH-1460] - Inconsistent behavior when using Session.get() with multiple subclasses * [HHH-1564] - deleting versioned object with collection leads to unecessary update * [HHH-1629] - SchemaUpdate/validator doesn't listen to quoting * [HHH-1631] - Missing table in SQL from clause that is referenced in where clause when using joined subclass * [HHH-1651] - hibernate does not find an existing sequence from an Oracle database * [HHH-1663] - with collection will produce "AssertionFailure: collection was not processed by flush()" * [HHH-1737] - Add a ConnectionWrapper interface to allow access to the underlying connection from a BorrowedConnectionProxy * [HHH-1756] - Proxy objects are not removed from the BatchFetchQueue during a session evict * [HHH-1774] - Component parameters bound incorrectly * [HHH-1921] - "dirty, but no dirty properties" thrown when Interceptor resets properties. * [HHH-1986] - javassist throws InvocationTargetException instead of original checked Exception * [HHH-2027] - merge listener over-writes Interceptor changes to component state for a transient entity * [HHH-2044] - DefaultMergeEventListener.entityIsDetached call StaleObjectStateException with wrong identifier * [HHH-2082] - UpdateTimestampsCache.isUpToDate returns before checking all spaces * [HHH-2108] - cacheable files broken * [HHH-2138] - merge with bidirectional one-to-one may fail * [HHH-2145] - set.retainAll calling set.addAll * [HHH-2174] - Wrong log message in SessionImpl.afterTransactionCompletion(...) * [HHH-2199] - Unique constraints on nullable columns should not be generated with unique-key is used and supportsNotNullUnique=false * [HHH-2202] - Clearing the connection warnings even when log is > WARN to workaround a Sybase issue * [HHH-2206] - SessionImpl tries to deserialize itself in an incorrect order * [HHH-2207] - Suggested fix for HQL - MySQL setMaxResults issue * [HHH-2226] - org.hibernate.hql.ast.tree.FromElementType contains warning log message that should be debug instead * [HHH-2229] - Performance issue with fix for HHH-1293, CGLIBLazyInitializer may be slower for certain Java classes * [HHH-2236] - Lazy property + setReadOnly + Instrumented classes results in NullPointerException when accessing lazy property ** Improvement * [HHH-2037] - provide Query.setProperties(Map) * [HHH-2042] - Typo in FlushMode.MANUAL Javadoc * [HHH-2057] - Add "remove" cascading style to CascadeStyle for XML mappings * [HHH-2127] - Document and defaultCondition * [HHH-2135] - Hibernate Deserialization: In org.hibernate.type.SerializableType the code makes a test for the return of a null object by simply testing the object as to whether or not it is null. * [HHH-2185] - introduce setting to control cglib caching of classes * [HHH-2203] - Make Post*Events extend AbstractEvent * [HHH-2208] - Table schema use in DatabaseMetadata * [HHH-2209] - ehcache.jar is old and does not contain the SingletonCacheProvider which are advised in exception messages * [HHH-2217] - Collection write methods and dirtying the collection ** New Feature * [HHH-2205] - Dialect for Intersystems' Cache SQL 2007.1 ** Patch * [HHH-1767] - read-only cache for immutable collection causes unnecessary warning ** Task * [HHH-2219] - Upgrade to Javassist 3.4 Changes in version 3.2.0.ga (16.10.2006) ----------------------------------------- (retag of 3.2.0.cr5 (2006.10.16)) Changes in version 3.2.0.cr5 (04.10.2006) ------------------------------------------- ** Bug * [HHH-1668] - PersistentSet write methods mark collection as dirty even if entry is not written * [HHH-1714] - Session.get() behavior * [HHH-1891] - Since rc3 deprecation Warning: The syntax 'TYPE=storage_engine' is deprecated and will be removed in MySQL 5.2. ** Improvement * [HHH-2093] - PERSIST_ON_FLUSH ineffective for recursive object graphs * [HHH-2103] - Rolling back 'SELECT is mandatory' on JPA strict compliance ** Task * [HHH-1931] - verify that the instrument tasks actually work Changes in version 3.2.0.cr4 (24.08.2006) ------------------------------------------- ** Bug * [HHH-1293] - java.lang.NoSuchMethodError: .getHibernateLazyInitializer() * [HHH-1677] - optimistic-lock="dirty|all" is ignored at delete time * [HHH-1710] - persistent collections with property-ref to secondary tables cannot be joined in HQL * [HHH-1713] - AbstractEntityPersister causes an exception when a row in a joined table is missing with fetch="select" * [HHH-1740] - Build-time instrumentation breaks lazy="proxy" * [HHH-1750] - Exception ORA-01000 too many open cursors by generated="insert" * [HHH-1806] - No Dialect mapping for JDBC type: 3 * [HHH-1848] - A session.lock generates a query with a version column in a joined subclass which does not exist * [HHH-1892] - finish HHH-1789 for ordered and sorted collections * [HHH-1898] - With hibernate 3.2.0-cr3 there is an hql parsing error on a one-to-one relation * [HHH-1924] - ForeignKeys: TransientObjectException is thrown without a message because of a wrong bracket in the code * [HHH-1927] - persist() and then merge() not handled correctly for multiple entity instances representing the same logical state * [HHH-1937] - Proxy creation failure leads to NPEs * [HHH-1943] - PersistenceContext not checked to see whether the associated entity is transient or not * [HHH-1944] - generated subqueries and jpaql compliance (derived select clause) check * [HHH-1947] - OF part of MEMBER OF is optional * [HHH-1948] - Query Idetification variables are case insensitive in JPA * [HHH-1949] - having trim(BOTH from c.name) translated into having ltrim(rtrim(BOTH)) on DB2 * [HHH-1954] - Proxies are never unassociated (evicted) from a session * [HHH-1958] - session.lock(LockMode.FORCE) can lead to NPE * [HHH-1963] - meta inheritance broken * [HHH-1992] - Some cascade actions should not trigger a property access on lazy properties * [HHH-2001] - javaassist does not setup the proper protection domain thus does not work with signed/secured deployments such as webstart * [HHH-2015] - where= does not set parenthesis leading to unexpected query when multiclause are used * [HHH-2017] - locate function defined on Oracle9Dialect is incorrect * [HHH-2022] - property names beginning with underscores cause Hibernate to generate invalid aliases ** Improvement * [HHH-1470] - Enhance Hibernate-Mapping DTD Definition of type element * [HHH-1934] - logging NonUniqueObjectException and WrongClassException * [HHH-1941] - Be more specific about x not found and invalid mapping exceptions to allow tools to tell about it * [HHH-1968] - unify bytecode instrumentation * [HHH-1980] - disallow the mapping combination of and optimistic-lock * [HHH-2005] - more standard build script * [HHH-2023] - performance optimization of JTATransactionFactory.isTransactionInProgress() ** Patch * [HHH-1271] - When using Stored Procedure for update or delete, the check is not done correctly. ** Task * [HHH-1931] - verify that the instrument tasks actually work Chages in version 3.2 cr3 (2006.07.06) ------------------------------------------- ** Bug * [HHH-1452] - Native SQL query is missing join if entity includes many-to-one on secondary table * [HHH-1507] - one-to-one can have formula or meta but not both of them. * [HHH-1552] - Error when using ?1 and parameterList * [HHH-1586] - ClassCastException in CollectionType.toLoggableString if using CustomCollectionType * [HHH-1732] - EhCache.toMap still assumes Serializable objects * [HHH-1734] - Connection leak when using hilo strategy in SE environment * [HHH-1741] - Bug in reference documentation * [HHH-1746] - NullPointerException at IdentNode.resolveAsNakedComponentPropertyRefLHS(IdentNode.java:195 * [HHH-1748] - Setting a comment that contains a single quote on a query results in an unintuitive exception * [HHH-1763] - Bug in InputStream org.hibernate.util.ConfigHelper.getResourceAsStream(String resource) * [HHH-1791] - property update="false" ignored since 3.2.0.cr2 * [HHH-1816] - serializing session from a named session factory to a different vm broken * [HHH-1822] - flushing entity linked to transient instance (non cascaded) should always fail * [HHH-1828] - registering a transaction marked for Rollback is illegal * [HHH-1833] - Not Generating HibernateException * [HHH-1838] - Wrong SQL generated for hql query on "any" relation * [HHH-1855] - booleans not properly handled in assignment clause of UPDATE statements * [HHH-1858] - wrong sql generated against many-to-any association table * [HHH-1871] - query type autodiscovery assume wrong column when mixing entities and scalars ** Deprecation * [HHH-1792] - Callable update/insert/delete statements should not force rowcount out parameter ** Improvement * [HHH-1617] - Check the second-level cache before adding a PK to a batch fetch * [HHH-1773] - Typo in ImprovedNamingStrategy * [HHH-1779] - Allow Session.remove() on transient object * [HHH-1789] - improve efficiency of collection initialization from L2 cache hits * [HHH-1795] - default cache provider to NoCacheProvider * [HHH-1796] - TreeCache based providers and Fqn * [HHH-1800] - session.get() / load() should raise exception when the id is of the wrong type * [HHH-1818] - remove() should force subsequent contains() calls to return false * [HHH-1831] - Batch loading the same EntityKey (one side of manytoone ) more than once * [HHH-1861] - More complete component handling in HQL * [HHH-1881] - introduce LoggableUserType interface ** New Feature * [HHH-1709] - Be able to raise ENFE rather than LIE in proxies * [HHH-1727] - Add a SQLFunctionRegistry * [HHH-1817] - Introduce setting for JPA-QL strict compliance * [HHH-1826] - Built-in type for char[] -> VARCHAR Byte[] and Character[] ** Patch * [HHH-1558] - Dialect for new database engine H2 * [HHH-1847] - QBE 'like' clause with backslashes don't work with MySQL ** Task * [HHH-1839] - rename FlushMode.NEVER -> FlushMode.MANUAL Changes in version 3.2 cr2 (2006.05.05) ------------------------------------------- ** Bug * [HHH-1114] - The first (HSQL) Hibernate Application doesn't work as expected due to lack of database shutdown * [HHH-1175] - Exception when loading inheritance mapping in single file * [HHH-1560] - PropertiesHelper.resolvePlaceHolders() fails with non-String values in System properties * [HHH-1620] - Errors on max_lo <=1 boundaries * [HHH-1625] - Hibernate.isPropertyInitialized() returns false on instrumented transient object * [HHH-1648] - Exception while resuming a transaction is silently eaten * [HHH-1674] - Configuration serialization error: filterDefinitions map not serializable * [HHH-1695] - subsequent calls to non-existent proxy causes NPE ** Improvement * [HHH-1266] - StatelessSession can implement refresh * [HHH-1414] - many-to-many and metadata order-by based on column from the target table * [HHH-1477] - Improve naming strategy for ANN-195 * [HHH-1538] - aggregations functions in EJBQL queries does not return the appropriate types * [HHH-1670] - Update EhCache and EhCache provider to support EhCache 1.2 * [HHH-1704] - Deduplicate unique constraints generation sharing the same column(s) ** New Feature * [HHH-870] - support SQL updates in named queries * [HHH-1591] - Replace LazyInitializationException by EntityNotFoundException * [HHH-1719] - Provide a ClassTransformer interface to the BytecodeProvider Changes in version 3.2 cr1 (2006.03.27) ------------------------------------------- ** Bug * [HHH-1453] - Broken exception handling in NullableType ** Improvement * [HHH-227] - remove reflection optimizer * [HHH-587] - Make ResultTransformer available for all query methods * [HHH-1588] - delay inserts for insert-generated-identifiers outside transaction * [HHH-1590] - redesign how PostInsertIdentifierGenerators are handled at insertion * [HHH-1592] - allow SelectGenerator to use a defined natural-id (if one) ** New Feature * [HHH-332] - create ability to add resulttransformer to HQL query * [HHH-1179] - support inline sequence id generation on Oracle using RETURNING clause Changes in version 3.2 alpha2 (2006.03.15) ------------------------------------------- ** Bug * [HHH-535] - properties element causes exception in interface/abstract class * [HHH-1325] - ArrayOutOfBounds expected in DatabaseMetadata.isTable when specifing schema * [HHH-1435] - many-to-one lazy seems to be broken in 3.1.x * [HHH-1531] - NPE with many-to-many and property-ref * [HHH-1546] - generated version properties fail with multiple actions per flush ** Improvement * [HHH-1540] - Better Error Feedback In CollectionEntry.postFlush(PersistentCollection) * [HHH-1555] - ConnectionReleaseMode.AFTER_STATEMENT and flushes * [HHH-1559] - introduce TransactionFactory.isTransactionInProgress to facilitate EJB3 joinTransaction handling Changes in version 3.2 alpha1 (2006.02.28) ------------------------------------------- ** Bug * [HHH-687] - Exception QuerySyntaxError not really serializable * [HHH-1236] - Remove static reference to classloader, to avoid memory leak at webapp reload * [HHH-1287] - Problem with WAS ExtendedJTATransaction not available when using MDB * [HHH-1419] - Update + Exists doesn't seem to work * [HHH-1445] - SchemaUpdate closes shared ConnectionProvider * [HHH-1464] - QueryException from Query.getReturnAliases when query uses "fetch" * [HHH-1486] - Concurrent access issues with both SoftLimitMRUCache and SimpleMRUCache * [HHH-1508] - Session.createQuery() should not flush the session ** Improvement * [HHH-1411] - Collection fetches and DISTINCT * [HHH-1412] - Collection fetches and firstResult/maxRows * [HHH-1416] - LockMode.FORCE to implement EJB3 LockModeType.WRITE * [HHH-1457] - support new optimisitc locking capabilities of JBossCache * [HHH-1466] - better handling of Antlr exceptions * [HHH-1516] - support DataDirect standard jdbc stored procedures * [HHH-1518] - Guarentee LockMode behaviors * [HHH-1520] - with clause with implied joins within an explicit join * [HHH-1526] - Improved DTDEntityResolver ** New Feature * [HHH-1251] - Avoid replicating the clearing of TreeCache on SessionFactory..close() * [HHH-1410] - FlushMode.AUTO -> COMMIT when outside a transaction * [HHH-1447] - pluggable bytecode libraries Changes in version 3.1.2 (01.27.2006) ------------------------------------------- ** Bug * [HHH-73] - Statistics for HQL queries use pre-processed query string * [HHH-1306] - HQL parsing problem with join fetching of arrays/collections of values * [HHH-1370] - Warning in hibernate-mapping-3.0.dtd * [HHH-1371] - MappingException is thrown when the same column is referenced with different case * [HHH-1386] - Numeric (long) literals not properly handled by HQL parser * [HHH-1390] - Session.isOpen() throws exeception when the session is closed with ThreadLocalSessionContext * [HHH-1391] - Invalid parameter index SQLException when using named parameters after positional parameters * [HHH-1392] - Proxies cannot be serialized after session is closed * [HHH-1398] - extends and entity-names broken with mapping-level package attribute * [HHH-1407] - return-join broken for entity collections ** Improvement * [HHH-1364] - Defensive check of isClosed when obtaining a connection from ConnectionManager * [HHH-1367] - warn level log "this operation breaks ==" may be disturbing ** New Feature * [HHH-1372] - Support for MySQL5 new varchar length ** Patch * [HHH-1005] - Criteria LEFT JOIN capability when adding Order to associations ** Task * [HHH-1373] - Document update versioned Changes in version 3.1.1 (01.13.2006) ------------------------------------------- ** Bug * [HHH-853] - DML-style HQL queries and associations * [HHH-1281] - FORWARD_ONLY ScrollableResults#next() throw GenericJDBCException * [HHH-1286] - Set entity in HQL query without prefix -> incorrect SQL * [HHH-1308] - Session.createFilter(...).iterate() results in bogus column names for result set extraction * [HHH-1314] - float/double literals not sent to the database correctly * [HHH-1316] - SchemaUpdate : java.sql.SQLException: You cannot commit during a managed transaction! * [HHH-1328] - org.hibernate.util.SimpleMRUCache keeps a soft reference to the cache key, so cached values get collected prematurely * [HHH-1336] - ForeignGenerator does not handle transient entities with an entity-name properly * [HHH-1337] - Mapped generated column names incorrect with ImprovedNamingStrategy * [HHH-1349] - HQL delete statement problem due to oracle lacking table aliases in delete clause * [HHH-1361] - creating temporary table for bulk delete will commit current transaction in managed environment such as J2EE ** Improvement * [HHH-1019] - Native SQL return-property mapping doesn't support dot-syntax in return-property for components * [HHH-1290] - Defensive checking of session status * [HHH-1302] - query.getReturnTypes inconsistent * [HHH-1304] - better handling of borrowed connections in non-ON_CLOSE release semantics * [HHH-1309] - schemaupdate does not handle TableHiLoGenerator * [HHH-1339] - empty property name in mapping file gives imcomprehensible error message * [HHH-1344] - ANSI-SQL trim function for SQLServer * [HHH-1345] - ANSI-SQL mod function for SQLServer * [HHH-1346] - ANSI-SQL bit_length function for SQLServer * [HHH-1351] - should be possible * [HHH-1360] - set autodiscovery flag for SQLQueries when resultsetmappings are used Changes in version 3.1 (12.12.2005) ------------------------------------------- ** Bug * [HHH-849] - Cartesian product + implicit joins * [HHH-1065] - user provided connection not usable by default due to agressive release changes * [HHH-1101] - associations join fetched in HQL without owner being selected * [HHH-1133] - Comparators, defined for collections in mapping files, are not set * [HHH-1149] - NPE flushing reattached entity w/ non-mutable natural-id * [HHH-1170] - HQL 'cast' function doesn't work with MySQL 4 when casting to string * [HHH-1187] - Cannot delete a object having a delete-orphan collection when user_rollback_id is set * [HHH-1191] - HQL fails backward compatibility using classic translator * [HHH-1194] - hql delete statements with joined-subclass hierarchies with a mapped where attribute at the root * [HHH-1206] - Mappings.TableDescription is not serializable * [HHH-1212] - mismatch in entity-modes defined in DTD and EntityMode class * [HHH-1227] - ClassCastException on DOM4J replicate of Calendar property * [HHH-1239] - BinaryArithmeticOperatorNode.getDataType() does not properly handle date/time arithmetic * [HHH-1240] - Track connection leakage in JDBCContext.afterTransactionCompletion() * [HHH-1245] - Calling the Session should register it with the current JTA txn. * [HHH-1254] - Serialization of Sessions using JDBCTransactions with auto-flush/auto-close ** New Feature * [HHH-1222] - Autodiscover scalar types in native-sql * [HHH-1243] - allow placeholders to system properties in config properties * [HHH-1244] - Support for MySQL5 stored procedures * [HHH-1260] - Configuration.mergeProperties() ** Task * [HHH-1066] - Upgrade CGLIB to fix proxy memory leak * [HHH-1242] - upgrade ANTLR to 2.7.6rc1 ** Improvement * [HHH-860] - insert ... select ... and version numbers * [HHH-926] - TypeDef should be global * [HHH-1138] - No ConstraintName when using PostgreSQL * [HHH-1144] - Implement naming convention for temporary test failures * [HHH-1153] - PropertiesHelper fails reading primitive values from hibernate-mapping when doc has whitespace * [HHH-1182] - Access to filter metadata * [HHH-1183] - Getting sql "plan" for DML operations * [HHH-1197] - Support for HQL delete on MaxDB * [HHH-1198] - post-insert event pass the entity wo the id field filled when the generator is identity * [HHH-1213] - make JACC event listeners auto configurable (through initialize(Configuration)) * [HHH-1215] - Added support for LVARCHAR in InformixDialect * [HHH-1218] - Add concat() function support to SAPDBDialect * [HHH-1255] - ThreadLocalSessionContext and Session serialization ** Patch * [HHH-967] - executeUpdate on StatelessSession * [HHH-1172] - Missing configuration templates for the new MimerSQLDialect ** Deprecation * [HHH-1229] - deprecate ability for entities to not define identifier properties Changes in version 3.1 rc3 (17.11.2005) ------------------------------------------- ** Bug * [HHH-755] - Setter / Getter for property gDate are wrong * [HHH-764] - XML mapping * [HHH-1034] - The connection is closed *outside* the JTA transaction in TransactionHelper * [HHH-1062] - java:comp/UserTransaction not correct for JBoss * [HHH-1064] - Exception using JTATransaction in WebSphere 6 * [HHH-1069] - Unnecessary commas generated in select with left outer joins * [HHH-1075] - New parser "not exists" command bug * [HHH-1077] - Typo in docs: "equiped" * [HHH-1080] - HQL delete fails on entities with where-fragments using operators other than '=' * [HHH-1081] - missing parens in example code for Criteria Associations * [HHH-1084] - incorrect method name "sql" in Restrictions example, should be "sqlRestriction" * [HHH-1091] - Can't write transparent CurrentSessionContext for BMT * [HHH-1098] - Patch for build.sh to be able to build latest version on linux * [HHH-1106] - HQL "not in" generatad wrong SQL * [HHH-1111] - JDBCTransaction.rollback() results in a call to Interceptor.beforeTransactionCompletion() * [HHH-1128] - Column alias clashes under certain circumstances * [HHH-1146] - latest cvs(11/10/05) hibernate3 issue with classic query * [HHH-1156] - StatefulPersistenceContext not serializable when property-ref is used * [HHH-1160] - Incorrect use of getGeneratedKey() for Oracle ** New Feature * [HHH-449] - korean hibernate reference manual * [HHH-1129] - use expected-type in 'untyped' Query.setParameter() ** Improvement * [HHH-221] - Proxy for one-to-one with property-ref * [HHH-844] - move parameter "bookkeeping" into QueryTranslator * [HHH-1051] - "Compiled" native SQL queries are not cached * [HHH-1061] - import.sql should allow more human readable and usable files * [HHH-1078] - requires type on property * [HHH-1120] - Make NamingStrategy to work nicely with HA and EJB3 naming strategy * [HHH-1142] - added getSelectSequenceNextValString() and getCurrentTimestampSelectString() to TimesTenDialect ** Patch * [HHH-1063] - support for 'locate' function in SQLServer and Sybase dialects * [HHH-1090] - Allow subqueries on criteria to obtain non-string results * [HHH-1095] - Hibernate takes incorrect HasCode when a lot of CompositeKeys and Lazy loading is involved * [HHH-1103] - finalize method filter for proxies * [HHH-1136] - more meaningful AssertionFailure message in org.hibernate.persister.entity.JoinedSubclassEntityPersister.getTableId(...) Changes in version 3.1 rc2 (17.10.2005) ------------------------------------------- ** Bug * [HHH-1045] - Example contains inner classes that aren't serializable * [HHH-1055] - optimistic-lock is not inherited from class to subclass et.al. ** Improvement * [HHH-702] - auto detect aliasing for collection properties (coll.key, coll.id etc.) * [HHH-1038] - make 'auto' the default for hibernate.connection.release_mode * [HHH-1042] - determine "expected type" of parameters during HQL parsing Changes in version 3.1 rc1 (07.10.2005) ------------------------------------------- ** Bug * [HHH-528] - component.manyToOne.id in HQL causes join * [HHH-871] - Configuration.setListener(String type, Object listener) throws ClassCastException * [HHH-873] - referencing raw HQL FromElement alias outide the from clause of update and delete statements generates incorrect sql * [HHH-876] - PreparedStatement being closed before being executed by AbstractBatcher * [HHH-884] - SchemaExport does not propagate parent indexes to tables * [HHH-887] - Aggressive release and Session.connection() * [HHH-893] - custom tuplizer are not instantiated for components * [HHH-905] - $PlaceHolder$ remains in generated SQL when filter is enabled * [HHH-907] - optimistic-lock="false" for timestamped object results in SQLException: Invalid column index * [HHH-908] - CLONE -NullPointerException when using BigInteger in a query * [HHH-911] - CGLIBLazyInitializer and Exceptions * [HHH-913] - NPE in CMTTransaction since javax.transaction.Transaction is never set * [HHH-918] - impossible to move objects to another session * [HHH-924] - Useless OracleErrorCodeConverter (and possibly others) * [HHH-932] - HQL UPDATE and * [HHH-946] - QuerySyntaxException might not be serializable * [HHH-964] - ORA-00936 with joined subclass / Oracle * [HHH-986] - Need to check Thread.currentThread().getContextClassLoader() in ConfigHelper * [HHH-991] - Cannot use comparator class * [HHH-1000] - varchar(xxx char) not supported on Oracle8i ** New Feature * [HHH-950] - interface for SessionFactory.getCurrentSession() handling ** Improvement * [HHH-608] - update HSQLDialect for HSQL 1.8 sequence support * [HHH-889] - Add read-only cache-mode comment in tables * [HHH-887] - Aggressive release and Session.connection() * [HHH-893] - custom tuplizer are not instantiated for components * [HHH-905] - $PlaceHolder$ remains in generated SQL when filter is enabled * [HHH-907] - optimistic-lock="false" for timestamped object results in SQLException: Invalid column index * [HHH-908] - NullPointerException when using BigInteger in a query * [HHH-911] - CGLIBLazyInitializer and Exceptions * [HHH-913] - NPE in CMTTransaction since javax.transaction.Transaction is never set * [HHH-918] - impossible to move objects to another session * [HHH-924] - Removed ErrorCodeConverters * [HHH-946] - QuerySyntaxException might not be serializable ** Improvement * [HHH-898] - OracleDialect UTF8 varchar2 * [HHH-909] - Unquoted primary key in IncrementGenerator Changes in version 3.1 beta 2 (16.08.2005) ------------------------------------------- ** Bug * [HHH-477] - Boolean discriminators generate invalid SQL for PostgreSQL dialect * [HHH-480] - SchemaExportTask ignores some properties not defined in hibernate.properties * [HHH-615] - SchemaExport outputFile ignores ant's basedir * [HHH-770] - hql query execution generates invalid SQL * [HHH-779] - Assertion failure occured with Hibernate 3 saving objects * [HHH-781] - SimpleExpression ignorecase regression * [HHH-799] - merge() and embedded composite identifiers * [HHH-801] - subselect fetch and named parameters * [HHH-802] - querying "mapped" composite identifiers * [HHH-803] - no version increment from delayed collection adds * [HHH-805] - Session.getStatistics().getEntityCount() throws UnsupportedOperationException * [HHH-819] - Firebird CONCAT SQL function * [HHH-821] - query by natural-id cache is not update when object is inserted or deleted * [HHH-822] - will actually pick up tags if it were allowed by the DTD * [HHH-825] - ReadWrite-Cache issues NullPointerException after modification of an array * [HHH-839] - Session.refresh not working for custom 'Load' SQL * [HHH-849] - Cartesian product + implicit joins * [HHH-854] - Class with mapped composite id can't have subclasses * [HHH-858] - Autocommit status inconsistent in connections created by DriverManagerConnectionProvider * [HHH-863] - Hibernate generates "notExists" instead of "not exists" * [HHH-868] - Missing parens after / or - ** New Feature * [HHH-35] - add attribute haltonerror to schemaexport Ant task * [HHH-182] - Mimer SQL Dialect for Hibernate 3 * [HHH-704] - Statistics for optimistic lock failures * [HHH-725] - Allow hooks into all executed sql by a session * [HHH-783] - collection lazy="extra" * [HHH-818] - Optimisitc locking using database current timestamp * [HHH-828] - session.getTransaction() * [HHH-829] - * [HHH-831] - allow database generated property values * [HHH-832] - allow database generated property values for versioning * [HHH-838] - Transaction.setTimeout() * [HHH-840] - allow definition of "auxiliary" database objects in mapping * [HHH-846] - Add Intializable interface for events * [HHH-848] - Validate mappings against JDBC metadata * [HHH-859] - post-commit events ** Improvement * [HHH-133] - schemaexport task: provide independent drop/create output * [HHH-135] - parameterized types can't be used on key-property or ir (possible others) * [HHH-552] - NoopAccessor for HQL-only properties * [HHH-680] - Easier support for doing UserCollectionType's * [HHH-686] - Final classes and classes with private null ctors cause unhelpful NullPointerException * [HHH-754] - Allow HQL DML for implicit polymorphism * [HHH-782] - Avoid unnecessary updates when component property is update='false' but modified * [HHH-786] - Improve lazy options for * [HHH-791] - Use cascade styles when fetching entities in refresh() and merge() * [HHH-815] - Confusing use of the term "dereference" * [HHH-830] - Improvements to caching lazy properties ** Patch * [HHH-378] - Better LockMode.UPGRADE for DB2 UDB v8.2 * [HHH-430] - Improved SizeExpression with greater, lesser, not equals, etc. capabilities * [HHH-735] - SchemaUpdate reads table metadata from wrong schema * [HHH-780] - org.hibernate.proxy.BasicLazyInitializer reflection hotspot * [HHH-864] - Use QUERY_CACHE for sessions with filters to improve performance Changes in version 3.1 beta 1 (21.07.2005) ------------------------------------------- ** Bug * [HHH-145] - union-subclass and oracle 8i * [HHH-374] - EJB3 example delete query doesn't work in Hibernate. * [HHH-447] - EHCache integration prevents multiple session factories * [HHH-488] - JACCListeners are not working at all * [HHH-564] - missing commas for implicit joins * [HHH-577] - joins within subqueries on dbs supporting ansi-joins result in extraneous commas * [HHH-592] - cast() function doesn't know its returned Hibernate type * [HHH-639] - CGLIB instrumentation of subclasses * [HHH-658] - Bug in Alias Name Generation * [HHH-671] - Firebird support of sequences/generators * [HHH-679] - setLockMode(LockMode.UPGRADE_NOWAIT) does not translate to correct SQL on Oracle * [HHH-688] - Bad implementation in org.hibernate.type.CustomType.stringToObject * [HHH-691] - generated column alias is incorrect if there is a prior relationship and the table column names are similar to the table name * [HHH-694] - NPE when accessing the SLCache stats with TreeCache * [HHH-698] - Exception on EG , trying to change immutable id (natural-id) * [HHH-699] - Incorrect Tablename genetaion when using MySQL Dialect and no Schema definition * [HHH-708] - Restrictions.in could not be used properly on composite-ids * [HHH-709] - ArrayType.replaceElements fails if original.length != target.length * [HHH-718] - HQL "fetch all properties" not working for column level lazy props * [HHH-726] - ConstraintViolationException with primitive collection * [HHH-727] - java.lang.StackOverflowError when cascade="true" on both sides of bidirectional one-to-one association using FK * [HHH-734] - HQL incorrectly parses certain query strings * [HHH-736] - Use of sql functions containing space not supported in filter conditions * [HHH-738] - formula property with select-before-update * [HHH-747] - Order.toSQLString generates incorrect statement * [HHH-748] - component dereferencing in subquery from clauses * [HHH-752] - Typo in 8.5.3 bidirectional one-to-one jjoin table example * [HHH-757] - NullPointerException when using BigInteger in a query ** New Feature * [HHH-595] - HQL insert select * [HHH-597] - Named XML resultsetmappings * [HHH-696] - handle discriminators on HQL insert * [HHH-697] - allow bumping versions in HQL update * [HHH-716] - handle version columns in bulk inserts * [HHH-723] - Need to be able to pass in javax.sql.DataSource in SF creation * [HHH-739] - Order.ignoreCase() * [HHH-741] - select clause subselects * [HHH-742] - Stateless session * [HHH-744] - collection fetching in scroll() via "break processing" * [HHH-768] - ** Improvement * [HHH-14] - Add Session.delete(String entityName, Object entity) * [HHH-295] - cleanup and expose the Tuplizers * [HHH-352] - HQL bulk and cache * [HHH-689] - exclude parens for components outside where-clause * [HHH-743] - {coll.key}, {coll.index}, {coll.element}, etc * [HHH-745] - EJB3 composite PK style * [HHH-749] - Cascade merge() and unidirectional one-to-many * [HHH-750] - use attribute name other than 'type' in dynamic-maps * [HHH-753] - Replace antlr System.exit with QueryException * [HHH-769] - property-ref="foo.bar" to a component property * [HHH-772] - null in maps are handled inconsistently * [TODO-18] - optimistic-lock="all|dirty" with components Changes in version 3.1 alpha 1 (24.06.2005) ------------------------------------ ** Bug * [HHH-204] - Wrong/uncommon log name in class ...hql ast ErrorCounter * [HHH-241] - HQL lexer doesn't support unicode quoted strings * [HHH-354] - property named "full" breaks HQL queries * [HHH-493] - WARNING: Keyword 'member' is being intepreted as an ident * [HHH-538] - length() function does not work in SQLServerDialect * [HHH-539] - ClassCastException on mapping a property with a formula in a set of composite elements * [HHH-540] - Mapping a one-to-many collection with a non-null foreign key within a component fails on save * [HHH-547] - Cannot commit using UserCollectionType and debug logging * [HHH-548] - many-to-many faulty delete optimization when filter in use * [HHH-554] - Hibernate 3 HQL to SQL FROM Clause Comma Generation Problem * [HHH-558] - HQL doesn't support multi-byte character in class name and property names * [HHH-559] - quoted multi-byte character in HQL is translated into weird character in SQL. * [HHH-565] - delete-orphan generating AssertionFailure * [HHH-566] - The result is not correct in 'createQuery("select new Foor(x,x) from Foo").scroll()' * [HHH-570] - size operator fails on a many to many in HQL * [HHH-571] - JDK 1.3 Compatibility Issue * [HHH-573] - error when merging entity graph has cascade level>2 * [HHH-575] - org.hibernate.cache.FilterKey is not Serializable * [HHH-589] - parameterized expression inside function * [HHH-594] - order-by mapping for collections overrides order by in HQL * [HHH-601] - New temporary table feature assumes all persisters are ready * [HHH-614] - SchemaUpdate broken in DB2/400 * [HHH-622] - Spelling mistake 'intepreted' in org.hibernate.hql.PARSER warning * [HHH-642] - criterias with projection * [HHH-650] - FilterImpl is Serializable yet FilterDefinition is not * [HHH-657] - Date parse exception using EntityMode.DOM4J * [HHH-666] - JTAHelper.isInProgress( txn.getStatus()) throws NPE when txn null ** New Feature * [HHH-620] - Extra join conditions in HQL * [HHH-640] - short-circuit dirty checking for instrumented classes * [HHH-643] - support mutable="false" for collections * [HHH-645] - Session.setReadOnly() * [HHH-549] - portable to_char() function * [HHH-576] - Hook to pre-process generated select strings in the Dialect * [HHH-662] - Add support for definition of functional composite key ("properties") in joined subclass ** Improvement * [HHH-46] - Allow access to properties that are not joined * [HHH-261] - Stored procedure support for SQLServer dialects * [HHH-351] - multi-table bulk operations * [HHH-574] - improve in naming named-query * [HHH-596] - Auto-detect {..} in native SQL queries * [HHH-641] - create constraints for many-to-one property-ref * [HHH-501] - warn when a final method is tried to be proxied * [HHH-525] - cglib related startup performance * [HHH-557] - Helpful error message for non Serializable classes with a composite-id * [HHH-586] - check immutable natural-ids * [HHH-609] - Adds substr to PostgreSQL dialect * [HHH-618] - documentation bugs ** Patch * [HHH-224] - JDataStore Dialect and updated Testfiles * [HHH-366] - InformixDialect SQLExceptionConverter * [HHH-536] - ImprovedNamingStrategy modifies capitalized column names inappropriately * [HHH-632] - Informix Dialect missing from automatic dialect discovery * [HHH-4] - CachedFile bugfix + configuration + autodetect resource as file Changes in version 3.0.5 (25.5.2005) ------------------------------------ ** Bug * [HHH-516] - Interceptor.onFlushDirty() sometimes not called * [HHH-517] - getDatabaseMajorVersion() not available in JDK 1.3 * [HHH-518] - SQL parser does not recognize all whitespace * [HHH-519] - broken SQL when traversing many-to-many to joined * [HHH-529] - Bug in merge() ** New Feature * added mapping * [HHH-533] - allow unique-key on and * [HHH-534] - efficient cache by natural key * support for on MySQL ** Improvement * [HHH-526] - log "Aggressively releasing JDBC Connection" as DEBUG instead of INFO * various logging improvements Changes in version 3.0.4 (23.5.2005) ------------------------------------ ** Bug * [HHH-452] - UnsavedValueFactory.instantiate does not wrap the Exception it catches * [HHH-456] - Session still holds references to entities after close() * [HHH-457] - Log info for structured second-level cache entries is incorrect * [HHH-466] - Made default for MS SQL dialect definition more flexible * [HHH-473] - Formula can't contain SQL cast keyword * [HHH-484] - Order-by not applied to collections fetched by OuterJoinLoader * [HHH-487] - Possible empty union in UnionSubclassEntityPersister * [HHH-505] - Possible NullPointerException in BigIntegerType * [HHH-507] - Cached List does not show additions * Fixed bugs in subselect fetching ** New Feature * [HHH-455] - Obtain non-intercepted Session by passing an EmptyInterceptor * [HHH-467] - HQL: support for case when then else end IN select clause * [HHH-485] - Support multiple collection join fetches (attention: Cartesian product) in native SQL queries * Added SessionStatistics metric interface * Added support for table and column level blocks * Added Simplified Chinese translation of reference documentation (Xiaogang Cao) ** Improvement * Any query may now join fetch >1 collection role (attention: Cartesian product) * [HHH-454] - Add 2292 integrityViolationCode to Oracle9Dialect * [HHH-503] - Implemented ViolatedConstraintNameExtracter for HSQLDialect (Frank Grimes) Changes in version 3.0.3 (8.5.2005) ----------------------------------- * fixed bug in HQL for composite key classes which have a property named the same as the owning entity's id property * replaced 'connection.aggressive_release' with 'hibernate.connection.release_mode' * added ConnectionReleaseMode * added eager fetch for any associations with fetch=join, even after a HQL query, or cache retrieval (EJB3) * added replicate() isUpdate flag to OnReplicateVisitor, useful for native ids * fixed ParameterizedTypes order of initialization * fixed bug in DB2Dialect * fixed EntityMode.DOM4J creation of duplicate output * fixed JDBCException error code handling * fixed Criteria Restrictions.isEmpty()/isNotEmpty() when collection is mapped to superclass * fixed HQL indexed collections access with no alias * fixed HQL aggregate functions on components when "id" property is used * fixed issue with non-cascading refresh to collections * fixed query-timeout not being applied to bulk HQL (Stephan Fudeus) * fixed pessimistic locking with Firebird (Yuichi Sugimura) * updated Ant 1.6.3 * improved validation of sql queries, throw QueryException if addEntity() nor addScalar() was called * added automatic dialect detection if no dialect is configured * added new tutorial (Michael Gloegl, Christian Bauer) Changes in version 3.0.2 (27.4.2005) ------------------------------------ * fixed union operations on PostgreSQL * fixed HQL concat() function for Oracle dialect * fixed auto-close/auto-flush during getCurrentSession() processing * fixed ClassCastException with EntityMode.DOM4J * fixed HQL dynamic instantiation with iterate() * fixed HQL bug with missing parantheses and implicit joins * fixed bug were Interceptor.getEntity() wasn't called if in cache * fixed bug in merge() of sorted sets * fixed bug in EntityMode.DOM4J with non-lazy embedded many-to-ones * fixed Criteria/Projection ordering bug * fixed HQL referencing component attribute * fixed column duplication detection for components * fixed eager fetching for many-to-many associations * fixed stack overflow with auto_close_session and aggressive_release and unclosed ScrollableResults/HibernateIterator * fixed bug in HQL parser regarding naked property refs which reference component properties * fixed bug with eager fetched arrays not being loaded * fixed bug in filter against joined-subclass * improved CacheMode.GET/IGNORE, disabled cache put * improved HQL support for standard SQL functions, including coalesce() and nullif() * improved filtering of many-to-many associations * added HQL support for cast(x as type) if SQL database supports it * added increment id generation for union-subclass * added ConnectionProvider.supportsAggressiveRelease() for managed environments * added support for caching of queries if filter is enabled * added PreparedStatement count to Statistics * added transactional/nontransactional read()/get() to Cache API * added quotation of schema names * added Distinct to Projection API * added config parameter 'connection.aggressive_release' Changes in version 3.0.1 (18.4.2005) ------------------------------------ * added HQL tuple constructor/comparison feature * added HQL "fetch all properties" override if instrumentation is used for lazy loading * added HQL projection feature, return Lists instead of arrays for projection * added HQL projection feature, return Maps with user-defined HQL SELECT aliases as keys * added HQL support for expressions in aggregation functions * added new IntegrityViolationException to MySQL dialect * added value mapping type 'big_integer' * added not-found="ignore|exception" switch for legacy associations (i.e. broken database integrity) * added fully automatic Session scoping in JTA environments with sf.getCurrentSession() * fixed bug in DTD that wouldn't allow union-subclass in separate file * fixed a MS SQL Server case sensitivity issue with native SQL queries * fixed a minor bug in subselect fetching * fixed case sensitivity in HQL functions * fixed a bug with listener assignment for save() operation (Matthew Inger) * fixed return-property in named SQL queries to work with all identifier names * fixed TransactionManager lookup (again) for WAS 6.0 * fixed a bug with HQL batch delete and MS SQL Server * fixed session not getting closed with auto_close when rollback occured * improved concatentation handling in AST parser * updated dom4j to avoid memory leak in old version * updated C3P0 Changes in version 3.0 (31.3.2005) ---------------------------------- * added support for autoflush/autoclose to HibernateServiceMBean * fixed initialization/session association detection problem of collections * fixed creation of FK constraints to union superclass table * fixed bug where union-subclass table did not get a PK constraint * added a separate log category for HQL parser warnings and errors * fixed bulk delete operation on MS SQL Server * added support for proxying protected methods (Juozas) * added support for unicode quoted strings in new HQL parser * fixed implied joins in subselect WHERE clause in new HQL parser * added SQLServer7Dialect to handle differences in functions * added support for JNDI-bound cache instances, future use for JBoss Cache * added scale attribute to column mappings for numeric precision control * added fetch=subselect for collections * added support for bulk update/delete against discriminator-based inheritence hierarchies * added the ability to use naked property refs in HQL (required in update/delete statements) * updated CGLIB 2.1.0 * fixed NPE at BasicEntityPersister.getPropertyIndex (Todd Nine) * fixed issue with entity-name and subclasses (Sverker Abrahamsson) * fixed issue with correlated subqueries in new HQL parser * fixed a problem with native SQL query mapping and embedded composite identifiers * improved mapping binding, allowing unordered extends for pure entity-name hiearchies * fixed NPE for delete() with deprecated Lifecycle interface * fixed a problem with serial joins ending in component value in new HQL parser * fixed inner join/subselect precedence problem in new HQL parser * fixed indices() function in new HQL parser * fixed a bug in InformixDialect, now correct LIMIT clause * fixed a bug in idbag.remove() (Sebastien Cesbron) * fixed a conflict on OracleDialect between setMaxResult and LockMode.UPGRADE * fixed XML configuration file issue with SchemaExport * fixed an ArrayIndexOutOfBounds problem * renamed executeUpate() to executeUpdate() * fixed batch loading for property-ref entities * fixed loading from cache of collection owner * fixed minor bug in SQL exception reporting * fixed dynamic-component cannot be bound to XML * fixed querying component with formula property * fixed incorrect table alias for order-by on many-to-many * fixed a bug for unidirectional one-to-many with moving child objects * fixed a bug with union-subclasses and persister creation * fixed a HQL concatenation problem on MySQL * fixed a bug where an unnecessary exception was thrown for a property-ref to a superclass property * fixed minor dtd bug * fixed new bug in Clob/Blob support * fixed issue with INDEX_OP and subclass joins on theta-join dialects * fixed some minor issues in query cache regions, including HB-1449 * fixed superflous import and regression bug in verifyparameters * fixed two bugs in select id generator (Malcolm Green) * fixed increment generator for union-subclass mappings * updated JBoss Cache to 1.2.1alpha, fixing locking issues * made stat classes serializable * fixed merge(), now ignores blob and clob fields * added support/dialect for TimesTen * improved algorithm for batch fetching, more aggressive * improved toStrings()s for Statistics objects (Ryan Lynch) * renamed to for externalized SQL query mapping * renamed Session.openSession() for EntityMode to Session.getSession() * added support for CASE in HQL * fixed bug with filters and polymorphic queries * fixed import ordering problem of super/subclass mappings * switched to patched ANTLR 2.7.5, now using context classloader before doing class.forname * TableHiloGenerator now falls back to TableGenerator properly with max_lo < 2 (Emmanuel Bernard) * better transaction handling of TableGenerator in a JTA environment (Emmanuel Bernard) * removed hard coded log4j dependency (Emmanuel Bernard) * added support for stored procedure in named queries (Max Andersen) * added to named SQL queries to allow users to use sql without {}-markup * added multi-column property support to native SQL mapping Changes in version 3.0rc1 (28.2.2005) ---------------------------------- * introduced EntityModes, and XML mapping preview * several minor dialect improvements * fixed a problem where filters were not applied to subclasses * fixed a problem where InstrumentTask would fail if applied to already-instrumented classes * fixed many problems with new parser and made it the default (thanks again to Joshua for the new parser) * implemented bulk update/delete queries for the new parser * fixed a minor bug in the classic query parser * renamed create() to persist() as per EJB3edr2 Changes in version 3.0 beta 4 (11.2.2005) ----------------------------------------- * support unidirection one-to-many with a not-null foreign key * support formulas for index and element of collections * support one-to-ones mapped to formulas * fixed a bug in proxying methods that return "this" * optimized proxies for embededded composite id classes * fixed a bug affecting * fixed a bug caching newly inserted objects * introduced DetachedCriteria * support subselects in Criteria queries * miscellaneous Criteria API enhancements * fixed a problem where hibernate.max_fetch_depth applied to eager fetching via setFetchMode() * use inner joins for join fetching not-null fk associations * support unique="true" in and mappings * union-subclass hierarchies may own collections (dtd bug) * added guid support for Oracle * new mechanism for auto-detecting unsaved-value * pass state array in delete events * improved implementation of hibernate.auto_close_session and hibernate.close_before_completion * fixed a bug where components with only collections would be incorrectly nullified * fixed a bug where criteria queries with projection could not be cached * fixed a problem where duplicate column name aliases could be generated Changes in version 3.0 beta 3 (30.1.2005) ------------------------------------------ * Major rework of Criteria queries, support for projection, grouping, aggregation, ordering by any attribute * various improvements to new HQL parser (Joshua Davis) * fixed a bug where was broken for subclasses with duplicated property names * fixed problems with long types in Oracle DDL generation * added EnhancedUserType, UserCollectionType, UserVersionType * added CacheMode * fixed minor performance problem where cascade delete could add objects to second-level cache * added hibernate.default_batch_fetch_size * added hibernate.cache.use_structured_entries * different classes and collection roles may now share a cache region * don't include discriminators for abstract classes in generated SQL * it is no longer truly necessary for composite identifier classes to implement equals()/hashCode() (but still recommended) * workaround for bug in MySQL InnoDB with self-referential foreign keys * added lazy="true" to many-to-one and one-to-one mappings (requires bytecode instrumentation) Changes in version 3.0 beta 2 (24.1.2005) ------------------------------------------ * added LockAcquisitionErrorCodes to MySQL dialect (Jesse Barnum, Emmanuel Bernard) * added MultipleHiLoPerTableGenerator, one hi value per row/per table (compliant with EJB3) * added a generator handling multiple hi values per table (Emmanuel Bernard) * added events for pre/post SQL operation interception * added experimental support for JACC-aware configuration and events * added full support for implicit polymorphism in Criteria queries * added support annotated classes through XML configuration (Emmanuel Bernard) * added support for WebSphere's weird TxManagerLookup * added support for filters with dynamic-class mappings * added support for lists of parameters in filters * added support for scalar queries in createSQLQuery (Michael Gloegl) * added support for scalar results in native SQL queries (Michael Gloegl) * fixed SchemaExport/SchemaUpdate, now respect default_schema and default_catalog (Michael Gloegl) * fixed a bug in one-to-one mapping with property-ref * fixed a bug in the query cache lookup routine * fixed compilation problems on IBM JDK 1.4. and JDK 1.3.1 * fixed custom SQL for loading when using composite identifiers * fixed exception thrown from optimistic locking failures * fixed support for limit queries (select first ?) in Informix * improved SchemaExport/Update, now respect default_schema and default_catalog * improved dialect handling, throw an exception if no dialect has been set * improved loading of mappings, no ordering of super/subclasses required anymore * improved statistics for second-level cache * improved table generators for hi/lo, can now be used in a JTA environment (Emmanuel Bernard) * query engine: added support for 'trim([leading | trailing | both] [expression from] expression)' * query engine: added support for DISTINCT and ALL * query engine: added support for FETCH * query engine: added support for HAVING count() * query engine: added support for HQL NOT IN and EJBQL '[NOT] MEMBER OF' * query engine: added support for ORDER BY COUNT(*) * query engine: added support for collections of scalar values * query engine: added support for literals in constructor select expressions. * query engine: added support for select elements(..) from Foo f * query engine: added support for template functions in the SELECT clause * query engine: fixed NOT LIKE * query engine: introduced EMPTY and added it to constant (support for IS [NOT] EMPTY) * updated dom4j, OSCache, EHCache, JBoss Cache, Xerces, Xalan, and Log4j * associated class where filter now applies to Changes in version 3.0 beta 1 (21.12.2004) ------------------------------------------ * reimplemented HQL using an ANTLR-based AST parser (Joshua Davis) * added class="select" id generator * added Query.setReadOnly() * added hibernate.order_updates * introduced cascade refresh * added typed JDBC exceptions (Steve Ebersole) * improved lifecycle for CacheProviders (Steve Ebersole) * added Expression.isEmpty() * fixed some minor mapping DTD bugs (Ben Sommerville) * fixed auto-commit mode for SchemaUpdate * added default-lazy to , which defaults to true! * added fetch="join|select" and deprecated outer-join attribute * fixed a bug where was not used for entities with "identity" id generation * fixed some problems with dynamic-class * added property-level optimistic-lock attribute, to allow an unchecked property * cascade lock() now cascades with LockMode.NONE * fixed some bugs in filter handling (Steve Ebersole) * added hibernate.transaction.flush_before_completion and hibernate.transaction.auto_flush_session * added JSR-220 compliant create() and merge() operations * cascade attribute is now multi-valued, with values save-update,create,merge,delete,delete-orphan,lock,evict,replicate,all-delete-orphan * index and unique-key attributes may now be multi-valued * introduced unsaved-value="undefined", the default for "assigned" ids and , which forces Hibernate to hit the db * primitive typed property mappings now default to unsaved-value="0" * added ScrollMode * added dialect for Derby (Simon Johnston) * added MySQLMyISAMDialect and MySQLInnoDBDialect * added precision and scale mapping attributes, for numeric types in DDL * fixed a problem with duplicate column mappings on Sybase * read-write cache now uses version numbers to ensure consistency with database, if available * native SQL queries may now fetch a collection role (Steve Ebersole) * added sequential-select, optional and inverse attributes to * added element, which can be the target of a property-ref * fixed a bug relating to composite property-refs * Hibernate now much more robust if user does not implement equals()/hashCode() on id and unique key classes * enabled batch deletes for versioned data * fixed a minor bug in Session.close() * removed uuid.string and renamed uuid.hex to plain uuid * workaround for a MySQL bug in SchemaUpdate * added JDBCException.getSQL() and made various improvements to exception flow * createSQLQuery() now fully supports components * fixed a bug in SQL generation for mappings * fixed a bug where filter and query parameters could be bound in the wrong order (Steve Ebersole) * fixed a problem where quantifiers could not appear in SQL fragments * fixed a bug with dynamic components * fixed a bug where Dialect default properties overrode user-specified properties (Ben Sommerville) * fixed a bug where duplicate column name in a joined table caused an exception * implemented two-phase load for dynamic components * fixed a bug where cancelQuery() canceled a re-pooled statement * deleted collections are now removed from session-level cache * fixed a bug in LocaleType (Steve Ebersole) * use "with rr" to obtain UPGRADE locks in DB2 * package attribute now significant for extends * fixed a minor problem with Hibernate Clobs and Blobs * extends attribute does no longer require specific ordering of mapping files Changes in version 3.0 alpha (23.8.2004) ---------------------------------------- * package rename net.sf.hibernate -> org.hibernate * checked exceptions are now runtime exceptions * some session methods deprecated and moved to org.hibernate.classic.Session * removed various deprecated functionality * added Filter API and mappings, for temporal, regional and permissioned data (Steve Ebersole, Gavin King) * support cascade delete via ON DELETE CASCADE constraint * added extra attributes to named query definition * added hibernate.use_identifier_rollback * added subselect mappings * added lazy="true" to property mappings * added for multitable mappings * added for table-per-concrete-class strategy * added Statistics API and JMX MBean (Gavin King, Emmanuel Bernard) * introduced new event-driven design (Steve Ebersole) * support for faster startup with Configuration.addCachableFile() (Joris Verschoor, Max Andersen) * mask connection password for log level greater of equals to info (Joris Verschoor, Emmanuel Bernard) * add check of named queries when building SessionFactory (Joris Verschoor, Emmanuel Bernard) * added custom EntityResolver setting capability (Emmanuel Ligne, Emmanuel Bernard) * PropertyValueException for null values in not-null properties of components (Emmanuel Bernard) * enhanced support for single- and no-argument sql-functions in HQL select clause (Michael Gloegl) * Added catalog element, to enable table names like catalog.schema.table (Michael Gloegl) * Added , and support (Max Andersen) * Support callable statements (stored procedures/functions) via callable="true" on custom sql (Max Andersen) * Added support for type parameters and typedefs (Michael Gloegl) * Added support for JDBC escape sequences in createSQLQuery (Max Andersen) * Added statistics per SessionFactory (Gavin King, Emmanuel Bernard) * Added a StatisticsService MBean for JMX publucation (Emmanuel Bernard) * support for updates via rownum in Oracle * fixed problems with SchemaUpdate * support for * added hibernate.use_sql_comments * added property-ref to collection * fixed performance problems with * enhanced UserType with new methods assemble()/disassemble() * better algorithm for batch fetch batch sizes * added * added entity-name concept, and session methods save(entityName, object), update(entityName, object), etc * added framework in proxy package * native SQL queries may now fetch a collection role * added for class and collection mappings * added getEntity() and getEntityName() to Interceptor * formula-based discriminators and association mappings * added "guid" id generation strategy * various improvements to dialects * now acts as a filter on collections * where filters now apply in the on clause in an outer join * added hibernate.jdbc.factory_class to select a custom batcher * session now uses entity name + id to enforce uniqueness, instead of table name + id Changes in version 2.1.6 (9.8.2004) ------------------------------------ * fixed Quickstart/readme.txt instructions * fixed DB2/400 identity column support * fixed the scroll() query method * fixed exotic classloader problems with CGLIB * added insert="false" for discriminator columns which are part of a composite identifier * added several new configuration settings to JMX HibernateService * added new instantiate() method to SessionFactory.getClassMetadata() * improved the HSQL DB dialect with features from new version * added hibernate.jdbc.batch_versioned_data (Steve Ebersole) Changes in version 2.1.4 (2.6.2004) ------------------------------------ * improved Session serialization support by adding ability to serialize unflushed sessions (Steve Ebersole) * fixed Session.clear() functionality to clear the internal nonExists cache (Steve Ebersole) * much better implementation of scroll() (Steve Ebersole) * support "select new ..." for iterate() and scroll() (Steve Ebersole) * added support for multi-parameter SQL functions (Steve Ebersole) * fixed hbm2ddl generating infinite indexes on MySQL (Michael Gloegl) * fixed alias precedence in HQL queries, function names are second (Steve Ebersole) * added "transactional" as allowed cache concurrency strategy in XML configuration file * improved System.getProperties() with security exception warning in secure environments * improved Proxool integration, better property handling * fixed problem with use of getDefinedMethod() in secure environments (Ken Arnold) * fixed bug in createSQLQuery() which prohibited multiple aliases for the same entity (Max Andersen) * fixed query cache misses when using named bind parameters (Michael Greer) * recognize "left" and "right as keywords in SQL fragments * recognize SQL quoted identifiers in SQL fragments * improved identity handling on SQL Server by using scope_identity() for update counts (Arthur Fitt) * added DB2390Dialect for DB2/390 databases (Kristoffer Dyrkorn) * fixed a bug in toArray() of identifier bag collections (Khachchou Mohammed) * fixed a problem with DDL generation for serial columns in Informix * fixed a problem with DDL generation for timestamp columns in Informix (Michael Schmidt) * fixed a NPE that occurred calling saveOrUpdateCopy() for components * fixed a bug with replicate() and uninitialized collections * fixed a bug caching one-to-one associations * fixed eviction from named query cache regions Changes in version 2.1.3 (25.4.2004) ----------------------------------- * added SELECT-clause SQL function support to main Dialects * fixed a problem where some unnecessary selects where issued for optional one-to-one associations * fixed a bug in SQL generation for criteria queries with multiple one-to-many joins * deprecated everything related to PersistentEnum * fixed an NPE that occurred when using with composite ids * fixed a problem with JCA adaptor on WebLogic (Michael Gloegl) * improved behavior when removing elements from s * fixed a bug in getGeneratedKeys() support (Michael Gloegl, Kevin Day) * fixed a bug when using Criteria queries with collections of joined-subclasses * fixed an NPE that occurred when calling comparator() on a lazy sorted set (Attila Szegedi) * fixed a bug when using setMaxResults() with native SQL queries in some Dialects * validate that composite id classes override hashCode() (Adrien) * fixed some minor problems with saveOrUpdateCopy() * fixed some problems in OSCache provider * fixed an NPE that occurred when calling a lazy collection after evicting from session * fixed an NPE that occurred when select-before-update is used with unversioned data (Patrick Peralta) * fixed a bug where dynamic-components could not be queried (Massimo Ferrari) * SQL formula parser now recognizes all Dialect-specific SQL functions (Anthony Patricio) * fixed a problem where SQL CASE statements could not appear in SQL formulas * fixed a problem where subselects with joins could not appear in SQL formulas * C3P0 and Proxool pools now cleaned up after SessionFactory.close() * fixed a bug where dirty checking of mutable properties was broken after lock() * fixed a minor bug where orphan delete was broken for newly saved instances * added Query.setFetchSize() and Criteria.setFetchSize() * PreparedStatement pooling in DBCPConnectionProvider can now be disabled (Emmanuel Bernard) * Query.setProperties(Object) now detects array and collection valued properties and delegates to Query.setParameterList() (Max Andersen, Nick Heudecker) * lengths of positional parameters and types arrays are now validated * fixed an obscure problem where a PreparedStatement was not closed Changes in version 2.1.2 (4.2.2004) ----------------------------------- * added Session.isDirty() * fixed a very obscure concurrency problem with read-write cache for inverse collections * deprecated Criteria.returnMaps() / Criteria.returnRootEntities() in favor of new ResultTransformer framework * don't cache objects with dynamic-update="true" or mappings immediately after insert/update * added version checking to saveOrUpdateCopy() * fixed constraint violations that occurred when mixing identity columns with other id generation strategies * added Sybase 11.9.2 dialect to support older versions of Sybase that do not support ANSI joins (Colm O' Flaherty) * added Informix9Dialect (Finn McCann and Max Andersen) * added DB2400Dialect (Peter DeGregorio) * fixed a problem where mapping validation failure was reported as duplicate import (Michael Gloegl) * fixed a problem with Expression.not() in MySQL (Michael Gloegl) * added support for ResultSet.getGeneratedKeys() (David Morris, John Kristian) * added check attribute to allow check constraints in DDL * implicit polymorphism for Criteria queries (Shorn Tolley) * use IF EXISTS for dropping hilo tables (Michael Gloegl) * better exception report if deleted object is resaved by cascade * support nested components in Example queries (Emmanuel Bernard) * fixed a minor problem with onDelete() callbacks * fixed an obscure problem with select-before-update * added SunONETransactionManagerLookup (Robert Davidson) * fixed a problem with replicate() and mappings * made setParameterList() accept empty lists and deny null values (Max Andersen) * validation check on query parameters now allows setParameter(x, null) (Max Andersen) * added default-access to DTD (Max Andersen) * made Query.setParameterList() accept empty lists and deny null values (Max Andersen) * allow Query.setParameter(x, null) (Max Andersen) * queries with "select new" now cacheable * throw meaningful exception when lazy initialization occurs on disconnected session * added default-access to (Max Andersen) * added -text support to SchemaUpdate (Max Andersen, Matt Hall) * fixed broken implementation of embedded composite keys with createSQLQuery() (Max Andersen) * added hibernate.cache.use_minimal_puts config property to reduce unnecessary second-level cache puts * optimized performance of orphan delete detection (Bertrand Renuart) * fixed problem where unnecessary UPDATE occurred after INSERT for versioned objects with collections * WebSphereTransactionManagerLookup for WAS 5.1 (Edina Pimp) * Criteria queries now cacheable (Mario Ivankovits) * fixed problem with ordered, paginated queries in DB2 (Tim Collins) * fixed a bug caching s * lazy="true" collections are now lazy even when available in cache * fixed a problem with version unsaved-value="negative" * added hibernate.cache.region_prefix config property (William Drai) * fixed problem where configuration input streams were not closed (Rajesh Patel) Changes in version 2.1.1 (17.12.2003) ------------------------------------- * added optional package attribute to * added element to allow simpler mapping * native SQL queries are now cacheable - added element to allow correct result set expiry * fixed a bug in CGLIB2 integration (Chris Nockleberg) * added NamingStrategy * don't cache objects with formula properties immediately after insert/update * log generated SQL to a special category * type of property with access="field" may now be guessed using reflection Changes in version 2.1 final (12.12.2003) ----------------------------------------- * fixed a problem with CGLIB2 proxies and method calls inside constructors * fixed a bug running SchemaExportTask with mappings in jar files (Tom McCune) * allow custom persister declaration for subclasses (Nick Johnson) * fixed handling of sequences in SchemaUpdate on Oracle (Andrew Delpha) * fixed a bug where Iterator did not handle single null values correctly * detect and throw exception in the case of a duplicate property mapping * don't auto-create indexes for collection foreign keys (roll back to 2.0.x) Changes in version 2.1 rc1 (29.11.2003) --------------------------------------- * long identifier and discriminator column names are now safely aliased (Max Andersen) * cleaned up mapping package to allow applications to manipulate metamodel programmatically * fixed a recent bug where collection sort order was lost in second-level cache * formula attribute now supported for joined-subclass mappings * formula properties may now be used anywhere in queries * dialect-specific query pagination for SQL Server * fixed a bug where a long path expression ending in collection access by index missed some tables in SQL FROM clause * fixed a very ancient performance problem where null one-to-one associations caused n+1 selects * added Session.saveOrUpdateCopy() * fixed some bugs in Example queries * fixed some minor bugs in dialect-specific query pagination * immutable entity passed to update() is now lock()ed instead * reworked the semantics of nonstrict-read-write * JCS cache support now deprecated * fixed some obscure bugs in collection handling * migrated to CGLIB2 (thanks to Chris Nockleberg) * fixed bugs in replicate() * fixed a bug affecting joined-subclass mappings with dynamic-update=true * performance improvements to boolean type mappings (Bertrand Renuart) * integrated JBoss TreeCache clustered cache (thanks to Bela Ban and Ben Wang) * fixed a bug in new query parameter validation (Steve Ebersole) * fixed a bug where mappings caused unnecessary ObjectDeletedException at flush time * fixed a bug where associations with property-ref mappings were not properly cached * throw PropertyValueException when not-null properties are null at flush time * added unsaved-value attribute to version property mapping (Emmanuel Bernard) * tolerate classnames containing $ (Steve Ebersole) Changes in version 2.1 beta 6 (5.11.2003) ----------------------------------------- * added Session.cancelQuery() * improvements to transaction handling for failed commit (thanks to Juergen Hoeller) * added cascade="delete-orphan" * fixed an exception that occurred when a property was declared not-null="true" update="false" (thanks to John Kristian) * support multiple named query cache regions (Mikheil Kapanadze) * some improvements to collection reattachment * fixed a bad bug with adds to an uninitialized bag or list * removed support for components * added mapping for properties of type Map * fixed a bug where schema export generated index names that were too long for DB2 * allow per-region expiry policies in OSCache (Matthias Bogaert) * fixed a stack overflow that could occur while initializing nonlazy collections * fixed a bug in case-insensitive like for Example queries * fixed a bug in ScrollableResults.setRowNumber() (Martin Priekopa) * improvements to the cache concurrency strategies Changes in version 2.1 beta 5 (30.10.2003) ------------------------------------------ * Support for custom CollectionPersister (Nick Johnson, Max Andersen) * Support for named SQL queries (Max Andersen) * duplicate named queries now throws MappingException instead of just logging warning (Max Andersen) * fixed problems with WebSphereTransactionManagerLookup (Ralf Taugerbeck, Daniel Bradby) * added support for custom collection persisters (thanks to Max Anderson, Nick Johnson) * fixed a performance problem during query compilation (Bulent Erdemir) * composite keys now supported in createSQLQuery() (Max Andersen) * fixed JCA adaptor to run in WebLogic (Daniel Bradby) * integrated SwarmCache (Jason Carreira) * integrated OSCache (Matthias Bogaert) * fixed an NPE that could occur with lists and orphan delete * allow nullable one-to-one with property-ref * improved usage of Dialect-specific limit SQL * fixed problem where non-lazy collections held by cached objects were not immediately initialized * fixed getReturnTypes() for native SQL queries (Max Andersen) * fixed problems with Criterions that applied to multi-column properties * check of rowcounts when JDBC batch updates enabled * added named SQL queries using element (Max Andersen) * added some extra validations so Hibernate fails earlier when user makes mistakes * allow lazy="true" as an alternative to proxy="ClassName" * removed dependency to commons-lang * SchemaExport now creates indexes for collection foreign key columns if specified by Dialect * fixed a bug parsing named parameters in setParameterList() * select new Foo(...) will now tolerate null values if the constructor accepts a wrapper type * fixed a problem detecting Proxool * added logging of persistent object states during flush() * allow "not null" as a discriminator value * added "parameters" config param to "sequence" generator (Matthias Bogaert) Changes in version 2.1 beta 4 (3.10.2003) ----------------------------------------- * fixed a bug where mappings did not handle proxies correctly * implemented new optimistic-lock strategies * fixed several bugs in Criteria query API * fixed a bug caching property-ref associations * improvements to XML Databinder (Ara Abrahamian) * added Session.replicate() and ReplicationMode * added ScrollableResults.setRowNumber() / ScrollableResults.getRowNumber() * added query cache and Query.setCacheable() * added Criteria.returnMaps() * fixed some problems with CGLIB proxies * fixed an NPE that occurred when a joined-subclass of a versioned entity defined only collections * added the access attribute, direct field access and the PropertyAccessor extension point * added MatchMode for use with Criteria queries (thanks to Michael Gloegl) * fixed a bug where some lazy="false" collections were not immediately initialized * fixed problem with WebSphere 5 TransactionManager * support schema attribute in MySQL, by using an underscore in the table name (Chris Hane) * now seperate Dialects for Interbase and Firebird (Reha Cenani, Max Andersen) * removed built-in PreparedStatement cache * added Session.getSessionFactory() * fixed problem with native SQL queries and Query.setProperties() (Max Andersen) * Query now fully validates parameters against the query string before passing them to JDBC (Max Andersen) * fixed an NPE in SessionFactory.close() * fixed an NPE that occurred when using s * added SQL-level query results paging to DB2Dialect * "foreign" id generator now handles detached instances Changes in version 2.1 beta 3 (7.9.2003) ---------------------------------------- * added Example queries * fixed an exception that occurred at startup with and * fixed a bug where composite-elements were not being updated if a property not in the equals() was changed * property of a composite-element may now be used in equals() * named parameters may now be used in HQL order by clause * null value of version property now indicates unsaved instance * added select-before-update attribute * two-phase loading now use for components * better implementation of equals()/hashCode() for proxies * added property-ref attribute to * renamed result() to uniqueResult() * added Session.get() * added HashtableCacheProvider * JTA TransactionManager now used even when not using Hibernate Transaction API * always bypass process-level cache for LockMode.READ Changes in version 2.1 beta 2 (27.8.2003) ----------------------------------------- * and may now appear outside of a element, by providing the extends attribute (Max Andersen) * fixed an NPE at startup that was introduced in beta 1 * fixed a bug in Map.putAll() * new pluggable cache API - deprecated in favor of - net.sf.hibernate.cache.CacheProvider settable via hibernate.cache.provider_class * more aggressive caching * added Hibernate.close(Iterator) * Criteria queries may now include joins - Criteria.addJoin() - Criteria.createCriteria() * hibernate.transaction.manager_lookup_class should now ALWAYS be specified in JTA environment when using jcs caching * fixed a bug caching * fixed bug where cached component did not get property populated * added hibernate.max_fetch_depth property * smarter outer-join fetching * transient object may now be associated with session using Session.lock() * added Query.result(), Criteria.result() Changes in version 2.1 beta 1 (10.8.2003) ----------------------------------------- * batch-size attribute for collection and class mappings, to allow batch loading * collections of "value types" (including composite-elements) may now appear in HQL from clause * more efficient loading of collections, and better handling of non-lazy collections * added HQL index() function to allow access to collection element index * added Session.createSQLQuery() (Max Andersen) * added outer-join attribute to collection mappings * Criteria.setFetchMode() now applies to collection-valued path expressions * added property-ref attribute to , enabling unique foreign key associations * added hibernate.max_fetch_depth config property * added hibernate.hbm2ddl.auto config property * fixed a bug with combination of and * support for Dialect-specific SQL functions in HQL select clause (David Channon) * added Session.clear() Changes in version 2.0.2 (2.8.2003) ----------------------------------- * subqueries may now use HAVING and GROUP BY clauses * fixed a bug with setMaxResults(), setFirstResult() in HSQL (introduced in 2.0.1) * fixed a bug in Set.removeAll() * fixed a bug in SchemaUpdate (Mathias Bogaert) * added weak typing functionality to ScrollableResults * fixed a bug with "calendar" versioning in IBM JDK1.3.1 (workaround for JDK bug) * fixed a bug in mapping DTD that caused a problem for hbm2java (Max Andersen) * fixed a bug querying nested components * SQL generation now prefers ANSI-style inner joins to theta inner joins * fixed a bug caching collection references loaded using FETCH * fixed a bug with composite foreign keys in normalized table mappings (Tom Sedge) * limit support for Interbase (Ludovic Orban) * added where attribute to mappings * added cascade="all-delete-orphan" for collection mappings * fixed a bug binding named parameters with setMaxResults()/setFirstResults() * fixed some minor bugs in HQL translator * fixed a long-standing bug where a could not be dereferenced in HQL * SQL UPDATEs now occur in a predictable order (same order as objects were loaded) * support for SELECT ... FOR UPDATE in SAPDB * fixed bug where Criteria queries against a subclass also returned superclass instances * fixed a very rare bug where an update could get lost with normalized mappings * fixed a problem with proxied class heirarchies rooted at an interface or abstract class * where and order-by attributes now allow SQL function calls and subselects * added formula attribute to tag, to allow "computed" properties * fixed a bug where PreparedStatements were sometimes not closed when an exception occured * workaround for a problem with and Interceptor.onFlushDirty() Changes in version 2.0.1 (17.6.2003) ------------------------------------ * fixed some problems with new dialect-specific LIMIT clauses * improved parsing of collection where attribute * made one-to-many bags more efficient (they are really sets!) * allowed type="calendar" for properties * fixed a bug with locking a versioned composite-id class * refresh() may now take a transient instance * added ProxoolConnectionProvider (Martin Crawford) * fixed some minor JCA issues (Mike Mosiewicz) * fixed a bug with FETCH and sorted associations * improved performance of SchemaUpdate tool (Teodor Danciu) * fixed a bug in Configuration.addFile(String) (Ken Geis) * tidied up and documented hbm2ddl package (esp. Ant tasks) * deprecated CounterGenerator in favor of IncrementGenerator * improved logging during initialization * deprecated "vm" in favor of "increment" id generator Changes in version 2.0 final (8.6.2003) --------------------------------------- * added "fetch" keyword to HQL * added evict() methods to SessionFactory for JVM-level cache * destroy caches from SessionFactory.close() * fixed an NPE in Session.evict() (Simon Spero) * added Query.setLockMode() * tidied up implementation of Loader * release ResultSets more aggressively * miscellaneous improvements to some Dialects * hbm2java now honors the sort attribute (Max Andersen) * added exceptions to Interceptor interface * fixed problem with setMaxResults(), setFirstResult() in Oracle (introduced in beta 6) * fixed some SQL generation that was a problem for Sybase (Dietmar Posselt) * fixed some problems with ODMG API (Oliver Gries) * added JOTMTransactionManagerLookup (Low Heng Sin) * added JOnASTransactionManagerLookup (?) * fixed a bug in WeblogicTransactionManagerLookup (Mathias Bogaert) * added Criteria.setFetchMode() * added new Expressions * much more elegant/robust handling of quoted identifiers * renamed Hibernate.association() to Hibernate.entity() * added dynamic-update and dynamic-insert mapping attributes * fixed a bug with refresh() of objects with collections * HQL aliases now optional - "from Cat" now legal * platform-independant quoting of identifiers using backticks Changes in version 2.0 beta 6 (10.5.2003) ----------------------------------------- * fixed a bug querying one-to-many associations to a * added support for dialect-specific LIMIT-style clauses (David White) * added * fixed bug in hashCode() of persistent collections * now supported in HSQL (Wolfgang Jung) * fixed problem for XML parsers which ignore default values declared in DTD * tags can now be set to not be inheritable * fixed bug in Expression.in() * fixed an NPE that could occur from update() in very strange cases (Chris Nockleberg) * disabled outer-join back to owner when initializing one-to-many (performance improvement) * fixed a bug in Query.setParameterList() (Nick Heudecker) * improved JCA support (Igor Fedorenko) Changes in version 2.0 beta 5 (21.4.2003) ----------------------------------------- * Informix support (Steve Molitor) * fixed a bug parsing "select new ... " queries * deprecated "object" type in favor of mappings * added Session.contains() * added extra DBCP config options (Alex Burgel) * SessionFactory.close() now unbinds from JNDI * added Session.evict() * got rid of an unnecessary SQL DELETE issued when an empty collection was dereferenced * where attribute of collection mappings no longer ignored for deletion * improved logging * support polymorphic associations to "embedded" composite id classes * various bugfixes to collection filter parameter binding * fixed some problems with proxies introduced in earlier beta versions * fixed bug with self-reference in the case of identity column id generation * added hibernate.cglib.use_reflection_optimizer property * added nonstrict-read-write cache * fixed an SQL-generation bug in new Criteria API * added CompositeUserType * sequence and table id generators now aware of default-schema * added update and insert attributes to element * fixed a bug with expressions like elements(foo.bar.baz) in where clause * more efficient Set initialization (two-phase load) * removed support for hibernate.query.imports and added mapping element * fixed problem in DBCP connection validation and added new config properties * hbm2java can now generate finder methods for persistent objects (experimental) (Matt Hall) * hbm2java small fixes/refactorings to support generating more than one file per persistent object (Max Andersen) Changes in version 2.0 beta 4 (22.3.2003) ----------------------------------------- * Major HQL improvements - from "Foo as foo join foo.bars as bar" instead of "from foo in class Foo, bar in elements(foo.bars)" - "select new Foo(bar.name, bar.amount) from ...." - outer and full join support * Query methods now return this, to allow chaining * FrontBase support (Run Lussier) * experimental JCA support (Daniel Bradby) * hbm2java now can generate Beans style property events (Klaus Zimmermann) * support SQL identifiers quoted with [] * fixed bug with PostgreSQL * name attribute now optional in .cfg.xml * support for postgres ilike operator (M Lang) * squash warnings with GNU JAXP (Chris Nockleberg) * fixed a bug in Query.setParameterList() * Ingres support (Ian Booth) * collections now detect changes not made via wrapper for newly saved objects * new (experimental) Criteria + Expression APIs * Query.setEntity(), etc, now aware of proxies (also improved hueristics for guessing Type) * added Hibernate.isInitialized() * detect changes made directly to newly-wrapped collection (ie. not via the wrapper) * added Hibernate.refresh(Object, LockMode) * update(), saveOrUpdate() no longer initialize a proxy * fixed problems with Sybase * added force attribute to * improved handling of null discriminator-value * support SQL-style '' escape for HQL strings Changes in version 2.0 beta 3 (24.2.2003) ---------------------------------------- * collections now represent null elements as a missing row * collections now deserialize correctly (fix for bug in beta 2) * standardised on dom4j for XML parsing * fixed bugs in collection caching (an exception occurred for some sorted collections and some kinds of maps) * allowed null discriminators * set autocommit to true in SchemaUpdate * fixed a stack overflow that could occur in toString() of classes created with hbm2java (Max Andersen) * fixed a bug where composite-element property was not being set after retrieval from cache * added where attribute to collection mappings to allow filtering * fixed a exception that occurred when wrapping collections with sort="MyComparator" (Jason Horne) * objects with mutable="false" are now never updated * fixed an exception that occurs with association to a class with a composite id (Stefano Travelli) * added SchemaExport Ant task (Rong C Ou) * integrated latest CGLIB release (Juozas Baliuka) - added support for new CGLIB reflection optimizer (Juozas Baliuka) * improved query cache algorithm (Who?) * fixed a bug in "object" type * Lists and arrays now represent null elements as a missing row * fixed a bug in Hibernate PreparedStatement cache where maxRows and fetchSize were not cleared before re-caching * fixed a bug in HibernateService that caused a restart to fail * added SybaseAnywhereDialect (?) * added SessionFactory.close() Changes in version 2.0 beta 2 (2.2.2003) ---------------------------------------- * property column names may now be of any length (Mark Woon) * fixed problem where CodeGenerator created private get/set pairs (Max Andersen) * fixed all silly bugs in Configuration.configure() * efficient collection updates from Session.update() * added and elements to hibernate-configuration.dtd * support for normalized mappings for databases with DECODE instead of CASE (Simon Harris) * added Oracle9Dialect * added JRun4TransactionManagerLookup (Joseph Bissen) * fixed JDBCException to keep reference to underlying SQLException * fixed a bug loading many-to-many associations with a repeated column name * fixed a bug in ShortType * added IngresDialect (Ian Booth) * added --config option to SchemaExport Changed in version 2.0 beta 1 (28.1.2003) ----------------------------------------- * renamed packages to net.sf.hibernate.* * all API methods now wrap SQLExceptions * removed support for toplevel collections / subcollections * created hibernate-mapping-2.0.dtd - renamed 'readonly' attribute to 'inverse' - renamed 'role' attribute to 'name' - changed default value for 'unsaved-value' to "null" - added mandatory 'name' attribute to - added tag * created hibernate-configuration-2.0.dtd * brand new Configuration API, including exposed mapping package * completely reworked IdentifierGenerator framework - built-in generators now auto-detect the type (so integer identity columns are supported, for example) - parameters are now named - built-in strategies are renamed * expanded Interceptor interface * removed exceptions that occur if an object is saved or deleted multiple times in a session * added subelement to and * collections except for s now implement by-value equals() and hashCode() * removed all deprecated methods * added Session.refresh() * added dynamic-update functionality * added update and insert attributes to and mappings * added elements(), indices(), size(), maxelement(), minelement(), maxindex(), minindex() collection functions to query language * huge improvements to CodeGenerator (Max Andersen) * enhanced outerjoin fetching support in queries * experimental support for DynaBeans as components Changes in version 1.2.3 (28.1.2003) ------------------------------------ * fixed a recently-introduced problem with Timestamp dirty checking * added createClob(), createBlob() for streams (Benoit Menendez) * SchemaUpdate now configures Dialect correctly (Michael Locher) * update() now working for classes with embedded composite ids * unsaved-value attribute now recognized for * fixed a minor problem where a very specific kind of SQL select did not qualify a column name * added Query.getQueryString() * fixed an NPE that sometimes occurred when hibernate.connection.username was not specified * fixed a bug in SchemaExport where foreign key constraints did not use qualified tablenames * added isFirst(), isLast() to ScrollableResults * fixed bug finding properties inherited by mapped interfaces Changes in version 1.2.1b (4.1.2003) ------------------------------------ * fixed an NPE that occurred while loading Hibernate classes in IBM JVM * arbitrary JNDI InitialContext properties may now be passed as hibernate.jndi.* * fixed a problem where index column was not being nullified when an entity was removed from a one-to-many Changes in version 1.2.1 (31.12.2002) ------------------------------------- * Changed the MySQL mapping of Hibernate "timestamp" to MySQL "DATETIME" (Matthias Schwinn) * TransactionManagerLookup classes now define defaut UserTransaction JNDI names * support for WebSphere 5 (Venkat Srinivasan) * fixed a bug with query expressions of the form "foo.bar.id" for normalized mappings * experimental Blob/Clob support (thanks to Benoit Menendez and Mark Woon) * improvements to SchemaUpdater (Benoit Menendez) * deprecated suspendFlushes() / resumeFlushes() in favor of FlushMode * deprecated IDGenerationException in favor of IdentifierGenerationException * fixed a bug introduced in 1.2 final where cascade save-update was sometimes ignored for readonly="true" bags * fixed a bug caching null-valued one-to-one associations * CodeGenerator now supports and * fixed problem with TimestampType on DB2 (Jonas) * fixed a bug in generated SQL for collections with mappings (Robson Miranda) * fixed a bug caching Maps (Benoit Menendez) * SchemaExport now accepts a .jar file as a source of mappings * hibernate.dbcp.validationQuery setting (Juozas Baliuka) * hibernate.c3p0.validate setting * added Query.setTimeout() * setMaxResults() now behaves sensibly on SAPDB (Russel Smyth) * added Query.setProperties() and Query.getNamedParameters(), fixed a bug in Query.getReturnTypes() * CodeGenerator now generates equals() and hashCode() for composite-id classes (and toString() for all classes) * CodeGenerator now includes superclass properties in subclass constructors (Max Andersen) * added Hibernate.custom() Changes in version 1.2 final (7.12.2002) ---------------------------------------- * fixed a bug where uppercase IS NOT NULL, NOT IN, etc were not parsed correctly * addition to readonly="true" bags now no longer requires collection initialization * added ResinTransactionManagerLookup (Aapo Laakkonen) * improved exception message when setting null to primitive type (Max Andersen) * improved exception message for an unserializable identifier * support for overloaded setter methods (patch by Alex Staubo) * CodeGenerator support for (patch by Wolfgang Jung) Changes in version 1.2 beta 4 (29.11.2002) ------------------------------------------ * fixed bugs in one-to-many associations to a * LockMode class now properly serializable * exceptions thrown by proxied objects are now propagated correctly (rather than being wrapped) * made Calendar types compilable in JDK1.2 * added --format and --delimiter options to SchemaExport (thanks to Richard Mixon) * fix for problem with class with no properties + native id generation + MS SQL Server contributed by Max Andersen * fixed a BAD bug in Hibernate.configure() (thanks to Rob Stokes) * CodeGenerator now recognizes (patch by Wolfgang Jung) * CodeGenerator now recognizes and (patch by Max Andersen) Changes in version 1.2 beta 3 (26.11.2002) ------------------------------------------ * fixed bug in UPDATE SQL generation for mapping strategy (fix by Robson Miranda) * support correctly in CodeGenerator (patch by Tom Cellucci) * fixed an exception that occurred with short qualified tablenames * added the polymorphism attribute to the element * allow "not between", "not in" in query language * allow subqueries beginning with a from clause in query language * query expressions like "not (foo.bar.baz=1)" now translated to "(bar.baz!=1 and foo.bar=bar.id)" * support for PostgreSQL ~ operator (regular expression match) * load(id, lockMode) now working for normalized table mappings * now compiling properly under JDK1.2, 1.3 (fix by Tom Cellucci) * support for subcollections in query language: foo.bars[2]['index'], foo.bars[4].elements, foo.bars[0].size, etc. * added calendar and calendar_date types * find() queries may now return scalar values * component-type properties may appear in a select clause * ConnectionProviders now set isolation level before toggle autocommit * Iterator.next() now throws NoSuchElementException as per Iterator contract (fix by Alex Staubo) * database reverse engineering GUI tool contributed by Tom Cellucci * SchemaExport now generates column in mapping file order (rather than alphabetical order) * mappings working on Oracle (?) Changes in version 1.2 beta 2 (15.11.2002) ------------------------------------------ * support multi-argument SQL functions in queries * reintroduced deprecated form of update() with slightly altered semantics * fixed BAD problem in the generated SQL for certain queries * added OrionTransactionManagerLookup Changes in version 1.2 beta 1 (11.11.2002) ------------------------------------------ * Fixed a bad bug binding to JNDI with servers that use serialization in preference to getReference() * support for quoted SQL identifiers (patch by Jean-Francois Nadeau) * Hibernate.initialize() allows the user to force initialization of a proxy or persistent collection * fix to minor bug in CodeGenerator by Max Andersen * fixed a problem with outerjoin fetching of one-to-one associations defined on subclasses * fixed a minor problem with proxies of classes that override finalize() * finished work on normalized table mappings using declaration (only for databases with ANSI OUTER JOIN and CASE) * deprecated hibernate-mapping.dtd in favor of hibernate-mapping-1.1.dtd * reworked unmapped class / interface / table-per-concrete-class query functionality, fixing several problems * removed deprecated methods * deprecated findIdentifiers() * fixed some problems with embedded composite identifiers * fixed a bug cascading deletes to one-to-one associations * CodeGenerator now generates isFoo() style getters for boolean properties (patch by Aapo Laakkonen) * components may now have a nonpublic constructor (patch by Jon Lipsky) * changes / bugfixes to MapGenerator tool * experimental SchemaUpdate tool contributed by Christoph Sturm Changes in version 1.1.8 (30.10.2002) ------------------------------------- * full support for composite keys in query language * fixed bug where character type could not be null * fixed bug parsing collection filters like: "group by this.date" * fixed a bad bug where C3P0 properties were not always being used * replaced hibernate.use_jdbc_batch with hibernate.jdbc.batch_size * renamed some other properties to hibernate.jdbc.* * made hibernate.show_sql settable from JMX (patch by Matas Veitas) * added SessionFactory.getAllClassMetadata(), getAllCollectionMetadata (patch by Max Andersen) * allowed use of concrete-class proxies with inherited classes ie. * HibernateException extends Apache commons lang NestableException (patch by Max Andersen) * subelement of allows a component to get a reference back to owning entity * Query.setParameterList() to bind lists of values to "in (:list)" * Java constants may now be used in Queries * serialization of an object graph now removes all initialized proxies * several other improvements to proxy handling * proxies may now be used in JDK 1.2 Changes in version 1.1.7 (25.10.2002) ------------------------------------- * added Session.createFilter() * fixed a bug parsing queries with properties of form idXXX (introduced in 1.1.6) * fixed a bug parsing queries with the id property named in the select clause (introduced in 1.1.6) * fixed a bug dirty checking big_decimal (fix by Andrea Aime) Changes in version 1.1.6 (24.10.2002) ------------------------------------- * classes without subclasses may now declare themselves as their own proxy * outer-join attribute now working for component properties and * outer-join="true" will now force outerjoin loading for an association even if associated class has a proxy * enabled oracle-style outerjoins for SAP DB * version properties may now be long or short (previously always integer) * discriminators may now be boolean type * fixed the foo.bar.id.baz syntax for queries doing composite-key joins * fixed an NPE that occurred when no Dialect was specified * CodeGenerator now fully proxy-aware (patch by Max Andersen) * removed dependency upon trove4j Changes in version 1.1.5b (20.10.2002) -------------------------------------- * fixed an NPE that occurred on JMX startup * smarter fetching for one-to-one associations Changes in version 1.1.5 (19.10.2002) ------------------------------------- * added built-in currency and timezone types * hibernate-mapping-1.1.dtd - added and subelements of - added and - renamed "save/update" to "save-update" - tightened up the dtd (now using enumerated attribute types) * enabled multi-column map indexes (ie. key of a Map) * composited-id may now include a many-to-one association * improvements to Databinder contributed by Brad Clow * fixed bugs in minIndex, maxIndex, minElement, maxElement * fixed a problem with JTATransaction in a JBoss BMT bean * added addMapResource() to the MBean * minor improvements to Configuration * more accurate cache entry timestamping to increase the likelihood of cache hits * JCS cache may now be used with JTATransaction in WebSphere, Weblogic, JBoss (thanks to Matt Baird) * improvements to CodeGenerator contributed by Andrea Aime * stopped a TransientObjectException that was being thrown when it shouldn't be * re-enabled primary key export for tables of sets with not-null elements * hibernate.statement.fetch_size configuration contributed by Matas Veitas * added Interceptor application callback interface * added metadata package to expose persistence metadata to the application * changed filter() argument type from Collection to Object to allow filtering of arrays and Maps * added index attribute to allow table indexes to be specified in mapping document * implemented support for queries against interfaces and abstract superclasses Changes in version 1.1.4b (4.10.2002) ------------------------------------- * fixed problems for JDK1.2 (thanks to Chris Webb) Changes in version 1.1.4 (4.10.2002) ------------------------------------ * New locking API * disabled 2-phase load for objects contained in Sets (because they should be initialized before equals() or hashCode() is called) * fixed a bug where non-serializable cache entries could not be cached by JCS auxiliary cache * fixed a bug in dirty checking PersistentEnums * deprecated getID() in favor of getIdentifier() (for mainly cosmetic reasons) * HibernateService may now be subclassed to obtain mapping files by some other mechanism (patch by Chris Winters) Changes in version 1.1.3 (1.10.2002) ------------------------------------ * new 2-phase loading process (replaces complicated "deferred" loading process) * new ScrollableResults interface for efficiently navigating Query results * removed deprecated interfaces * created engine package to hold "internal" APIs (ie. the external contract of the impl package) * fixed bug where a component defined before all collections in the mapping file caused collections to not be persisted (thanks to Michael Link) * fixed a bug where cascaded saveOrUpdate was ignoring the unsaved-value setting * faster Timestamp dirty checking Changes in version 1.1.2 (29.9.2002) ------------------------------------ * added persister attibute of class mapping to support custom persistence strategies * Support for Oracle outerjoins contributed by Jon Lipsky * Reworked versioning, fixing bugs (and tightening tests) * Fixed a bug where an ObjectNotFoundException was thrown for null one-to-one associations * fixed problems with timestamps introduced in 1.1.1 * added batch file for running demo Changes in version 1.1.1 (27.9.2002) ------------------------------------ * Major refactoring / abstraction of persistence logic * added maxIndex, minIndex, maxElement, minElement properties for collections * added support for class names in where clause of queries * fixed a bug where an association could become null after caching * fixed a bug where an NPE could occur for a null component * fixed minor bugs in SortedMap, SortedSet * object type is now cacheable * added big_integer type * improved dirty checking for timestamp type Changes in version 1.1.0 (22.9.2002) ------------------------------------ * implemented collection indexing with [] in query language * fixed some minor query-language bugs Changes in version 1.1 beta 14 (19.9.2002) ------------------------------------------ * bags now implement java.util.List * delete() may now take a transient object * bug where sorted collections were not being sorted fixed by Brad Clow * fixed a bug in many-to-many association filtering * no longer try to query connection metadata when using user-supplied connections * added hibernate.use_scrollable_resultsets for user-supplied connections * fixed a problem where sublists were not being proxied * fixed a problem where Hibernate could not call methods of package-visibility classes * removed obsolete select attribute from MapGenerator * multiple occurrences of same path in a query no longer require multiple joins * added WrongClassException Changes in version 1.1 beta 13 (15.9.2002) ------------------------------------------ * added constants to Lifecycle interface * fix for circular cascade="save/update" * fixed a bug in cascaded update introduced in version 1.1 beta 11 * added object type Changes in version 1.1 beta 12 (14.9.2002) ------------------------------------------ * Session.filter() for applying a filter query to collections * experimental ODMG API (OQL features are not yet compliant) * new DBCPConnectionProvider for Apache commons-dbcp connection pool * Session.lock() now does version number check even on databases with no FOR UPDATE clause * introduced new cascade styles: cascade="save/update", cascade="delete" * added default-cascade attribute * foreign key columns lengths now automatically set to primary key column lengths for SchemaExport * added error checking of row update counts when batching disabled * major improvements to ProxyGenerator tool * CodeGenerator now aware of proxy attribute * integrated PointbaseDialect contributed by Ed Mackenzie * fix for problem where Proxies were being initialized on identifier access by Christoph Sturm Changes in version 1.1 beta 11 (7.9.2002) ----------------------------------------- * deprecated update() in favor of saveOrUpdate() and introduced unsaved-value attribute of * children mapped with cascade="all" are now always saved/updated even without a call to update(parent) * support for composite-id classes where the composite id consists of properties of the persistent class * added constrained attribute to element * added Validatable interface * renamed several config properties (Hibernate issues log warnings for obsolete property usage) * arbitrary JDBC connection properties may now be passed using hibernate.connection.* * fixed a classloading bug in C3P0ConnectionProvider (introduced in 1.1 beta 10) * CodeGenerator may now take multiple mapping files on the commandline Changes in version 1.1 beta 10 (28.8.2002) ------------------------------------------ * fixed a bug that occurred when calling Session.update() for an object with no properties * changed class loading to use the context classloader first * introduced as an alternative to * added Query.getReturnTypes() * fixed a bug with composite-elements introduced in 1.1 beta 7 * save() may now be used to persist classes with composite-ids * improved handling of nanoseconds values in Timestamps * support for composite id properties + objects in select clause of iterate() * beefed-up collection tests Changes in version 1.1 beta 9 (26.8.2002) ----------------------------------------- * fixed a bug introduced in 1.1 beta 8 that could cause an NPE after deserializing a session with proxies * deprecated insert() in favor of more flexible save() * deprecated IDGenerator in favor of new IdentifierGenerator interface * "assigned" id generator now returns the existing value of the id property instead of throwing an Exception * fixed a problem where PreparedStatements were not being recached after retrieving a natively generated id Changes in version 1.1 beta 8 (25.8.2002) ----------------------------------------- * fixed a bug introduced in 1.1 beta 6 where an updated element of an indexed one-to-many collection caused an SQLException * uninitialized collections passed to update() may now be initialized in the new Session * uninitialized proxies passed to update() may now be initialized in the new Session Changes in version 1.1 beta 7 (23.8.2002) ----------------------------------------- * fixed a bug where Hibernate was not returning statements to the cache when batch updates were disabled * fixed a bad bug parsing mappings with toplevel one-to-many associations * fixed a bug with versioning and subcollections * reworked Set updates again for much improved efficiency * schema export now creates primary keys for indexed collection tables * minor refactor to Type hierarchy * improved some user-error detection * fixed foreign key constraint creation for MySQL with Innodb tables Changes in version 1.1 beta 6b (20.8.2002) ------------------------------------------ * Fixed a problem updating Sets * added mapping for java.util.Collection Changes in version 1.1 beta 6 (20.8.2002) ----------------------------------------- * completely reworked fetching code - one-to-many associations now always fetched in a single select - many-to-many associations fetched in a single select when outerjoin fetching is enabled - this includes nested outerjoin fetching of the associated class! - outerjoin fetching for nested inside or - code refactored to be cleaner and faster * removed unnecessary order by clause in List and array fetching SQL * collections now individually update, insert and delete only rows that changed (thanks to Doug Currie) * fixed a problem where exceptions were being wrapped in a LazyInitializationException for non-lazy collections * added order-by attribute to and to specify a table column as defining the iteration order (JDK1.4 only) * improved error detection in Session.update() * further usage of JDBC2 batch updates * some fine-tuning of JDBC2 feature usage configuration * CodeGenerator will now generate components and arrays * fixed problem where CodeGenerator could not generate classes in the default package * improved logging of flush() activity * renamed property hibernate.use_jdbc2 to hibernate.use_jdbc_batch Changes in version 1.1 beta 5 (13.8.2002) ----------------------------------------- * hibernate.query.imports property to allow use of unqualified classnames in queries * fixed a bug in collection flushing that was introduced in 1.1 beta 4 Changes in version 1.1 beta 4 (11.8.2002) ----------------------------------------- * JMX integration (thanks to John Urberg) * "having" clause in query language Changes in version 1.1 beta 3 (10.8.2002) ----------------------------------------- * removed the select="all" attribute for mappings - "select distinct" now specified in the hibernate query * system properties now override hibernate.properties * Session now flushes changes even less often (only when actual updates to the queried table(s) are waiting) * fixed a *very* rare problem where an unnecessary update could be accidently issued before a delete Changes in version 1.1 beta 2 (6.8.2002) ---------------------------------------- * fixed a bug exporting schemas with identity columns * implemented factory-level caching of collections * Datastore.storeJar() contributed by Christian Meunier * added to hibernate.cfg.xml Changes in version 1.1 beta 1 (4.8.2002) ---------------------------------------- * new Query API including named parameters, pageable results * subqueries in Hibernate queries (only for databases that support subselects) * new DocBook documentation (contributed by Christian Bauer) * support collections .elements, .indices inside select clause (even in aggregate functions) * don't load collections before removal unless absolutely necessary * mutable="false" attribute in element to map immutable classes * use JDBC batch to insert collection elements if hibernate.use_jdbc2 is set * brand new PreparedStatementCache * improvements to MYSQL dialect for long datatypes * always check isAccessible() before setAccessible(true) * removed extra unnecessary table join in queries with one-to-many association * removed ugly "WHERE 1=1" from generated SQL * fixed exception mapping a class with no properties (fix by Rob Stokes) * logging enhancements including SQLException logging * reworked factory-level cache and integrated JCS support (thanks to Christian Meunier) * fixed a bug with circular references in cached data * removed blocking cache support * now rendering outerjoins as "LEFT OUTER JOIN" because "LEFT JOIN" caused problems for some Sybase versions * added default Hibernate properties to Dialects * native id generation now falls back to sequence id generation when identity columns not supported by the dialect * fixed some problems with native id generation under HSQL * may now use Session.insert() even when using native id generation Changes in version 1.0.1b (18.7.2002) ------------------------------------- * fixed a bad bug in query parser when hibernate.query.substitutions was unset * much improved build.xml Ant script * latest c3p0.jar Changes in version 1.0.1 (17.7.2002) ------------------------------------ * enabled use of scalar values and aggregate SQL functions in select clause of iterate() queries * fixed bug in JNDI lookup for SessionFactory * changed ordering of SQL inserts/deletes for child collections of a cascade-enabled association - better behaviour for some not-null constraints - performance optimization for bidirectional many-to-one associations * added hibernate.query.substitutions property to allow named query constants (eg. translate 'true' to '1') * added locale type for java.util.Locale * added sequence hi/lo generator (seqhilo.long) * fixed bug where load(), onLoad() callbacks were sometimes called at wrong time * fixed an exception (fix by Eric Everman) and improved identifier searching in MapGenerator tool * refactored SerializableType * extra logging + error handling * documentation enhancements Changes in version 0.9.17 (3.7.2002) ------------------------------------ * Added UserType interface * documented Lifecycle * added some new trace messages to log * bugfix to allow SQL functions like upper(), lower(), etc to work on all platforms * documented SAP DB support (dialect contributed by Brad Clow) * foreign key constraint export for SAP DB * map index may be the composite-id of the element class (contributed by Jon Lipsky) * fixes to CodeGenerator tool (contributed by Uros Jurglic) Changes in version 0.9.16 (19.6.2002) ------------------------------------ * fixed bug cacheing objects with references to themselves * support for composite ids of classes with no id property * may now disable outer join (deep) fetching for an association by setting outer-join="false" * enabled outer join fetching for one-to-one * fixed a bug for mappings that specify class attribute of * fixed a bug where Hashbelt did not expire cached data in a timely fashion * fixed a mistake in the mapping DTD * new user-error check in update() Changes in version 0.9.15 (15.6.2002) ------------------------------------ * one-to-one associations * support for "tricky" mappings in SchemaExport tool (multiple properties to one column, etc) * Transaction API contributed by Anton van Straaten * SessionFactory may be bound to JNDI name by setting hibernate.session_factory_name * Sessions are now Serializable! * added Session.findIdentifiers() query methods * new Lifecycle interface to replace deprecated PersistentLifecycle * fixed problem where session did not autoflush on iterate() queries * performance enhancements to collection dirty checking * added Hibernate.configure() and configuration file format * removed some deprecated methods * refactored Type hierarchy * query language identifiers now case sensitive (bugfix for case sensitive SQL dialects) * username/password now optional for datasource (contributed by Emmanuel Bourg) * much improved API documentation * binary types now saved using streams if hibernate.use_streams_for_binary=true (contributed by Jon Lipsky) * MySQL Strings now mapped to TEXT columns if length > 255 (contributed by Christoph Beck) Changes in version 0.9.14 (4.6.2002) ------------------------------------- * lifecycle objects - properties now have a cascade attribute to cascade save, update, delete * composite id properties may now be used in queries eg. foo.id.bar (contributed by Jon Lipsky) * slightly changed semantics of update() so it now also save()s new transient instances * Session now flushes() itself less often before query execution (performance enhancement) * fixed problem where Session.save() returned null instead of the natively generated id * fixed bug with object identity for cached classes * fixed bug where delete(x) could not be called after update(x) * MUCH improved Exception hierarchy * deprecated create() * added sql-type attribute to tag to allow user to override default type mapping * deeper fetching with use_outer_join * new ConnectionProvider framework * fixed a bug where blocking cache could return stale data * now working again in JDK1.2.2 * fixed problem with not-null associations + native key generation * minor changes to PersistentLifecycle interface * initial, minimal version of new Transaction mechanism * MUCH improved documentation Changes in version 0.9.13 (25.5.2002) ------------------------------------- * Datastore.storeResource() to load mapping files from classpath * fixed a problem executing under JDK1.3 when compiled from JDK1.4 * documentation improvements Changes in version 0.9.12 (24.5.2002) ------------------------------------ * Session.update() methods to update a persistent instance from transient copy (as requested by many users) * discriminator column name, type, length, etc now configurable by tag in mapping file * discriminator column values configurable by discriminator-value attribute of and tags * added Session.insert(object, id) for classes with no identifier property * fixed another bad bug with connection handling (fix by Anton van Straaten) * fixed a problem with deferred loading * fixed a problem with sorted collections (fix by Anton van Straaten) * nested collections of objects now require 2 SQL SELECTs to load, rather than size+1 * session is NO LONGER atomic - application should discard session when exception occurs * fixed problem where character type was mapped to VARCHAR column * arrays of proxies now possible by using new element-class attribute of tag * fixed various problems with proxies * added proxy generation tool * proxy unit tests * replaced two RuntimeExceptions with checked exceptions * made hibernate.username/hibernate.password optional for DriverManager * CodeGenerator now supports all hibernate basic types * much improved caching algorithm for compiled queries * may now specify properties simply by placing hibernate.properties in classpath * documentation improvements + fixes * --abstract switch to MapGenerator (contributed by Eric Everman) Changes in version 0.9.11 (12.5.2002) ------------------------------------ * fixed major bug with connection handling (fix by Anton van Straaten) Changes in version 0.9.10 (11.5.2002) ------------------------------------ * set a default schema name using SessionFactory property hibernate.default_schema * code generator tool contributed by Brad Clow (www.workingmouse.com) * lazy object initialization under JDK 1.3 and above * fixed some error messages to go to logging framework, not stdout * new system property hibernate.show_sql=true logs all executed SQL to stdout * integration of bugfixes in c3p0 * wrap IllegalArgumentExceptions in HibernateExceptions * added ObjectNotFoundException and StaleObjectStateException * fixed a bug when using schemas * new caching strategy (and documented cache feature) Changes in version 0.9.9 (25.4.2002) ----------------------------------- * sorted sets and maps (thanks to Doug Currie) * mapping files may now be loaded using getResourceAsStream() (thanks to Markus Meissner) * hibernate messages now logged by Apache commons-logging * default hi/lo generator table now has column named "next_id", instead of "next" * query language may now refer to identifier property name (eg. foo.fooKey as alternative to foo.id) * hibernate.jndi_class, hibernate.jndi_url now optional when using datasource * hibernate now throws an exception if you try to persist an object with a reference to a transient object * improved connection pooling algorithm (hibernate.pool_size limits pooled conections) * very experimental integration of c3p0 JDBC connection pool (http://sourceforge.net/projects/c3p0) * now compiles under JDK 1.2.2 * fixed bug persisting null components * fixed bug where cached prepared statements were not cleaned up after disconnect() session * fixed a null pointer exception in MappingByReflection Changes in version 0.9.8 (13.3.2002) ----------------------------------- * supports database native key generation in Sybase, MS SQL, MySQL, DB2, Hypersonic (contributed by Christoph Sturm) * supports Mckoi (dialect contributed by Doug Currie) * supports Progress (dialect contributed by Phillip Baird) * added exceptions to catch Session reentrancy from PersistentLifecycle.load() + store() * experimental cross-transaction cache * Session.lock() and Session.loadWithLock() for pessimistic locking * HiLoGenerators may now use their own DriverManager connection properties + may now use same table across diff mapping files * Session.flush(), Session.close() and Session.connection() replace Session.commit(), Session.cancel() * Session.disconnect() and Session.reconnect() for long transactions * added single JVM id generators vm.long, vm.hex * added unique column constraints to mappings * extensions to IDGenerator framework * support sequence-style ID generation in Oracle, PostgreSQL, DB2, Interbase * fixed problem where subcollections of a collection that changed roles would be deleted * changed class loading strategy to be compatible with JBoss * stopped queries retrieving unnecessary columns * mutable types (binary + serializable) now always detected as dirty Changes in version 0.9.7 (26.2.2002) ----------------------------------- * save() now safe from foreign key violations (so create() is no longer preferred method of adding data) * delete() now completely safe from foreign key violations - it no longer matters what order objects are deleted in * removed Session.copy() * hilo generators now NOT for use with application server datasources * fixed two intermittent bugs in queries * fixed a problem where components not detected as dirty * fixed broken hilo generator which was not updating database * fixed a minor bug when hibernate.use_outer_join was set Changes in version 0.9.6 (24.2.2002) ----------------------------------- * experimental XML generation * added support for bi-directional associations (one-to-set, set-to-set) with config * reflective generation of mappings tool was contributed by Doug Currie * Session operations now atomic, so exceptions are recoverable * made ID properties optional in persistent classes * support for multiple schemas through schema attribute of , , , , etc. * auto-creation of tables for hilo id generators (restriction: cannot use same table from more than one mapping file) * added some more assertions to catch user "mistakes" like deleting transient or saving persistent objects * major rework of collections and fixed some bad bugs * lazy initialization re-enabled for one-to-many associations (thanks to Georg Schneemayer) * fixed a problem in the mapping DTD to allow nested components in collections * fixed a BAD bug in RelationalDatabaseSession when loading objects with PersistentLifecycle callbacks (thanks to Paul Szego) * fixed problems with quoted strings in query language * fixed a bug where a stack overflow occurred instead of HibernateException thrown (thanks to Georg Schneemayer) * fixed a bug deleting updated versioned data * fixed some problems with name generation for indexes + foreign keys * fixed problem in Sun JDK 1.4 (only?) where IllegalArgumentException was not handled * minor improvements to handling of dates and times * HiLoGenerator now safe for all transaction isolation levels + safe when rollback occurs * noticed and fixed obscure piece of nonthreadsafe code outside of core persistence engine * removed unnecessary drop constraints for some dialects * MUCH more comprehensive test suite * changed some terminology used in documentation * added javadoc for API classes * commented the mapping DTD Changes in version 0.9.5 (8.2.2002) ----------------------------------- * supports HypersonicSQL (dialect contributed by Phillip Baird) * supports Microsoft SQL server (with third party JDBC driver) * proper command-line tool for schema generation and export * deprecated the interface cirrus.hibernate.Persistent (due to popular demand) * changes to hibernate-mapping DTD (required to support optional Persistent interface): - deprecated in favor of - deprecated in favor of - deprecated in favor of - deprecated in favor of - deprecated in favor of * class attribute optional in and tags (determined by reflection) * querying components of components now supported * one-shot table creation (no use of unportable "alter table") * time dataype support * reflective mappings of java.sql.Time, java.sql.Timestamp, java.sql.Date * fixed error msg thrown when class is missing a method but has a superclass * property names now conform to JavaBean spec ("foo" instead of "Foo"). Note that "Foo" still works * constructors of persistent classes may now be non-public * collection indexes now mapped to not-null columns * fixed obscure bug with querying collections inside components of components * fixed potential bug related to cacheing of compiled queries * major rewrite of code relating to O-R mappings * Session.copy() and Session.equals() as convenience for users * fixed repeated invocations of hasNext() on iterator + iterators now always work with distinct SQL resultsets * McKoi dialect was contributed by Gabe Hicks Changes in version 0.9.4 (29.1.2002) ------------------------------------ * fixed BAD bug where XML parsing would not work for parsers other than Xerces - thanks to Christian Winkler * added some more assertions to catch user "mistakes" like changing ids or reusing existing ids Changes in version 0.9.3 (27.1.2002) ------------------------------------ * repackaged (corrupted DatasourceConnectionProvider.class) * better exception reporting using datasource * added Datastore.storeClass() which looks for mapping file in classpath (class foo.Bar -> foo/Bar.hbm.xml) * improved documentation Changes in version 0.9.2 (25.1.2002) ------------------------------------ * iterate over query results (lazy instantiation of query results) * added "select foo, bar" style queries returning multiple objects per row * delete by query * composite key support * outer joins for faster (?) loading of associated objects ( set "hibernate.use_outer_join" to "true" ) * connection pooling when using DriverManager * foreign key constraint from unkeyed collection table to owner entity table * improved drop tables script execution (still not infallible) * added tag * added not-null properties and elements * added an optimisation for dates and components * made some XML attributes optional * fixed errors in documentation + documented some extra features * bugfix: store() not getting called on lifecycle interface * bugfix: schema generation for indexed associations * added many tests Changes in version 0.9.1 (20.1.2002) ------------------------------------ Too many to list version 0.8.1 ------------- Initial alpha version libhibernate3-java-3.6.10.Final/project/0000755000175000017500000000000011714611271017262 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/0000755000175000017500000000000012143273450023662 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/pom.xml0000644000175000017500000000564611714611271025212 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent 3.6.10.Final ../hibernate-parent/pom.xml hibernate-jdbc4-testing Hibernate JDBC4-JdbcSupport Testing Test support of JDBC4 through JdbcSupport true org.apache.maven.plugins maven-compiler-plugin 1.6 1.6 1.6 ${jdk16_home}/bin/javac true true org.apache.maven.plugins maven-surefire-plugin ${jdk16_home}/bin/java ${project.groupId} hibernate-core ${project.version} libhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/0000755000175000017500000000000011714611271024451 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/0000755000175000017500000000000011714611271025430 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/0000755000175000017500000000000011714611271026351 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/0000755000175000017500000000000011714611271027140 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/0000755000175000017500000000000011714611271031101 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/0000755000175000017500000000000011714611271032346 5ustar ebourgebourg././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/jdbc/libhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/j0000755000175000017500000000000011714611271032520 5ustar ebourgebourg././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/jdbc/jdbc4/libhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/j0000755000175000017500000000000012143273450032520 5ustar ebourgebourg././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/jdbc/jdbc4/JdbcSupportTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/java/org/hibernate/engine/j0000644000175000017500000002370111714611271032525 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.engine.jdbc.jdbc4; import java.sql.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import junit.framework.TestCase; import org.hibernate.engine.jdbc.LobCreationContext; import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.JdbcSupportLoader; import org.hibernate.engine.jdbc.ContextualLobCreator; import org.hibernate.engine.jdbc.BlobImplementer; import org.hibernate.engine.jdbc.ClobImplementer; import org.hibernate.engine.jdbc.NClobImplementer; import org.hibernate.engine.jdbc.NonContextualLobCreator; import org.hibernate.engine.jdbc.WrappedBlob; import org.hibernate.engine.jdbc.WrappedClob; /** * TODO : javadoc * * @author Steve Ebersole */ public class JdbcSupportTest extends TestCase { public void testConnectedLobCreator() throws SQLException { final Connection connection = createConnectionProxy( 4, new JdbcLobBuilder() { public Blob createBlob() { return new JdbcBlob(); } public Clob createClob() { return new JdbcClob(); } public NClob createNClob() { return new JdbcNClob(); } } ); final LobCreationContext lobCreationContext = new LobCreationContext() { public Object execute(Callback callback) { try { return callback.executeOnConnection( connection ); } catch ( SQLException e ) { throw new RuntimeException( "Unexpected SQLException", e ); } } }; LobCreator lobCreator = JdbcSupportLoader.loadJdbcSupport( connection ).getLobCreator( lobCreationContext ); assertTrue( lobCreator instanceof ContextualLobCreator ); Blob blob = lobCreator.createBlob( new byte[] {} ); assertTrue( blob instanceof JdbcBlob ); blob = lobCreator.wrap( blob ); assertTrue( blob instanceof WrappedBlob ); Clob clob = lobCreator.createClob( "Hi" ); assertTrue( clob instanceof JdbcClob ); clob = lobCreator.wrap( clob ); assertTrue( clob instanceof WrappedClob ); Clob nclob = lobCreator.createNClob( "Hi" ); assertTrue( nclob instanceof JdbcNClob ); nclob = lobCreator.wrap( nclob ); assertTrue( nclob instanceof WrappedClob ); blob.free(); clob.free(); nclob.free(); connection.close(); } public void testConnectedLobCreatorWithUnSupportedCreations() throws SQLException { final Connection connection = createConnectionProxy( 3, new JdbcLobBuilder() { public Blob createBlob() { throw new UnsupportedOperationException(); } public Clob createClob() { throw new UnsupportedOperationException(); } public NClob createNClob() { throw new UnsupportedOperationException(); } } ); final LobCreationContext lobCreationContext = new LobCreationContext() { public Object execute(Callback callback) { try { return callback.executeOnConnection( connection ); } catch ( SQLException e ) { throw new RuntimeException( "Unexpected SQLException", e ); } } }; LobCreator lobCreator = JdbcSupportLoader.loadJdbcSupport( connection ).getLobCreator( lobCreationContext ); assertTrue( lobCreator instanceof NonContextualLobCreator ); Blob blob = lobCreator.createBlob( new byte[] {} ); assertTrue( blob instanceof BlobImplementer ); blob = lobCreator.wrap( blob ); assertTrue( blob instanceof WrappedBlob ); Clob clob = lobCreator.createClob( "Hi" ); assertTrue( clob instanceof ClobImplementer ); clob = lobCreator.wrap( clob ); assertTrue( clob instanceof WrappedClob ); Clob nclob = lobCreator.createNClob( "Hi" ); assertTrue( nclob instanceof ClobImplementer ); assertTrue( nclob instanceof NClobImplementer ); nclob = lobCreator.wrap( nclob ); assertTrue( nclob instanceof WrappedClob ); blob.free(); clob.free(); nclob.free(); connection.close(); } public void testLegacyLobCreator() throws SQLException { LobCreator lobCreator = JdbcSupportLoader.loadJdbcSupport( null ).getLobCreator(); Blob blob = lobCreator.createBlob( new byte[] {} ); assertTrue( blob instanceof BlobImplementer ); blob = lobCreator.wrap( blob ); assertTrue( blob instanceof WrappedBlob ); Clob clob = lobCreator.createClob( "Hi" ); assertTrue( clob instanceof ClobImplementer ); clob = lobCreator.wrap( clob ); assertTrue( clob instanceof WrappedClob ); Clob nclob = lobCreator.createNClob( "Hi" ); assertTrue( nclob instanceof NClobImplementer ); assertTrue( NClob.class.isInstance( nclob ) ); nclob = lobCreator.wrap( nclob ); assertTrue( nclob instanceof WrappedClob ); blob.free(); clob.free(); nclob.free(); } private interface JdbcLobBuilder { public Blob createBlob(); public Clob createClob(); public NClob createNClob(); } private class ConnectionProxyHandler implements InvocationHandler { private final JdbcLobBuilder lobBuilder; private final DatabaseMetaData metadata; private ConnectionProxyHandler(int version, JdbcLobBuilder lobBuilder) { this.lobBuilder = lobBuilder; this.metadata = createMetadataProxy( version ); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // the only methods we are interested in are the LOB creation methods... if ( args == null || args.length == 0 ) { final String methodName = method.getName(); if ( "createBlob".equals( methodName ) ) { return lobBuilder.createBlob(); } else if ( "createClob".equals( methodName ) ) { return lobBuilder.createClob(); } else if ( "createNClob".equals( methodName ) ) { return lobBuilder.createNClob(); } else if ( "getMetaData".equals( methodName ) ) { return metadata; } } return null; } } private static Class[] CONN_PROXY_TYPES = new Class[] { Connection.class }; private Connection createConnectionProxy(int version, JdbcLobBuilder jdbcLobBuilder) { ConnectionProxyHandler handler = new ConnectionProxyHandler( version, jdbcLobBuilder ); return ( Connection ) Proxy.newProxyInstance( getClass().getClassLoader(), CONN_PROXY_TYPES, handler ); } private class MetadataProxyHandler implements InvocationHandler { private final int jdbcVersion; private MetadataProxyHandler(int jdbcVersion) { this.jdbcVersion = jdbcVersion; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); if ( "getJDBCMajorVersion".equals( methodName ) ) { return jdbcVersion; } return null; } } private static Class[] META_PROXY_TYPES = new Class[] { DatabaseMetaData.class }; private DatabaseMetaData createMetadataProxy(int version) { MetadataProxyHandler handler = new MetadataProxyHandler( version ); return ( DatabaseMetaData ) Proxy.newProxyInstance( getClass().getClassLoader(), META_PROXY_TYPES, handler ); } private class JdbcBlob implements Blob { public long length() throws SQLException { return 0; } public byte[] getBytes(long pos, int length) throws SQLException { return new byte[0]; } public InputStream getBinaryStream() throws SQLException { return null; } public long position(byte[] pattern, long start) throws SQLException { return 0; } public long position(Blob pattern, long start) throws SQLException { return 0; } public int setBytes(long pos, byte[] bytes) throws SQLException { return 0; } public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException { return 0; } public OutputStream setBinaryStream(long pos) throws SQLException { return null; } public void truncate(long len) throws SQLException { } public void free() throws SQLException { } public InputStream getBinaryStream(long pos, long length) throws SQLException { return null; } } private class JdbcClob implements Clob { public long length() throws SQLException { return 0; } public String getSubString(long pos, int length) throws SQLException { return null; } public Reader getCharacterStream() throws SQLException { return null; } public InputStream getAsciiStream() throws SQLException { return null; } public long position(String searchstr, long start) throws SQLException { return 0; } public long position(Clob searchstr, long start) throws SQLException { return 0; } public int setString(long pos, String str) throws SQLException { return 0; } public int setString(long pos, String str, int offset, int len) throws SQLException { return 0; } public OutputStream setAsciiStream(long pos) throws SQLException { return null; } public Writer setCharacterStream(long pos) throws SQLException { return null; } public void truncate(long len) throws SQLException { } public void free() throws SQLException { } public Reader getCharacterStream(long pos, long length) throws SQLException { return null; } } private class JdbcNClob extends JdbcClob implements NClob { } } libhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/resources/0000755000175000017500000000000012143273450027442 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-jdbc4-testing/src/test/resources/log4j.properties0000644000175000017500000000041311714611271032575 0ustar ebourgebourglog4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=info, stdout libhibernate3-java-3.6.10.Final/project/tagRelease.sh0000644000175000017500000000631311714611271021675 0ustar ebourgebourg#! /bin/sh ################################################################################ # tagRelease.sh # # Replacement for the maven-release-plugin ################################################################################ # be defensive and stop the script set -o nounset # when there are uninitalised variables set -o errexit # or when statements return non true values usage="Usage: tagRelease [-u] [-e exportDirectory] [-r releaseVersion] [-d devVersion]" projectDir=`pwd` releaseVersion= devVersion= performUpdate='' exportDirectory='' ################################################################################ # Update all project poms and commit the changes. # # $1: project directory (base directory of recursve find) # $2: new value for the pom version ################################################################################ updatePomVersionsAndCommit() { for i in `find $1 -name "pom.xml"`; do xmlstarlet ed -P -N x="http://maven.apache.org/POM/4.0.0" \ -u "/x:project/x:parent/x:version" -v $2 \ -u "/x:project/x:version" -v $2 \ $i > tmp mv tmp $i done git commit -a -m "Updating pom versions to $2" } ################################################################################ # Start script processing ################################################################################ while getopts ":e:r:d:u" opt; do case $opt in r) releaseVersion=$OPTARG;; d) devVersion=$OPTARG;; u) performUpdate="true";; e) exportDirectory=$OPTARG;; h) echo $usage;; \?) echo $usage exit 1;; *) echo $usage exit 1;; esac done if [ -z $releaseVersion ]; then read -p "Enter the release version: " releaseVersion fi if [ -z $devVersion ]; then read -p "Enter the development version: " devVersion fi projectName=`xmlstarlet sel -N x=http://maven.apache.org/POM/4.0.0 -t -v "/x:project/x:artifactId" pom.xml` if [ -z "$projectName" ]; then echo "Could not determine propject name (misasing/incomplete pom?)." exit; fi ################################################################################ # Confirm data echo "About to tag release with following information:" echo " tag version : $releaseVersion" echo " dev version : $devVersion" while true; do read -p "Continue? " yn case $yn in [Yy]* ) break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done ################################################################################ # Go, go , go if [ -n "$performUpdate" ]; then echo "Performing requested git pull..." git pull fi updatePomVersionsAndCommit $projectDir $releaseVersion git tag -m "Tagging $releaseVersion release" $releaseVersion updatePomVersionsAndCommit $projectDir $devVersion if [ $exportDirectory ]; then git archive $releaseVersion | tar -x -C $exportDirectory fi # So far all changes were locally. Still need to push them to the remote repo git push origin $releaseVersion git push origin libhibernate3-java-3.6.10.Final/project/hibernate-ehcache/0000755000175000017500000000000012143273450022601 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/pom.xml0000644000175000017500000000562111714611271024122 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent 3.6.10.Final ../hibernate-parent/pom.xml org.hibernate hibernate-ehcache jar Hibernate Ehcache Integration Integration of Hibernate with Ehcache ${project.groupId} hibernate-core ${project.version} net.sf.ehcache ehcache-core 2.4.3 ${project.groupId} hibernate-testing ${project.version} test hsqldb hsqldb 1.8.0.2 test cglib cglib test javassist javassist test libhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/0000755000175000017500000000000011714611271023370 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/0000755000175000017500000000000011714611271024347 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/0000755000175000017500000000000011714611271025270 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/0000755000175000017500000000000011714611271026057 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/0000755000175000017500000000000011714611271030020 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/cache/0000755000175000017500000000000012143273450031063 5ustar ebourgebourg././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/cache/EhCacheProviderTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/cache/EhCacheP0000644000175000017500000000363411714611271032414 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache; import junit.framework.Test; import org.hibernate.cfg.Environment; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.testing.cache.BaseCacheProviderTestCase; /** * @author Emmanuel Bernard */ public class EhCacheProviderTest extends BaseCacheProviderTestCase { public EhCacheProviderTest(String x) { super(x); } public static Test suite() { return new FunctionalTestClassTestSuite(EhCacheProviderTest.class); } public String getCacheConcurrencyStrategy() { return "read-write"; } protected Class getCacheProvider() { return EhCacheProvider.class; } protected String getConfigResourceKey() { return Environment.CACHE_PROVIDER_CONFIG; } protected String getConfigResourceLocation() { return "ehcache.xml"; } protected boolean useTransactionManager() { return false; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/cache/EhCacheRegionFactoryTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/java/org/hibernate/cache/EhCacheR0000644000175000017500000000162011714611271032407 0ustar ebourgebourgpackage org.hibernate.cache; import org.hibernate.cfg.Environment; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.testing.cache.BaseCacheRegionFactoryTestCase; import junit.framework.Test; /** * @author Alex Snaps */ public class EhCacheRegionFactoryTest extends BaseCacheRegionFactoryTestCase { public EhCacheRegionFactoryTest(String x) { super(x); } protected Class getCacheRegionFactory() { return EhCacheRegionFactory.class; } public static Test suite() { return new FunctionalTestClassTestSuite(EhCacheRegionFactoryTest.class); } public String getCacheConcurrencyStrategy() { return "read-write"; } protected String getConfigResourceKey() { return Environment.CACHE_PROVIDER_CONFIG; } protected String getConfigResourceLocation() { return "ehcache.xml"; } protected boolean useTransactionManager() { return false; } }libhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/resources/0000755000175000017500000000000012143273450026361 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/resources/log4j.properties0000644000175000017500000000417111714611271031521 0ustar ebourgebourg################################################################################ # Hibernate, Relational Persistence for Idiomatic Java # # # # Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as # # indicated by the @author tags or express copyright attribution # # statements applied by the authors.  All third-party contributions are # # distributed under license by Red Hat Middleware LLC. # # # # This copyrighted material is made available to anyone wishing to use, modify,# # copy, or redistribute it subject to the terms and conditions of the GNU # # Lesser General Public License, as published by the Free Software Foundation. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with this distribution; if not, write to: # # Free Software Foundation, Inc. # # 51 Franklin Street, Fifth Floor # # Boston, MA 02110-1301 USA # ################################################################################ log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=info, stdout log4j.logger.org.hibernate.test=infolibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/resources/ehcache.xml0000644000175000017500000001171711714611271030472 0ustar ebourgebourg --> libhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/test/resources/hibernate.properties0000644000175000017500000000416311714611271032444 0ustar ebourgebourg################################################################################ # Hibernate, Relational Persistence for Idiomatic Java # # # # Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as # # indicated by the @author tags or express copyright attribution # # statements applied by the authors.  All third-party contributions are # # distributed under license by Red Hat Middleware LLC. # # # # This copyrighted material is made available to anyone wishing to use, modify,# # copy, or redistribute it subject to the terms and conditions of the GNU # # Lesser General Public License, as published by the Free Software Foundation. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with this distribution; if not, write to: # # Free Software Foundation, Inc. # # 51 Franklin Street, Fifth Floor # # Boston, MA 02110-1301 USA # ################################################################################ hibernate.dialect org.hibernate.dialect.HSQLDialect hibernate.connection.driver_class org.hsqldb.jdbcDriver hibernate.connection.url jdbc:hsqldb:mem:/test hibernate.connection.username sa hibernate.connection.password hibernate.connection.pool_size 5 hibernate.cache.region_prefix hibernate.test libhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/0000755000175000017500000000000011714611271024314 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/0000755000175000017500000000000011714611271025235 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/0000755000175000017500000000000011714611271026024 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/0000755000175000017500000000000011714611271027765 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/0000755000175000017500000000000012143273450031030 5ustar ebourgebourg././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheProvider.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheP0000644000175000017500000001570311714611271032361 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache; import java.util.Properties; import java.net.URL; import net.sf.ehcache.CacheManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.cfg.Environment; import org.hibernate.util.StringHelper; import org.hibernate.util.ConfigHelper; /** * Cache Provider plugin for Hibernate * * Use hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider * in Hibernate 3.x or later * * Taken from EhCache 0.9 distribution * @author Greg Luck * @author Emmanuel Bernard */ /** * Cache Provider plugin for ehcache-1.2. New in this provider are ehcache support for multiple * Hibernate session factories, each with its own ehcache configuration, and non Serializable keys and values. * Ehcache-1.2 also has many other features such as cluster support and listeners, which can be used seamlessly simply * by configurion in ehcache.xml. *

* Use hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider in the Hibernate configuration * to enable this provider for Hibernate's second level cache. *

* When configuring multiple ehcache CacheManagers, as you would where you have multiple Hibernate Configurations and * multiple SessionFactories, specify in each Hibernate configuration the ehcache configuration using * the property hibernate.cache.provider_configuration_file_resource_path An example to set an ehcache configuration * called ehcache-2.xml would be hibernate.cache.provider_configuration_file_resource_path=/ehcache-2.xml. If the leading * slash is not there one will be added. The configuration file will be looked for in the root of the classpath. *

* Updated for ehcache-1.2. Note this provider requires ehcache-1.2.jar. Make sure ehcache-1.1.jar or earlier * is not in the classpath or it will not work. *

* See http://ehcache.sf.net for documentation on ehcache *

* * @author Greg Luck * @author Emmanuel Bernard */ public class EhCacheProvider implements CacheProvider { private static final Logger log = LoggerFactory.getLogger(EhCacheProvider.class); private CacheManager manager; /** * Builds a Cache. *

* Even though this method provides properties, they are not used. * Properties for EHCache are specified in the ehcache.xml file. * Configuration will be read from ehcache.xml for a cache declaration * where the name attribute matches the name parameter in this builder. * * @param name the name of the cache. Must match a cache configured in ehcache.xml * @param properties not used * @return a newly built cache will be built and initialised * @throws CacheException inter alia, if a cache of the same name already exists */ public Cache buildCache(String name, Properties properties) throws CacheException { try { net.sf.ehcache.Cache cache = manager.getCache(name); if (cache == null) { log.warn("Could not find configuration [" + name + "]; using defaults."); manager.addCache(name); cache = manager.getCache(name); log.debug("started EHCache region: " + name); } return new EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } } /** * Returns the next timestamp. */ public long nextTimestamp() { return Timestamper.next(); } /** * Callback to perform any necessary initialization of the underlying cache implementation * during SessionFactory construction. * * @param properties current configuration settings. */ public void start(Properties properties) throws CacheException { if (manager != null) { log.warn("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " + " between repeated calls to buildSessionFactory. Using previously created EhCacheProvider." + " If this behaviour is required, consider using net.sf.ehcache.hibernate.SingletonEhCacheProvider."); return; } try { String configurationResourceName = null; if (properties != null) { configurationResourceName = (String) properties.get( Environment.CACHE_PROVIDER_CONFIG ); } if ( StringHelper.isEmpty( configurationResourceName ) ) { manager = new CacheManager(); } else { URL url = loadResource(configurationResourceName); manager = new CacheManager(url); } } catch (net.sf.ehcache.CacheException e) { //yukky! Don't you have subclasses for that! //TODO race conditions can happen here if (e.getMessage().startsWith("Cannot parseConfiguration CacheManager. Attempt to create a new instance of " + "CacheManager using the diskStorePath")) { throw new CacheException("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " + " between repeated calls to buildSessionFactory. Consider using net.sf.ehcache.hibernate.SingletonEhCacheProvider." , e ); } else { throw e; } } } private URL loadResource(String configurationResourceName) { URL url = ConfigHelper.locateConfig( configurationResourceName ); if (log.isDebugEnabled()) { log.debug("Creating EhCacheProvider from a specified resource: " + configurationResourceName + " Resolved to URL: " + url); } return url; } /** * Callback to perform any necessary cleanup of the underlying cache implementation * during SessionFactory.close(). */ public void stop() { if (manager != null) { manager.shutdown(); manager = null; } } public boolean isMinimalPutsEnabledByDefault() { return false; } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/SingletonEhCacheRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/Singleto0000644000175000017500000000050711714611271032541 0ustar ebourgebourgpackage org.hibernate.cache; import java.util.Properties; /** * @author Alex Snaps */ public class SingletonEhCacheRegionFactory extends DelegatingRegionFactory { public SingletonEhCacheRegionFactory(Properties properties) { super(new net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory(properties)); } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/SingletonEhCacheProvider.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/Singleto0000644000175000017500000001556711714611271032555 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.util.ClassLoaderUtil; import java.net.URL; import java.util.Properties; import java.util.logging.Logger; import java.util.logging.Level; /** * Singleton cache Provider plugin for Hibernate 3.2 and ehcache-1.2. New in this provider is support for * non Serializable keys and values. This provider works as a Singleton. No matter how many Hibernate Configurations * you have, only one ehcache CacheManager is used. See EhCacheProvider for a non-singleton implementation. *

* Ehcache-1.2 also has many other features such as cluster support and listeners, which can be used seamlessly simply * by configurion in ehcache.xml. *

* Use hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider in the Hibernate configuration * to enable this provider for Hibernate's second level cache. *

* Updated for ehcache-1.2. Note this provider requires ehcache-1.2.jar. Make sure ehcache-1.1.jar or earlier * is not in the classpath or it will not work. *

* See http://ehcache.sf.net for documentation on ehcache *

* * @author Greg Luck * @author Emmanuel Bernard * @version $Id: SingletonEhCacheProvider.java 744 2008-08-16 20:10:49Z gregluck $ */ public final class SingletonEhCacheProvider implements CacheProvider { /** * The Hibernate system property specifying the location of the ehcache configuration file name. *

* If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath. */ public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName"; private static final Logger LOG = Logger.getLogger( SingletonEhCacheProvider.class.getName() ); /** * To be backwardly compatible with a lot of Hibernate code out there, allow multiple starts and stops on the * one singleton CacheManager. Keep a count of references to only stop on when only one reference is held. */ private static int referenceCount; private CacheManager manager; /** * Builds a Cache. *

* Even though this method provides properties, they are not used. * Properties for EHCache are specified in the ehcache.xml file. * Configuration will be read from ehcache.xml for a cache declaration * where the name attribute matches the name parameter in this builder. * * @param name the name of the cache. Must match a cache configured in ehcache.xml * @param properties not used * * @return a newly built cache will be built and initialised * * @throws org.hibernate.cache.CacheException * inter alia, if a cache of the same name already exists */ public final Cache buildCache(String name, Properties properties) throws CacheException { try { net.sf.ehcache.Ehcache cache = manager.getEhcache( name ); if ( cache == null ) { SingletonEhCacheProvider.LOG.warning( "Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults." ); manager.addCache( name ); cache = manager.getEhcache( name ); SingletonEhCacheProvider.LOG.fine( "started EHCache region: " + name ); } return new EhCache( cache ); } catch ( net.sf.ehcache.CacheException e ) { throw new CacheException( e ); } } /** * Returns the next timestamp. */ public final long nextTimestamp() { return Timestamper.next(); } /** * Callback to perform any necessary initialization of the underlying cache implementation * during SessionFactory construction. *

* * @param properties current configuration settings. */ public final void start(Properties properties) throws CacheException { String configurationResourceName = null; if ( properties != null ) { configurationResourceName = ( String ) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME ); } if ( configurationResourceName == null || configurationResourceName.length() == 0 ) { manager = CacheManager.create(); referenceCount++; } else { if ( !configurationResourceName.startsWith( "/" ) ) { configurationResourceName = "/" + configurationResourceName; if ( LOG.isLoggable( Level.FINE ) ) { LOG.fine( "prepending / to " + configurationResourceName + ". It should be placed in the root" + "of the classpath rather than in a package." ); } } URL url = loadResource( configurationResourceName ); manager = CacheManager.create( url ); referenceCount++; } } private URL loadResource(String configurationResourceName) { ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader(); URL url = null; if ( standardClassloader != null ) { url = standardClassloader.getResource( configurationResourceName ); } if ( url == null ) { url = this.getClass().getResource( configurationResourceName ); } if ( LOG.isLoggable( Level.FINE ) ) { LOG.fine( "Creating EhCacheProvider from a specified resource: " + configurationResourceName + " Resolved to URL: " + url ); } if ( url == null ) { if ( LOG.isLoggable( Level.WARNING ) ) { LOG.warning( "A configurationResourceName was set to " + configurationResourceName + " but the resource could not be loaded from the classpath." + "Ehcache will configure itself using defaults." ); } } return url; } /** * Callback to perform any necessary cleanup of the underlying cache implementation * during SessionFactory.close(). */ public void stop() { if ( manager != null ) { referenceCount--; if ( referenceCount == 0 ) { manager.shutdown(); } manager = null; } } /** * Not sure what this is supposed to do. * * @return false to be safe */ public final boolean isMinimalPutsEnabledByDefault() { return false; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/DelegatingRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/Delegati0000644000175000017500000000375311714611271032501 0ustar ebourgebourgpackage org.hibernate.cache; import org.hibernate.cache.access.AccessType; import org.hibernate.cfg.Settings; import java.util.Properties; /** * @author Alex Snaps */ public class DelegatingRegionFactory implements RegionFactory { private final RegionFactory regionFactory; DelegatingRegionFactory(final RegionFactory regionFactory) { this.regionFactory = regionFactory; } public final void start(final Settings settings, final Properties properties) throws CacheException { regionFactory.start(settings, properties); } public final void stop() { regionFactory.stop(); } public final boolean isMinimalPutsEnabledByDefault() { return regionFactory.isMinimalPutsEnabledByDefault(); } public final AccessType getDefaultAccessType() { return regionFactory.getDefaultAccessType(); } public final long nextTimestamp() { return regionFactory.nextTimestamp(); } public final EntityRegion buildEntityRegion(final String regionName, final Properties properties, final CacheDataDescription metadata) throws CacheException { return regionFactory.buildEntityRegion(regionName, properties, metadata); } public final CollectionRegion buildCollectionRegion(final String regionName, final Properties properties, final CacheDataDescription metadata) throws CacheException { return regionFactory.buildCollectionRegion(regionName, properties, metadata); } public final QueryResultsRegion buildQueryResultsRegion(final String regionName, final Properties properties) throws CacheException { return regionFactory.buildQueryResultsRegion(regionName, properties); } public final TimestampsRegion buildTimestampsRegion(final String regionName, final Properties properties) throws CacheException { return regionFactory.buildTimestampsRegion(regionName, properties); } }././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.0000644000175000017500000001613011714611271032312 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * EHCache plugin for Hibernate *

* EHCache uses a {@link net.sf.ehcache.store.MemoryStore} and a * {@link net.sf.ehcache.store.DiskStore}. * The {@link net.sf.ehcache.store.DiskStore} requires that both keys and values be {@link java.io.Serializable}. * However the MemoryStore does not and in ehcache-1.2 nonSerializable Objects are permitted. They are discarded * if an attempt it made to overflow them to Disk or to replicate them to remote cache peers. * * @author Greg Luck * @author Emmanuel Bernard */ public class EhCache implements Cache { private static final Logger log = LoggerFactory.getLogger( EhCache.class ); private static final int SIXTY_THOUSAND_MS = 60000; private net.sf.ehcache.Ehcache cache; /** * Creates a new Hibernate pluggable cache based on a cache name. *

* * @param cache The underlying EhCache instance to use. */ public EhCache(net.sf.ehcache.Ehcache cache) { this.cache = cache; } /** * Gets a value of an element which matches the given key. * * @param key the key of the element to return. * @return The value placed into the cache with an earlier put, or null if not found or expired * @throws CacheException */ public Object get(Object key) throws CacheException { try { if ( log.isDebugEnabled() ) { log.debug( "key: " + key ); } if ( key == null ) { return null; } else { Element element = cache.get( key ); if ( element == null ) { if ( log.isDebugEnabled() ) { log.debug( "Element for " + key + " is null" ); } return null; } else { return element.getObjectValue(); } } } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } public Object read(Object key) throws CacheException { return get( key ); } /** * Puts an object into the cache. * * @param key a key * @param value a value * @throws CacheException if the {@link CacheManager} * is shutdown or another {@link Exception} occurs. */ public void update(Object key, Object value) throws CacheException { put( key, value ); } /** * Puts an object into the cache. * * @param key a key * @param value a value * @throws CacheException if the {@link CacheManager} * is shutdown or another {@link Exception} occurs. */ public void put(Object key, Object value) throws CacheException { try { Element element = new Element( key, value ); cache.put( element ); } catch (IllegalArgumentException e) { throw new CacheException( e ); } catch (IllegalStateException e) { throw new CacheException( e ); } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } /** * Removes the element which matches the key. *

* If no element matches, nothing is removed and no Exception is thrown. * * @param key the key of the element to remove * @throws CacheException */ public void remove(Object key) throws CacheException { try { cache.remove( key ); } catch (ClassCastException e) { throw new CacheException( e ); } catch (IllegalStateException e) { throw new CacheException( e ); } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } /** * Remove all elements in the cache, but leave the cache * in a useable state. * * @throws CacheException */ public void clear() throws CacheException { try { cache.removeAll(); } catch (IllegalStateException e) { throw new CacheException( e ); } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } /** * Remove the cache and make it unuseable. * * @throws CacheException */ public void destroy() throws CacheException { try { cache.getCacheManager().removeCache( cache.getName() ); } catch (IllegalStateException e) { throw new CacheException( e ); } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } /** * Calls to this method should perform there own synchronization. * It is provided for distributed caches. Because EHCache is not distributed * this method does nothing. */ public void lock(Object key) throws CacheException { } /** * Calls to this method should perform there own synchronization. * It is provided for distributed caches. Because EHCache is not distributed * this method does nothing. */ public void unlock(Object key) throws CacheException { } /** * Gets the next timestamp; */ public long nextTimestamp() { return Timestamper.next(); } /** * Returns the lock timeout for this cache. */ public int getTimeout() { // 60 second lock timeout return Timestamper.ONE_MS * SIXTY_THOUSAND_MS; } public String getRegionName() { return cache.getName(); } /** * Warning: This method can be very expensive to run. Allow approximately 1 second * per 1MB of entries. Running this method could create liveness problems * because the object lock is held for a long period *

* * @return the approximate size of memory ehcache is using for the MemoryStore for this cache */ public long getSizeInMemory() { try { return cache.calculateInMemorySize(); } catch (Throwable t) { return -1; } } public long getElementCountInMemory() { try { return cache.getMemoryStoreSize(); } catch (net.sf.ehcache.CacheException ce) { throw new CacheException( ce ); } } public long getElementCountOnDisk() { return cache.getDiskStoreSize(); } public Map toMap() { try { Map result = new HashMap(); Iterator iter = cache.getKeys().iterator(); while ( iter.hasNext() ) { Object key = iter.next(); result.put( key, cache.get( key ).getObjectValue() ); } return result; } catch (Exception e) { throw new CacheException( e ); } } public String toString() { return "EHCache(" + getRegionName() + ')'; } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheR0000644000175000017500000000046311714611271032360 0ustar ebourgebourgpackage org.hibernate.cache; import java.util.Properties; /** * @author Alex Snaps */ public class EhCacheRegionFactory extends DelegatingRegionFactory { public EhCacheRegionFactory(final Properties properties) { super(new net.sf.ehcache.hibernate.EhCacheRegionFactory(properties)); } }libhibernate3-java-3.6.10.Final/project/hibernate-parent/0000755000175000017500000000000012143273450022512 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-parent/pom.xml0000644000175000017500000013106311714611271024033 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent pom 3.6.10.Final Hibernate Core Parent POM The base POM for all Hibernate Core modules. http://hibernate.org 2002 Hibernate.org http://hibernate.org hibernate.org Hibernate.org Developers Hibernate.org http://www.hibernate.org GNU Lesser General Public License http://www.gnu.org/licenses/lgpl-2.1.html See discussion at http://hibernate.org/license for more details. repo scm:git:git//github.com:hibernate/hibernate-core.git scm:git:git//github.com:hibernate/hibernate-core.git http://github.com/hibernate/hibernate-core hudson http://hudson.jboss.org/hudson/job/hibernate-core-trunk/ mail

hibernate-dev@lists.jboss.org
jira http://opensource.atlassian.com/projects/hibernate/browse/HHH Hibernate Announcements hibernate-announce@lists.jboss.org https://lists.jboss.org/mailman/listinfo/hibernate-announce https://lists.jboss.org/mailman/listinfo/hibernate-announce http://lists.jboss.org/pipermail/hibernate-dev/ Hibernate Commit Notificatons hibernate-commits@lists.jboss.org https://lists.jboss.org/mailman/listinfo/hibernate-commits https://lists.jboss.org/mailman/listinfo/hibernate-commits http://lists.jboss.org/pipermail/hibernate-commits/ Hibernate Developers hibernate-dev@lists.jboss.org https://lists.jboss.org/mailman/listinfo/hibernate-dev https://lists.jboss.org/mailman/listinfo/hibernate-dev http://lists.jboss.org/pipermail/hibernate-dev/ http://www.mail-archive.com/hibernate-dev%40lists.jboss.org/index.html Hibernate Issue Notifications hibernate-issues@lists.jboss.org https://lists.jboss.org/mailman/listinfo/hibernate-issues https://lists.jboss.org/mailman/listinfo/hibernate-issues http://lists.jboss.org/pipermail/hibernate-issues/ org.jboss.maven.plugins maven-jdocbook-style-plugin true org.codehaus.groovy.maven gmaven-plugin 1.0 deploy execute org.apache.maven.plugins maven-enforcer-plugin enforce-java enforce [1.5,) (2.0.7,) org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 org.apache.maven.plugins maven-jar-plugin true true http://hibernate.org org.apache.maven.plugins maven-surefire-plugin true -Xmx1024m org.apache.maven.plugins maven-source-plugin attach-sources verify jar-no-fork org.jboss.maven.plugins maven-jdocbook-plugin 2.3.4 true org.hibernate hibernate-jdocbook-style 2.0.1 jdocbook-style pdf classpath:/xslt/org/hibernate/jdocbook/xslt/pdf.xsl hibernate_reference.pdf html_single classpath:/xslt/org/hibernate/jdocbook/xslt/xhtml-single.xsl index.html html classpath:/xslt/org/hibernate/jdocbook/xslt/xhtml.xsl index.html true saxon 1.72.0 - org.jboss.maven.plugins maven-jdocbook-style-plugin 2.0.0 org.apache.maven.plugins maven-javadoc-plugin 2.5 http://download.oracle.com/javase/1.5.0/docs/api/ http://download.oracle.com/javaee/5/api/ Hibernate Packages Hibernate Core ${project.version} Hibernate Core ${project.version} Red Hat Middleware, LLC. All Rights Reserved]]> orh.hibernate.tutorial* Core API org.hibernate:org.hibernate.classic:org.hibernate.criterion:org.hibernate.mapping:org.hibernate.metadata:org.hibernate.cfg:org.hibernate.stat Extension SPI/API org.hibernate.id*:org.hibernate.connection:org.hibernate.transaction:org.hibernate.type:org.hibernate.dialect*:org.hibernate.cache*:org.hibernate.event*:org.hibernate.property:org.hibernate.loader*:org.hibernate.persister*:org.hibernate.proxy:org.hibernate.tuple:org.hibernate.transform:org.hibernate.collection:org.hibernate.jdbc:org.hibernate.usertype JBoss Cache Integration org.hibernate.cache.jbc2* Miscellaneous API org.hibernate.tool.hbm2ddl:org.hibernate.jmx:org.hibernate.tool.instrument* org.apache.maven.plugins maven-surefire-plugin 2.4.3 org.apache.maven.plugins maven-jar-plugin 2.1 org.apache.maven.plugins maven-enforcer-plugin 1.0-alpha-3 org.apache.maven.plugins maven-compiler-plugin 2.0.2 org.apache.maven.plugins maven-source-plugin 2.1.1 org.apache.maven.plugins maven-antrun-plugin 1.3 org.jboss.maven.plugins maven-test-ext-plugin 1.1.0 extend org.jboss.maven.plugins maven-injection-plugin 1.0.2 compile bytecode org.apache.maven.wagon wagon-webdav 1.0-beta-2 org.apache.maven.wagon wagon-scm 1.0-beta-6 org.apache.maven.scm maven-scm-manager-plexus 1.0 org.apache.maven.scm maven-scm-provider-svnexe 1.0 org.apache.maven.plugins maven-surefire-report-plugin 2.4.3 org.codehaus.mojo findbugs-maven-plugin 1.1.1 org.hibernate.* org.slf4j slf4j-api junit junit 3.8.1 test org.slf4j jcl-over-slf4j ${slf4jVersion} test org.slf4j slf4j-log4j12 ${slf4jVersion} test commons-logging commons-logging 99.0-does-not-exist test commons-logging commons-logging-api 99.0-does-not-exist test org.slf4j slf4j-api ${slf4jVersion} antlr antlr 2.7.6 commons-collections commons-collections 3.1 dom4j dom4j 1.6.1 javassist javassist 3.12.0.GA cglib cglib 2.2 org.hibernate.javax.persistence hibernate-jpa-2.0-api 1.0.1.Final org.hibernate hibernate-commons-annotations 3.2.0.Final javax.validation validation-api 1.0.0.GA org.hibernate hibernate-validator 4.1.0.Final com.h2database h2 1.2.145 org.jboss.byteman byteman ${bytemanVersion} jboss-releases-repository JBoss Releases Repository https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/ jboss-snapshots-repository JBoss Snapshot Repository https://repository.jboss.org/nexus/content/repositories/snapshots/ hsqldb false org.hsqldb hsqldb 2.0.0 test org.hibernate.dialect.HSQLDialect org.hsqldb.jdbcDriver jdbc:hsqldb:. sa h2 true com.h2database h2 test org.hibernate.dialect.H2Dialect org.h2.Driver jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE sa derby org.apache.derby derby 10.7.1.1 test org.hibernate.dialect.DerbyDialect org.apache.derby.jdbc.EmbeddedDriver jdbc:derby:${project.build.outputDirectory}/test/derby;create=true sa mysql50 mysql mysql-connector-java 5.1.16 test org.hibernate.dialect.MySQL5InnoDBDialect com.mysql.jdbc.Driver jdbc:mysql://vmg08.mw.lab.eng.bos.redhat.com/hibbr35 hibbr35 hibbr35 mysql51 mysql mysql-connector-java 5.1.16 test org.hibernate.dialect.MySQL5InnoDBDialect com.mysql.jdbc.Driver jdbc:mysql://vmg02.mw.lab.eng.bos.redhat.com/hibbr35 hibbr35 hibbr35 mysql51-cluster mysql mysql-connector-java 5.1.8 test org.hibernate.dialect.MySQL5Dialect com.mysql.jdbc.Driver jdbc:mysql:loadbalance://dev61.qa.atl2.redhat.com:3306,dev62.qa.atl2.redhat.com:3306/hibbr35 hibbr35 hibbr35 postgresql82 postgresql postgresql 8.4-701.jdbc3 test org.hibernate.dialect.PostgreSQLDialect org.postgresql.Driver jdbc:postgresql://vmg01.mw.lab.eng.bos.redhat.com:5432:hibbr35 hibbr35 hibbr35 postgresql83 postgresql postgresql 8.4-701.jdbc3 test org.hibernate.dialect.PostgreSQLDialect org.postgresql.Driver jdbc:postgresql://vmg03.mw.lab.eng.bos.redhat.com:5432:hibbr35 hibbr35 hibbr35 db2v82 com.ibm db2jcc 3.1.57 test com.ibm db2jcc_license_cu 3.1.57 test org.hibernate.dialect.DB2Dialect com.ibm.db2.jcc.DB2Driver jdbc:db2://dev32.qa.atl.jboss.com:50000/jbossqa hibbr35 hibbr35 db2-91 com.ibm db2jcc 3.8.47 test com.ibm db2jcc_license_cu 3.8.47 test org.hibernate.dialect.DB2Dialect com.ibm.db2.jcc.DB2Driver jdbc:db2://dev67.qa.atl.jboss.com:50000/jbossqa hibbr35 hibbr35 db2-97 com.ibm db2jcc 3.57.86 test com.ibm db2jcc_license_cu 3.57.86 test org.hibernate.dialect.DB2Dialect com.ibm.db2.jcc.DB2Driver jdbc:db2://vmg06.mw.lab.eng.bos.redhat.com:50000/jbossqa hibbr35 hibbr35 oracle9i com.oracle ojdbc14 10.0.2.0 test org.hibernate.dialect.Oracle9iDialect oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@dev20.qa.atl.jboss.com:1521:qa hibbr35 hibbr35 oracle10g com.oracle ojdbc14 10.0.2.0 test org.hibernate.dialect.Oracle10gDialect oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@vmg05.mw.lab.eng.bos.redhat.com:1521:qaora10 hibbr35 hibbr35 oracle11g com.oracle ojdbc5 11.1.0.7.0 test org.hibernate.dialect.Oracle10gDialect oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@dev04.qa.atl2.redhat.com:1521:qaora11 hibbr35 hibbr35 oracle11gRAC com.oracle ojdbc5 11.1.0.7.0 test org.hibernate.dialect.Oracle10gDialect oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=vmg24-vip.mw.lab.eng.bos.redhat.com)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=vmg25-vip.mw.lab.eng.bos.redhat.com)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=qarac.jboss))) hibbr35 hibbr35 sybase15 com.sybase jconnect 6.0.5 test org.hibernate.dialect.SybaseASE15Dialect com.sybase.jdbc3.jdbc.SybDriver jdbc:sybase:Tds:vmg07.mw.lab.eng.bos.redhat.com:5000/hibbr35?SQLINITSTRING=set quoted_identifier on&DYNAMIC_PREPARE=true hibbr35 hibbr35 sybase15-jdbc4 com.sybase jconnect 7.0.0_26502 test org.hibernate.dialect.SybaseASE15Dialect com.sybase.jdbc4.jdbc.SybDriver jdbc:sybase:Tds:vmg07.mw.lab.eng.bos.redhat.com:5000/hibbr35?SQLINITSTRING=set quoted_identifier on hibbr35 hibbr35 sybase155 com.sybase jconnect 6.0.5 test org.hibernate.dialect.SybaseASE15Dialect com.sybase.jdbc3.jdbc.SybDriver jdbc:sybase:Tds:vmg09.mw.lab.eng.bos.redhat.com:5000/hibbr35?SQLINITSTRING=set quoted_identifier on&DYNAMIC_PREPARE=true hibbr35 hibbr35 sybase155-jdbc4 com.sybase jconnect 7.0.0_26502 test org.hibernate.dialect.SybaseASE15Dialect com.sybase.jdbc4.jdbc.SybDriver jdbc:sybase:Tds:vmg09.mw.lab.eng.bos.redhat.com:5000/hibbr35?SQLINITSTRING=set quoted_identifier on hibbr35 hibbr35 mssql2005 com.microsoft.sqlserver msjdbc 2.0.1008.2 test org.hibernate.dialect.SQLServerDialect com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://dev30.qa.atl.jboss.com:3918 hibbr35 hibbr35 4096 mssql2008 com.microsoft.sqlserver msjdbc 2.0.1008.2 test org.hibernate.dialect.SQLServerDialect com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://vmg04.mw.lab.eng.bos.redhat.com:1433 hibbr35 hibbr35 4096 1.6.1 UTF-8 1.5.1 libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/0000755000175000017500000000000012143273450023357 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/pom.xml0000644000175000017500000002165211714611271024702 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent 3.6.10.Final ../hibernate-parent/pom.xml org.hibernate hibernate-infinispan jar Hibernate Infinispan Integration Integration of Hibernate with Infinispan 4.2.1.CR1 1.8.0.2 2.2 3.4.GA 5.0.3.GA 1.5.0 true 127.0.0.1 ${project.groupId} hibernate-core ${project.version} org.infinispan infinispan-core ${version.infinispan} ${project.groupId} hibernate-testing ${project.version} org.infinispan infinispan-core ${version.infinispan} test-jar test hsqldb hsqldb ${version.hsqldb} test cglib cglib ${version.cglib} test javassist javassist ${version.javassist} test org.jboss.naming jnp-client test ${version.org.jboss.naming} org.jboss.naming jnpserver test ${version.org.jboss.naming} com.experlog xapool test ${version.xapool} jboss.jbossts jbossjta 4.9.0.GA test org.apache.maven.plugins maven-compiler-plugin 1.6 1.6 1.6 ${jdk16_home}/bin/javac true true org.apache.maven.plugins maven-surefire-plugin ${jdk16_home}/bin/java **/ClusteredConcurrentTimestampRegionTestCase.java hibernate.test.validatefailureexpected true jgroups.bind_addr ${jgroups.bind_addr} java.net.preferIPv4Stack true jgroups.ping.timeout 500 jgroups.ping.num_initial_members 1 jgroups.udp.enable_bundling false ${skipUnitTests} test false false libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/0000755000175000017500000000000011714611271024146 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/0000755000175000017500000000000011714611271025125 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/0000755000175000017500000000000011714611271026046 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/0000755000175000017500000000000011714611271026635 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/0000755000175000017500000000000011714611271030576 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/0000755000175000017500000000000011714611271031555 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000011714611271032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/QueryRegionImplTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002410711714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.query; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.AssertionFailedError; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.Region; import org.hibernate.cache.StandardQueryCache; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.transaction.tm.BatchModeTransactionManager; import org.infinispan.util.concurrent.IsolationLevel; /** * Tests of QueryResultRegionImpl. * * @author Galder Zamarreño * @since 3.5 */ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase { // protected static final String REGION_NAME = "test/" + StandardQueryCache.class.getName(); /** * Create a new EntityRegionImplTestCase. * * @param name */ public QueryRegionImplTestCase(String name) { super(name); } @Override protected Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd) { return regionFactory.buildQueryResultsRegion(regionName, properties); } @Override protected String getStandardRegionName(String regionPrefix) { return regionPrefix + "/" + StandardQueryCache.class.getName(); } @Override protected CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory) { return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache("local-query")); } @Override protected Configuration createConfiguration() { return CacheTestUtil.buildCustomQueryCacheConfiguration("test", "replicated-query"); } public void testPutDoesNotBlockGet() throws Exception { putDoesNotBlockGetTest(); } private void putDoesNotBlockGetTest() throws Exception { Configuration cfg = createConfiguration(); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), cfg .getProperties()); region.put(KEY, VALUE1); assertEquals(VALUE1, region.get(KEY)); final CountDownLatch readerLatch = new CountDownLatch(1); final CountDownLatch writerLatch = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(1); final ExceptionHolder holder = new ExceptionHolder(); Thread reader = new Thread() { public void run() { try { BatchModeTransactionManager.getInstance().begin(); log.debug("Transaction began, get value for key"); assertTrue(VALUE2.equals(region.get(KEY)) == false); BatchModeTransactionManager.getInstance().commit(); } catch (AssertionFailedError e) { holder.a1 = e; rollback(); } catch (Exception e) { holder.e1 = e; rollback(); } finally { readerLatch.countDown(); } } }; Thread writer = new Thread() { public void run() { try { BatchModeTransactionManager.getInstance().begin(); log.debug("Put value2"); region.put(KEY, VALUE2); log.debug("Put finished for value2, await writer latch"); writerLatch.await(); log.debug("Writer latch finished"); BatchModeTransactionManager.getInstance().commit(); log.debug("Transaction committed"); } catch (Exception e) { holder.e2 = e; rollback(); } finally { completionLatch.countDown(); } } }; reader.setDaemon(true); writer.setDaemon(true); writer.start(); assertFalse("Writer is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); // Start the reader reader.start(); assertTrue("Reader finished promptly", readerLatch.await(1000000000, TimeUnit.MILLISECONDS)); writerLatch.countDown(); assertTrue("Reader finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); assertEquals(VALUE2, region.get(KEY)); if (holder.a1 != null) throw holder.a1; else if (holder.a2 != null) throw holder.a2; assertEquals("writer saw no exceptions", null, holder.e1); assertEquals("reader saw no exceptions", null, holder.e2); } public void testGetDoesNotBlockPut() throws Exception { getDoesNotBlockPutTest(); } private void getDoesNotBlockPutTest() throws Exception { Configuration cfg = createConfiguration(); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), cfg .getProperties()); region.put(KEY, VALUE1); assertEquals(VALUE1, region.get(KEY)); // final Fqn rootFqn = getRegionFqn(getStandardRegionName(REGION_PREFIX), REGION_PREFIX); final CacheAdapter jbc = getInfinispanCache(regionFactory); final CountDownLatch blockerLatch = new CountDownLatch(1); final CountDownLatch writerLatch = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(1); final ExceptionHolder holder = new ExceptionHolder(); Thread blocker = new Thread() { public void run() { // Fqn toBlock = new Fqn(rootFqn, KEY); GetBlocker blocker = new GetBlocker(blockerLatch, KEY); try { jbc.addListener(blocker); BatchModeTransactionManager.getInstance().begin(); region.get(KEY); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { holder.e1 = e; rollback(); } finally { jbc.removeListener(blocker); } } }; Thread writer = new Thread() { public void run() { try { writerLatch.await(); BatchModeTransactionManager.getInstance().begin(); region.put(KEY, VALUE2); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { holder.e2 = e; rollback(); } finally { completionLatch.countDown(); } } }; blocker.setDaemon(true); writer.setDaemon(true); boolean unblocked = false; try { blocker.start(); writer.start(); assertFalse("Blocker is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); // Start the writer writerLatch.countDown(); assertTrue("Writer finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); blockerLatch.countDown(); unblocked = true; if (IsolationLevel.REPEATABLE_READ.equals(jbc.getConfiguration().getIsolationLevel())) { assertEquals(VALUE1, region.get(KEY)); } else { assertEquals(VALUE2, region.get(KEY)); } if (holder.a1 != null) throw holder.a1; else if (holder.a2 != null) throw holder.a2; assertEquals("blocker saw no exceptions", null, holder.e1); assertEquals("writer saw no exceptions", null, holder.e2); } finally { if (!unblocked) blockerLatch.countDown(); } } @Listener public class GetBlocker { private CountDownLatch latch; // private Fqn fqn; private Object key; GetBlocker(CountDownLatch latch, Object key) { this.latch = latch; this.key = key; } @CacheEntryVisited public void nodeVisisted(CacheEntryVisitedEvent event) { if (event.isPre() && event.getKey().equals(key)) { try { latch.await(); } catch (InterruptedException e) { log.error("Interrupted waiting for latch", e); } } } } private class ExceptionHolder { Exception e1; Exception e2; AssertionFailedError a1; AssertionFailedError a2; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000023400000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/access/PutFromLoadValidatorUnitTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000004444611714611271032636 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat, Inc or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.access; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import junit.framework.TestCase; /** * Tests of {@link PutFromLoadValidator}. * * @author Brian Stansberry * @author Galder Zamarreño * @version $Revision: $ */ public class PutFromLoadValidatorUnitTestCase extends TestCase { private Object KEY1 = "KEY1"; private TransactionManager tm; public PutFromLoadValidatorUnitTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); tm = DualNodeJtaTransactionManagerImpl.getInstance("test"); } @Override protected void tearDown() throws Exception { try { super.tearDown(); } finally { tm = null; try { DualNodeJtaTransactionManagerImpl.cleanupTransactions(); } finally { DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers(); } } } public void testNakedPut() throws Exception { nakedPutTest(false); } public void testNakedPutTransactional() throws Exception { nakedPutTest(true); } private void nakedPutTest(boolean transactional) throws Exception { PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null); if (transactional) { tm.begin(); } boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertTrue(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testRegisteredPut() throws Exception { registeredPutTest(false); } public void testRegisteredPutTransactional() throws Exception { registeredPutTest(true); } private void registeredPutTest(boolean transactional) throws Exception { PutFromLoadValidator testee = new PutFromLoadValidator( transactional ? tm : null); if (transactional) { tm.begin(); } testee.registerPendingPut(KEY1); boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertTrue(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testNakedPutAfterKeyRemoval() throws Exception { nakedPutAfterRemovalTest(false, false); } public void testNakedPutAfterKeyRemovalTransactional() throws Exception { nakedPutAfterRemovalTest(true, false); } public void testNakedPutAfterRegionRemoval() throws Exception { nakedPutAfterRemovalTest(false, true); } public void testNakedPutAfterRegionRemovalTransactional() throws Exception { nakedPutAfterRemovalTest(true, true); } private void nakedPutAfterRemovalTest(boolean transactional, boolean removeRegion) throws Exception { PutFromLoadValidator testee = new PutFromLoadValidator( transactional ? tm : null); if (removeRegion) { testee.invalidateRegion(); } else { testee.invalidateKey(KEY1); } if (transactional) { tm.begin(); } boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertFalse(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testRegisteredPutAfterKeyRemoval() throws Exception { registeredPutAfterRemovalTest(false, false); } public void testRegisteredPutAfterKeyRemovalTransactional() throws Exception { registeredPutAfterRemovalTest(true, false); } public void testRegisteredPutAfterRegionRemoval() throws Exception { registeredPutAfterRemovalTest(false, true); } public void testRegisteredPutAfterRegionRemovalTransactional() throws Exception { registeredPutAfterRemovalTest(true, true); } private void registeredPutAfterRemovalTest(boolean transactional, boolean removeRegion) throws Exception { PutFromLoadValidator testee = new PutFromLoadValidator( transactional ? tm : null); if (removeRegion) { testee.invalidateRegion(); } else { testee.invalidateKey(KEY1); } if (transactional) { tm.begin(); } testee.registerPendingPut(KEY1); boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertTrue(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testRegisteredPutWithInterveningKeyRemoval() throws Exception { registeredPutWithInterveningRemovalTest(false, false); } public void testRegisteredPutWithInterveningKeyRemovalTransactional() throws Exception { registeredPutWithInterveningRemovalTest(true, false); } public void testRegisteredPutWithInterveningRegionRemoval() throws Exception { registeredPutWithInterveningRemovalTest(false, true); } public void testRegisteredPutWithInterveningRegionRemovalTransactional() throws Exception { registeredPutWithInterveningRemovalTest(true, true); } private void registeredPutWithInterveningRemovalTest(boolean transactional, boolean removeRegion) throws Exception { PutFromLoadValidator testee = new PutFromLoadValidator( transactional ? tm : null); if (transactional) { tm.begin(); } testee.registerPendingPut(KEY1); if (removeRegion) { testee.invalidateRegion(); } else { testee.invalidateKey(KEY1); } boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertFalse(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testDelayedNakedPutAfterKeyRemoval() throws Exception { delayedNakedPutAfterRemovalTest(false, false); } public void testDelayedNakedPutAfterKeyRemovalTransactional() throws Exception { delayedNakedPutAfterRemovalTest(true, false); } public void testDelayedNakedPutAfterRegionRemoval() throws Exception { delayedNakedPutAfterRemovalTest(false, true); } public void testDelayedNakedPutAfterRegionRemovalTransactional() throws Exception { delayedNakedPutAfterRemovalTest(true, true); } private void delayedNakedPutAfterRemovalTest(boolean transactional, boolean removeRegion) throws Exception { PutFromLoadValidator testee = new TestValidator(transactional ? tm : null, 100, 1000, 500, 10000); if (removeRegion) { testee.invalidateRegion(); } else { testee.invalidateKey(KEY1); } if (transactional) { tm.begin(); } Thread.sleep(110); boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertTrue(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } public void testMultipleRegistrations() throws Exception { multipleRegistrationtest(false); } public void testMultipleRegistrationsTransactional() throws Exception { multipleRegistrationtest(true); } private void multipleRegistrationtest(final boolean transactional) throws Exception { final PutFromLoadValidator testee = new PutFromLoadValidator(transactional ? tm : null); final CountDownLatch registeredLatch = new CountDownLatch(3); final CountDownLatch finishedLatch = new CountDownLatch(3); final AtomicInteger success = new AtomicInteger(); Runnable r = new Runnable() { public void run() { try { if (transactional) { tm.begin(); } testee.registerPendingPut(KEY1); registeredLatch.countDown(); registeredLatch.await(5, TimeUnit.SECONDS); if (testee.acquirePutFromLoadLock(KEY1)) { try { success.incrementAndGet(); } finally { testee.releasePutFromLoadLock(KEY1); } } finishedLatch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; ExecutorService executor = Executors.newFixedThreadPool(3); // Start with a removal so the "isPutValid" calls will fail if // any of the concurrent activity isn't handled properly testee.invalidateRegion(); // Do the registration + isPutValid calls executor.execute(r); executor.execute(r); executor.execute(r); finishedLatch.await(5, TimeUnit.SECONDS); assertEquals("All threads succeeded", 3, success.get()); } /** * White box test for ensuring key removals get cleaned up. Note: Since this test is test sensitive, if you * add trace logging, it might fail * * @throws Exception */ public void testRemovalCleanup() throws Exception { TestValidator testee = new TestValidator(null, 200, 1000, 500, 10000); testee.invalidateKey("KEY1"); testee.invalidateKey("KEY2"); Thread.sleep(210); assertEquals(2, testee.getRemovalQueueLength()); testee.invalidateKey("KEY1"); assertEquals(2, testee.getRemovalQueueLength()); testee.invalidateKey("KEY2"); assertEquals(2, testee.getRemovalQueueLength()); } /** * Very much a white box test of the logic for ensuring pending put registrations get cleaned up. * * @throws Exception */ public void testPendingPutCleanup() throws Exception { TestValidator testee = new TestValidator(tm, 5000, 600, 300, 900); // Start with a regionRemoval so we can confirm at the end that all // registrations have been cleaned out testee.invalidateRegion(); testee.registerPendingPut("1"); testee.registerPendingPut("2"); testee.registerPendingPut("3"); testee.registerPendingPut("4"); testee.registerPendingPut("5"); testee.registerPendingPut("6"); testee.acquirePutFromLoadLock("6"); testee.releasePutFromLoadLock("6"); testee.acquirePutFromLoadLock("2"); testee.releasePutFromLoadLock("2"); // ppq = [1,2(c),3,4,5,6(c)] assertEquals(6, testee.getPendingPutQueueLength()); assertEquals(0, testee.getOveragePendingPutQueueLength()); // Sleep past "pendingPutRecentPeriod" Thread.sleep(310); testee.registerPendingPut("7"); // White box -- should have cleaned out 2 (completed) but // not gotten to 6 (also removed) // ppq = [1,3,4,5,6(c),7] assertEquals(0, testee.getOveragePendingPutQueueLength()); assertEquals(6, testee.getPendingPutQueueLength()); // Sleep past "pendingPutOveragePeriod" Thread.sleep(310); testee.registerPendingPut("8"); // White box -- should have cleaned out 6 (completed) and // moved 1, 3, 4 and 5 to overage queue // oppq = [1,3,4,5] ppq = [7,8] assertEquals(4, testee.getOveragePendingPutQueueLength()); assertEquals(2, testee.getPendingPutQueueLength()); // Sleep past "maxPendingPutDelay" Thread.sleep(310); testee.acquirePutFromLoadLock("3"); testee.releasePutFromLoadLock("3"); // White box -- should have cleaned out 1 (overage) and // moved 7 to overage queue // oppq = [3(c),4,5,7] ppq=[8] assertEquals(4, testee.getOveragePendingPutQueueLength()); assertEquals(1, testee.getPendingPutQueueLength()); // Sleep past "maxPendingPutDelay" Thread.sleep(310); tm.begin(); testee.registerPendingPut("7"); Transaction tx = tm.suspend(); // White box -- should have cleaned out 3 (completed) // and 4 (overage) and moved 8 to overage queue // We now have 5,7,8 in overage and 7tx in pending // oppq = [5,7,8] ppq=[7tx] assertEquals(3, testee.getOveragePendingPutQueueLength()); assertEquals(1, testee.getPendingPutQueueLength()); // Validate that only expected items can do puts, thus indirectly // proving the others have been cleaned out of pendingPuts map boolean locked = testee.acquirePutFromLoadLock("1"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); // 5 was overage, so should have been cleaned assertEquals(2, testee.getOveragePendingPutQueueLength()); locked = testee.acquirePutFromLoadLock("2"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); // 7 was overage, so should have been cleaned assertEquals(1, testee.getOveragePendingPutQueueLength()); locked = testee.acquirePutFromLoadLock("3"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); locked = testee.acquirePutFromLoadLock("4"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); locked = testee.acquirePutFromLoadLock("5"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); locked = testee.acquirePutFromLoadLock("1"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(testee.acquirePutFromLoadLock("6")); locked = testee.acquirePutFromLoadLock("7"); if (locked) { testee.releasePutFromLoadLock("1"); } assertFalse(locked); assertTrue(testee.acquirePutFromLoadLock("8")); testee.releasePutFromLoadLock("8"); tm.resume(tx); assertTrue(testee.acquirePutFromLoadLock("7")); testee.releasePutFromLoadLock("7"); } public void testInvalidateKeyBlocksForInProgressPut() throws Exception { invalidationBlocksForInProgressPutTest(true); } public void testInvalidateRegionBlocksForInProgressPut() throws Exception { invalidationBlocksForInProgressPutTest(false); } private void invalidationBlocksForInProgressPutTest(final boolean keyOnly) throws Exception { final PutFromLoadValidator testee = new PutFromLoadValidator(null); final CountDownLatch removeLatch = new CountDownLatch(1); final CountDownLatch pferLatch = new CountDownLatch(1); final AtomicReference cache = new AtomicReference("INITIAL"); Callable pferCallable = new Callable() { public Boolean call() throws Exception { testee.registerPendingPut(KEY1); if (testee.acquirePutFromLoadLock(KEY1)) { try { removeLatch.countDown(); pferLatch.await(); cache.set("PFER"); return Boolean.TRUE; } finally { testee.releasePutFromLoadLock(KEY1); } } return Boolean.FALSE; } }; Callable invalidateCallable = new Callable() { public Void call() throws Exception { removeLatch.await(); if (keyOnly) { testee.invalidateKey(KEY1); } else { testee.invalidateRegion(); } cache.set(null); return null; } }; ExecutorService executorService = Executors.newCachedThreadPool(); Future pferFuture = executorService.submit(pferCallable); Future invalidateFuture = executorService.submit(invalidateCallable); try { invalidateFuture.get(1, TimeUnit.SECONDS); fail("invalidateFuture did not block"); } catch (TimeoutException good) {} pferLatch.countDown(); assertTrue(pferFuture.get(5, TimeUnit.SECONDS)); invalidateFuture.get(5, TimeUnit.SECONDS); assertNull(cache.get()); } private static class TestValidator extends PutFromLoadValidator { protected TestValidator(TransactionManager transactionManager, long nakedPutInvalidationPeriod, long pendingPutOveragePeriod, long pendingPutRecentPeriod, long maxPendingPutDelay) { super(transactionManager, nakedPutInvalidationPeriod, pendingPutOveragePeriod, pendingPutRecentPeriod, maxPendingPutDelay); } @Override public int getOveragePendingPutQueueLength() { // TODO Auto-generated method stub return super.getOveragePendingPutQueueLength(); } @Override public int getPendingPutQueueLength() { // TODO Auto-generated method stub return super.getPendingPutQueueLength(); } @Override public int getRemovalQueueLength() { // TODO Auto-generated method stub return super.getRemovalQueueLength(); } } } ././@LongLink0000000000000000000000000000022600000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractGeneralDataRegionTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001611511714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan; import java.util.Set; import org.hibernate.cache.GeneralDataRegion; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.Region; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of QueryResultsRegion and TimestampsRegion. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionImplTestCase { protected static final String KEY = "Key"; protected static final String VALUE1 = "value1"; protected static final String VALUE2 = "value2"; public AbstractGeneralDataRegionTestCase(String name) { super(name); } @Override protected void putInRegion(Region region, Object key, Object value) { ((GeneralDataRegion) region).put(key, value); } @Override protected void removeFromRegion(Region region, Object key) { ((GeneralDataRegion) region).evict(key); } /** * Test method for {@link QueryResultsRegion#evict(java.lang.Object)}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * CollectionRegionAccessStrategy API. */ public void testEvict() throws Exception { evictOrRemoveTest(); } private void evictOrRemoveTest() throws Exception { Configuration cfg = createConfiguration(); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); CacheAdapter localCache = getInfinispanCache(regionFactory); boolean invalidation = localCache.isClusteredInvalidation(); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); GeneralDataRegion localRegion = (GeneralDataRegion) createRegion(regionFactory, getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); cfg = createConfiguration(); regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory, getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); assertNull("local is clean", localRegion.get(KEY)); assertNull("remote is clean", remoteRegion.get(KEY)); localRegion.put(KEY, VALUE1); assertEquals(VALUE1, localRegion.get(KEY)); // allow async propagation sleep(250); Object expected = invalidation ? null : VALUE1; assertEquals(expected, remoteRegion.get(KEY)); localRegion.evict(KEY); // allow async propagation sleep(250); assertEquals(null, localRegion.get(KEY)); assertEquals(null, remoteRegion.get(KEY)); } protected abstract String getStandardRegionName(String regionPrefix); /** * Test method for {@link QueryResultsRegion#evictAll()}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * CollectionRegionAccessStrategy API. */ public void testEvictAll() throws Exception { evictOrRemoveAllTest("entity"); } private void evictOrRemoveAllTest(String configName) throws Exception { Configuration cfg = createConfiguration(); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); CacheAdapter localCache = getInfinispanCache(regionFactory); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); GeneralDataRegion localRegion = (GeneralDataRegion) createRegion(regionFactory, getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); cfg = createConfiguration(); regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); CacheAdapter remoteCache = getInfinispanCache(regionFactory); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory, getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); Set keys = localCache.keySet(); assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); keys = remoteCache.keySet(); assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); assertNull("local is clean", localRegion.get(KEY)); assertNull("remote is clean", remoteRegion.get(KEY)); localRegion.put(KEY, VALUE1); assertEquals(VALUE1, localRegion.get(KEY)); // Allow async propagation sleep(250); remoteRegion.put(KEY, VALUE1); assertEquals(VALUE1, remoteRegion.get(KEY)); // Allow async propagation sleep(250); localRegion.evictAll(); // allow async propagation sleep(250); // This should re-establish the region root node in the optimistic case assertNull(localRegion.get(KEY)); assertEquals("No valid children in " + keys, 0, getValidKeyCount(localCache.keySet())); // Re-establishing the region root on the local node doesn't // propagate it to other nodes. Do a get on the remote node to re-establish // This only adds a node in the case of optimistic locking assertEquals(null, remoteRegion.get(KEY)); assertEquals("No valid children in " + keys, 0, getValidKeyCount(remoteCache.keySet())); assertEquals("local is clean", null, localRegion.get(KEY)); assertEquals("remote is clean", null, remoteRegion.get(KEY)); } protected Configuration createConfiguration() { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, false, true); return cfg; } protected void rollback() { try { BatchModeTransactionManager.getInstance().rollback(); } catch (Exception e) { log.error(e.getMessage(), e); } } }././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaTransactionManagerImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000736011714611271032630 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.tm; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; /** * XaResourceCapableTransactionManagerImpl. * * @author Galder Zamarreño * @since 3.5 */ public class XaTransactionManagerImpl implements TransactionManager { private static final XaTransactionManagerImpl INSTANCE = new XaTransactionManagerImpl(); private XaTransactionImpl currentTransaction; public static XaTransactionManagerImpl getInstance() { return INSTANCE; } public int getStatus() throws SystemException { return currentTransaction == null ? Status.STATUS_NO_TRANSACTION : currentTransaction.getStatus(); } public Transaction getTransaction() throws SystemException { return currentTransaction; } public XaTransactionImpl getCurrentTransaction() { return currentTransaction; } public void begin() throws NotSupportedException, SystemException { currentTransaction = new XaTransactionImpl(this); } public Transaction suspend() throws SystemException { Transaction suspended = currentTransaction; currentTransaction = null; return suspended; } public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { currentTransaction = (XaTransactionImpl) transaction; } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { if (currentTransaction == null) { throw new IllegalStateException("no current transaction to commit"); } currentTransaction.commit(); } public void rollback() throws IllegalStateException, SecurityException, SystemException { if (currentTransaction == null) { throw new IllegalStateException("no current transaction"); } currentTransaction.rollback(); } public void setRollbackOnly() throws IllegalStateException, SystemException { if (currentTransaction == null) { throw new IllegalStateException("no current transaction"); } currentTransaction.setRollbackOnly(); } public void setTransactionTimeout(int i) throws SystemException { } void endCurrent(Transaction transaction) { if (transaction == currentTransaction) { currentTransaction = null; } } } ././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaTransactionManagerLookup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000355211714611271032627 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.tm; import java.util.Properties; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; import org.hibernate.transaction.TransactionManagerLookup; /** * XaResourceCapableTransactionManagerLookup. * * @author Galder Zamarreño * @since 3.5 */ public class XaTransactionManagerLookup implements TransactionManagerLookup { public Object getTransactionIdentifier(Transaction transaction) { return transaction; } public TransactionManager getTransactionManager(Properties props) throws HibernateException { return XaTransactionManagerImpl.getInstance(); } public String getUserTransactionName() { throw new UnsupportedOperationException( "jndi currently not implemented for these tests" ); } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaConnectionProvider.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000532511714611271032627 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.tm; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.connection.ConnectionProvider; import org.hibernate.connection.ConnectionProviderFactory; /** * XaConnectionProvider. * * @author Galder Zamarreño * @since 3.5 */ public class XaConnectionProvider implements ConnectionProvider { private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider(); private boolean isTransactional; public static ConnectionProvider getActualConnectionProvider() { return actualConnectionProvider; } public void configure(Properties props) throws HibernateException { } public Connection getConnection() throws SQLException { XaTransactionImpl currentTransaction = XaTransactionManagerImpl.getInstance().getCurrentTransaction(); if (currentTransaction == null) { isTransactional = false; return actualConnectionProvider.getConnection(); } else { isTransactional = true; Connection connection = currentTransaction.getEnlistedConnection(); if (connection == null) { connection = actualConnectionProvider.getConnection(); currentTransaction.enlistConnection(connection); } return connection; } } public void closeConnection(Connection conn) throws SQLException { if (!isTransactional) { conn.close(); } } public void close() throws HibernateException { actualConnectionProvider.close(); } public boolean supportsAggressiveRelease() { return true; } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaTransactionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002440311714611271032625 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.tm; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionImpl; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * XaResourceCapableTransactionImpl. * * @author Galder Zamarreño * @since 3.5 */ public class XaTransactionImpl implements Transaction { private static final Log log = LogFactory.getLog(XaTransactionImpl.class); private int status; private LinkedList synchronizations; private Connection connection; // the only resource we care about is jdbc connection private final XaTransactionManagerImpl jtaTransactionManager; private List enlistedResources = new ArrayList(); private Xid xid = new XaResourceCapableTransactionXid(); public XaTransactionImpl(XaTransactionManagerImpl jtaTransactionManager) { this.jtaTransactionManager = jtaTransactionManager; this.status = Status.STATUS_ACTIVE; } public XaTransactionImpl(XaTransactionManagerImpl jtaTransactionManager, Xid xid) { this.jtaTransactionManager = jtaTransactionManager; this.status = Status.STATUS_ACTIVE; this.xid = xid; } public int getStatus() { return status; } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { if (status == Status.STATUS_MARKED_ROLLBACK) { log.trace("on commit, status was marked for rollback-only"); rollback(); } else { status = Status.STATUS_PREPARING; for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.beforeCompletion(); } if (!runXaResourcePrepare()) { status = Status.STATUS_ROLLING_BACK; } else { status = Status.STATUS_PREPARED; } status = Status.STATUS_COMMITTING; if (connection != null) { try { connection.commit(); connection.close(); } catch (SQLException sqle) { status = Status.STATUS_UNKNOWN; throw new SystemException(); } } runXaResourceCommitTx(); status = Status.STATUS_COMMITTED; for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.afterCompletion(status); } // status = Status.STATUS_NO_TRANSACTION; jtaTransactionManager.endCurrent(this); } } public void rollback() throws IllegalStateException, SystemException { status = Status.STATUS_ROLLING_BACK; runXaResourceRollback(); status = Status.STATUS_ROLLEDBACK; if (connection != null) { try { connection.rollback(); connection.close(); } catch (SQLException sqle) { status = Status.STATUS_UNKNOWN; throw new SystemException(); } } if (synchronizations != null) { for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.afterCompletion(status); } } // status = Status.STATUS_NO_TRANSACTION; jtaTransactionManager.endCurrent(this); } public void setRollbackOnly() throws IllegalStateException, SystemException { status = Status.STATUS_MARKED_ROLLBACK; } public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { // todo : find the spec-allowable statuses during which synch can be registered... if (synchronizations == null) { synchronizations = new LinkedList(); } synchronizations.add(synchronization); } public void enlistConnection(Connection connection) { if (this.connection != null) { throw new IllegalStateException("Connection already registered"); } this.connection = connection; } public Connection getEnlistedConnection() { return connection; } public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException { enlistedResources.add(new WrappedXaResource(xaResource)); try { xaResource.start(xid, 0); } catch (XAException e) { log.error("Got an exception", e); throw new SystemException(e.getMessage()); } return true; } public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException { throw new SystemException("not supported"); } public Collection getEnlistedResources() { return enlistedResources; } private boolean runXaResourcePrepare() throws SystemException { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.prepare(xid); } catch (XAException e) { log.trace("The resource wants to rollback!", e); return false; } catch (Throwable th) { log.error("Unexpected error from resource manager!", th); throw new SystemException(th.getMessage()); } } return true; } private void runXaResourceRollback() { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.rollback(xid); } catch (XAException e) { log.warn("Error while rolling back",e); } } } private boolean runXaResourceCommitTx() throws HeuristicMixedException { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.commit(xid, false);//todo we only support one phase commit for now, change this!!! } catch (XAException e) { log.warn("exception while committing",e); throw new HeuristicMixedException(e.getMessage()); } } return true; } private static class XaResourceCapableTransactionXid implements Xid { private static AtomicInteger txIdCounter = new AtomicInteger(0); private int id = txIdCounter.incrementAndGet(); public int getFormatId() { return id; } public byte[] getGlobalTransactionId() { throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!! } public byte[] getBranchQualifier() { throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!! } @Override public String toString() { return getClass().getSimpleName() + "{" + "id=" + id + '}'; } } private class WrappedXaResource implements XAResource { private final XAResource xaResource; private int prepareResult; public WrappedXaResource(XAResource xaResource) { this.xaResource = xaResource; } @Override public void commit(Xid xid, boolean b) throws XAException { // Commit only if not read only. if (prepareResult != XAResource.XA_RDONLY) xaResource.commit(xid, b); else log.trace("Not committing {0} due to readonly.", xid); } @Override public void end(Xid xid, int i) throws XAException { xaResource.end(xid, i); } @Override public void forget(Xid xid) throws XAException { xaResource.forget(xid); } @Override public int getTransactionTimeout() throws XAException { return xaResource.getTransactionTimeout(); } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return xaResource.isSameRM(xaResource); } @Override public int prepare(Xid xid) throws XAException { prepareResult = xaResource.prepare(xid); return prepareResult; } @Override public Xid[] recover(int i) throws XAException { return xaResource.recover(i); } @Override public void rollback(Xid xid) throws XAException { xaResource.rollback(xid); } @Override public boolean setTransactionTimeout(int i) throws XAException { return xaResource.setTransactionTimeout(i); } @Override public void start(Xid xid, int i) throws XAException { xaResource.start(xid, i); } } } ././@LongLink0000000000000000000000000000022500000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002756311714611271032637 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.tm; import junit.framework.TestCase; import org.enhydra.jdbc.standard.StandardXADataSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; import org.hibernate.stat.Statistics; import org.hibernate.test.cache.infinispan.functional.Item; import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jboss.util.naming.NonSerializableFactory; import org.jnp.interfaces.NamingContext; import org.jnp.server.Main; import org.jnp.server.NamingServer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.transaction.Status; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.Properties; /** * This is an example test based on http://community.jboss.org/docs/DOC-14617 that shows how to interact with * Hibernate configured with Infinispan second level cache provider using JTA transactions. * * In this test, an XADataSource wrapper is in use where we have associated our transaction manager to it so that * commits/rollbacks are propagated to the database as well. * * @author Galder Zamarreño * @since 3.5 */ public class JBossStandaloneJtaExampleTest extends TestCase { private static final Log log = LogFactory.getLog(JBossStandaloneJtaExampleTest.class); private static final JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup(); Context ctx; Main jndiServer; @Override protected void setUp() throws Exception { super.setUp(); jndiServer = startJndiServer(); ctx = createJndiContext(); bindTransactionManager(); bindUserTransaction(); bindDataSource(); } @Override protected void tearDown() throws Exception { super.tearDown(); ctx.close(); jndiServer.stop(); } public void testPersistAndLoadUnderJta() throws Exception { Item item; SessionFactory sessionFactory = buildSessionFactory(); try { UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); item = new Item("anItem", "An item owned by someone"); session.persist(item); session.getTransaction().commit(); session.close(); } catch(Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); Item found = (Item) session.load(Item.class, item.getId()); Statistics stats = session.getSessionFactory().getStatistics(); log.info(stats.toString()); assertEquals(item.getDescription(), found.getDescription()); assertEquals(0, stats.getSecondLevelCacheMissCount()); assertEquals(1, stats.getSecondLevelCacheHitCount()); session.delete(found); session.getTransaction().commit(); session.close(); } catch(Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); assertNull(session.get(Item.class, item.getId())); session.getTransaction().commit(); session.close(); } catch(Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } } finally { if (sessionFactory != null) sessionFactory.close(); } } public static class ExtendedXADataSource extends StandardXADataSource { // XAPOOL @Override public Connection getConnection() throws SQLException { if (getTransactionManager() == null) { // although already set before, it results null again after retrieving the datasource by jndi TransactionManager tm; // this is because the TransactionManager information is not serialized. try { tm = lookup.getTransactionManager(); } catch (Exception e) { throw new SQLException(e); } setTransactionManager(tm); // resets the TransactionManager on the datasource retrieved by jndi, // this makes the datasource JTA-aware } // According to Enhydra documentation, here we must return the connection of our XAConnection // see http://cvs.forge.objectweb.org/cgi-bin/viewcvs.cgi/xapool/xapool/examples/xapooldatasource/DatabaseHelper.java?sortby=rev return super.getXAConnection().getConnection(); } @Override public T unwrap(Class iface) throws SQLException { return null; // JDK6 stuff } @Override public boolean isWrapperFor(Class iface) throws SQLException { return false; // JDK6 stuff } } private Main startJndiServer() throws Exception { // Create an in-memory jndi NamingServer namingServer = new NamingServer(); NamingContext.setLocal(namingServer); Main namingMain = new Main(); namingMain.setInstallGlobalService(true); namingMain.setPort(-1); namingMain.start(); return namingMain; } private Context createJndiContext() throws Exception { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); return new InitialContext(props); } private void bindTransactionManager() throws Exception { // as JBossTransactionManagerLookup extends JNDITransactionManagerLookup we must also register the TransactionManager bind("java:/TransactionManager", lookup.getTransactionManager(), lookup.getTransactionManager().getClass(), ctx); } private void bindUserTransaction() throws Exception { // also the UserTransaction must be registered on jndi: org.hibernate.transaction.JTATransactionFactory#getUserTransaction() requires this bind("UserTransaction", lookup.getUserTransaction(), lookup.getUserTransaction().getClass(), ctx); } private void bindDataSource() throws Exception { ExtendedXADataSource xads = new ExtendedXADataSource(); xads.setDriverName("org.hsqldb.jdbcDriver"); xads.setUrl("jdbc:hsqldb:mem:/test"); ctx.bind("java:/MyDatasource", xads); } /** * Helper method that binds the a non serializable object to the JNDI tree. * * @param jndiName Name under which the object must be bound * @param who Object to bind in JNDI * @param classType Class type under which should appear the bound object * @param ctx Naming context under which we bind the object * @throws Exception Thrown if a naming exception occurs during binding */ private void bind(String jndiName, Object who, Class classType, Context ctx) throws Exception { // Ah ! This service isn't serializable, so we use a helper class NonSerializableFactory.bind(jndiName, who); Name n = ctx.getNameParser("").parse(jndiName); while (n.size() > 1) { String ctxName = n.get(0); try { ctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException e) { System.out.println("Creating subcontext:" + ctxName); ctx = ctx.createSubcontext(ctxName); } n = n.getSuffix(1); } // The helper class NonSerializableFactory uses address type nns, we go on to // use the helper class to bind the service object in JNDI StringRefAddr addr = new StringRefAddr("nns", jndiName); Reference ref = new Reference(classType.getName(), addr, NonSerializableFactory.class.getName(), null); ctx.rebind(n.get(0), ref); } private void unbind(String jndiName, Context ctx) throws Exception { NonSerializableFactory.unbind(jndiName); ctx.unbind(jndiName); } private SessionFactory buildSessionFactory() { // Extra options located in src/test/resources/hibernate.properties Configuration cfg = new Configuration(); cfg.setProperty(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect"); cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); cfg.setProperty(Environment.DATASOURCE, "java:/MyDatasource"); cfg.setProperty(Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory"); cfg.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.transaction.JBossTransactionManagerLookup"); cfg.setProperty(Environment.TRANSACTION_STRATEGY, "org.hibernate.transaction.JTATransactionFactory"); cfg.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "jta"); cfg.setProperty(Environment.RELEASE_CONNECTIONS, "auto"); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); cfg.setProperty(Environment.CACHE_REGION_FACTORY, "org.hibernate.cache.infinispan.InfinispanRegionFactory"); String[] mappings = new String[]{"org/hibernate/test/cache/infinispan/functional/Item.hbm.xml"}; for (String mapping : mappings) { cfg.addResource(mapping, Thread.currentThread().getContextClassLoader()); } cfg.buildMappings(); Iterator iter = cfg.getClassMappings(); while (iter.hasNext()) { PersistentClass clazz = (PersistentClass) iter.next(); cfg.setCacheConcurrencyStrategy(clazz.getEntityName(), "transactional"); } iter = cfg.getCollectionMappings(); while (iter.hasNext()) { Collection coll = (Collection) iter.next(); cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), "transactional"); } return cfg.buildSessionFactory(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000024600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000005703111714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.entity; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.extensions.TestSetup; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.impl.CacheDataDescriptionImpl; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.impl.BaseRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.hibernate.util.ComparableComparator; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of EntityRegionAccessStrategy impls. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractEntityRegionAccessStrategyTestCase extends AbstractNonFunctionalTestCase { public static final String REGION_NAME = "test/com.foo.test"; public static final String KEY_BASE = "KEY"; public static final String VALUE1 = "VALUE1"; public static final String VALUE2 = "VALUE2"; protected static int testCount; protected static Configuration localCfg; protected static InfinispanRegionFactory localRegionFactory; protected CacheAdapter localCache; protected static Configuration remoteCfg; protected static InfinispanRegionFactory remoteRegionFactory; protected CacheAdapter remoteCache; protected boolean invalidation; protected boolean synchronous; protected EntityRegion localEntityRegion; protected EntityRegionAccessStrategy localAccessStrategy; protected EntityRegion remoteEntityRegion; protected EntityRegionAccessStrategy remoteAccessStrategy; protected Exception node1Exception; protected Exception node2Exception; protected AssertionFailedError node1Failure; protected AssertionFailedError node2Failure; public static Test getTestSetup(Class testClass, String configName) { TestSuite suite = new TestSuite(testClass); return new AccessStrategyTestSetup(suite, configName); } public static Test getTestSetup(Test test, String configName) { return new AccessStrategyTestSetup(test, configName); } /** * Create a new TransactionalAccessTestCase. * * @param name */ public AbstractEntityRegionAccessStrategyTestCase(String name) { super(name); } protected abstract AccessType getAccessType(); protected void setUp() throws Exception { super.setUp(); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); localEntityRegion = localRegionFactory.buildEntityRegion(REGION_NAME, localCfg .getProperties(), getCacheDataDescription()); localAccessStrategy = localEntityRegion.buildAccessStrategy(getAccessType()); localCache = ((BaseRegion) localEntityRegion).getCacheAdapter(); invalidation = localCache.isClusteredInvalidation(); synchronous = localCache.isSynchronous(); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); remoteEntityRegion = remoteRegionFactory.buildEntityRegion(REGION_NAME, remoteCfg .getProperties(), getCacheDataDescription()); remoteAccessStrategy = remoteEntityRegion.buildAccessStrategy(getAccessType()); remoteCache = ((BaseRegion) remoteEntityRegion).getCacheAdapter(); node1Exception = null; node2Exception = null; node1Failure = null; node2Failure = null; } protected void tearDown() throws Exception { super.tearDown(); try { localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); } catch (Exception e) { log.error("Problem purging local cache", e); } try { remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); } catch (Exception e) { log.error("Problem purging remote cache", e); } node1Exception = null; node2Exception = null; node1Failure = null; node2Failure = null; } protected static Configuration createConfiguration(String configName) { Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); return cfg; } protected CacheDataDescription getCacheDataDescription() { return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); } protected boolean isUsingInvalidation() { return invalidation; } protected boolean isSynchronous() { return synchronous; } protected void assertThreadsRanCleanly() { if (node1Failure != null) throw node1Failure; if (node2Failure != null) throw node2Failure; if (node1Exception != null) { log.error("node1 saw an exception", node1Exception); assertEquals("node1 saw no exceptions", null, node1Exception); } if (node2Exception != null) { log.error("node2 saw an exception", node2Exception); assertEquals("node2 saw no exceptions", null, node2Exception); } } /** * This is just a setup test where we assert that the cache config is as we expected. */ public abstract void testCacheConfiguration(); /** * Test method for {@link TransactionalAccess#getRegion()}. */ public void testGetRegion() { assertEquals("Correct region", localEntityRegion, localAccessStrategy.getRegion()); } /** * Test method for * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} * . */ public void testPutFromLoad() throws Exception { putFromLoadTest(false); } /** * Test method for * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} * . */ public void testPutFromLoadMinimal() throws Exception { putFromLoadTest(true); } /** * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First * does a putFromLoad, then an update. Second tries to do a putFromLoad with stale data (i.e. it * took longer to read from the db). Both commit their tx. Then both start a new tx and get. * First should see the updated data; second should either see the updated data (isInvalidation() * == false) or null (isInvalidation() == true). * * @param useMinimalAPI * @throws Exception */ private void putFromLoadTest(final boolean useMinimalAPI) throws Exception { final String KEY = KEY_BASE + testCount++; final CountDownLatch writeLatch1 = new CountDownLatch(1); final CountDownLatch writeLatch2 = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(2); Thread node1 = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertNull("node1 starts clean", localAccessStrategy.get(KEY, txTimestamp)); writeLatch1.await(); if (useMinimalAPI) { localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); } else { localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); } localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { // Let node2 write writeLatch2.countDown(); completionLatch.countDown(); } } }; Thread node2 = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertNull("node1 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); // Let node1 write writeLatch1.countDown(); // Wait for node1 to finish writeLatch2.await(); if (useMinimalAPI) { remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); } else { remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); } BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node2 caught exception", e); node2Exception = e; rollback(); } catch (AssertionFailedError e) { node2Failure = e; rollback(); } finally { completionLatch.countDown(); } } }; node1.setDaemon(true); node2.setDaemon(true); node1.start(); node2.start(); assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); assertThreadsRanCleanly(); long txTimestamp = System.currentTimeMillis(); assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); if (isUsingInvalidation()) { // no data version to prevent the PFER; we count on db locks preventing this assertEquals("Expected node2 value", VALUE1, remoteAccessStrategy.get(KEY, txTimestamp)); } else { // The node1 update is replicated, preventing the node2 PFER assertEquals("Correct node2 value", VALUE2, remoteAccessStrategy.get(KEY, txTimestamp)); } } /** * Test method for * {@link TransactionalAccess#insert(java.lang.Object, java.lang.Object, java.lang.Object)}. */ public void testInsert() throws Exception { final String KEY = KEY_BASE + testCount++; final CountDownLatch readLatch = new CountDownLatch(1); final CountDownLatch commitLatch = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(2); Thread inserter = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertNull("Correct initial value", localAccessStrategy.get(KEY, txTimestamp)); localAccessStrategy.insert(KEY, VALUE1, new Integer(1)); readLatch.countDown(); commitLatch.await(); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { completionLatch.countDown(); } } }; Thread reader = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); readLatch.await(); // Object expected = !isBlockingReads() ? null : VALUE1; Object expected = null; assertEquals("Correct initial value", expected, localAccessStrategy.get(KEY, txTimestamp)); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { commitLatch.countDown(); completionLatch.countDown(); } } }; inserter.setDaemon(true); reader.setDaemon(true); inserter.start(); reader.start(); assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); assertThreadsRanCleanly(); long txTimestamp = System.currentTimeMillis(); assertEquals("Correct node1 value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); Object expected = isUsingInvalidation() ? null : VALUE1; assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); } /** * Test method for * {@link TransactionalAccess#update(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)} * . */ public void testUpdate() throws Exception { final String KEY = KEY_BASE + testCount++; // Set up initial state localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); // Let the async put propagate sleep(250); final CountDownLatch readLatch = new CountDownLatch(1); final CountDownLatch commitLatch = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(2); Thread updater = new Thread("testUpdate-updater") { public void run() { boolean readerUnlocked = false; try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); log.debug("Transaction began, get initial value"); assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); log.debug("Now update value"); localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); log.debug("Notify the read latch"); readLatch.countDown(); readerUnlocked = true; log.debug("Await commit"); commitLatch.await(); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { if (!readerUnlocked) readLatch.countDown(); log.debug("Completion latch countdown"); completionLatch.countDown(); } } }; Thread reader = new Thread("testUpdate-reader") { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); log.debug("Transaction began, await read latch"); readLatch.await(); log.debug("Read latch acquired, verify local access strategy"); // This won't block w/ mvc and will read the old value Object expected = VALUE1; assertEquals("Correct value", expected, localAccessStrategy.get(KEY, txTimestamp)); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { commitLatch.countDown(); log.debug("Completion latch countdown"); completionLatch.countDown(); } } }; updater.setDaemon(true); reader.setDaemon(true); updater.start(); reader.start(); // Should complete promptly assertTrue(completionLatch.await(2, TimeUnit.SECONDS)); assertThreadsRanCleanly(); long txTimestamp = System.currentTimeMillis(); assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); Object expected = isUsingInvalidation() ? null : VALUE2; assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); } /** * Test method for {@link TransactionalAccess#remove(java.lang.Object)}. */ public void testRemove() { evictOrRemoveTest(false); } /** * Test method for {@link TransactionalAccess#removeAll()}. */ public void testRemoveAll() { evictOrRemoveAllTest(false); } /** * Test method for {@link TransactionalAccess#evict(java.lang.Object)}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * EntityRegionAccessStrategy API. */ public void testEvict() { evictOrRemoveTest(true); } /** * Test method for {@link TransactionalAccess#evictAll()}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * EntityRegionAccessStrategy API. */ public void testEvictAll() { evictOrRemoveAllTest(true); } private void evictOrRemoveTest(boolean evict) { final String KEY = KEY_BASE + testCount++; assertEquals(0, getValidKeyCount(localCache.keySet())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); if (evict) localAccessStrategy.evict(KEY); else localAccessStrategy.remove(KEY); assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(localCache.keySet())); assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); } private void evictOrRemoveAllTest(boolean evict) { final String KEY = KEY_BASE + testCount++; assertEquals(0, getValidKeyCount(localCache.keySet())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); // Wait for async propagation sleep(250); remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); // Wait for async propagation sleep(250); if (evict) { log.debug("Call evict all locally"); localAccessStrategy.evictAll(); } else { localAccessStrategy.removeAll(); } // This should re-establish the region root node in the optimistic case assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(localCache.keySet())); // Re-establishing the region root on the local node doesn't // propagate it to other nodes. Do a get on the remote node to re-establish assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); // Test whether the get above messes up the optimistic version remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(1, getValidKeyCount(remoteCache.keySet())); // Wait for async propagation sleep(250); assertEquals("local is correct", (isUsingInvalidation() ? null : VALUE1), localAccessStrategy .get(KEY, System.currentTimeMillis())); assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System .currentTimeMillis())); } protected void rollback() { try { BatchModeTransactionManager.getInstance().rollback(); } catch (Exception e) { log.error(e.getMessage(), e); } } private static class AccessStrategyTestSetup extends TestSetup { private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; private final String configName; private String preferIPv4Stack; public AccessStrategyTestSetup(Test test, String configName) { super(test); this.configName = configName; } @Override protected void setUp() throws Exception { try { super.tearDown(); } finally { if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); } // Try to ensure we use IPv4; otherwise cluster formation is very slow preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); localCfg = createConfiguration(configName); localRegionFactory = CacheTestUtil.startRegionFactory(localCfg); remoteCfg = createConfiguration(configName); remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg); } @Override protected void tearDown() throws Exception { super.tearDown(); if (localRegionFactory != null) localRegionFactory.stop(); if (remoteRegionFactory != null) remoteRegionFactory.stop(); } } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/ReadOnlyTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000371511714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.entity; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests READ_ONLY access when pessimistic locking and invalidation are used. * * @author Galder Zamarreño * @since 3.5 */ public class ReadOnlyTestCase extends AbstractReadOnlyAccessTestCase { /** * Create a new PessimisticTransactionalAccessTestCase. * * @param name */ public ReadOnlyTestCase(String name) { super(name); } public static Test suite() throws Exception { TestSuite suite = CacheTestUtil.createFailureExpectedSuite(ReadOnlyTestCase.class); return getTestSetup(suite, "entity"); } // Known failures // Overrides @Override public void testCacheConfiguration() { assertTrue("Using Invalidation", isUsingInvalidation()); } } ././@LongLink0000000000000000000000000000022400000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/EntityRegionImplTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000710211714611271032622 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.entity; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.Region; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.test.cache.infinispan.AbstractEntityCollectionRegionTestCase; /** * Tests of EntityRegionImpl. * * @author Galder Zamarreño * @since 3.5 */ public class EntityRegionImplTestCase extends AbstractEntityCollectionRegionTestCase { public EntityRegionImplTestCase(String name) { super(name); } @Override protected void supportedAccessTypeTest(RegionFactory regionFactory, Properties properties) { EntityRegion region = regionFactory.buildEntityRegion("test", properties, null); assertNull("Got TRANSACTIONAL", region.buildAccessStrategy(AccessType.TRANSACTIONAL) .lockRegion()); try { region.buildAccessStrategy(AccessType.READ_ONLY).lockRegion(); fail("Did not get READ_ONLY"); } catch (UnsupportedOperationException good) { } try { region.buildAccessStrategy(AccessType.NONSTRICT_READ_WRITE); fail("Incorrectly got NONSTRICT_READ_WRITE"); } catch (CacheException good) { } try { region.buildAccessStrategy(AccessType.READ_WRITE); fail("Incorrectly got READ_WRITE"); } catch (CacheException good) { } } @Override protected void putInRegion(Region region, Object key, Object value) { ((EntityRegion) region).buildAccessStrategy(AccessType.TRANSACTIONAL).insert(key, value, new Integer(1)); } @Override protected void removeFromRegion(Region region, Object key) { ((EntityRegion) region).buildAccessStrategy(AccessType.TRANSACTIONAL).remove(key); } @Override protected Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd) { return regionFactory.buildEntityRegion(regionName, properties, cdd); } @Override protected CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory) { return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache(InfinispanRegionFactory.DEF_ENTITY_RESOURCE)); } } ././@LongLink0000000000000000000000000000023700000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractTransactionalAccessTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001062711714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.entity; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.AssertionFailedError; import org.hibernate.cache.access.AccessType; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of TRANSACTIONAL access. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractTransactionalAccessTestCase extends AbstractEntityRegionAccessStrategyTestCase { public AbstractTransactionalAccessTestCase(String name) { super(name); } @Override protected AccessType getAccessType() { return AccessType.TRANSACTIONAL; } public void testContestedPutFromLoad() throws Exception { final String KEY = KEY_BASE + testCount++; localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); final CountDownLatch pferLatch = new CountDownLatch(1); final CountDownLatch pferCompletionLatch = new CountDownLatch(1); final CountDownLatch commitLatch = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(1); Thread blocker = new Thread("Blocker") { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); pferLatch.countDown(); commitLatch.await(); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { completionLatch.countDown(); } } }; Thread putter = new Thread("Putter") { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { pferCompletionLatch.countDown(); } } }; blocker.start(); assertTrue("Active tx has done an update", pferLatch.await(1, TimeUnit.SECONDS)); putter.start(); assertTrue("putFromLoadreturns promtly", pferCompletionLatch.await(10, TimeUnit.MILLISECONDS)); commitLatch.countDown(); assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); assertThreadsRanCleanly(); long txTimestamp = System.currentTimeMillis(); assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); } } ././@LongLink0000000000000000000000000000022400000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/ReadOnlyExtraAPITestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000640111714611271032623 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.entity; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.EntityRegionAccessStrategy; /** * Tests for the "extra API" in EntityRegionAccessStrategy; *

* By "extra API" we mean those methods that are superfluous to the * function of the Infinispan integration, where the impl is a no-op or a static * false return value, UnsupportedOperationException, etc. * * @author Galder Zamarreño * @since 3.5 */ public class ReadOnlyExtraAPITestCase extends TransactionalExtraAPITestCase { private static EntityRegionAccessStrategy localAccessStrategy; public ReadOnlyExtraAPITestCase(String name) { super(name); } @Override protected AccessType getAccessType() { return AccessType.READ_ONLY; } @Override protected EntityRegionAccessStrategy getEntityAccessStrategy() { return localAccessStrategy; } @Override protected void setEntityRegionAccessStrategy(EntityRegionAccessStrategy strategy) { localAccessStrategy = strategy; } /** * Test method for {@link TransactionalAccess#lockItem(java.lang.Object, java.lang.Object)}. */ @Override public void testLockItem() { try { getEntityAccessStrategy().lockItem(KEY, new Integer(1)); fail("Call to lockItem did not throw exception"); } catch (UnsupportedOperationException expected) {} } /** * Test method for {@link TransactionalAccess#lockRegion()}. */ @Override public void testLockRegion() { try { getEntityAccessStrategy().lockRegion(); fail("Call to lockRegion did not throw exception"); } catch (UnsupportedOperationException expected) {} } /** * Test method for {@link TransactionalAccess#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, org.hibernate.cache.access.SoftLock)}. */ @Override public void testAfterUpdate() { try { getEntityAccessStrategy().afterUpdate(KEY, VALUE2, new Integer(1), new Integer(2), new MockSoftLock()); fail("Call to afterUpdate did not throw exception"); } catch (UnsupportedOperationException expected) {} } } ././@LongLink0000000000000000000000000000023200000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractReadOnlyAccessTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000635211714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.entity; import org.hibernate.cache.access.AccessType; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of TRANSACTIONAL access. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractReadOnlyAccessTestCase extends AbstractEntityRegionAccessStrategyTestCase { /** * Create a new AbstractTransactionalAccessTestCase. * */ public AbstractReadOnlyAccessTestCase(String name) { super(name); } @Override protected AccessType getAccessType() { return AccessType.READ_ONLY; } @Override public void testPutFromLoad() throws Exception { putFromLoadTest(false); } @Override public void testPutFromLoadMinimal() throws Exception { putFromLoadTest(true); } private void putFromLoadTest(boolean minimal) throws Exception { final String KEY = KEY_BASE + testCount++; long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); if (minimal) localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); else localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); sleep(250); Object expected = isUsingInvalidation() ? null : VALUE1; assertEquals(expected, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); BatchModeTransactionManager.getInstance().commit(); assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(expected, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); } @Override public void testUpdate() throws Exception { final String KEY = KEY_BASE + testCount++; try { localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); fail("Call to update did not throw exception"); } catch (UnsupportedOperationException good) {} } } ././@LongLink0000000000000000000000000000023100000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/TransactionalExtraAPITestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001242111714611271032622 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.entity; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; /** * Tests for the "extra API" in EntityRegionAccessStrategy;. *

* By "extra API" we mean those methods that are superfluous to the * function of the JBC integration, where the impl is a no-op or a static * false return value, UnsupportedOperationException, etc. * * @author Galder Zamarreño * @since 3.5 */ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase { public TransactionalExtraAPITestCase(String name) { super(name); } public static final String REGION_NAME = "test/com.foo.test"; public static final String KEY = "KEY"; public static final String VALUE1 = "VALUE1"; public static final String VALUE2 = "VALUE2"; private static EntityRegionAccessStrategy localAccessStrategy; private static boolean optimistic; protected void setUp() throws Exception { super.setUp(); if (getEntityAccessStrategy() == null) { Configuration cfg = createConfiguration(); InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); EntityRegion localEntityRegion = rf.buildEntityRegion(REGION_NAME, cfg.getProperties(), null); setEntityRegionAccessStrategy(localEntityRegion.buildAccessStrategy(getAccessType())); } } protected void tearDown() throws Exception { super.tearDown(); } protected Configuration createConfiguration() { Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, getCacheConfigName()); return cfg; } protected String getCacheConfigName() { return "entity"; } protected AccessType getAccessType() { return AccessType.TRANSACTIONAL; } protected EntityRegionAccessStrategy getEntityAccessStrategy() { return localAccessStrategy; } protected void setEntityRegionAccessStrategy(EntityRegionAccessStrategy strategy) { localAccessStrategy = strategy; } /** * Test method for {@link TransactionalAccess#lockItem(java.lang.Object, java.lang.Object)}. */ public void testLockItem() { assertNull(getEntityAccessStrategy().lockItem(KEY, new Integer(1))); } /** * Test method for {@link TransactionalAccess#lockRegion()}. */ public void testLockRegion() { assertNull(getEntityAccessStrategy().lockRegion()); } /** * Test method for {@link TransactionalAccess#unlockItem(java.lang.Object, org.hibernate.cache.access.SoftLock)}. */ public void testUnlockItem() { getEntityAccessStrategy().unlockItem(KEY, new MockSoftLock()); } /** * Test method for {@link TransactionalAccess#unlockRegion(org.hibernate.cache.access.SoftLock)}. */ public void testUnlockRegion() { getEntityAccessStrategy().unlockItem(KEY, new MockSoftLock()); } /** * Test method for {@link TransactionalAccess#afterInsert(java.lang.Object, java.lang.Object, java.lang.Object)}. */ public void testAfterInsert() { assertFalse("afterInsert always returns false", getEntityAccessStrategy().afterInsert(KEY, VALUE1, new Integer(1))); } /** * Test method for {@link TransactionalAccess#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, org.hibernate.cache.access.SoftLock)}. */ public void testAfterUpdate() { assertFalse("afterInsert always returns false", getEntityAccessStrategy().afterUpdate(KEY, VALUE2, new Integer(1), new Integer(2), new MockSoftLock())); } public static class MockSoftLock implements SoftLock { } } ././@LongLink0000000000000000000000000000023400000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/InvalidatedTransactionalTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000353011714611271032623 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.entity; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import junit.framework.Test; import junit.framework.TestSuite; /** * InvalidatedTransactionalTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class InvalidatedTransactionalTestCase extends AbstractTransactionalAccessTestCase { public InvalidatedTransactionalTestCase(String name) { super(name); } @Override public void testCacheConfiguration() { assertTrue("Using Invalidation", isUsingInvalidation()); assertTrue("Synchronous mode", isSynchronous()); } public static Test suite() throws Exception { TestSuite suite = CacheTestUtil.createFailureExpectedSuite(InvalidatedTransactionalTestCase.class); return getTestSetup(suite, "entity"); } } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractRegionImplTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000440511714611271032625 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.Region; import org.hibernate.cache.impl.CacheDataDescriptionImpl; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.util.ComparableComparator; /** * Base class for tests of Region implementations. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractRegionImplTestCase extends AbstractNonFunctionalTestCase { public AbstractRegionImplTestCase(String name) { super(name); } protected abstract CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory); protected abstract Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd); protected abstract void putInRegion(Region region, Object key, Object value); protected abstract void removeFromRegion(Region region, Object key); protected CacheDataDescription getCacheDataDescription() { return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); } } ././@LongLink0000000000000000000000000000022400000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/InfinispanRegionFactoryTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000007440511714611271032634 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan; import java.util.Properties; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.collection.CollectionRegionImpl; import org.hibernate.cache.infinispan.entity.EntityRegionImpl; import org.hibernate.cache.infinispan.query.QueryResultsRegionImpl; import org.hibernate.cache.infinispan.timestamp.TimestampsRegionImpl; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.infinispan.config.Configuration; import org.infinispan.config.Configuration.CacheMode; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.manager.DefaultCacheManager; import junit.framework.TestCase; import org.infinispan.manager.EmbeddedCacheManager; /** * InfinispanRegionFactoryTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class InfinispanRegionFactoryTestCase extends TestCase { public void testConfigurationProcessing() { final String person = "com.acme.Person"; final String addresses = "com.acme.Person.addresses"; Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "person-addresses-cache"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "120000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "60000"); p.setProperty("hibernate.cache.infinispan.query.cfg", "my-query-cache"); p.setProperty("hibernate.cache.infinispan.query.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.query.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.query.eviction.max_entries", "10000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); assertEquals("entity", factory.getTypeOverrides().get("entity").getCacheName()); assertEquals("entity", factory.getTypeOverrides().get("collection").getCacheName()); assertEquals("timestamps", factory.getTypeOverrides().get("timestamps").getCacheName()); assertEquals("person-cache", factory.getTypeOverrides().get(person).getCacheName()); assertEquals(EvictionStrategy.LRU, factory.getTypeOverrides().get(person).getEvictionStrategy()); assertEquals(2000, factory.getTypeOverrides().get(person).getEvictionWakeUpInterval()); assertEquals(5000, factory.getTypeOverrides().get(person).getEvictionMaxEntries()); assertEquals(60000, factory.getTypeOverrides().get(person).getExpirationLifespan()); assertEquals(30000, factory.getTypeOverrides().get(person).getExpirationMaxIdle()); assertEquals("person-addresses-cache", factory.getTypeOverrides().get(addresses).getCacheName()); assertEquals(120000, factory.getTypeOverrides().get(addresses).getExpirationLifespan()); assertEquals(60000, factory.getTypeOverrides().get(addresses).getExpirationMaxIdle()); assertEquals("my-query-cache", factory.getTypeOverrides().get("query").getCacheName()); assertEquals(EvictionStrategy.FIFO, factory.getTypeOverrides().get("query").getEvictionStrategy()); assertEquals(3000, factory.getTypeOverrides().get("query").getEvictionWakeUpInterval()); assertEquals(10000, factory.getTypeOverrides().get("query").getEvictionMaxEntries()); } public void testBuildEntityCollectionRegionsPersonPlusEntityCollectionOverrides() { final String person = "com.acme.Person"; final String address = "com.acme.Address"; final String car = "com.acme.Car"; final String addresses = "com.acme.Person.addresses"; final String parts = "com.acme.Car.parts"; Properties p = new Properties(); // First option, cache defined for entity and overrides for generic entity data type and entity itself. p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "20000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "addresses-cache"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.wake_up_interval", "2500"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.max_entries", "5500"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "65000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "35000"); p.setProperty("hibernate.cache.infinispan.collection.cfg", "mycollection-cache"); p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500"); p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "25000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { assertFalse(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics()); assertNotNull(factory.getTypeOverrides().get(person)); assertFalse(factory.getDefinedConfigurations().contains(person)); assertNotNull(factory.getTypeOverrides().get(addresses)); assertFalse(factory.getDefinedConfigurations().contains(addresses)); CacheAdapter cache = null; EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null); assertNotNull(factory.getTypeOverrides().get(person)); assertTrue(factory.getDefinedConfigurations().contains(person)); assertNull(factory.getTypeOverrides().get(address)); cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy()); assertEquals(2000, cacheCfg.getEvictionWakeUpInterval()); assertEquals(5000, cacheCfg.getEvictionMaxEntries()); assertEquals(60000, cacheCfg.getExpirationLifespan()); assertEquals(30000, cacheCfg.getExpirationMaxIdle()); assertFalse(cacheCfg.isExposeJmxStatistics()); region = (EntityRegionImpl) factory.buildEntityRegion(address, p, null); assertNotNull(factory.getTypeOverrides().get(person)); assertTrue(factory.getDefinedConfigurations().contains(person)); assertNull(factory.getTypeOverrides().get(address)); cache = region.getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy()); assertEquals(3000, cacheCfg.getEvictionWakeUpInterval()); assertEquals(20000, cacheCfg.getEvictionMaxEntries()); assertFalse(cacheCfg.isExposeJmxStatistics()); region = (EntityRegionImpl) factory.buildEntityRegion(car, p, null); assertNotNull(factory.getTypeOverrides().get(person)); assertTrue(factory.getDefinedConfigurations().contains(person)); assertNull(factory.getTypeOverrides().get(address)); cache = region.getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy()); assertEquals(3000, cacheCfg.getEvictionWakeUpInterval()); assertEquals(20000, cacheCfg.getEvictionMaxEntries()); assertFalse(cacheCfg.isExposeJmxStatistics()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(addresses, p, null); assertNotNull(factory.getTypeOverrides().get(addresses)); assertTrue(factory.getDefinedConfigurations().contains(person)); assertNull(factory.getTypeOverrides().get(parts)); cache = collectionRegion .getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy()); assertEquals(2500, cacheCfg.getEvictionWakeUpInterval()); assertEquals(5500, cacheCfg.getEvictionMaxEntries()); assertEquals(65000, cacheCfg.getExpirationLifespan()); assertEquals(35000, cacheCfg.getExpirationMaxIdle()); assertFalse(cacheCfg.isExposeJmxStatistics()); collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null); assertNotNull(factory.getTypeOverrides().get(addresses)); assertTrue(factory.getDefinedConfigurations().contains(addresses)); assertNull(factory.getTypeOverrides().get(parts)); cache = collectionRegion.getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy()); assertEquals(3500, cacheCfg.getEvictionWakeUpInterval()); assertEquals(25000, cacheCfg.getEvictionMaxEntries()); assertFalse(cacheCfg.isExposeJmxStatistics()); collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null); assertNotNull(factory.getTypeOverrides().get(addresses)); assertTrue(factory.getDefinedConfigurations().contains(addresses)); assertNull(factory.getTypeOverrides().get(parts)); cache = collectionRegion.getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy()); assertEquals(3500, cacheCfg.getEvictionWakeUpInterval()); assertEquals(25000, cacheCfg.getEvictionMaxEntries()); assertFalse(cacheCfg.isExposeJmxStatistics()); } finally { factory.stop(); } } public void testBuildEntityCollectionRegionOverridesOnly() { CacheAdapter cache = null; Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "30000"); p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500"); p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "35000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); factory.getCacheManager(); try { EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null); assertNull(factory.getTypeOverrides().get("com.acme.Address")); cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy()); assertEquals(3000, cacheCfg.getEvictionWakeUpInterval()); assertEquals(30000, cacheCfg.getEvictionMaxEntries()); assertEquals(100000, cacheCfg.getExpirationMaxIdle()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null); assertNull(factory.getTypeOverrides().get("com.acme.Person.addresses")); cache = collectionRegion.getCacheAdapter(); cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy()); assertEquals(3500, cacheCfg.getEvictionWakeUpInterval()); assertEquals(35000, cacheCfg.getEvictionMaxEntries()); assertEquals(100000, cacheCfg.getExpirationMaxIdle()); } finally { factory.stop(); } } public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() { final String person = "com.acme.Person"; Properties p = new Properties(); // Third option, no cache defined for entity and overrides for generic entity data type and entity itself. p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { assertNotNull(factory.getTypeOverrides().get(person)); assertFalse(factory.getDefinedConfigurations().contains(person)); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null); assertNotNull(factory.getTypeOverrides().get(person)); assertTrue(factory.getDefinedConfigurations().contains(person)); CacheAdapter cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy()); assertEquals(3000, cacheCfg.getEvictionWakeUpInterval()); assertEquals(10000, cacheCfg.getEvictionMaxEntries()); assertEquals(60000, cacheCfg.getExpirationLifespan()); assertEquals(30000, cacheCfg.getExpirationMaxIdle()); } finally { factory.stop(); } } public void testTimestampValidation() { Properties p = new Properties(); final DefaultCacheManager manager = new DefaultCacheManager(); InfinispanRegionFactory factory = new InfinispanRegionFactory() { @Override protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { return manager; } }; Configuration config = new Configuration(); config.setCacheMode(CacheMode.INVALIDATION_SYNC); manager.defineConfiguration("timestamps", config); try { factory.start(null, p); fail("Should have failed saying that invalidation is not allowed for timestamp caches."); } catch(CacheException ce) { } } public void testBuildDefaultTimestampsRegion() { final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); try { assertTrue(factory.getDefinedConfigurations().contains("timestamps")); assertTrue(factory.getTypeOverrides().get("timestamps").getCacheName().equals("timestamps")); Configuration config = new Configuration(); config.setFetchInMemoryState(false); manager.defineConfiguration("timestamps", config); TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); CacheAdapter cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.NONE, cacheCfg.getEvictionStrategy()); assertEquals(CacheMode.REPL_ASYNC, cacheCfg.getCacheMode()); assertTrue(cacheCfg.isUseLazyDeserialization()); assertFalse(cacheCfg.isExposeJmxStatistics()); } finally { factory.stop(); } } public void testBuildDiffCacheNameTimestampsRegion() { final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); try { assertFalse(factory.getDefinedConfigurations().contains("timestamp")); assertTrue(factory.getDefinedConfigurations().contains("unrecommended-timestamps")); assertTrue(factory.getTypeOverrides().get("timestamps").getCacheName().equals("unrecommended-timestamps")); Configuration config = new Configuration(); config.setFetchInMemoryState(false); config.setCacheMode(CacheMode.REPL_SYNC); manager.defineConfiguration("unrecommended-timestamps", config); TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); CacheAdapter cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.NONE, cacheCfg.getEvictionStrategy()); assertEquals(CacheMode.REPL_SYNC, cacheCfg.getCacheMode()); assertFalse(cacheCfg.isUseLazyDeserialization()); assertFalse(cacheCfg.isExposeJmxStatistics()); } finally { factory.stop(); } } public void testBuildTimestamRegionWithCacheNameOverride() { final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache"); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { factory.buildTimestampsRegion(timestamps, p); assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache")); } finally { factory.stop(); } } public void testBuildTimestamRegionWithFifoEvictionOverride() { final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000"); try { factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); factory.buildTimestampsRegion(timestamps, p); assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache")); fail("Should fail cos no eviction configurations are allowed for timestamp caches"); } catch(CacheException ce) { } finally { factory.stop(); } } public void testBuildTimestamRegionWithNoneEvictionOverride() { final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "timestamps-none-eviction"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "NONE"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000"); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { factory.buildTimestampsRegion(timestamps, p); assertTrue(factory.getDefinedConfigurations().contains("timestamps-none-eviction")); } finally { factory.stop(); } } public void testBuildQueryRegion() { final String query = "org.hibernate.cache.StandardQueryCache"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { assertTrue(factory.getDefinedConfigurations().contains("local-query")); QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p); CacheAdapter cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(CacheMode.LOCAL, cacheCfg.getCacheMode()); assertFalse(cacheCfg.isExposeJmxStatistics()); } finally { factory.stop(); } } public void testBuildQueryRegionWithCustomRegionName() { final String queryRegionName = "myquery"; Properties p = new Properties(); InfinispanRegionFactory factory = new InfinispanRegionFactory(); p.setProperty("hibernate.cache.infinispan.myquery.cfg", "timestamps-none-eviction"); p.setProperty("hibernate.cache.infinispan.myquery.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.myquery.eviction.wake_up_interval", "2222"); p.setProperty("hibernate.cache.infinispan.myquery.eviction.max_entries", "11111"); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); manager.getGlobalConfiguration().setTransportClass(null); try { assertTrue(factory.getDefinedConfigurations().contains("local-query")); QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(queryRegionName, p); assertNotNull(factory.getTypeOverrides().get(queryRegionName)); assertTrue(factory.getDefinedConfigurations().contains(queryRegionName)); CacheAdapter cache = region.getCacheAdapter(); Configuration cacheCfg = cache.getConfiguration(); assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy()); assertEquals(2222, cacheCfg.getEvictionWakeUpInterval()); assertEquals(11111, cacheCfg.getEvictionMaxEntries()); } finally { factory.stop(); } } public void testEnableStatistics() { Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.statistics", "true"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); try { assertTrue(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics()); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null); CacheAdapter cache = region.getCacheAdapter(); assertTrue(factory.getTypeOverrides().get("entity").isExposeStatistics()); assertTrue(cache.getConfiguration().isExposeJmxStatistics()); region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null); cache = region.getCacheAdapter(); assertTrue(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics()); assertTrue(cache.getConfiguration().isExposeJmxStatistics()); final String query = "org.hibernate.cache.StandardQueryCache"; QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p); cache = queryRegion.getCacheAdapter(); assertTrue(factory.getTypeOverrides().get("query").isExposeStatistics()); assertTrue(cache.getConfiguration().isExposeJmxStatistics()); final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Configuration config = new Configuration(); config.setFetchInMemoryState(false); manager.defineConfiguration("timestamps", config); TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); cache = timestampsRegion.getCacheAdapter(); assertTrue(factory.getTypeOverrides().get("timestamps").isExposeStatistics()); assertTrue(cache.getConfiguration().isExposeJmxStatistics()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null); cache = collectionRegion.getCacheAdapter(); assertTrue(factory.getTypeOverrides().get("collection").isExposeStatistics()); assertTrue(cache.getConfiguration().isExposeJmxStatistics()); } finally { factory.stop(); } } public void testDisableStatistics() { Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.statistics", "false"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000"); InfinispanRegionFactory factory = new InfinispanRegionFactory(); factory.start(null, p); EmbeddedCacheManager manager = factory.getCacheManager(); try { assertFalse(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics()); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null); CacheAdapter cache = region.getCacheAdapter(); assertFalse(factory.getTypeOverrides().get("entity").isExposeStatistics()); assertFalse(cache.getConfiguration().isExposeJmxStatistics()); region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null); cache = region.getCacheAdapter(); assertFalse(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics()); assertFalse(cache.getConfiguration().isExposeJmxStatistics()); final String query = "org.hibernate.cache.StandardQueryCache"; QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p); cache = queryRegion.getCacheAdapter(); assertFalse(factory.getTypeOverrides().get("query").isExposeStatistics()); assertFalse(cache.getConfiguration().isExposeJmxStatistics()); final String timestamps = "org.hibernate.cache.UpdateTimestampsCache"; Configuration config = new Configuration(); config.setFetchInMemoryState(false); manager.defineConfiguration("timestamps", config); TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p); cache = timestampsRegion.getCacheAdapter(); assertFalse(factory.getTypeOverrides().get("timestamps").isExposeStatistics()); assertFalse(cache.getConfiguration().isExposeJmxStatistics()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null); cache = collectionRegion.getCacheAdapter(); assertFalse(factory.getTypeOverrides().get("collection").isExposeStatistics()); assertFalse(cache.getConfiguration().isExposeJmxStatistics()); } finally { factory.stop(); } } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Customer.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000355011714611271032625 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional; import java.io.Serializable; import java.util.Set; /** * Company customer * * @author Emmanuel Bernard * @author Kabir Khan */ public class Customer implements Serializable { Integer id; String name; private transient Set contacts; public Customer() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String string) { name = string; } public Set getContacts() { return contacts; } public void setContacts(Set contacts) { this.contacts = contacts; } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Item.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000434311714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional; import java.util.HashSet; import java.util.Set; /** * @author Gavin King */ public class Item { private Long id; private String name; private String description; private Item owner; private Set items = new HashSet(); public Item() {} public Item( String name, String description ) { this.name = name; this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Item getOwner() { return owner; } public void setOwner( Item owner ) { this.owner = owner; } public Set getItems() { return items; } public void setItems( Set items ) { this.items = items; } public void addItem( Item item ) { item.setOwner( this ); getItems().add( item ); } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/Contact.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000471511714611271032631 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional; import java.io.Serializable; /** * Entity that has a many-to-one relationship to a Customer * * @author Galder Zamarreño * @since 3.5 */ public class Contact implements Serializable { Integer id; String name; String tlf; Customer customer; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTlf() { return tlf; } public void setTlf(String tlf) { this.tlf = tlf; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Contact)) return false; Contact c = (Contact) o; return c.id.equals(id) && c.name.equals(name) && c.tlf.equals(tlf); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); result = 31 * result + name.hashCode(); result = 31 * result + tlf.hashCode(); return result; } } ././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/SingleNodeTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000754411714611271032634 0ustar ebourgebourgpackage org.hibernate.test.cache.infinispan.functional; import java.util.Map; import javax.transaction.Status; import javax.transaction.TransactionManager; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.connection.ConnectionProvider; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.hibernate.transaction.CMTTransactionFactory; import org.hibernate.transaction.TransactionFactory; import org.hibernate.transaction.TransactionManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * @author Galder Zamarreño * @since 3.5 */ public abstract class SingleNodeTestCase extends FunctionalTestCase { private static final Log log = LogFactory.getLog(SingleNodeTestCase.class); private final TransactionManager tm; public SingleNodeTestCase(String string) { super(string); tm = getTransactionManager(); } protected TransactionManager getTransactionManager() { try { if (getTransactionManagerLookupClass() == null) return null; else return getTransactionManagerLookupClass().newInstance().getTransactionManager(null); } catch (Exception e) { log.error("Error", e); throw new RuntimeException(e); } } public String[] getMappings() { return new String[] { "cache/infinispan/functional/Item.hbm.xml", "cache/infinispan/functional/Customer.hbm.xml", "cache/infinispan/functional/Contact.hbm.xml"}; } @Override public String getCacheConcurrencyStrategy() { return "transactional"; } protected Class getCacheRegionFactory() { return InfinispanRegionFactory.class; } protected Class getTransactionFactoryClass() { return CMTTransactionFactory.class; } protected Class getConnectionProviderClass() { return org.hibernate.test.cache.infinispan.tm.XaConnectionProvider.class; } protected Class getTransactionManagerLookupClass() { return org.hibernate.test.cache.infinispan.tm.XaTransactionManagerLookup.class; } protected boolean getUseQueryCache() { return true; } public void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, String.valueOf(getUseQueryCache())); cfg.setProperty(Environment.CACHE_REGION_FACTORY, getCacheRegionFactory().getName()); cfg.setProperty(Environment.CONNECTION_PROVIDER, getConnectionProviderClass().getName()); if (getTransactionManagerLookupClass() != null) { cfg.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, getTransactionManagerLookupClass().getName()); } cfg.setProperty(Environment.TRANSACTION_STRATEGY, getTransactionFactoryClass().getName()); } protected void beginTx() throws Exception { tm.begin(); } protected void setRollbackOnlyTx() throws Exception { tm.setRollbackOnly(); } protected void setRollbackOnlyTx(Exception e) throws Exception { log.error("Error", e); tm.setRollbackOnly(); throw e; } protected void setRollbackOnlyTxExpected(Exception e) throws Exception { log.debug("Expected behaivour", e); tm.setRollbackOnly(); } protected void commitOrRollbackTx() throws Exception { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } }././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000025000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoader.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002073611714611271032632 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.classloader; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A ClassLoader that loads classes whose classname begins with one of a given set of strings, * without attempting first to delegate to its parent loader. *

* This class is intended to allow emulation of 2 different types of common J2EE classloading * situations. *

    *
  • Servlet-style child-first classloading, where this class is the child loader.
  • *
  • Parent-first classloading where the parent does not have access to certain classes
  • *
*

*

* This class can also be configured to raise a ClassNotFoundException if asked to load certain * classes, thus allowing classes on the classpath to be hidden from a test environment. *

* * @author Brian Stansberry */ public class SelectedClassnameClassLoader extends ClassLoader { private Logger log = LoggerFactory.getLogger(SelectedClassnameClassLoader.class); private String[] includedClasses = null; private String[] excludedClasses = null; private String[] notFoundClasses = null; private Map classes = new java.util.HashMap(); /** * Creates a new classloader that loads the given classes. * * @param includedClasses * array of class or package names that should be directly loaded by this loader. * Classes whose name starts with any of the strings in this array will be loaded by * this class, unless their name appears in excludedClasses. Can be * null * @param excludedClasses * array of class or package names that should NOT be directly loaded by this loader. * Loading of classes whose name starts with any of the strings in this array will be * delegated to parent, even if the classes package or classname appears * in includedClasses. Typically this parameter is used to exclude loading * one or more classes in a package whose other classes are loaded by this object. * @param parent * ClassLoader to which loading of classes should be delegated if necessary */ public SelectedClassnameClassLoader(String[] includedClasses, String[] excludedClasses, ClassLoader parent) { this(includedClasses, excludedClasses, null, parent); } /** * Creates a new classloader that loads the given classes. * * @param includedClasses * array of class or package names that should be directly loaded by this loader. * Classes whose name starts with any of the strings in this array will be loaded by * this class, unless their name appears in excludedClasses. Can be * null * @param excludedClasses * array of class or package names that should NOT be directly loaded by this loader. * Loading of classes whose name starts with any of the strings in this array will be * delegated to parent, even if the classes package or classname appears * in includedClasses. Typically this parameter is used to exclude loading * one or more classes in a package whose other classes are loaded by this object. * @param notFoundClasses * array of class or package names for which this should raise a ClassNotFoundException * @param parent * ClassLoader to which loading of classes should be delegated if necessary */ public SelectedClassnameClassLoader(String[] includedClasses, String[] excludedClasses, String[] notFoundClasses, ClassLoader parent) { super(parent); this.includedClasses = includedClasses; this.excludedClasses = excludedClasses; this.notFoundClasses = notFoundClasses; log.debug("created " + this); } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { log.trace("loadClass(" + name + "," + resolve + ")"); if (isIncluded(name) && (isExcluded(name) == false)) { Class c = findClass(name); if (resolve) { resolveClass(c); } return c; } else if (isNotFound(name)) { throw new ClassNotFoundException(name + " is discarded"); } else { return super.loadClass(name, resolve); } } protected Class findClass(String name) throws ClassNotFoundException { log.trace("findClass(" + name + ")"); Class result = classes.get(name); if (result != null) { return result; } if (isIncluded(name) && (isExcluded(name) == false)) { result = createClass(name); } else if (isNotFound(name)) { throw new ClassNotFoundException(name + " is discarded"); } else { result = super.findClass(name); } classes.put(name, result); return result; } protected Class createClass(String name) throws ClassFormatError, ClassNotFoundException { log.info("createClass(" + name + ")"); try { InputStream is = getResourceAsStream(name.replace('.', '/').concat(".class")); byte[] bytes = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); int read; while ((read = is.read(bytes)) > -1) { baos.write(bytes, 0, read); } bytes = baos.toByteArray(); return this.defineClass(name, bytes, 0, bytes.length); } catch (FileNotFoundException e) { throw new ClassNotFoundException("cannot find " + name, e); } catch (IOException e) { throw new ClassNotFoundException("cannot read " + name, e); } } protected boolean isIncluded(String className) { if (includedClasses != null) { for (int i = 0; i < includedClasses.length; i++) { if (className.startsWith(includedClasses[i])) { return true; } } } return false; } protected boolean isExcluded(String className) { if (excludedClasses != null) { for (int i = 0; i < excludedClasses.length; i++) { if (className.startsWith(excludedClasses[i])) { return true; } } } return false; } protected boolean isNotFound(String className) { if (notFoundClasses != null) { for (int i = 0; i < notFoundClasses.length; i++) { if (className.startsWith(notFoundClasses[i])) { return true; } } } return false; } public String toString() { String s = getClass().getName(); s += "[includedClasses="; s += listClasses(includedClasses); s += ";excludedClasses="; s += listClasses(excludedClasses); s += ";notFoundClasses="; s += listClasses(notFoundClasses); s += ";parent="; s += getParent(); s += "]"; return s; } private static String listClasses(String[] classes) { if (classes == null) return null; String s = ""; for (int i = 0; i < classes.length; i++) { if (i > 0) s += ","; s += classes[i]; } return s; } } ././@LongLink0000000000000000000000000000024300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedClassLoaderTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000003320611714611271032626 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.classloader; import javax.transaction.TransactionManager; import junit.framework.Test; import junit.framework.TestSuite; import org.hibernate.SessionFactory; import org.hibernate.cache.StandardQueryCache; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase; import org.hibernate.test.cache.infinispan.functional.cluster.ClusterAwareRegionFactory; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tests entity and query caching when class of objects being cached are not visible to Infinispan's * classloader. Also serves as a general integration test. *

* This test stores an object (AccountHolder) that isn't visible to the Infinispan classloader in * the cache in two places: * * 1) As part of the value tuple in an Account entity 2) As part of the FQN in a query cache entry * (see query in ClassLoaderTestDAO.getBranch()) * * @author Galder Zamarreño * @since 3.5 */ public class IsolatedClassLoaderTest extends DualNodeTestCase { public static final String OUR_PACKAGE = IsolatedClassLoaderTest.class.getPackage().getName(); private static final String CACHE_CONFIG = "classloader"; protected static final long SLEEP_TIME = 300L; protected final Logger log = LoggerFactory.getLogger(getClass()); static int test = 0; private Cache localQueryCache ; private CacheAccessListener localQueryListener; private Cache remoteQueryCache; private CacheAccessListener remoteQueryListener; public IsolatedClassLoaderTest(String string) { super(string); } public static Test suite() throws Exception { TestSuite suite = new TestSuite(IsolatedClassLoaderTest.class); String[] acctClasses = { OUR_PACKAGE + ".Account", OUR_PACKAGE + ".AccountHolder" }; return new IsolatedCacheTestSetup(suite, acctClasses); } @Override public String[] getMappings() { return new String[] { "cache/infinispan/functional/classloader/Account.hbm.xml" }; } @Override protected void standardConfigure(Configuration cfg) { super.standardConfigure(cfg); cfg.setProperty(InfinispanRegionFactory.QUERY_CACHE_RESOURCE_PROP, "replicated-query"); cfg.setProperty("hibernate.cache.infinispan.AccountRegion.cfg", "replicated-query"); } @Override protected void cleanupTransactionManagement() { // Don't clean up the managers, just the transactions // Managers are still needed by the long-lived caches DualNodeJtaTransactionManagerImpl.cleanupTransactions(); } @Override protected void cleanupTest() throws Exception { try { if (localQueryCache != null && localQueryListener != null) localQueryCache.removeListener(localQueryListener); if (remoteQueryCache != null && remoteQueryListener != null) remoteQueryCache.removeListener(remoteQueryListener); } finally { super.cleanupTest(); } } /** * Simply confirms that the test fixture's classloader isolation setup is functioning as * expected. * * @throws Exception */ public void testIsolatedSetup() throws Exception { // Bind a listener to the "local" cache // Our region factory makes its CacheManager available to us CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); Cache localReplicatedCache = localManager.getCache("replicated-entity"); // Bind a listener to the "remote" cache CacheContainer remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); Cache remoteReplicatedCache = remoteManager.getCache("replicated-entity"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(cl.getParent()); log.info("TCCL is " + cl.getParent()); Account acct = new Account(); acct.setAccountHolder(new AccountHolder()); try { localReplicatedCache.put("isolated1", acct); // With lazy deserialization, retrieval in remote forces class resolution remoteReplicatedCache.get("isolated1"); fail("Should not have succeeded in putting acct -- classloader not isolated"); } catch (Exception e) { if (e.getCause() instanceof ClassNotFoundException) { log.info("Caught exception as desired", e); } else { throw new IllegalStateException("Unexpected exception", e); } } Thread.currentThread().setContextClassLoader(cl); log.info("TCCL is " + cl); localReplicatedCache.put("isolated2", acct); assertEquals(acct.getClass().getName(), remoteReplicatedCache.get("isolated2").getClass().getName()); } public void testClassLoaderHandlingNamedQueryRegion() throws Exception { queryTest(true); } public void testClassLoaderHandlingStandardQueryCache() throws Exception { queryTest(false); } protected void queryTest(boolean useNamedRegion) throws Exception { // Bind a listener to the "local" cache // Our region factory makes its CacheManager available to us EmbeddedCacheManager localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); // Bind a listener to the "remote" cache EmbeddedCacheManager remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); String cacheName; if (useNamedRegion) { cacheName = "AccountRegion"; // As defined by ClassLoaderTestDAO via calls to query.setCacheRegion // Define cache configurations for region early to avoid ending up with local caches for this region localManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); remoteManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); } else { cacheName = "replicated-query"; } localQueryCache = localManager.getCache(cacheName); localQueryListener = new CacheAccessListener(); localQueryCache.addListener(localQueryListener); TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); remoteQueryCache = remoteManager.getCache(cacheName); remoteQueryListener = new CacheAccessListener(); remoteQueryCache.addListener(remoteQueryListener); TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); SessionFactory localFactory = getEnvironment().getSessionFactory(); SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); // Initial ops on node 0 setupEntities(dao0); String branch = "63088"; // Query on post code count assertEquals(branch + " has correct # of accounts", 6, dao0.getCountForBranch(branch, useNamedRegion)); assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); localQueryListener.clearSawRegionModification(); // log.info("First query (get count for branch + " + branch + " ) on node0 done, contents of local query cache are: " + TestingUtil.printCache(localQueryCache)); // Sleep a bit to allow async repl to happen sleep(SLEEP_TIME); assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); remoteQueryListener.clearSawRegionModification(); // Do query again from node 1 log.info("Repeat first query (get count for branch + " + branch + " ) on remote node"); assertEquals("63088 has correct # of accounts", 6, dao1.getCountForBranch(branch, useNamedRegion)); assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); remoteQueryListener.clearSawRegionModification(); sleep(SLEEP_TIME); assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); localQueryListener.clearSawRegionModification(); log.info("First query on node 1 done"); // Sleep a bit to allow async repl to happen sleep(SLEEP_TIME); // Do some more queries on node 0 log.info("Do query Smith's branch"); assertEquals("Correct branch for Smith", "94536", dao0.getBranch(dao0.getSmith(), useNamedRegion)); log.info("Do query Jone's balance"); assertEquals("Correct high balances for Jones", 40, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); assertEquals("Query cache used", 2, localQueryListener.getSawRegionModificationCount()); localQueryListener.clearSawRegionModification(); // // Clear the access state // localQueryListener.getSawRegionAccess("???"); log.info("Second set of queries on node0 done"); // Sleep a bit to allow async repl to happen sleep(SLEEP_TIME); // Check if the previous queries replicated assertEquals("Query cache remotely modified", 2, remoteQueryListener.getSawRegionModificationCount()); remoteQueryListener.clearSawRegionModification(); log.info("Repeat second set of queries on node1"); // Do queries again from node 1 log.info("Again query Smith's branch"); assertEquals("Correct branch for Smith", "94536", dao1.getBranch(dao1.getSmith(), useNamedRegion)); log.info("Again query Jone's balance"); assertEquals("Correct high balances for Jones", 40, dao1.getTotalBalance(dao1.getJones(), useNamedRegion)); // Should be no change; query was already there assertEquals("Query cache modified", 0, remoteQueryListener.getSawRegionModificationCount()); assertEquals("Query cache accessed", 2, remoteQueryListener.getSawRegionAccessCount()); remoteQueryListener.clearSawRegionAccess(); log.info("Second set of queries on node1 done"); // allow async to propagate sleep(SLEEP_TIME); // Modify underlying data on node 1 modifyEntities(dao1); // allow async timestamp change to propagate sleep(SLEEP_TIME); // Confirm query results are correct on node 0 assertEquals("63088 has correct # of accounts", 7, dao0.getCountForBranch("63088", useNamedRegion)); assertEquals("Correct branch for Smith", "63088", dao0.getBranch(dao0.getSmith(), useNamedRegion)); assertEquals("Correct high balances for Jones", 50, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); log.info("Third set of queries on node0 done"); } protected void setupEntities(ClassLoaderTestDAO dao) throws Exception { dao.cleanup(); dao.createAccount(dao.getSmith(), new Integer(1001), new Integer(5), "94536"); dao.createAccount(dao.getSmith(), new Integer(1002), new Integer(15), "94536"); dao.createAccount(dao.getSmith(), new Integer(1003), new Integer(20), "94536"); dao.createAccount(dao.getJones(), new Integer(2001), new Integer(5), "63088"); dao.createAccount(dao.getJones(), new Integer(2002), new Integer(15), "63088"); dao.createAccount(dao.getJones(), new Integer(2003), new Integer(20), "63088"); dao.createAccount(dao.getBarney(), new Integer(3001), new Integer(5), "63088"); dao.createAccount(dao.getBarney(), new Integer(3002), new Integer(15), "63088"); dao.createAccount(dao.getBarney(), new Integer(3003), new Integer(20), "63088"); log.info("Standard entities created"); } protected void resetRegionUsageState(CacheAccessListener localListener, CacheAccessListener remoteListener) { String stdName = StandardQueryCache.class.getName(); String acctName = Account.class.getName(); localListener.getSawRegionModification(stdName); localListener.getSawRegionModification(acctName); localListener.getSawRegionAccess(stdName); localListener.getSawRegionAccess(acctName); remoteListener.getSawRegionModification(stdName); remoteListener.getSawRegionModification(acctName); remoteListener.getSawRegionAccess(stdName); remoteListener.getSawRegionAccess(acctName); log.info("Region usage state cleared"); } protected void modifyEntities(ClassLoaderTestDAO dao) throws Exception { dao.updateAccountBranch(1001, "63088"); dao.updateAccountBalance(2001, 15); log.info("Entities modified"); } } ././@LongLink0000000000000000000000000000023100000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/AccountHolder.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000603711714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.classloader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * Comment * * @author Brian Stansberry */ public class AccountHolder implements Serializable { private static final long serialVersionUID = 1L; private String lastName; private String ssn; private transient boolean deserialized; public AccountHolder() { this("Stansberry", "123-456-7890"); } public AccountHolder(String lastName, String ssn) { this.lastName = lastName; this.ssn = ssn; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSsn() { return ssn; } public void setSsn(String ssn) { this.ssn = ssn; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof AccountHolder)) return false; AccountHolder pk = (AccountHolder) obj; if (!lastName.equals(pk.lastName)) return false; if (!ssn.equals(pk.ssn)) return false; return true; } @Override public int hashCode() { int result = 17; result = result * 31 + lastName.hashCode(); result = result * 31 + ssn.hashCode(); return result; } @Override public String toString() { StringBuffer sb = new StringBuffer(getClass().getName()); sb.append("[lastName="); sb.append(lastName); sb.append(",ssn="); sb.append(ssn); sb.append(",deserialized="); sb.append(deserialized); sb.append("]"); return sb.toString(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); deserialized = true; } } ././@LongLink0000000000000000000000000000024200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedCacheTestSetup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000475211714611271032632 0ustar ebourgebourg/* * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, v. 2.1. This program is distributed in the * hope that it will be useful, but WITHOUT A WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received a * copy of the GNU Lesser General Public License, v.2.1 along with this * distribution; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Red Hat Author(s): Brian Stansberry */ package org.hibernate.test.cache.infinispan.functional.classloader; import org.hibernate.test.cache.infinispan.functional.cluster.ClusterAwareRegionFactory; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import junit.framework.Test; /** * A TestSetup that uses SelectedClassnameClassLoader to ensure that certain classes are not visible * to Infinispan or JGroups' classloader. * * @author Galder Zamarreño */ public class IsolatedCacheTestSetup extends SelectedClassnameClassLoaderTestSetup { private String[] isolatedClasses; private String cacheConfig; /** * Create a new IsolatedCacheTestSetup. */ public IsolatedCacheTestSetup(Test test, String[] isolatedClasses) { super(test, null, null, isolatedClasses); this.isolatedClasses = isolatedClasses; } @Override protected void setUp() throws Exception { super.setUp(); // At this point the TCCL cannot see the isolatedClasses // We want the caches to use this CL as their default classloader ClassLoader tccl = Thread.currentThread().getContextClassLoader(); // Now make the isolatedClasses visible to the test driver itself SelectedClassnameClassLoader visible = new SelectedClassnameClassLoader(isolatedClasses, null, null, tccl); Thread.currentThread().setContextClassLoader(visible); } @Override protected void tearDown() throws Exception { try { super.tearDown(); } finally { ClusterAwareRegionFactory.clearCacheManagers(); DualNodeJtaTransactionManagerImpl.cleanupTransactions(); DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers(); } } } ././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/Account.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000673711714611271032637 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.classloader; import java.io.Serializable; /** * Comment * * @author Brian Stansberry */ public class Account implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private AccountHolder accountHolder; private Integer balance; private String branch; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public AccountHolder getAccountHolder() { return accountHolder; } public void setAccountHolder(AccountHolder accountHolder) { this.accountHolder = accountHolder; } public Integer getBalance() { return balance; } public void setBalance(Integer balance) { this.balance = balance; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Account)) return false; Account acct = (Account) obj; if (!safeEquals(id, acct.id)) return false; if (!safeEquals(branch, acct.branch)) return false; if (!safeEquals(balance, acct.balance)) return false; if (!safeEquals(accountHolder, acct.accountHolder)) return false; return true; } @Override public int hashCode() { int result = 17; result = result * 31 + safeHashCode(id); result = result * 31 + safeHashCode(branch); result = result * 31 + safeHashCode(balance); result = result * 31 + safeHashCode(accountHolder); return result; } @Override public String toString() { StringBuffer sb = new StringBuffer(getClass().getName()); sb.append("[id="); sb.append(id); sb.append(",branch="); sb.append(branch); sb.append(",balance="); sb.append(balance); sb.append(",accountHolder="); sb.append(accountHolder); sb.append("]"); return sb.toString(); } private static int safeHashCode(Object obj) { return obj == null ? 0 : obj.hashCode(); } private static boolean safeEquals(Object a, Object b) { return (a == b || (a != null && a.equals(b))); } } ././@LongLink0000000000000000000000000000023600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/ClassLoaderTestDAO.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002274611714611271032635 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.classloader; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import javax.transaction.TransactionManager; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Comment * * @author Brian Stansberry */ public class ClassLoaderTestDAO { private static final Log log = LogFactory.getLog(ClassLoaderTestDAO.class); private SessionFactory sessionFactory; private TransactionManager tm; private Class acctClass; private Class holderClass; private Method setId; private Method setBalance; private Method setBranch; private Method setHolder; private Object smith; private Object jones; private Object barney; private Method setName; private Method setSsn; public ClassLoaderTestDAO(SessionFactory factory, TransactionManager tm) throws Exception { this.sessionFactory = factory; this.tm = tm; acctClass = Thread.currentThread().getContextClassLoader().loadClass( getClass().getPackage().getName() + ".Account"); holderClass = Thread.currentThread().getContextClassLoader().loadClass( getClass().getPackage().getName() + ".AccountHolder"); setId = acctClass.getMethod("setId", Integer.class); setBalance = acctClass.getMethod("setBalance", Integer.class); setBranch = acctClass.getMethod("setBranch", String.class); setHolder = acctClass.getMethod("setAccountHolder", holderClass); setName = holderClass.getMethod("setLastName", String.class); setSsn = holderClass.getMethod("setSsn", String.class); smith = holderClass.newInstance(); setName.invoke(smith, "Smith"); setSsn.invoke(smith, "1000"); jones = holderClass.newInstance(); setName.invoke(jones, "Jones"); setSsn.invoke(jones, "2000"); barney = holderClass.newInstance(); setName.invoke(barney, "Barney"); setSsn.invoke(barney, "3000"); } public Object getSmith() { return smith; } public Object getJones() { return jones; } public Object getBarney() { return barney; } public void updateAccountBranch(Integer id, String branch) throws Exception { log.debug("Updating account " + id + " to branch " + branch); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Object account = session.get(acctClass, id); log.debug("Set branch " + branch); setBranch.invoke(account, branch); session.update(account); tm.commit(); } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } log.debug("Updated account " + id + " to branch " + branch); } public int getCountForBranch(String branch, boolean useRegion) throws Exception { tm.begin(); try { Query query = sessionFactory.getCurrentSession().createQuery( "select account from Account as account where account.branch = :branch"); query.setString("branch", branch); if (useRegion) { query.setCacheRegion("AccountRegion"); } query.setCacheable(true); int result = query.list().size(); tm.commit(); return result; } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } } public void createAccount(Object holder, Integer id, Integer openingBalance, String branch) throws Exception { log.debug("Creating account " + id); tm.begin(); try { Object account = acctClass.newInstance(); setId.invoke(account, id); setHolder.invoke(account, holder); setBalance.invoke(account, openingBalance); log.debug("Set branch " + branch); setBranch.invoke(account, branch); sessionFactory.getCurrentSession().persist(account); tm.commit(); } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } log.debug("Created account " + id); } public Account getAccount(Integer id) throws Exception { log.debug("Getting account " + id); Session session = sessionFactory.openSession(); try { return (Account) session.get(acctClass, id); } finally { session.close(); } } public Account getAccountWithRefresh(Integer id) throws Exception { log.debug("Getting account " + id + " with refresh"); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Account acct = (Account) session.get(acctClass, id); session.refresh(acct); acct = (Account) session.get(acctClass, id); tm.commit(); return acct; } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } } public void updateAccountBalance(Integer id, Integer newBalance) throws Exception { log.debug("Updating account " + id + " to balance " + newBalance); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Object account = session.get(acctClass, id); setBalance.invoke(account, newBalance); session.update(account); tm.commit(); } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } log.debug("Updated account " + id + " to balance " + newBalance); } public String getBranch(Object holder, boolean useRegion) throws Exception { tm.begin(); try { Query query = sessionFactory.getCurrentSession().createQuery( "select account.branch from Account as account where account.accountHolder = ?"); query.setParameter(0, holder); if (useRegion) { query.setCacheRegion("AccountRegion"); } query.setCacheable(true); String result = (String) query.list().get(0); tm.commit(); return result; } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } } public int getTotalBalance(Object holder, boolean useRegion) throws Exception { List results = null; tm.begin(); try { Query query = sessionFactory.getCurrentSession().createQuery( "select account.balance from Account as account where account.accountHolder = ?"); query.setParameter(0, holder); if (useRegion) { query.setCacheRegion("AccountRegion"); } query.setCacheable(true); results = query.list(); tm.commit(); } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } int total = 0; if (results != null) { for (Iterator it = results.iterator(); it.hasNext();) { total += ((Integer) it.next()).intValue(); System.out.println("Total = " + total); } } return total; } public void cleanup() throws Exception { internalCleanup(); } private void internalCleanup() throws Exception { if (sessionFactory != null) { tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("select account from Account as account"); List accts = query.list(); if (accts != null) { for (Iterator it = accts.iterator(); it.hasNext();) { try { Object acct = it.next(); log.info("Removing " + acct); session.delete(acct); } catch (Exception ignored) { } } } tm.commit(); } catch (Exception e) { tm.rollback(); throw e; } } } public void remove() { try { internalCleanup(); } catch (Exception e) { log.error("Caught exception in remove", e); } } } ././@LongLink0000000000000000000000000000026100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoaderTestSetup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000453111714611271032625 0ustar ebourgebourg/* * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, v. 2.1. This program is distributed in the * hope that it will be useful, but WITHOUT A WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received a * copy of the GNU Lesser General Public License, v.2.1 along with this * distribution; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Red Hat Author(s): Brian Stansberry */ package org.hibernate.test.cache.infinispan.functional.classloader; import junit.extensions.TestSetup; import junit.framework.Test; /** * A TestSetup that makes SelectedClassnameClassLoader the thread context classloader for the * duration of the test. * * @author Brian Stansberry * @version $Revision: 1 $ */ public class SelectedClassnameClassLoaderTestSetup extends TestSetup { private ClassLoader originalTCCL; private String[] includedClasses; private String[] excludedClasses; private String[] notFoundClasses; /** * Create a new SelectedClassnameClassLoaderTestSetup. * * @param test */ public SelectedClassnameClassLoaderTestSetup(Test test, String[] includedClasses, String[] excludedClasses, String[] notFoundClasses) { super(test); this.includedClasses = includedClasses; this.excludedClasses = excludedClasses; this.notFoundClasses = notFoundClasses; } @Override protected void setUp() throws Exception { super.setUp(); originalTCCL = Thread.currentThread().getContextClassLoader(); ClassLoader parent = originalTCCL == null ? getClass().getClassLoader() : originalTCCL; ClassLoader selectedTCCL = new SelectedClassnameClassLoader(includedClasses, excludedClasses, notFoundClasses, parent); Thread.currentThread().setContextClassLoader(selectedTCCL); } @Override protected void tearDown() throws Exception { Thread.currentThread().setContextClassLoader(originalTCCL); super.tearDown(); } } ././@LongLink0000000000000000000000000000023700000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/CacheAccessListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000722111714611271032624 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.classloader; import java.util.HashSet; import java.util.Set; import org.hibernate.cache.infinispan.util.CacheHelper; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Listener public class CacheAccessListener { protected final Logger log = LoggerFactory.getLogger(getClass()); HashSet modified = new HashSet(); HashSet accessed = new HashSet(); public void clear() { modified.clear(); accessed.clear(); } @CacheEntryModified public void nodeModified(CacheEntryModifiedEvent event) { if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { Object key = event.getKey(); log.info("Modified node " + key); modified.add(key.toString()); } } @CacheEntryCreated public void nodeCreated(CacheEntryCreatedEvent event) { if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { Object key = event.getKey(); log.info("Created node " + key); modified.add(key.toString()); } } @CacheEntryVisited public void nodeVisited(CacheEntryVisitedEvent event) { if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { Object key = event.getKey(); log.info("Visited node " + key); accessed.add(key.toString()); } } public boolean getSawRegionModification(Object key) { return getSawRegion(key, modified); } public int getSawRegionModificationCount() { return modified.size(); } public void clearSawRegionModification() { modified.clear(); } public boolean getSawRegionAccess(Object key) { return getSawRegion(key, accessed); } public int getSawRegionAccessCount() { return accessed.size(); } public void clearSawRegionAccess() { accessed.clear(); } private boolean getSawRegion(Object key, Set sawEvents) { if (sawEvents.contains(key)) { sawEvents.remove(key); return true; } return false; } }././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/BulkOperationsTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000003324511714611271032631 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.bulk; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.transaction.Status; import javax.transaction.TransactionManager; import org.hibernate.FlushMode; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.classic.Session; import org.hibernate.connection.ConnectionProvider; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.test.cache.infinispan.functional.Contact; import org.hibernate.test.cache.infinispan.functional.Customer; import org.hibernate.transaction.CMTTransactionFactory; import org.hibernate.transaction.TransactionFactory; import org.hibernate.transaction.TransactionManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * BulkOperationsTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class BulkOperationsTestCase extends FunctionalTestCase { private static final Log log = LogFactory.getLog(BulkOperationsTestCase.class); private TransactionManager tm; public BulkOperationsTestCase(String string) { super(string); } public String[] getMappings() { return new String[] { "cache/infinispan/functional/Contact.hbm.xml", "cache/infinispan/functional/Customer.hbm.xml" }; } @Override public String getCacheConcurrencyStrategy() { return "transactional"; } protected Class getCacheRegionFactory() { return InfinispanRegionFactory.class; } protected Class getTransactionFactoryClass() { return CMTTransactionFactory.class; } protected Class getConnectionProviderClass() { return org.hibernate.test.cache.infinispan.tm.XaConnectionProvider.class; } protected Class getTransactionManagerLookupClass() { return org.hibernate.test.cache.infinispan.tm.XaTransactionManagerLookup.class; } public void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "false"); cfg.setProperty(Environment.CACHE_REGION_FACTORY, getCacheRegionFactory().getName()); cfg.setProperty(Environment.CONNECTION_PROVIDER, getConnectionProviderClass().getName()); cfg.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, getTransactionManagerLookupClass().getName()); cfg.setProperty(Environment.TRANSACTION_STRATEGY, getTransactionFactoryClass().getName()); } public void testBulkOperations() throws Throwable { log.info("*** testBulkOperations()"); boolean cleanedUp = false; try { tm = getTransactionManagerLookupClass().newInstance().getTransactionManager(null); createContacts(); List rhContacts = getContactsByCustomer("Red Hat"); assertNotNull("Red Hat contacts exist", rhContacts); assertEquals("Created expected number of Red Hat contacts", 10, rhContacts.size()); SecondLevelCacheStatistics contactSlcs = getEnvironment().getSessionFactory() .getStatistics().getSecondLevelCacheStatistics(Contact.class.getName()); assertEquals(20, contactSlcs.getElementCountInMemory()); assertEquals("Deleted all Red Hat contacts", 10, deleteContacts()); assertEquals(0, contactSlcs.getElementCountInMemory()); List jbContacts = getContactsByCustomer("JBoss"); assertNotNull("JBoss contacts exist", jbContacts); assertEquals("JBoss contacts remain", 10, jbContacts.size()); for (Integer id : rhContacts) { assertNull("Red Hat contact " + id + " cannot be retrieved", getContact(id)); } rhContacts = getContactsByCustomer("Red Hat"); if (rhContacts != null) { assertEquals("No Red Hat contacts remain", 0, rhContacts.size()); } updateContacts("Kabir", "Updated"); assertEquals(0, contactSlcs.getElementCountInMemory()); for (Integer id : jbContacts) { Contact contact = getContact(id); assertNotNull("JBoss contact " + id + " exists", contact); String expected = ("Kabir".equals(contact.getName())) ? "Updated" : "2222"; assertEquals("JBoss contact " + id + " has correct TLF", expected, contact.getTlf()); } List updated = getContactsByTLF("Updated"); assertNotNull("Got updated contacts", updated); assertEquals("Updated contacts", 5, updated.size()); updateContactsWithOneManual("Kabir", "UpdatedAgain"); assertEquals(contactSlcs.getElementCountInMemory(), 0); for (Integer id : jbContacts) { Contact contact = getContact(id); assertNotNull("JBoss contact " + id + " exists", contact); String expected = ("Kabir".equals(contact.getName())) ? "UpdatedAgain" : "2222"; assertEquals("JBoss contact " + id + " has correct TLF", expected, contact.getTlf()); } updated = getContactsByTLF("UpdatedAgain"); assertNotNull("Got updated contacts", updated); assertEquals("Updated contacts", 5, updated.size()); } catch (Throwable t) { cleanedUp = true; log.debug("Exceptional cleanup"); cleanup(true); throw t; } finally { // cleanup the db so we can run this test multiple times w/o restarting the cluster if (!cleanedUp) { log.debug("Non exceptional cleanup"); cleanup(false); } } } public void createContacts() throws Exception { log.debug("Create 10 contacts"); tm.begin(); try { for (int i = 0; i < 10; i++) createCustomer(i); } catch (Exception e) { log.error("Unable to create customer", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public int deleteContacts() throws Exception { String deleteHQL = "delete Contact where customer in "; deleteHQL += " (select customer FROM Customer as customer "; deleteHQL += " where customer.name = :cName)"; tm.begin(); try { Session session = getSessions().getCurrentSession(); int rowsAffected = session.createQuery(deleteHQL).setFlushMode(FlushMode.AUTO) .setParameter("cName", "Red Hat").executeUpdate(); tm.commit(); return rowsAffected; } catch (Exception e) { log.error("Unable to delete contac", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.commit(); } else { try { tm.rollback(); } catch (Exception ee) { // ignored } } } } public List getContactsByCustomer(String customerName) throws Exception { String selectHQL = "select contact.id from Contact contact"; selectHQL += " where contact.customer.name = :cName"; log.debug("Get contacts for customer " + customerName); tm.begin(); try { Session session = getSessions().getCurrentSession(); List results = session.createQuery(selectHQL).setFlushMode(FlushMode.AUTO).setParameter( "cName", customerName).list(); return results; } catch (Exception e) { log.error("Unable to get contacts by customer", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public List getContactsByTLF(String tlf) throws Exception { String selectHQL = "select contact.id from Contact contact"; selectHQL += " where contact.tlf = :cTLF"; tm.begin(); try { Session session = getSessions().getCurrentSession(); List results = session.createQuery(selectHQL).setFlushMode(FlushMode.AUTO).setParameter( "cTLF", tlf).list(); return results; } catch (Exception e) { log.error("Unable to get contacts", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public int updateContacts(String name, String newTLF) throws Exception { String updateHQL = "update Contact set tlf = :cNewTLF where name = :cName"; tm.begin(); try { Session session = getSessions().getCurrentSession(); int rowsAffected = session.createQuery(updateHQL).setFlushMode(FlushMode.AUTO) .setParameter("cNewTLF", newTLF).setParameter("cName", name).executeUpdate(); return rowsAffected; } catch (Exception e) { log.error("Unable to update contacts", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public int updateContactsWithOneManual(String name, String newTLF) throws Exception { String queryHQL = "from Contact c where c.name = :cName"; String updateHQL = "update Contact set tlf = :cNewTLF where name = :cName"; tm.begin(); try { Session session = getSessions().getCurrentSession(); @SuppressWarnings("unchecked") List list = session.createQuery(queryHQL).setParameter("cName", name).list(); list.get(0).setTlf(newTLF); int rowsAffected = session.createQuery(updateHQL).setFlushMode(FlushMode.AUTO) .setParameter("cNewTLF", newTLF).setParameter("cName", name).executeUpdate(); return rowsAffected; } catch (Exception e) { log.error("Unable to update contacts with one manual", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public Contact getContact(Integer id) throws Exception { tm.begin(); try { Session session = getSessions().getCurrentSession(); Contact contact = (Contact) session.get(Contact.class, id); return contact; } catch (Exception e) { log.error("Unable to get contact", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } } public void cleanup(boolean ignore) throws Exception { String deleteContactHQL = "delete from Contact"; String deleteCustomerHQL = "delete from Customer"; tm.begin(); try { Session session = getSessions().getCurrentSession(); session.createQuery(deleteContactHQL).setFlushMode(FlushMode.AUTO).executeUpdate(); session.createQuery(deleteCustomerHQL).setFlushMode(FlushMode.AUTO).executeUpdate(); } catch (Exception e) { log.error("Unable to get contact", e); tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.commit(); } else { if (!ignore) { try { tm.rollback(); } catch (Exception ee) { // ignored } } } } } private Customer createCustomer(int id) throws Exception { System.out.println("CREATE CUSTOMER " + id); try { Customer customer = new Customer(); customer.setName((id % 2 == 0) ? "JBoss" : "Red Hat"); Set contacts = new HashSet(); Contact kabir = new Contact(); kabir.setCustomer(customer); kabir.setName("Kabir"); kabir.setTlf("1111"); contacts.add(kabir); Contact bill = new Contact(); bill.setCustomer(customer); bill.setName("Bill"); bill.setTlf("2222"); contacts.add(bill); customer.setContacts(contacts); Session s = openSession(); s.getTransaction().begin(); s.persist(customer); s.getTransaction().commit(); s.close(); return customer; } finally { System.out.println("CREATE CUSTOMER " + id + " - END"); } } } ././@LongLink0000000000000000000000000000023100000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/JndiRegionFactoryTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001520311714611271032623 0ustar ebourgebourgpackage org.hibernate.test.cache.infinispan.functional; import org.hibernate.Session; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.JndiInfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Mappings; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.testing.junit.functional.ExecutionEnvironment; import org.hibernate.stat.Statistics; import org.infinispan.Cache; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jboss.util.naming.NonSerializableFactory; import org.jnp.server.Main; import org.jnp.server.SingletonNamingServer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.Reference; import javax.naming.StringRefAddr; import java.util.Properties; /** * // TODO: Document this * * @author Galder Zamarreño * @since // TODO */ public class JndiRegionFactoryTestCase extends SingleNodeTestCase { private static final Log log = LogFactory.getLog(JndiRegionFactoryTestCase.class); private static final String JNDI_NAME = "java:CacheManager"; private Main namingMain; private SingletonNamingServer namingServer; private Properties props; private boolean bindToJndi = true; private EmbeddedCacheManager manager; public JndiRegionFactoryTestCase(String string) { super(string); } @Override protected void cleanupTest() throws Exception { Context ctx = new InitialContext(props); unbind(JNDI_NAME, ctx); namingServer.destroy(); namingMain.stop(); manager.stop(); // Need to stop cos JNDI region factory does not stop it. } @Override protected Class getCacheRegionFactory() { return JndiInfinispanRegionFactory.class; } @Override public void afterConfigurationBuilt(Mappings mappings, Dialect dialect) { if (bindToJndi) { try { // Create an in-memory jndi namingServer = new SingletonNamingServer(); namingMain = new Main(); namingMain.setInstallGlobalService(true); namingMain.setPort(-1); namingMain.start(); props = new Properties(); props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); manager = new DefaultCacheManager(InfinispanRegionFactory.DEF_INFINISPAN_CONFIG_RESOURCE, false); Context ctx = new InitialContext(props); bind(JNDI_NAME, manager, EmbeddedCacheManager.class, ctx); } catch(Exception e) { throw new RuntimeException("Failure to set up JNDI", e); } } } @Override public void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(JndiInfinispanRegionFactory.CACHE_MANAGER_RESOURCE_PROP, JNDI_NAME); cfg.setProperty(Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory"); cfg.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); } public void testRedeployment() throws Exception { addEntityCheckCache(); getEnvironment().getSessionFactory().close(); bindToJndi = false; ExecutionEnvironment environment = new ExecutionEnvironment( this ); environment.initialize(); setEnvironment(environment); addEntityCheckCache(); JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) ((SessionFactoryImplementor) environment.getSessionFactory()).getSettings().getRegionFactory(); Cache cache = regionFactory.getCacheManager().getCache("org.hibernate.test.cache.infinispan.functional.Item"); assertEquals(ComponentStatus.RUNNING, cache.getStatus()); } private void addEntityCheckCache() throws Exception { Item item = new Item("chris", "Chris's Item"); beginTx(); try { Session s = openSession(); s.getTransaction().begin(); s.persist(item); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { Session s = openSession(); Item found = (Item) s.load(Item.class, item.getId()); Statistics stats = s.getSessionFactory().getStatistics(); log.info(stats.toString()); assertEquals(item.getDescription(), found.getDescription()); assertEquals(0, stats.getSecondLevelCacheMissCount()); assertEquals(1, stats.getSecondLevelCacheHitCount()); s.delete(found); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } /** * Helper method that binds the a non serializable object to the JNDI tree. * * @param jndiName Name under which the object must be bound * @param who Object to bind in JNDI * @param classType Class type under which should appear the bound object * @param ctx Naming context under which we bind the object * @throws Exception Thrown if a naming exception occurs during binding */ private void bind(String jndiName, Object who, Class classType, Context ctx) throws Exception { // Ah ! This service isn't serializable, so we use a helper class NonSerializableFactory.bind(jndiName, who); Name n = ctx.getNameParser("").parse(jndiName); while (n.size() > 1) { String ctxName = n.get(0); try { ctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException e) { log.debug("creating Subcontext " + ctxName); ctx = ctx.createSubcontext(ctxName); } n = n.getSuffix(1); } // The helper class NonSerializableFactory uses address type nns, we go on to // use the helper class to bind the service object in JNDI StringRefAddr addr = new StringRefAddr("nns", jndiName); Reference ref = new Reference(classType.getName(), addr, NonSerializableFactory.class.getName(), null); ctx.rebind(n.get(0), ref); } private void unbind(String jndiName, Context ctx) throws Exception { NonSerializableFactory.unbind(jndiName); // ctx.unbind(jndiName); } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/VersionedItem.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000346111714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional; /** * @author Steve Ebersole */ public class VersionedItem { private Long id; private Long version; private String name; private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000024200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeJtaTransactionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002410311714611271032622 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * SimpleJtaTransactionImpl variant that works with DualNodeTransactionManagerImpl. * * TODO: Merge with single node transaction manager * * @author Brian Stansberry */ public class DualNodeJtaTransactionImpl implements Transaction { private static final Log log = LogFactory.getLog(DualNodeJtaTransactionImpl.class); private int status; private LinkedList synchronizations; private Connection connection; // the only resource we care about is jdbc connection private final DualNodeJtaTransactionManagerImpl jtaTransactionManager; private List enlistedResources = new ArrayList(); private Xid xid = new DualNodeJtaTransactionXid(); public DualNodeJtaTransactionImpl(DualNodeJtaTransactionManagerImpl jtaTransactionManager) { this.jtaTransactionManager = jtaTransactionManager; this.status = Status.STATUS_ACTIVE; } public int getStatus() { return status; } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { if (status == Status.STATUS_MARKED_ROLLBACK) { log.trace("on commit, status was marked for rollback-only"); rollback(); } else { status = Status.STATUS_PREPARING; for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.beforeCompletion(); } if (!runXaResourcePrepare()) { status = Status.STATUS_ROLLING_BACK; } else { status = Status.STATUS_PREPARED; } status = Status.STATUS_COMMITTING; if (connection != null) { try { connection.commit(); connection.close(); } catch (SQLException sqle) { status = Status.STATUS_UNKNOWN; throw new SystemException(); } } runXaResourceCommitTx(); status = Status.STATUS_COMMITTED; for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.afterCompletion(status); } // status = Status.STATUS_NO_TRANSACTION; jtaTransactionManager.endCurrent(this); } } public void rollback() throws IllegalStateException, SystemException { status = Status.STATUS_ROLLING_BACK; runXaResourceRollback(); status = Status.STATUS_ROLLEDBACK; if (connection != null) { try { connection.rollback(); connection.close(); } catch (SQLException sqle) { status = Status.STATUS_UNKNOWN; throw new SystemException(); } } if (synchronizations != null) { for (int i = 0; i < synchronizations.size(); i++) { Synchronization s = (Synchronization) synchronizations.get(i); s.afterCompletion(status); } } // status = Status.STATUS_NO_TRANSACTION; jtaTransactionManager.endCurrent(this); } public void setRollbackOnly() throws IllegalStateException, SystemException { status = Status.STATUS_MARKED_ROLLBACK; } public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { // todo : find the spec-allowable statuses during which synch can be registered... if (synchronizations == null) { synchronizations = new LinkedList(); } synchronizations.add(synchronization); } public void enlistConnection(Connection connection) { if (this.connection != null) { throw new IllegalStateException("Connection already registered"); } this.connection = connection; } public Connection getEnlistedConnection() { return connection; } public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException { enlistedResources.add(new WrappedXaResource(xaResource)); try { xaResource.start(xid, 0); } catch (XAException e) { log.error("Got an exception", e); throw new SystemException(e.getMessage()); } return true; } public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException { throw new SystemException("not supported"); } public Collection getEnlistedResources() { return enlistedResources; } private boolean runXaResourcePrepare() throws SystemException { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.prepare(xid); } catch (XAException e) { log.trace("The resource wants to rollback!", e); return false; } catch (Throwable th) { log.error("Unexpected error from resource manager!", th); throw new SystemException(th.getMessage()); } } return true; } private void runXaResourceRollback() { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.rollback(xid); } catch (XAException e) { log.warn("Error while rolling back",e); } } } private boolean runXaResourceCommitTx() throws HeuristicMixedException { Collection resources = getEnlistedResources(); for (XAResource res : resources) { try { res.commit(xid, false);//todo we only support one phase commit for now, change this!!! } catch (XAException e) { log.warn("exception while committing",e); throw new HeuristicMixedException(e.getMessage()); } } return true; } private static class DualNodeJtaTransactionXid implements Xid { private static AtomicInteger txIdCounter = new AtomicInteger(0); private int id = txIdCounter.incrementAndGet(); public int getFormatId() { return id; } public byte[] getGlobalTransactionId() { throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!! } public byte[] getBranchQualifier() { throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!! } @Override public String toString() { return getClass().getSimpleName() + "{" + "id=" + id + '}'; } } private class WrappedXaResource implements XAResource { private final XAResource xaResource; private int prepareResult; public WrappedXaResource(XAResource xaResource) { this.xaResource = xaResource; } @Override public void commit(Xid xid, boolean b) throws XAException { // Commit only if not read only. if (prepareResult != XAResource.XA_RDONLY) xaResource.commit(xid, b); else log.trace("Not committing {0} due to readonly.", xid); } @Override public void end(Xid xid, int i) throws XAException { xaResource.end(xid, i); } @Override public void forget(Xid xid) throws XAException { xaResource.forget(xid); } @Override public int getTransactionTimeout() throws XAException { return xaResource.getTransactionTimeout(); } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return xaResource.isSameRM(xaResource); } @Override public int prepare(Xid xid) throws XAException { prepareResult = xaResource.prepare(xid); return prepareResult; } @Override public Xid[] recover(int i) throws XAException { return xaResource.recover(i); } @Override public void rollback(Xid xid) throws XAException { xaResource.rollback(xid); } @Override public boolean setTransactionTimeout(int i) throws XAException { return xaResource.setTransactionTimeout(i); } @Override public void start(Xid xid, int i) throws XAException { xaResource.start(xid, i); } } } ././@LongLink0000000000000000000000000000024600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeConnectionProviderImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000622511714611271032627 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.connection.ConnectionProvider; import org.hibernate.connection.ConnectionProviderFactory; /** * A {@link ConnectionProvider} implementation adding JTA-style transactionality around the returned * connections using the {@link DualNodeJtaTransactionManagerImpl}. * * @author Brian Stansberry */ public class DualNodeConnectionProviderImpl implements ConnectionProvider { private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider(); private String nodeId; private boolean isTransactional; public static ConnectionProvider getActualConnectionProvider() { return actualConnectionProvider; } public void configure(Properties props) throws HibernateException { nodeId = props.getProperty(DualNodeTestCase.NODE_ID_PROP); if (nodeId == null) throw new HibernateException(DualNodeTestCase.NODE_ID_PROP + " not configured"); } public Connection getConnection() throws SQLException { DualNodeJtaTransactionImpl currentTransaction = DualNodeJtaTransactionManagerImpl .getInstance(nodeId).getCurrentTransaction(); if (currentTransaction == null) { isTransactional = false; return actualConnectionProvider.getConnection(); } else { isTransactional = true; Connection connection = currentTransaction.getEnlistedConnection(); if (connection == null) { connection = actualConnectionProvider.getConnection(); currentTransaction.enlistConnection(connection); } return connection; } } public void closeConnection(Connection conn) throws SQLException { if (!isTransactional) { conn.close(); } } public void close() throws HibernateException { actualConnectionProvider.close(); } public boolean supportsAggressiveRelease() { return true; } } ././@LongLink0000000000000000000000000000025100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeJtaTransactionManagerImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001330711714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.util.Hashtable; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.test.cache.infinispan.tm.XaTransactionManagerImpl; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Variant of SimpleJtaTransactionManagerImpl that doesn't use a VM-singleton, but rather a set of * impls keyed by a node id. * * TODO: Merge with single node transaction manager as much as possible * * @author Brian Stansberry */ public class DualNodeJtaTransactionManagerImpl implements TransactionManager { private static final Log log = LogFactory.getLog(DualNodeJtaTransactionManagerImpl.class); private static final Hashtable INSTANCES = new Hashtable(); private ThreadLocal currentTransaction = new ThreadLocal(); private String nodeId; public synchronized static DualNodeJtaTransactionManagerImpl getInstance(String nodeId) { DualNodeJtaTransactionManagerImpl tm = (DualNodeJtaTransactionManagerImpl) INSTANCES .get(nodeId); if (tm == null) { tm = new DualNodeJtaTransactionManagerImpl(nodeId); INSTANCES.put(nodeId, tm); } return tm; } public synchronized static void cleanupTransactions() { for (java.util.Iterator it = INSTANCES.values().iterator(); it.hasNext();) { TransactionManager tm = (TransactionManager) it.next(); try { tm.suspend(); } catch (Exception e) { log.error("Exception cleaning up TransactionManager " + tm); } } } public synchronized static void cleanupTransactionManagers() { INSTANCES.clear(); } private DualNodeJtaTransactionManagerImpl(String nodeId) { this.nodeId = nodeId; } public int getStatus() throws SystemException { Transaction tx = getCurrentTransaction(); return tx == null ? Status.STATUS_NO_TRANSACTION : tx.getStatus(); } public Transaction getTransaction() throws SystemException { return (Transaction) currentTransaction.get(); } public DualNodeJtaTransactionImpl getCurrentTransaction() { return (DualNodeJtaTransactionImpl) currentTransaction.get(); } public void begin() throws NotSupportedException, SystemException { currentTransaction.set(new DualNodeJtaTransactionImpl(this)); } public Transaction suspend() throws SystemException { DualNodeJtaTransactionImpl suspended = getCurrentTransaction(); log.trace(nodeId + ": Suspending " + suspended + " for thread " + Thread.currentThread().getName()); currentTransaction.set(null); return suspended; } public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { currentTransaction.set((DualNodeJtaTransactionImpl) transaction); log.trace(nodeId + ": Resumed " + transaction + " for thread " + Thread.currentThread().getName()); } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { Transaction tx = getCurrentTransaction(); if (tx == null) { throw new IllegalStateException("no current transaction to commit"); } tx.commit(); } public void rollback() throws IllegalStateException, SecurityException, SystemException { Transaction tx = getCurrentTransaction(); if (tx == null) { throw new IllegalStateException("no current transaction"); } tx.rollback(); } public void setRollbackOnly() throws IllegalStateException, SystemException { Transaction tx = getCurrentTransaction(); if (tx == null) { throw new IllegalStateException("no current transaction"); } tx.setRollbackOnly(); } public void setTransactionTimeout(int i) throws SystemException { } void endCurrent(DualNodeJtaTransactionImpl transaction) { if (transaction == currentTransaction.get()) { currentTransaction.set(null); } } public String toString() { StringBuffer sb = new StringBuffer(getClass().getName()); sb.append("[nodeId="); sb.append(nodeId); sb.append("]"); return sb.toString(); } } ././@LongLink0000000000000000000000000000024400000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/RepeatableSessionRefreshTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000274711714611271032634 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.cluster; /** * RepeatableSessionRefreshTest. * * @author Galder Zamarreño * @since 3.5 */ public class RepeatableSessionRefreshTest extends SessionRefreshTestCase { private static final String CACHE_CONFIG = "entity-repeatable"; public RepeatableSessionRefreshTest(String string) { super(string); } @Override protected String getEntityCacheConfigName() { return CACHE_CONFIG; } } ././@LongLink0000000000000000000000000000024100000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/ClusterAwareRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001126111714611271032623 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.util.Hashtable; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.TimestampsRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Settings; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * ClusterAwareRegionFactory. * * @author Galder Zamarreño * @since 3.5 */ public class ClusterAwareRegionFactory implements RegionFactory { private static final Log log = LogFactory.getLog(ClusterAwareRegionFactory.class); private static final Hashtable cacheManagers = new Hashtable(); private final InfinispanRegionFactory delegate = new InfinispanRegionFactory(); private String cacheManagerName; private boolean locallyAdded; public ClusterAwareRegionFactory(Properties props) { } public static EmbeddedCacheManager getCacheManager(String name) { return cacheManagers.get(name); } public static void addCacheManager(String name, EmbeddedCacheManager manager) { cacheManagers.put(name, manager); } public static void clearCacheManagers() { for (EmbeddedCacheManager manager : cacheManagers.values()) { try { manager.stop(); } catch (Exception e) { log.error("Exception cleaning up CacheManager " + manager, e); } } cacheManagers.clear(); } public void start(Settings settings, Properties properties) throws CacheException { cacheManagerName = properties.getProperty(DualNodeTestCase.NODE_ID_PROP); EmbeddedCacheManager existing = getCacheManager(cacheManagerName); locallyAdded = (existing == null); if (locallyAdded) { delegate.start(settings, properties); cacheManagers.put(cacheManagerName, delegate.getCacheManager()); } else { delegate.setCacheManager(existing); } } public void stop() { if (locallyAdded) cacheManagers.remove(cacheManagerName); delegate.stop(); } public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { return delegate.buildCollectionRegion(regionName, properties, metadata); } public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { return delegate.buildEntityRegion(regionName, properties, metadata); } public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { return delegate.buildQueryResultsRegion(regionName, properties); } public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { return delegate.buildTimestampsRegion(regionName, properties); } public boolean isMinimalPutsEnabledByDefault() { return delegate.isMinimalPutsEnabledByDefault(); } @Override public AccessType getDefaultAccessType() { return AccessType.TRANSACTIONAL; } public long nextTimestamp() { return delegate.nextTimestamp(); } } ././@LongLink0000000000000000000000000000025400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/EntityCollectionInvalidationTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000003235511714611271032632 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.transaction.TransactionManager; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cache.CacheKey; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.test.cache.infinispan.functional.Contact; import org.hibernate.test.cache.infinispan.functional.Customer; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.jboss.util.collection.ConcurrentSet; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * EntityCollectionInvalidationTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class EntityCollectionInvalidationTestCase extends DualNodeTestCase { private static final Log log = LogFactory.getLog(EntityCollectionInvalidationTestCase.class); private static final long SLEEP_TIME = 50l; private static final Integer CUSTOMER_ID = new Integer(1); static int test = 0; public EntityCollectionInvalidationTestCase(String string) { super(string); } protected String getEntityCacheConfigName() { return "entity"; } public void testAll() throws Exception { log.info("*** testAll()"); // Bind a listener to the "local" cache // Our region factory makes its CacheManager available to us CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); // Cache localCache = localManager.getCache("entity"); Cache localCustomerCache = localManager.getCache(Customer.class.getName()); Cache localContactCache = localManager.getCache(Contact.class.getName()); Cache localCollectionCache = localManager.getCache(Customer.class.getName() + ".contacts"); MyListener localListener = new MyListener("local"); localCustomerCache.addListener(localListener); localContactCache.addListener(localListener); localCollectionCache.addListener(localListener); TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); // Bind a listener to the "remote" cache CacheContainer remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); Cache remoteCustomerCache = remoteManager.getCache(Customer.class.getName()); Cache remoteContactCache = remoteManager.getCache(Contact.class.getName()); Cache remoteCollectionCache = remoteManager.getCache(Customer.class.getName() + ".contacts"); MyListener remoteListener = new MyListener("remote"); remoteCustomerCache.addListener(remoteListener); remoteContactCache.addListener(remoteListener); remoteCollectionCache.addListener(remoteListener); TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); SessionFactory localFactory = getEnvironment().getSessionFactory(); SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); try { assertTrue(remoteListener.isEmpty()); assertTrue(localListener.isEmpty()); log.debug("Create node 0"); IdContainer ids = createCustomer(localFactory, localTM); assertTrue(remoteListener.isEmpty()); assertTrue(localListener.isEmpty()); // Sleep a bit to let async commit propagate. Really just to // help keep the logs organized for debugging any issues sleep(SLEEP_TIME); log.debug("Find node 0"); // This actually brings the collection into the cache getCustomer(ids.customerId, localFactory, localTM); sleep(SLEEP_TIME); // Now the collection is in the cache so, the 2nd "get" // should read everything from the cache log.debug("Find(2) node 0"); localListener.clear(); getCustomer(ids.customerId, localFactory, localTM); // Check the read came from the cache log.debug("Check cache 0"); assertLoadedFromCache(localListener, ids.customerId, ids.contactIds); log.debug("Find node 1"); // This actually brings the collection into the cache since invalidation is in use getCustomer(ids.customerId, remoteFactory, remoteTM); // Now the collection is in the cache so, the 2nd "get" // should read everything from the cache log.debug("Find(2) node 1"); remoteListener.clear(); getCustomer(ids.customerId, remoteFactory, remoteTM); // Check the read came from the cache log.debug("Check cache 1"); assertLoadedFromCache(remoteListener, ids.customerId, ids.contactIds); // Modify customer in remote remoteListener.clear(); ids = modifyCustomer(ids.customerId, remoteFactory, remoteTM); sleep(250); assertLoadedFromCache(remoteListener, ids.customerId, ids.contactIds); // After modification, local cache should have been invalidated and hence should be empty assertEquals(0, getValidKeyCount(localCollectionCache.keySet())); assertEquals(0, getValidKeyCount(localCustomerCache.keySet())); } catch (Exception e) { log.error("Error", e); throw e; } finally { // cleanup the db log.debug("Cleaning up"); cleanup(localFactory, localTM); } } private IdContainer createCustomer(SessionFactory sessionFactory, TransactionManager tm) throws Exception { log.debug("CREATE CUSTOMER"); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Customer customer = new Customer(); customer.setName("JBoss"); Set contacts = new HashSet(); Contact kabir = new Contact(); kabir.setCustomer(customer); kabir.setName("Kabir"); kabir.setTlf("1111"); contacts.add(kabir); Contact bill = new Contact(); bill.setCustomer(customer); bill.setName("Bill"); bill.setTlf("2222"); contacts.add(bill); customer.setContacts(contacts); session.save(customer); tm.commit(); IdContainer ids = new IdContainer(); ids.customerId = customer.getId(); Set contactIds = new HashSet(); contactIds.add(kabir.getId()); contactIds.add(bill.getId()); ids.contactIds = contactIds; return ids; } catch (Exception e) { log.error("Caught exception creating customer", e); try { tm.rollback(); } catch (Exception e1) { log.error("Exception rolling back txn", e1); } throw e; } finally { log.debug("CREATE CUSTOMER - END"); } } private Customer getCustomer(Integer id, SessionFactory sessionFactory, TransactionManager tm) throws Exception { log.debug("Find customer with id=" + id); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Customer customer = doGetCustomer(id, session, tm); tm.commit(); return customer; } catch (Exception e) { try { tm.rollback(); } catch (Exception e1) { log.error("Exception rolling back txn", e1); } throw e; } finally { log.debug("Find customer ended."); } } private Customer doGetCustomer(Integer id, Session session, TransactionManager tm) throws Exception { Customer customer = (Customer) session.get(Customer.class, id); // Access all the contacts for (Iterator it = customer.getContacts().iterator(); it.hasNext();) { ((Contact) it.next()).getName(); } return customer; } private IdContainer modifyCustomer(Integer id, SessionFactory sessionFactory, TransactionManager tm) throws Exception { log.debug("Modify customer with id=" + id); tm.begin(); try { Session session = sessionFactory.getCurrentSession(); IdContainer ids = new IdContainer(); Set contactIds = new HashSet(); Customer customer = doGetCustomer(id, session, tm); customer.setName("NewJBoss"); ids.customerId = customer.getId(); Set contacts = customer.getContacts(); for (Contact c : contacts) { contactIds.add(c.getId()); } Contact contact = contacts.iterator().next(); contacts.remove(contact); contactIds.remove(contact.getId()); ids.contactIds = contactIds; contact.setCustomer(null); session.save(customer); tm.commit(); return ids; } catch (Exception e) { try { tm.rollback(); } catch (Exception e1) { log.error("Exception rolling back txn", e1); } throw e; } finally { log.debug("Find customer ended."); } } private void cleanup(SessionFactory sessionFactory, TransactionManager tm) throws Exception { tm.begin(); try { Session session = sessionFactory.getCurrentSession(); Customer c = (Customer) session.get(Customer.class, CUSTOMER_ID); if (c != null) { Set contacts = c.getContacts(); for (Iterator it = contacts.iterator(); it.hasNext();) session.delete(it.next()); c.setContacts(null); session.delete(c); } tm.commit(); } catch (Exception e) { try { tm.rollback(); } catch (Exception e1) { log.error("Exception rolling back txn", e1); } log.error("Caught exception in cleanup", e); } } private void assertLoadedFromCache(MyListener listener, Integer custId, Set contactIds) { assertTrue("Customer#" + custId + " was in cache", listener.visited.contains("Customer#" + custId)); for (Iterator it = contactIds.iterator(); it.hasNext();) { Integer contactId = (Integer) it.next(); assertTrue("Contact#" + contactId + " was in cache", listener.visited.contains("Contact#" + contactId)); assertTrue("Contact#" + contactId + " was in cache", listener.visited.contains("Contact#" + contactId)); } assertTrue("Customer.contacts" + custId + " was in cache", listener.visited .contains("Customer.contacts#" + custId)); } protected int getValidKeyCount(Set keys) { int result = 0; for (Object key : keys) { if (!(CacheHelper.isEvictAllNotification(key))) { result++; } } return result; } @Listener public static class MyListener { private static final Log log = LogFactory.getLog(MyListener.class); private Set visited = new ConcurrentSet(); private final String name; public MyListener(String name) { this.name = name; } public void clear() { visited.clear(); } public boolean isEmpty() { return visited.isEmpty(); } @CacheEntryVisited public void nodeVisited(CacheEntryVisitedEvent event) { log.debug(event.toString()); if (!event.isPre()) { CacheKey cacheKey = (CacheKey) event.getKey(); Integer primKey = (Integer) cacheKey.getKey(); String key = (String) cacheKey.getEntityOrRoleName() + '#' + primKey; log.debug("MyListener[" + name +"] - Visiting key " + key); // String name = fqn.toString(); String token = ".functional."; int index = key.indexOf(token); if (index > -1) { index += token.length(); key = key.substring(index); log.debug("MyListener[" + name +"] - recording visit to " + key); visited.add(key); } } } } private class IdContainer { Integer customerId; Set contactIds; } } ././@LongLink0000000000000000000000000000023600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/SessionRefreshTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001325011714611271032623 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.cluster; import javax.transaction.TransactionManager; import org.hibernate.SessionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.test.cache.infinispan.functional.classloader.Account; import org.hibernate.test.cache.infinispan.functional.classloader.ClassLoaderTestDAO; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.test.TestingUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SessionRefreshTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class SessionRefreshTestCase extends DualNodeTestCase { public static final String OUR_PACKAGE = SessionRefreshTestCase.class.getPackage().getName(); protected final Logger log = LoggerFactory.getLogger(getClass()); static int test = 0; private Cache localCache; public SessionRefreshTestCase(String string) { super(string); } protected String getEntityCacheConfigName() { return "entity"; } /** * Disables use of the second level cache for this session factory. * * {@inheritDoc} */ @Override protected void configureSecondNode(Configuration cfg) { super.configureSecondNode(cfg); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false"); } @Override protected void standardConfigure(Configuration cfg) { super.standardConfigure(cfg); cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, getEntityCacheConfigName()); } @Override public String[] getMappings() { return new String[] { "cache/infinispan/functional/classloader/Account.hbm.xml" }; } @Override protected void cleanupTransactionManagement() { // Don't clean up the managers, just the transactions // Managers are still needed by the long-lived caches DualNodeJtaTransactionManagerImpl.cleanupTransactions(); } public void testRefreshAfterExternalChange() throws Exception { // First session factory uses a cache CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); localCache = localManager.getCache(Account.class.getName()); TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); SessionFactory localFactory = getEnvironment().getSessionFactory(); // Second session factory doesn't; just needs a transaction manager // However, start at least the cache to avoid issues with replication and cache not being there ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE).getCache(Account.class.getName()); TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); Integer id = new Integer(1); dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTestCase.LOCAL); // Basic sanity check Account acct1 = dao1.getAccount(id); assertNotNull(acct1); assertEquals(DualNodeTestCase.LOCAL, acct1.getBranch()); // This dao's session factory isn't caching, so cache won't see this change dao1.updateAccountBranch(id, DualNodeTestCase.REMOTE); // dao1's session doesn't touch the cache, // so reading from dao0 should show a stale value from the cache // (we check to confirm the cache is used) Account acct0 = dao0.getAccount(id); assertNotNull(acct0); assertEquals(DualNodeTestCase.LOCAL, acct0.getBranch()); log.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache)); // Now call session.refresh and confirm we get the correct value acct0 = dao0.getAccountWithRefresh(id); assertNotNull(acct0); assertEquals(DualNodeTestCase.REMOTE, acct0.getBranch()); log.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache)); // Double check with a brand new session, in case the other session // for some reason bypassed the 2nd level cache ClassLoaderTestDAO dao0A = new ClassLoaderTestDAO(localFactory, localTM); Account acct0A = dao0A.getAccount(id); assertNotNull(acct0A); assertEquals(DualNodeTestCase.REMOTE, acct0A.getBranch()); log.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache)); } } ././@LongLink0000000000000000000000000000023000000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001723611714611271032633 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional.cluster; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Mappings; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.testing.junit.functional.ExecutionEnvironment; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.transaction.CMTTransactionFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * AbstractDualNodeTestCase. * * @author Galder Zamarreño * @since 3.5 */ public abstract class DualNodeTestCase extends FunctionalTestCase { private static final Log log = LogFactory.getLog(DualNodeTestCase.class); public static final String NODE_ID_PROP = "hibernate.test.cluster.node.id"; public static final String LOCAL = "local"; public static final String REMOTE = "remote"; private ExecutionEnvironment secondNodeEnvironment; private Session secondNodeSession; public DualNodeTestCase(String string) { super(string); } public String[] getMappings() { return new String[] { "cache/infinispan/functional/Contact.hbm.xml", "cache/infinispan/functional/Customer.hbm.xml" }; } @Override public String getCacheConcurrencyStrategy() { return "transactional"; } protected Class getCacheRegionFactory() { return ClusterAwareRegionFactory.class; } @Override public void configure(Configuration cfg) { standardConfigure(cfg); configureFirstNode(cfg); } @Override protected void prepareTest() throws Exception { log.info("Building second node locally managed execution env"); secondNodeEnvironment = new ExecutionEnvironment(new SecondNodeSettings()); secondNodeEnvironment.initialize(); super.prepareTest(); } @Override protected void runTest() throws Throwable { try { super.runTest(); } finally { if ( secondNodeSession != null && secondNodeSession.isOpen() ) { if ( secondNodeSession.isConnected() ) { secondNodeSession.connection().rollback(); } secondNodeSession.close(); secondNodeSession = null; fail( "unclosed session" ); } else { secondNodeSession = null; } } } @Override protected void cleanupTest() throws Exception { try { super.cleanupTest(); log.info( "Destroying second node locally managed execution env" ); secondNodeEnvironment.complete(); secondNodeEnvironment = null; } finally { cleanupTransactionManagement(); } } protected void cleanupTransactionManagement() { DualNodeJtaTransactionManagerImpl.cleanupTransactions(); DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers(); } public ExecutionEnvironment getSecondNodeEnvironment() { return secondNodeEnvironment; } protected Class getConnectionProviderClass() { return DualNodeConnectionProviderImpl.class; } protected Class getTransactionManagerLookupClass() { return DualNodeTransactionManagerLookup.class; } protected Class getTransactionFactoryClass() { return CMTTransactionFactory.class; } /** * Apply any node-specific configurations to our first node. * * @param cfg * Configuration to update. */ protected void configureFirstNode(Configuration cfg) { cfg.setProperty(NODE_ID_PROP, LOCAL); } /** * Apply any node-specific configurations to our second node. * * @param cfg * Configuration to update. */ protected void configureSecondNode(Configuration cfg) { cfg.setProperty(NODE_ID_PROP, REMOTE); } protected void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { log.warn("Interrupted during sleep", e); } } protected boolean getUseQueryCache() { return true; } protected void standardConfigure(Configuration cfg) { super.configure(cfg); cfg.setProperty(Environment.CONNECTION_PROVIDER, getConnectionProviderClass().getName()); cfg.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, getTransactionManagerLookupClass().getName()); cfg.setProperty(Environment.TRANSACTION_STRATEGY, getTransactionFactoryClass().getName()); cfg.setProperty(Environment.CACHE_REGION_FACTORY, getCacheRegionFactory().getName()); cfg.setProperty(Environment.USE_QUERY_CACHE, String.valueOf(getUseQueryCache())); } /** * Settings impl that delegates most calls to the DualNodeTestCase itself, but overrides the * configure method to allow separate cache settings for the second node. */ public class SecondNodeSettings implements ExecutionEnvironment.Settings { private final DualNodeTestCase delegate; public SecondNodeSettings() { this.delegate = DualNodeTestCase.this; } @Override public Class[] getAnnotatedClasses() { return this.delegate.getAnnotatedClasses(); } /** * This is the important one -- we extend the delegate's work by adding second-node specific * settings */ public void configure(Configuration arg0) { delegate.standardConfigure(arg0); configureSecondNode(arg0); } /** * Disable creating of schemas; we let the primary session factory do that to our shared * database. */ public boolean createSchema() { return false; } /** * Disable creating of schemas; we let the primary session factory do that to our shared * database. */ public boolean recreateSchemaAfterFailure() { return false; } public void afterConfigurationBuilt(Mappings arg0, Dialect arg1) { delegate.afterConfigurationBuilt(arg0, arg1); } public void afterSessionFactoryBuilt(SessionFactoryImplementor arg0) { delegate.afterSessionFactoryBuilt(arg0); } public boolean appliesTo(Dialect arg0) { return delegate.appliesTo(arg0); } public String getBaseForMappings() { return delegate.getBaseForMappings(); } public String getCacheConcurrencyStrategy() { return delegate.getCacheConcurrencyStrategy(); } public String[] getMappings() { return delegate.getMappings(); } public boolean overrideCacheStrategy() { return delegate.overrideCacheStrategy(); } } } ././@LongLink0000000000000000000000000000025000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTransactionManagerLookup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000434611714611271032631 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional.cluster; import java.util.Properties; import javax.transaction.TransactionManager; import javax.transaction.Transaction; import org.hibernate.transaction.TransactionManagerLookup; import org.hibernate.HibernateException; /** * SimpleJtaTransactionManagerLookupImpl subclass that finds a different DualNodeTransactionManager * based on the value of property {@link DualNodeTestUtil#NODE_ID_PROP}. * * @author Brian Stansberry */ public class DualNodeTransactionManagerLookup implements TransactionManagerLookup { public TransactionManager getTransactionManager(Properties props) throws HibernateException { String nodeId = props.getProperty(DualNodeTestCase.NODE_ID_PROP); if (nodeId == null) throw new HibernateException(DualNodeTestCase.NODE_ID_PROP + " not configured"); return DualNodeJtaTransactionManagerImpl.getInstance(nodeId); } public String getUserTransactionName() { throw new UnsupportedOperationException("jndi currently not implemented for these tests"); } public Object getTransactionIdentifier(Transaction transaction) { return transaction; } } ././@LongLink0000000000000000000000000000023200000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicTransactionalTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002451411714611271032630 0ustar ebourgebourgpackage org.hibernate.test.cache.infinispan.functional; import java.io.Serializable; import java.util.Map; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cache.entry.CacheEntry; import org.hibernate.cfg.Configuration; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * @author Galder Zamarreño * @since 3.5 */ public class BasicTransactionalTestCase extends SingleNodeTestCase { private static final Log log = LogFactory.getLog(BasicTransactionalTestCase.class); public BasicTransactionalTestCase(String string) { super(string); } @Override public void configure(Configuration cfg) { super.configure(cfg); } public void testEntityCache() throws Exception { Item item = new Item("chris", "Chris's Item"); beginTx(); try { Session s = openSession(); s.getTransaction().begin(); s.persist(item); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } log.info("Entry persisted, let's load and delete it."); beginTx(); try { Session s = openSession(); Item found = (Item) s.load(Item.class, item.getId()); Statistics stats = s.getSessionFactory().getStatistics(); log.info(stats.toString()); assertEquals(item.getDescription(), found.getDescription()); assertEquals(0, stats.getSecondLevelCacheMissCount()); assertEquals(1, stats.getSecondLevelCacheHitCount()); s.delete(found); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testCollectionCache() throws Exception { Item item = new Item("chris", "Chris's Item"); Item another = new Item("another", "Owned Item"); item.addItem(another); beginTx(); try { Session s = openSession(); s.getTransaction().begin(); s.persist(item); s.persist(another); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { Session s = openSession(); Item loaded = (Item) s.load(Item.class, item.getId()); assertEquals(1, loaded.getItems().size()); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { Session s = openSession(); Statistics stats = s.getSessionFactory().getStatistics(); SecondLevelCacheStatistics cStats = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".items"); Item loadedWithCachedCollection = (Item) s.load(Item.class, item.getId()); stats.logSummary(); assertEquals(item.getName(), loadedWithCachedCollection.getName()); assertEquals(item.getItems().size(), loadedWithCachedCollection.getItems().size()); assertEquals(1, cStats.getHitCount()); Map cacheEntries = cStats.getEntries(); assertEquals(1, cacheEntries.size()); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testStaleWritesLeaveCacheConsistent() throws Exception { VersionedItem item = null; Transaction txn = null; Session s = null; beginTx(); try { s = openSession(); txn = s.beginTransaction(); item = new VersionedItem(); item.setName("steve"); item.setDescription("steve's item"); s.save(item); txn.commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } Long initialVersion = item.getVersion(); // manually revert the version property item.setVersion(new Long(item.getVersion().longValue() - 1)); beginTx(); try { s = openSession(); txn = s.beginTransaction(); s.update(item); txn.commit(); fail("expected stale write to fail"); } catch (Exception e) { setRollbackOnlyTxExpected(e); } finally { commitOrRollbackTx(); if (s != null && s.isOpen()) { try { s.close(); } catch (Throwable ignore) { } } } // check the version value in the cache... SecondLevelCacheStatistics slcs = sfi().getStatistics().getSecondLevelCacheStatistics(VersionedItem.class.getName()); Object entry = slcs.getEntries().get(item.getId()); Long cachedVersionValue; cachedVersionValue = (Long) ((CacheEntry) entry).getVersion(); assertEquals(initialVersion.longValue(), cachedVersionValue.longValue()); beginTx(); try { // cleanup s = openSession(); txn = s.beginTransaction(); item = (VersionedItem) s.load(VersionedItem.class, item.getId()); s.delete(item); txn.commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testQueryCacheInvalidation() throws Exception { Session s = null; Transaction t = null; Item i = null; beginTx(); try { s = openSession(); t = s.beginTransaction(); i = new Item(); i.setName("widget"); i.setDescription("A really top-quality, full-featured widget."); s.persist(i); t.commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } SecondLevelCacheStatistics slcs = s.getSessionFactory().getStatistics().getSecondLevelCacheStatistics(Item.class.getName()); assertEquals(slcs.getPutCount(), 1); assertEquals(slcs.getElementCountInMemory(), 1); assertEquals(slcs.getEntries().size(), 1); beginTx(); try { s = openSession(); t = s.beginTransaction(); i = (Item) s.get(Item.class, i.getId()); assertEquals(slcs.getHitCount(), 1); assertEquals(slcs.getMissCount(), 0); i.setDescription("A bog standard item"); t.commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } assertEquals(slcs.getPutCount(), 2); CacheEntry entry = (CacheEntry) slcs.getEntries().get(i.getId()); Serializable[] ser = entry.getDisassembledState(); assertTrue(ser[0].equals("widget")); assertTrue(ser[1].equals("A bog standard item")); beginTx(); try { // cleanup s = openSession(); t = s.beginTransaction(); s.delete(i); t.commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testQueryCache() throws Exception { Session s; Item item = new Item("chris", "Chris's Item"); beginTx(); try { s = openSession(); s.getTransaction().begin(); s.persist(item); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } // Delay added to guarantee that query cache results won't be considered // as not up to date due to persist session and query results from first // query happening within same 100ms gap. Thread.sleep(100); beginTx(); try { s = openSession(); s.createQuery("from Item").setCacheable(true).list(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { s = openSession(); Statistics stats = s.getSessionFactory().getStatistics(); s.createQuery("from Item").setCacheable(true).list(); assertEquals(1, stats.getQueryCacheHitCount()); s.createQuery("delete from Item").executeUpdate(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testQueryCacheHitInSameTransaction() throws Exception { Session s = null; Item item = new Item("galder", "Galder's Item"); beginTx(); try { s = openSession(); s.getTransaction().begin(); s.persist(item); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } // Delay added to guarantee that query cache results won't be considered // as not up to date due to persist session and query results from first // query happening within same 100ms gap. Thread.sleep(100); beginTx(); try { s = openSession(); Statistics stats = s.getSessionFactory().getStatistics(); s.createQuery("from Item").setCacheable(true).list(); s.createQuery("from Item").setCacheable(true).list(); assertEquals(1, stats.getQueryCacheHitCount()); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { s = openSession(); s.createQuery("delete from Item").executeUpdate(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } public void testEmptySecondLevelCacheEntry() throws Exception { getSessions().getCache().evictEntityRegion(Item.class.getName()); Statistics stats = getSessions().getStatistics(); stats.clear(); SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".items"); Map cacheEntries = statistics.getEntries(); assertEquals(0, cacheEntries.size()); } } ././@LongLink0000000000000000000000000000022500000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicReadOnlyTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000157711714611271032634 0ustar ebourgebourgpackage org.hibernate.test.cache.infinispan.functional; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import java.util.Map; /** * @author Galder Zamarreño * @since 3.5 */ public class BasicReadOnlyTestCase extends SingleNodeTestCase { public BasicReadOnlyTestCase(String string) { super(string); } @Override public String getCacheConcurrencyStrategy() { return "read-only"; } public void testEmptySecondLevelCacheEntry() throws Exception { getSessions().getCache().evictEntityRegion(Item.class.getName()); Statistics stats = getSessions().getStatistics(); stats.clear(); SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".items"); Map cacheEntries = statistics.getEntries(); assertEquals(0, cacheEntries.size()); } }././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000004372111714611271032631 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.functional; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.transaction.TransactionManager; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.connection.ConnectionProvider; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeConnectionProviderImpl; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTransactionManagerLookup; import org.hibernate.transaction.TransactionManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * * @author nikita_tovstoles@mba.berkeley.edu * @author Galder Zamarreño */ public class ConcurrentWriteTest extends SingleNodeTestCase { private static final Log log = LogFactory.getLog(ConcurrentWriteTest.class); private static final boolean trace = log.isTraceEnabled(); /** * when USER_COUNT==1, tests pass, when >4 tests fail */ private static final int USER_COUNT = 5; private static final int ITERATION_COUNT = 150; private static final int THINK_TIME_MILLIS = 10; private static final long LAUNCH_INTERVAL_MILLIS = 10; private static final Random random = new Random(); /** * kill switch used to stop all users when one fails */ private static volatile boolean TERMINATE_ALL_USERS = false; /** * collection of IDs of all customers participating in this test */ private Set customerIDs = new HashSet(); private TransactionManager tm; public ConcurrentWriteTest(String x) { super(x); } @Override protected TransactionManager getTransactionManager() { return DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); } @Override protected Class getCacheRegionFactory() { return InfinispanRegionFactory.class; } @Override protected Class getConnectionProviderClass() { return DualNodeConnectionProviderImpl.class; } @Override protected Class getTransactionManagerLookupClass() { return DualNodeTransactionManagerLookup.class; } /** * test that DB can be queried * * @throws java.lang.Exception */ public void testPingDb() throws Exception { try { beginTx(); getEnvironment().getSessionFactory().getCurrentSession().createQuery("from " + Customer.class.getName()).list(); } catch (Exception e) { setRollbackOnlyTx(e); // setRollbackOnly(); // fail("failed to query DB; exception=" + e); } finally { commitOrRollbackTx(); } } @Override protected void prepareTest() throws Exception { super.prepareTest(); TERMINATE_ALL_USERS = false; } @Override protected void cleanupTest() throws Exception { try { super.cleanupTest(); } finally { cleanup(); // DualNodeJtaTransactionManagerImpl.cleanupTransactions(); // DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers(); } } @Override public void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(DualNodeTestCase.NODE_ID_PROP, DualNodeTestCase.LOCAL); } @Override protected boolean getUseQueryCache() { return true; } public void testSingleUser() throws Exception { // setup Customer customer = createCustomer(0); final Integer customerId = customer.getId(); getCustomerIDs().add(customerId); assertNull("contact exists despite not being added", getFirstContact(customerId)); // check that cache was hit SecondLevelCacheStatistics customerSlcs = getEnvironment().getSessionFactory() .getStatistics().getSecondLevelCacheStatistics(Customer.class.getName()); assertEquals(customerSlcs.getPutCount(), 1); assertEquals(customerSlcs.getElementCountInMemory(), 1); assertEquals(customerSlcs.getEntries().size(), 1); SecondLevelCacheStatistics contactsCollectionSlcs = getEnvironment().getSessionFactory() .getStatistics().getSecondLevelCacheStatistics(Customer.class.getName() + ".contacts"); assertEquals(1, contactsCollectionSlcs.getPutCount()); assertEquals(1, contactsCollectionSlcs.getElementCountInMemory()); assertEquals(1, contactsCollectionSlcs.getEntries().size()); log.info("Add contact to customer {0}", customerId); final Contact contact = addContact(customerId); assertNotNull("contact returned by addContact is null", contact); assertEquals("Customer.contacts cache was not invalidated after addContact", 0, contactsCollectionSlcs.getElementCountInMemory()); assertNotNull("Contact missing after successful add call", getFirstContact(customerId)); // read everyone's contacts readEveryonesFirstContact(); removeContact(customerId); assertNull("contact still exists after successful remove call", getFirstContact(customerId)); } /** * TODO: This will fail until ISPN-??? has been fixed. * * @throws Exception */ public void testManyUsers() throws Throwable { try { // setup - create users for (int i = 0; i < USER_COUNT; i++) { Customer customer = createCustomer(0); getCustomerIDs().add(customer.getId()); } assertEquals("failed to create enough Customers", USER_COUNT, getCustomerIDs().size()); final ExecutorService executor = Executors.newFixedThreadPool(USER_COUNT); CyclicBarrier barrier = new CyclicBarrier(USER_COUNT + 1); List> futures = new ArrayList>(USER_COUNT); for (Integer customerId : getCustomerIDs()) { Future future = executor.submit(new UserRunner(customerId, barrier)); futures.add(future); Thread.sleep(LAUNCH_INTERVAL_MILLIS); // rampup } // barrier.await(); // wait for all threads to be ready barrier.await(45, TimeUnit.SECONDS); // wait for all threads to finish log.info("All threads finished, let's shutdown the executor and check whether any exceptions were reported"); for (Future future : futures) future.get(); log.info("All future gets checked"); } catch (Throwable t) { log.error("Error running test", t); throw t; } } public void cleanup() throws Exception { getCustomerIDs().clear(); String deleteContactHQL = "delete from Contact"; String deleteCustomerHQL = "delete from Customer"; beginTx(); try { Session session = getEnvironment().getSessionFactory().getCurrentSession(); session.createQuery(deleteContactHQL).setFlushMode(FlushMode.AUTO).executeUpdate(); session.createQuery(deleteCustomerHQL).setFlushMode(FlushMode.AUTO).executeUpdate(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } private Customer createCustomer(int nameSuffix) throws Exception { Customer customer = null; beginTx(); try { customer = new Customer(); customer.setName("customer_" + nameSuffix); customer.setContacts(new HashSet()); getEnvironment().getSessionFactory().getCurrentSession().persist(customer); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } return customer; } /** * read first contact of every Customer participating in this test. this forces concurrent cache * writes of Customer.contacts Collection cache node * * @return who cares * @throws java.lang.Exception */ private void readEveryonesFirstContact() throws Exception { beginTx(); try { for (Integer customerId : getCustomerIDs()) { if (TERMINATE_ALL_USERS) { setRollbackOnlyTx(); return; } Customer customer = (Customer) getEnvironment().getSessionFactory().getCurrentSession().load(Customer.class, customerId); Set contacts = customer.getContacts(); if (!contacts.isEmpty()) { contacts.iterator().next(); } } } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } /** * -load existing Customer -get customer's contacts; return 1st one * * @param customerId * @return first Contact or null if customer has none */ private Contact getFirstContact(Integer customerId) throws Exception { assert customerId != null; Contact firstContact = null; beginTx(); try { final Customer customer = (Customer) getEnvironment().getSessionFactory() .getCurrentSession().load(Customer.class, customerId); Set contacts = customer.getContacts(); firstContact = contacts.isEmpty() ? null : contacts.iterator().next(); if (TERMINATE_ALL_USERS) setRollbackOnlyTx(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } return firstContact; } /** * -load existing Customer -create a new Contact and add to customer's contacts * * @param customerId * @return added Contact */ private Contact addContact(Integer customerId) throws Exception { assert customerId != null; Contact contact = null; beginTx(); try { final Customer customer = (Customer) getEnvironment().getSessionFactory() .getCurrentSession().load(Customer.class, customerId); contact = new Contact(); contact.setName("contact name"); contact.setTlf("wtf is tlf?"); contact.setCustomer(customer); customer.getContacts().add(contact); // assuming contact is persisted via cascade from customer if (TERMINATE_ALL_USERS) setRollbackOnlyTx(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } return contact; } /** * remove existing 'contact' from customer's list of contacts * * @param customerId * @throws IllegalStateException * if customer does not own a contact */ private void removeContact(Integer customerId) throws Exception { assert customerId != null; beginTx(); try { Customer customer = (Customer) getEnvironment().getSessionFactory().getCurrentSession() .load(Customer.class, customerId); Set contacts = customer.getContacts(); if (contacts.size() != 1) { throw new IllegalStateException("can't remove contact: customer id=" + customerId + " expected exactly 1 contact, " + "actual count=" + contacts.size()); } Contact contact = contacts.iterator().next(); contacts.remove(contact); contact.setCustomer(null); // explicitly delete Contact because hbm has no 'DELETE_ORPHAN' cascade? // getEnvironment().getSessionFactory().getCurrentSession().delete(contact); //appears to // not be needed // assuming contact is persisted via cascade from customer if (TERMINATE_ALL_USERS) setRollbackOnlyTx(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } } /** * @return the customerIDs */ public Set getCustomerIDs() { return customerIDs; } private String statusOfRunnersToString(Set runners) { assert runners != null; StringBuilder sb = new StringBuilder("TEST CONFIG [userCount=" + USER_COUNT + ", iterationsPerUser=" + ITERATION_COUNT + ", thinkTimeMillis=" + THINK_TIME_MILLIS + "] " + " STATE of UserRunners: "); for (UserRunner r : runners) { sb.append(r.toString() + System.getProperty("line.separator")); } return sb.toString(); } class UserRunner implements Callable { private final CyclicBarrier barrier; final private Integer customerId; private int completedIterations = 0; private Throwable causeOfFailure; public UserRunner(Integer cId, CyclicBarrier barrier) { assert cId != null; this.customerId = cId; this.barrier = barrier; } private boolean contactExists() throws Exception { return getFirstContact(customerId) != null; } public Void call() throws Exception { // name this thread for easier log tracing Thread.currentThread().setName("UserRunnerThread-" + getCustomerId()); log.info("Wait for all executions paths to be ready to perform calls"); try { // barrier.await(); for (int i = 0; i < ITERATION_COUNT && !TERMINATE_ALL_USERS; i++) { contactExists(); if (trace) log.trace("Add contact for customer " + customerId); addContact(customerId); if (trace) log.trace("Added contact"); thinkRandomTime(); contactExists(); thinkRandomTime(); if (trace) log.trace("Read all customers' first contact"); // read everyone's contacts readEveryonesFirstContact(); if (trace) log.trace("Read completed"); thinkRandomTime(); if (trace) log.trace("Remove contact of customer" + customerId); removeContact(customerId); if (trace) log.trace("Removed contact"); contactExists(); thinkRandomTime(); ++completedIterations; if (log.isTraceEnabled()) log.trace("Iteration completed {0}", completedIterations); } } catch (Throwable t) { TERMINATE_ALL_USERS = true; log.error("Error", t); throw new Exception(t); // rollback current transaction if any // really should not happen since above methods all follow begin-commit-rollback pattern // try { // if // (DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestUtil.LOCAL).getTransaction() // != null) { // DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestUtil.LOCAL).rollback(); // } // } catch (SystemException ex) { // throw new RuntimeException("failed to rollback tx", ex); // } } finally { log.info("Wait for all execution paths to finish"); barrier.await(); } return null; } public boolean isSuccess() { return ITERATION_COUNT == getCompletedIterations(); } public int getCompletedIterations() { return completedIterations; } public Throwable getCauseOfFailure() { return causeOfFailure; } public Integer getCustomerId() { return customerId; } @Override public String toString() { return super.toString() + "[customerId=" + getCustomerId() + " iterationsCompleted=" + getCompletedIterations() + " completedAll=" + isSuccess() + " causeOfFailure=" + (this.causeOfFailure != null ? getStackTrace(causeOfFailure) : "") + "] "; } } public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.getBuffer().toString(); } /** * sleep between 0 and THINK_TIME_MILLIS. * * @throws RuntimeException * if sleep is interrupted or TERMINATE_ALL_USERS flag was set to true i n the * meantime */ private void thinkRandomTime() { try { Thread.sleep(random.nextInt(THINK_TIME_MILLIS)); } catch (InterruptedException ex) { throw new RuntimeException("sleep interrupted", ex); } if (TERMINATE_ALL_USERS) { throw new RuntimeException("told to terminate (because a UserRunner had failed)"); } } } ././@LongLink0000000000000000000000000000023600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicJdbcTransactionalTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001031211714611271032617 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.functional; import java.util.Map; import org.hibernate.Session; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.hibernate.transaction.JDBCTransactionFactory; import org.hibernate.transaction.TransactionFactory; import org.hibernate.transaction.TransactionManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * BasicJdbcTransactionalTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class BasicJdbcTransactionalTestCase extends SingleNodeTestCase { private static final Log log = LogFactory.getLog(BasicJdbcTransactionalTestCase.class); public BasicJdbcTransactionalTestCase(String string) { super(string); } protected Class getTransactionFactoryClass() { return JDBCTransactionFactory.class; } protected Class getTransactionManagerLookupClass() { return null; } public void testCollectionCache() throws Exception { Item item = new Item("chris", "Chris's Item"); Item another = new Item("another", "Owned Item"); item.addItem(another); Session s = null; try { s = openSession(); s.beginTransaction(); s.persist(item); s.persist(another); s.getTransaction().commit(); } catch (Exception e) { log.error("Exception", e); s.getTransaction().rollback(); throw e; } finally { s.close(); } try { s = openSession(); s.beginTransaction(); Item loaded = (Item) s.load(Item.class, item.getId()); assertEquals(1, loaded.getItems().size()); } catch (Exception e) { log.error("Exception", e); s.getTransaction().rollback(); throw e; } finally { s.close(); } try { s = openSession(); s.beginTransaction(); Statistics stats = s.getSessionFactory().getStatistics(); SecondLevelCacheStatistics cStats = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".items"); Item loadedWithCachedCollection = (Item) s.load(Item.class, item.getId()); stats.logSummary(); assertEquals(item.getName(), loadedWithCachedCollection.getName()); assertEquals(item.getItems().size(), loadedWithCachedCollection.getItems().size()); assertEquals(1, cStats.getHitCount()); Map cacheEntries = cStats.getEntries(); assertEquals(1, cacheEntries.size()); } catch (Exception e) { log.error("Exception", e); s.getTransaction().rollback(); throw e; } finally { s.close(); } } public void testEmptySecondLevelCacheEntry() throws Exception { getSessions().getCache().evictEntityRegion(Item.class.getName()); Statistics stats = getSessions().getStatistics(); stats.clear(); SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".items"); Map cacheEntries = statistics.getEntries(); assertEquals(0, cacheEntries.size()); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/ReadOnlyTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000337511714611271032632 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests READ_ONLY access when invalidation is used. * * @author Galder Zamarreño * @since 3.5 */ public class ReadOnlyTestCase extends AbstractReadOnlyAccessTestCase { public ReadOnlyTestCase(String name) { super(name); } public static Test suite() throws Exception { TestSuite suite = CacheTestUtil.createFailureExpectedSuite(ReadOnlyTestCase.class); return getTestSetup(suite, "entity"); } @Override public void testCacheConfiguration() { assertTrue("Using Invalidation", isUsingInvalidation()); } } ././@LongLink0000000000000000000000000000024300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractTransactionalAccessTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000327011714611271032624 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.cache.access.AccessType; /** * Base class for tests of TRANSACTIONAL access. * * @author Brian Stansberry */ public abstract class AbstractTransactionalAccessTestCase extends AbstractCollectionRegionAccessStrategyTestCase { /** * Create a new AbstractTransactionalAccessTestCase. * */ public AbstractTransactionalAccessTestCase(String name) { super(name); } @Override protected AccessType getAccessType() { return AccessType.TRANSACTIONAL; } } ././@LongLink0000000000000000000000000000023000000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/ReadOnlyExtraAPITestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000506611714611271032631 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; /** * ReadOnlyExtraAPITestCase. * * @author Galder Zamarreño * @since 3.5 */ public class ReadOnlyExtraAPITestCase extends TransactionalExtraAPITestCase { public ReadOnlyExtraAPITestCase(String name) { super(name); } private static CollectionRegionAccessStrategy localAccessStrategy; @Override protected AccessType getAccessType() { return AccessType.READ_ONLY; } @Override protected CollectionRegionAccessStrategy getCollectionAccessStrategy() { return localAccessStrategy; } @Override protected void setCollectionAccessStrategy(CollectionRegionAccessStrategy strategy) { localAccessStrategy = strategy; } /** * Test method for {@link TransactionalAccess#lockItem(java.lang.Object, java.lang.Object)}. */ @Override public void testLockItem() { try { getCollectionAccessStrategy().lockItem(KEY, new Integer(1)); fail("Call to lockItem did not throw exception"); } catch (UnsupportedOperationException expected) {} } /** * Test method for {@link TransactionalAccess#lockRegion()}. */ @Override public void testLockRegion() { try { getCollectionAccessStrategy().lockRegion(); fail("Call to lockRegion did not throw exception"); } catch (UnsupportedOperationException expected) {} } } ././@LongLink0000000000000000000000000000025600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000004764011714611271032635 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.collection; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import junit.extensions.TestSetup; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.impl.CacheDataDescriptionImpl; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate; import org.hibernate.cache.infinispan.collection.CollectionRegionImpl; import org.hibernate.cache.infinispan.impl.BaseRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.hibernate.util.ComparableComparator; import org.infinispan.Cache; import org.infinispan.transaction.tm.BatchModeTransactionManager; import javax.transaction.TransactionManager; /** * Base class for tests of CollectionRegionAccessStrategy impls. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends AbstractNonFunctionalTestCase { public static final String REGION_NAME = "test/com.foo.test"; public static final String KEY_BASE = "KEY"; public static final String VALUE1 = "VALUE1"; public static final String VALUE2 = "VALUE2"; protected static int testCount; protected static Configuration localCfg; protected static InfinispanRegionFactory localRegionFactory; protected CacheAdapter localCache; protected static Configuration remoteCfg; protected static InfinispanRegionFactory remoteRegionFactory; protected CacheAdapter remoteCache; protected CollectionRegion localCollectionRegion; protected CollectionRegionAccessStrategy localAccessStrategy; protected CollectionRegion remoteCollectionRegion; protected CollectionRegionAccessStrategy remoteAccessStrategy; protected boolean invalidation; protected boolean synchronous; protected Exception node1Exception; protected Exception node2Exception; protected AssertionFailedError node1Failure; protected AssertionFailedError node2Failure; public static Test getTestSetup(Class testClass, String configName) { TestSuite suite = new TestSuite(testClass); return new AccessStrategyTestSetup(suite, configName); } public static Test getTestSetup(Test test, String configName) { return new AccessStrategyTestSetup(test, configName); } /** * Create a new TransactionalAccessTestCase. * * @param name */ public AbstractCollectionRegionAccessStrategyTestCase(String name) { super(name); } protected abstract AccessType getAccessType(); protected void setUp() throws Exception { super.setUp(); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); localCollectionRegion = localRegionFactory.buildCollectionRegion(REGION_NAME, localCfg.getProperties(), getCacheDataDescription()); localCache = ((BaseRegion) localCollectionRegion).getCacheAdapter(); localAccessStrategy = localCollectionRegion.buildAccessStrategy(getAccessType()); invalidation = localCache.isClusteredInvalidation(); synchronous = localCache.isSynchronous(); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); remoteCollectionRegion = remoteRegionFactory.buildCollectionRegion(REGION_NAME, remoteCfg.getProperties(), getCacheDataDescription()); remoteCache = ((BaseRegion) remoteCollectionRegion).getCacheAdapter(); remoteAccessStrategy = remoteCollectionRegion.buildAccessStrategy(getAccessType()); node1Exception = null; node2Exception = null; node1Failure = null; node2Failure = null; } protected void tearDown() throws Exception { super.tearDown(); try { localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); } catch (Exception e) { log.error("Problem purging local cache", e); } try { remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); } catch (Exception e) { log.error("Problem purging remote cache", e); } node1Exception = null; node2Exception = null; node1Failure = null; node2Failure = null; } protected static Configuration createConfiguration(String configName, String configResource) { Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); return cfg; } protected CacheDataDescription getCacheDataDescription() { return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); } protected boolean isUsingInvalidation() { return invalidation; } protected boolean isSynchronous() { return synchronous; } /** * This is just a setup test where we assert that the cache config is as we expected. */ public abstract void testCacheConfiguration(); /** * Test method for {@link CollectionRegionAccessStrategy#getRegion()}. */ public void testGetRegion() { assertEquals("Correct region", localCollectionRegion, localAccessStrategy.getRegion()); } public void testPutFromLoadRemoveDoesNotProduceStaleData() throws Exception { final CountDownLatch pferLatch = new CountDownLatch(1); final CountDownLatch removeLatch = new CountDownLatch(1); TransactionManager tm = DualNodeJtaTransactionManagerImpl.getInstance("test1234"); PutFromLoadValidator validator = new PutFromLoadValidator(tm) { @Override public boolean acquirePutFromLoadLock(Object key) { boolean acquired = super.acquirePutFromLoadLock(key); try { removeLatch.countDown(); pferLatch.await(2, TimeUnit.SECONDS); } catch (InterruptedException e) { log.debug("Interrupted"); Thread.currentThread().interrupt(); } catch (Exception e) { log.error("Error", e); throw new RuntimeException("Error", e); } return acquired; } }; final TransactionalAccessDelegate delegate = new TransactionalAccessDelegate((CollectionRegionImpl) localCollectionRegion, validator); Callable pferCallable = new Callable() { public Void call() throws Exception { delegate.putFromLoad("k1", "v1", 0, null); return null; } }; Callable removeCallable = new Callable() { public Void call() throws Exception { removeLatch.await(); delegate.remove("k1"); pferLatch.countDown(); return null; } }; ExecutorService executorService = Executors.newCachedThreadPool(); Future pferFuture = executorService.submit(pferCallable); Future removeFuture = executorService.submit(removeCallable); pferFuture.get(); removeFuture.get(); assertFalse(localCache.containsKey("k1")); } /** * Test method for * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} * . */ public void testPutFromLoad() throws Exception { putFromLoadTest(false); } /** * Test method for * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} * . */ public void testPutFromLoadMinimal() throws Exception { putFromLoadTest(true); } /** * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First * does a putFromLoad, then an evict (to represent a change). Second tries to do a putFromLoad * with stale data (i.e. it took longer to read from the db). Both commit their tx. Then both * start a new tx and get. First should see the updated data; second should either see the * updated data (isInvalidation()( == false) or null (isInvalidation() == true). * * @param useMinimalAPI * @throws Exception */ private void putFromLoadTest(final boolean useMinimalAPI) throws Exception { final String KEY = KEY_BASE + testCount++; final CountDownLatch writeLatch1 = new CountDownLatch(1); final CountDownLatch writeLatch2 = new CountDownLatch(1); final CountDownLatch completionLatch = new CountDownLatch(2); Thread node1 = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertEquals("node1 starts clean", null, localAccessStrategy.get(KEY, txTimestamp)); writeLatch1.await(); if (useMinimalAPI) { localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2), true); } else { localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2)); } BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node1 caught exception", e); node1Exception = e; rollback(); } catch (AssertionFailedError e) { node1Failure = e; rollback(); } finally { // Let node2 write writeLatch2.countDown(); completionLatch.countDown(); } } }; Thread node2 = new Thread() { public void run() { try { long txTimestamp = System.currentTimeMillis(); BatchModeTransactionManager.getInstance().begin(); assertNull("node2 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); // Let node1 write writeLatch1.countDown(); // Wait for node1 to finish writeLatch2.await(); // Let the first PFER propagate sleep(200); if (useMinimalAPI) { remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); } else { remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); } BatchModeTransactionManager.getInstance().commit(); } catch (Exception e) { log.error("node2 caught exception", e); node2Exception = e; rollback(); } catch (AssertionFailedError e) { node2Failure = e; rollback(); } finally { completionLatch.countDown(); } } }; node1.setDaemon(true); node2.setDaemon(true); node1.start(); node2.start(); assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); if (node1Failure != null) throw node1Failure; if (node2Failure != null) throw node2Failure; assertEquals("node1 saw no exceptions", null, node1Exception); assertEquals("node2 saw no exceptions", null, node2Exception); // let the final PFER propagate sleep(100); long txTimestamp = System.currentTimeMillis(); String msg1 = "Correct node1 value"; String msg2 = "Correct node2 value"; Object expected1 = null; Object expected2 = null; if (isUsingInvalidation()) { // PFER does not generate any invalidation, so each node should // succeed. We count on database locking and Hibernate removing // the collection on any update to prevent the situation we have // here where the caches have inconsistent data expected1 = VALUE2; expected2 = VALUE1; } else { // the initial VALUE2 should prevent the node2 put expected1 = VALUE2; expected2 = VALUE2; } assertEquals(msg1, expected1, localAccessStrategy.get(KEY, txTimestamp)); assertEquals(msg2, expected2, remoteAccessStrategy.get(KEY, txTimestamp)); } /** * Test method for {@link CollectionRegionAccessStrategy#remove(java.lang.Object)}. */ public void testRemove() { evictOrRemoveTest(false); } /** * Test method for {@link CollectionRegionAccessStrategy#removeAll()}. */ public void testRemoveAll() { evictOrRemoveAllTest(false); } /** * Test method for {@link CollectionRegionAccessStrategy#evict(java.lang.Object)}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * CollectionRegionAccessStrategy API. */ public void testEvict() { evictOrRemoveTest(true); } /** * Test method for {@link CollectionRegionAccessStrategy#evictAll()}. * * FIXME add testing of the "immediately without regard for transaction isolation" bit in the * CollectionRegionAccessStrategy API. */ public void testEvictAll() { evictOrRemoveAllTest(true); } private void evictOrRemoveTest(boolean evict) { final String KEY = KEY_BASE + testCount++; assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); // Wait for async propagation sleep(250); if (evict) localAccessStrategy.evict(KEY); else localAccessStrategy.remove(KEY); assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); } private void evictOrRemoveAllTest(boolean evict) { final String KEY = KEY_BASE + testCount++; assertEquals(0, getValidKeyCount(localCache.keySet())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); // Wait for async propagation sleep(250); if (evict) localAccessStrategy.evictAll(); else localAccessStrategy.removeAll(); // This should re-establish the region root node assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(localCache.keySet())); // Re-establishing the region root on the local node doesn't // propagate it to other nodes. Do a get on the remote node to re-establish assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(0, getValidKeyCount(remoteCache.keySet())); // Test whether the get above messes up the optimistic version remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); assertEquals(1, getValidKeyCount(remoteCache.keySet())); // Wait for async propagation of the putFromLoad sleep(250); assertEquals("local is correct", (isUsingInvalidation() ? null : VALUE1), localAccessStrategy.get(KEY, System .currentTimeMillis())); assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); } private void rollback() { try { BatchModeTransactionManager.getInstance().rollback(); } catch (Exception e) { log.error(e.getMessage(), e); } } private static class AccessStrategyTestSetup extends TestSetup { private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; private final String configResource; private final String configName; private String preferIPv4Stack; public AccessStrategyTestSetup(Test test, String configName) { this(test, configName, null); } public AccessStrategyTestSetup(Test test, String configName, String configResource) { super(test); this.configName = configName; this.configResource = configResource; } @Override protected void setUp() throws Exception { super.setUp(); // Try to ensure we use IPv4; otherwise cluster formation is very slow preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); localCfg = createConfiguration(configName, configResource); localRegionFactory = CacheTestUtil.startRegionFactory(localCfg); remoteCfg = createConfiguration(configName, configResource); remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg); } @Override protected void tearDown() throws Exception { try { super.tearDown(); } finally { if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); } if (localRegionFactory != null) localRegionFactory.stop(); if (remoteRegionFactory != null) remoteRegionFactory.stop(); } } } ././@LongLink0000000000000000000000000000023600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractReadOnlyAccessTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000313111714611271032620 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.cache.access.AccessType; /** * Base class for tests of TRANSACTIONAL access. * * @author Brian Stansberry */ public abstract class AbstractReadOnlyAccessTestCase extends AbstractCollectionRegionAccessStrategyTestCase { public AbstractReadOnlyAccessTestCase(String name) { super(name); } @Override protected AccessType getAccessType() { return AccessType.READ_ONLY; } } ././@LongLink0000000000000000000000000000023400000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/CollectionRegionImplTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000733511714611271032632 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.collection; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.Region; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.test.cache.infinispan.AbstractEntityCollectionRegionTestCase; /** * Tests of CollectionRegionImpl. * * @author Galder Zamarreño */ public class CollectionRegionImplTestCase extends AbstractEntityCollectionRegionTestCase { public CollectionRegionImplTestCase(String name) { super(name); } @Override protected void supportedAccessTypeTest(RegionFactory regionFactory, Properties properties) { CollectionRegion region = regionFactory.buildCollectionRegion("test", properties, null); assertNull("Got TRANSACTIONAL", region.buildAccessStrategy(AccessType.TRANSACTIONAL) .lockRegion()); try { region.buildAccessStrategy(AccessType.READ_ONLY).lockRegion(); fail("Did not get READ_ONLY"); } catch (UnsupportedOperationException good) { } try { region.buildAccessStrategy(AccessType.NONSTRICT_READ_WRITE); fail("Incorrectly got NONSTRICT_READ_WRITE"); } catch (CacheException good) { } try { region.buildAccessStrategy(AccessType.READ_WRITE); fail("Incorrectly got READ_WRITE"); } catch (CacheException good) { } } @Override protected Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd) { return regionFactory.buildCollectionRegion(regionName, properties, cdd); } @Override protected CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory) { return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache(InfinispanRegionFactory.DEF_ENTITY_RESOURCE)); } @Override protected void putInRegion(Region region, Object key, Object value) { CollectionRegionAccessStrategy strategy = ((CollectionRegion) region).buildAccessStrategy(AccessType.TRANSACTIONAL); strategy.putFromLoad(key, value, System.currentTimeMillis(), new Integer(1)); } @Override protected void removeFromRegion(Region region, Object key) { ((CollectionRegion) region).buildAccessStrategy(AccessType.TRANSACTIONAL).remove(key); } } ././@LongLink0000000000000000000000000000023500000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/TransactionalExtraAPITestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001060711714611271032626 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; /** * TransactionalExtraAPITestCase. * * @author Galder Zamarreño * @since 3.5 */ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase { public static final String REGION_NAME = "test/com.foo.test"; public static final String KEY = "KEY"; public static final String VALUE1 = "VALUE1"; public static final String VALUE2 = "VALUE2"; private static CollectionRegionAccessStrategy localAccessStrategy; public TransactionalExtraAPITestCase(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); if (getCollectionAccessStrategy() == null) { Configuration cfg = createConfiguration(); InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); CollectionRegion localCollectionRegion = rf.buildCollectionRegion(REGION_NAME, cfg.getProperties(), null); setCollectionAccessStrategy(localCollectionRegion.buildAccessStrategy(getAccessType())); } } protected void tearDown() throws Exception { super.tearDown(); } protected Configuration createConfiguration() { Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, getCacheConfigName()); return cfg; } protected String getCacheConfigName() { return "entity"; } protected AccessType getAccessType() { return AccessType.TRANSACTIONAL; } protected CollectionRegionAccessStrategy getCollectionAccessStrategy() { return localAccessStrategy; } protected void setCollectionAccessStrategy(CollectionRegionAccessStrategy strategy) { localAccessStrategy = strategy; } /** * Test method for {@link TransactionalAccess#lockItem(java.lang.Object, java.lang.Object)}. */ public void testLockItem() { assertNull(getCollectionAccessStrategy().lockItem(KEY, new Integer(1))); } /** * Test method for {@link TransactionalAccess#lockRegion()}. */ public void testLockRegion() { assertNull(getCollectionAccessStrategy().lockRegion()); } /** * Test method for {@link TransactionalAccess#unlockItem(java.lang.Object, org.hibernate.cache.access.SoftLock)}. */ public void testUnlockItem() { getCollectionAccessStrategy().unlockItem(KEY, new MockSoftLock()); } /** * Test method for {@link TransactionalAccess#unlockRegion(org.hibernate.cache.access.SoftLock)}. */ public void testUnlockRegion() { getCollectionAccessStrategy().unlockItem(KEY, new MockSoftLock()); } public static class MockSoftLock implements SoftLock { } } ././@LongLink0000000000000000000000000000024000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/InvalidatedTransactionalTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000353311714611271032626 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.test.cache.infinispan.collection; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import junit.framework.Test; import junit.framework.TestSuite; /** * InvalidatedTransactionalTestCase. * * @author Galder Zamarreño * @since 3.5 */ public class InvalidatedTransactionalTestCase extends AbstractTransactionalAccessTestCase { public InvalidatedTransactionalTestCase(String name) { super(name); } @Override public void testCacheConfiguration() { assertTrue("Using Invalidation", isUsingInvalidation()); assertTrue("Synchronous mode", isSynchronous()); } public static Test suite() throws Exception { TestSuite suite = CacheTestUtil.createFailureExpectedSuite(InvalidatedTransactionalTestCase.class); return getTestSetup(suite, "entity"); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/TimestampsRegionImplTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000002250611714611271032627 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.timestamp; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.Region; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.UpdateTimestampsCache; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cache.infinispan.impl.ClassLoaderAwareCache; import org.hibernate.cache.infinispan.timestamp.TimestampsRegionImpl; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTestCase; import org.hibernate.test.cache.infinispan.functional.classloader.Account; import org.hibernate.test.cache.infinispan.functional.classloader.AccountHolder; import org.hibernate.test.cache.infinispan.functional.classloader.SelectedClassnameClassLoader; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.infinispan.AdvancedCache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.Event; import javax.transaction.TransactionManager; /** * Tests of TimestampsRegionImpl. * * @author Galder Zamarreño * @since 3.5 */ public class TimestampsRegionImplTestCase extends AbstractGeneralDataRegionTestCase { public TimestampsRegionImplTestCase(String name) { super(name); } @Override protected String getStandardRegionName(String regionPrefix) { return regionPrefix + "/" + UpdateTimestampsCache.class.getName(); } @Override protected Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd) { return regionFactory.buildTimestampsRegion(regionName, properties); } @Override protected CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory) { return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache("timestamps")); } public void testClearTimestampsRegionInIsolated() throws Exception { Configuration cfg = createConfiguration(); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); Configuration cfg2 = createConfiguration(); InfinispanRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory(cfg2, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); TimestampsRegionImpl region = (TimestampsRegionImpl) regionFactory.buildTimestampsRegion(getStandardRegionName(REGION_PREFIX), cfg.getProperties()); TimestampsRegionImpl region2 = (TimestampsRegionImpl) regionFactory2.buildTimestampsRegion(getStandardRegionName(REGION_PREFIX), cfg2.getProperties()); // QueryResultsRegion region2 = regionFactory2.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), cfg2.getProperties()); // ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Thread.currentThread().setContextClassLoader(cl.getParent()); // log.info("TCCL is " + cl.getParent()); Account acct = new Account(); acct.setAccountHolder(new AccountHolder()); region.getCacheAdapter().withFlags(FlagAdapter.FORCE_SYNCHRONOUS).put(acct, "boo"); // region.put(acct, "boo"); // // region.evictAll(); // Account acct = new Account(); // acct.setAccountHolder(new AccountHolder()); } @Override protected Configuration createConfiguration() { Configuration cfg = CacheTestUtil.buildConfiguration("test", MockInfinispanRegionFactory.class, false, true); return cfg; } public static class MockInfinispanRegionFactory extends InfinispanRegionFactory { public MockInfinispanRegionFactory() { } public MockInfinispanRegionFactory(Properties props) { super(props); } // @Override // protected TimestampsRegionImpl createTimestampsRegion(CacheAdapter cacheAdapter, String regionName) { // return new MockTimestampsRegionImpl(cacheAdapter, regionName, getTransactionManager(), this); // } @Override protected ClassLoaderAwareCache createCacheWrapper(AdvancedCache cache) { return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()) { @Override public void addListener(Object listener) { super.addListener(new MockClassLoaderAwareListener(listener, this)); } }; } // @Override // protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { // try { // EmbeddedCacheManager manager = new DefaultCacheManager(InfinispanRegionFactory.DEF_INFINISPAN_CONFIG_RESOURCE); // org.infinispan.config.Configuration ispnCfg = new org.infinispan.config.Configuration(); // ispnCfg.setCacheMode(org.infinispan.config.Configuration.CacheMode.REPL_SYNC); // manager.defineConfiguration("timestamps", ispnCfg); // return manager; // } catch (IOException e) { // throw new CacheException("Unable to create default cache manager", e); // } // } @Listener public static class MockClassLoaderAwareListener extends ClassLoaderAwareCache.ClassLoaderAwareListener { MockClassLoaderAwareListener(Object listener, ClassLoaderAwareCache cache) { super(listener, cache); } @CacheEntryActivated @CacheEntryCreated @CacheEntryEvicted @CacheEntryInvalidated @CacheEntryLoaded @CacheEntryModified @CacheEntryPassivated @CacheEntryRemoved @CacheEntryVisited public void event(Event event) throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String notFoundPackage = "org.hibernate.test.cache.infinispan.functional.classloader"; String[] notFoundClasses = { notFoundPackage + ".Account", notFoundPackage + ".AccountHolder" }; SelectedClassnameClassLoader visible = new SelectedClassnameClassLoader(null, null, notFoundClasses, cl); Thread.currentThread().setContextClassLoader(visible); super.event(event); Thread.currentThread().setContextClassLoader(cl); } } } // @Listener // public static class MockTimestampsRegionImpl extends TimestampsRegionImpl { // // public MockTimestampsRegionImpl(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) { // super(cacheAdapter, name, transactionManager, factory); // } // // @CacheEntryModified // public void nodeModified(CacheEntryModifiedEvent event) { //// ClassLoader cl = Thread.currentThread().getContextClassLoader(); //// String notFoundPackage = "org.hibernate.test.cache.infinispan.functional.classloader"; //// String[] notFoundClasses = { notFoundPackage + ".Account", notFoundPackage + ".AccountHolder" }; //// SelectedClassnameClassLoader visible = new SelectedClassnameClassLoader(null, null, notFoundClasses, cl); //// Thread.currentThread().setContextClassLoader(visible); // super.nodeModified(event); //// Thread.currentThread().setContextClassLoader(cl); // } // } } ././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractEntityCollectionRegionTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001216511714611271032627 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan; import java.util.Properties; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.TransactionalDataRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; /** * Base class for tests of EntityRegion and CollectionRegion implementations. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractRegionImplTestCase { /** * Create a new EntityCollectionRegionTestCaseBase. * * @param name */ public AbstractEntityCollectionRegionTestCase(String name) { super(name); } /** * Creates a Region backed by an PESSIMISTIC locking JBoss Cache, and then ensures that it * handles calls to buildAccessStrategy as expected when all the various {@link AccessType}s are * passed as arguments. */ public void testSupportedAccessTypes() throws Exception { supportedAccessTypeTest(); } private void supportedAccessTypeTest() throws Exception { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); String entityCfg = "entity"; cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, entityCfg); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); supportedAccessTypeTest(regionFactory, cfg.getProperties()); } /** * Creates a Region using the given factory, and then ensure that it handles calls to * buildAccessStrategy as expected when all the various {@link AccessType}s are passed as * arguments. */ protected abstract void supportedAccessTypeTest(RegionFactory regionFactory, Properties properties); /** * Test that the Region properly implements {@link TransactionalDataRegion#isTransactionAware()}. * * @throws Exception */ public void testIsTransactionAware() throws Exception { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); assertTrue("Region is transaction-aware", region.isTransactionAware()); CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport()); cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); // Make it non-transactional cfg.getProperties().remove(Environment.TRANSACTION_MANAGER_STRATEGY); regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); assertFalse("Region is not transaction-aware", region.isTransactionAware()); CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport()); } public void testGetCacheDataDescription() throws Exception { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); CacheDataDescription cdd = region.getCacheDataDescription(); assertNotNull(cdd); CacheDataDescription expected = getCacheDataDescription(); assertEquals(expected.isMutable(), cdd.isMutable()); assertEquals(expected.isVersioned(), cdd.isVersioned()); assertEquals(expected.getVersionComparator(), cdd.getVersionComparator()); } } ././@LongLink0000000000000000000000000000023000000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/JndiInfinispanRegionFactoryTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000105611714611271032624 0ustar ebourgebourgpackage org.hibernate.test.cache.infinispan; import junit.framework.TestCase; import org.hibernate.cfg.SettingsFactory; import java.util.Properties; /** * // TODO: Document this * * @author Galder Zamarreño * @since 3.5 */ public class JndiInfinispanRegionFactoryTestCase extends TestCase { public void testConstruction() { Properties p = new Properties(); p.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.infinispan.JndiInfinispanRegionFactory"); SettingsFactory.createRegionFactory(p, true); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000755000175000017500000000000012143273450032620 5ustar ebourgebourg././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestSupport.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001045411714611271032626 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.util; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.hibernate.cache.RegionFactory; import org.infinispan.Cache; /** * Support class for tracking and cleaning up objects used in tests. * * @author Brian Stansberry */ public class CacheTestSupport { private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; private Logger log; private Set caches = new HashSet(); private Set factories = new HashSet(); private Exception exception; private String preferIPv4Stack; public CacheTestSupport(Logger log) { this.log = log; } public void registerCache(Cache cache) { caches.add(cache); } public void registerFactory(RegionFactory factory) { factories.add(factory); } public void unregisterCache(Cache cache) { caches.remove(cache); } public void unregisterFactory(RegionFactory factory) { factories.remove(factory); } public void setUp() throws Exception { // Try to ensure we use IPv4; otherwise cluster formation is very slow preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); cleanUp(); throwStoredException(); } public void tearDown() throws Exception { if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); cleanUp(); throwStoredException(); } public void avoidConcurrentFlush() { // JG 2.6.1 has a problem where calling flush more than once too quickly // can result in several second delays sleep(100); } private void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { log.warn("Interrupted during sleep", e); } } private void cleanUp() { for (Iterator it = factories.iterator(); it.hasNext(); ) { try { ((RegionFactory) it.next()).stop(); } catch (Exception e) { storeException(e); } finally { it.remove(); } } factories.clear(); for (Iterator it = caches.iterator(); it.hasNext(); ) { try { Cache cache = (Cache) it.next(); cache.stop(); } catch (Exception e) { storeException(e); } finally { it.remove(); } avoidConcurrentFlush(); } caches.clear(); } private void storeException(Exception e) { if (this.exception == null) { this.exception = e; } } private void throwStoredException() throws Exception { if (exception != null) { Exception toThrow = exception; exception = null; throw toThrow; } } } ././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/BatchModeTransactionManagerLookup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000423711714611271032630 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.util; import java.util.Properties; import javax.transaction.TransactionManager; import javax.transaction.Transaction; import org.hibernate.HibernateException; import org.hibernate.transaction.TransactionManagerLookup; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Uses the JBoss Cache BatchModeTransactionManager. Should not be used in * any tests that simulate usage of database connections. * * @author Brian Stansberry */ public class BatchModeTransactionManagerLookup implements TransactionManagerLookup { public TransactionManager getTransactionManager(Properties props) throws HibernateException { try { return BatchModeTransactionManager.getInstance(); } catch (Exception e) { throw new HibernateException("Failed getting BatchModeTransactionManager", e); } } public String getUserTransactionName() { throw new UnsupportedOperationException(); } public Object getTransactionIdentifier(Transaction transaction) { return transaction; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestUtil.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000001330111714611271032620 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan.util; import java.util.Enumeration; import java.util.HashSet; import java.util.Properties; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; /** * Utilities for cache testing. * * @author Brian Stansberry */ public class CacheTestUtil { public static Configuration buildConfiguration(String regionPrefix, Class regionFactory, boolean use2ndLevel, boolean useQueries) { Configuration cfg = new Configuration(); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(Environment.USE_STRUCTURED_CACHE, "true"); cfg.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, BatchModeTransactionManagerLookup.class.getName()); cfg.setProperty(Environment.CACHE_REGION_FACTORY, regionFactory.getName()); cfg.setProperty(Environment.CACHE_REGION_PREFIX, regionPrefix); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, String.valueOf(use2ndLevel)); cfg.setProperty(Environment.USE_QUERY_CACHE, String.valueOf(useQueries)); return cfg; } public static Configuration buildLocalOnlyConfiguration(String regionPrefix, boolean use2ndLevel, boolean useQueries) { Configuration cfg = buildConfiguration(regionPrefix, InfinispanRegionFactory.class, use2ndLevel, useQueries); cfg.setProperty(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP, InfinispanRegionFactory.DEF_INFINISPAN_CONFIG_RESOURCE); return cfg; } public static Configuration buildCustomQueryCacheConfiguration(String regionPrefix, String queryCacheName) { Configuration cfg = buildConfiguration(regionPrefix, InfinispanRegionFactory.class, true, true); cfg.setProperty(InfinispanRegionFactory.QUERY_CACHE_RESOURCE_PROP, queryCacheName); return cfg; } public static InfinispanRegionFactory startRegionFactory(Configuration cfg) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Settings settings = cfg.buildSettings(); Properties properties = cfg.getProperties(); String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY); Class factoryClass = Thread.currentThread().getContextClassLoader().loadClass(factoryType); InfinispanRegionFactory regionFactory = (InfinispanRegionFactory) factoryClass.newInstance(); regionFactory.start(settings, properties); return regionFactory; } public static InfinispanRegionFactory startRegionFactory(Configuration cfg, CacheTestSupport testSupport) throws ClassNotFoundException, InstantiationException, IllegalAccessException { InfinispanRegionFactory factory = startRegionFactory(cfg); testSupport.registerFactory(factory); return factory; } public static void stopRegionFactory(InfinispanRegionFactory factory, CacheTestSupport testSupport) { factory.stop(); testSupport.unregisterFactory(factory); } /** * Supports easy creation of a TestSuite where a subclass' "FailureExpected" version of a base * test is included in the suite, while the base test is excluded. E.g. test class FooTestCase * includes method testBar(), while test class SubFooTestCase extends FooTestCase includes method * testBarFailureExcluded(). Passing SubFooTestCase.class to this method will return a suite that * does not include testBar(). * * FIXME Move this to UnitTestCase */ public static TestSuite createFailureExpectedSuite(Class testClass) { TestSuite allTests = new TestSuite(testClass); Set failureExpected = new HashSet(); Enumeration tests = allTests.tests(); while (tests.hasMoreElements()) { Test t = (Test) tests.nextElement(); if (t instanceof TestCase) { String name = ((TestCase) t).getName(); if (name.endsWith("FailureExpected")) failureExpected.add(name); } } TestSuite result = new TestSuite(); tests = allTests.tests(); while (tests.hasMoreElements()) { Test t = (Test) tests.nextElement(); if (t instanceof TestCase) { String name = ((TestCase) t).getName(); if (!failureExpected.contains(name + "FailureExpected")) { result.addTest(t); } } } return result; } /** * Prevent instantiation. */ private CacheTestUtil() { } } ././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractNonFunctionalTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/0000644000175000017500000000633311714611271032627 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.cache.infinispan; import java.util.Set; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.testing.junit.UnitTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestSupport; import org.infinispan.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all non-functional tests of Infinispan integration. * * @author Galder Zamarreño * @since 3.5 */ public abstract class AbstractNonFunctionalTestCase extends UnitTestCase { public static final String REGION_PREFIX = "test"; private CacheTestSupport testSupport; protected final Logger log = LoggerFactory.getLogger(getClass()); public AbstractNonFunctionalTestCase(String name) { super(name); testSupport = new CacheTestSupport(log); } @Override protected void setUp() throws Exception { super.setUp(); testSupport.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); testSupport.tearDown(); } protected void registerCache(Cache cache) { testSupport.registerCache(cache); } protected void unregisterCache(Cache cache) { testSupport.unregisterCache(cache); } protected void registerFactory(RegionFactory factory) { testSupport.registerFactory(factory); } protected void unregisterFactory(RegionFactory factory) { testSupport.unregisterFactory(factory); } protected CacheTestSupport getCacheTestSupport() { return testSupport; } protected void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { log.warn("Interrupted during sleep", e); } } protected void avoidConcurrentFlush() { testSupport.avoidConcurrentFlush(); } protected int getValidKeyCount(Set keys) { int result = 0; for (Object key : keys) { if (!(CacheHelper.isEvictAllNotification(key))) { result++; } } return result; } }libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/0000755000175000017500000000000012143273450027137 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/log4j.properties0000644000175000017500000000451411714611271032300 0ustar ebourgebourg################################################################################ # Hibernate, Relational Persistence for Idiomatic Java # # # # Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as # # indicated by the @author tags or express copyright attribution # # statements applied by the authors.  All third-party contributions are # # distributed under license by Red Hat, Inc. and/or it's affiliates. # # # # This copyrighted material is made available to anyone wishing to use, modify,# # copy, or redistribute it subject to the terms and conditions of the GNU # # Lesser General Public License, as published by the Free Software Foundation. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with this distribution; if not, write to: # # Free Software Foundation, Inc. # # 51 Franklin Street, Fifth Floor # # Boston, MA 02110-1301 USA # ################################################################################ log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%n log4j.rootLogger=info, stdout #log4j.logger.org.hibernate.test=info log4j.logger.org.hibernate.test=info log4j.logger.org.hibernate.cache=info log4j.logger.org.hibernate.SQL=info #log4j.logger.org.jgroups=info #log4j.logger.org.infinispan=tracelibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/hibernate.properties0000644000175000017500000000427511714611271033226 0ustar ebourgebourg################################################################################ # Hibernate, Relational Persistence for Idiomatic Java # # # # Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as # # indicated by the @author tags or express copyright attribution # # statements applied by the authors.  All third-party contributions are # # distributed under license by Red Hat, Inc. and/or it's affiliates. # # # # This copyrighted material is made available to anyone wishing to use, modify,# # copy, or redistribute it subject to the terms and conditions of the GNU # # Lesser General Public License, as published by the Free Software Foundation. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with this distribution; if not, write to: # # Free Software Foundation, Inc. # # 51 Franklin Street, Fifth Floor # # Boston, MA 02110-1301 USA # ################################################################################ hibernate.dialect org.hibernate.dialect.HSQLDialect hibernate.connection.driver_class org.hsqldb.jdbcDriver hibernate.connection.url jdbc:hsqldb:mem:/test hibernate.connection.username sa hibernate.connection.password hibernate.connection.pool_size 5 hibernate.format_sql true hibernate.max_fetch_depth 5 hibernate.generate_statistics true libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/0000755000175000017500000000000011714611271027726 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/0000755000175000017500000000000011714611271031667 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/0000755000175000017500000000000011714611271032646 5ustar ebourgebourg././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000755000175000017500000000000011714611271033011 5ustar ebourgebourg././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000755000175000017500000000000011714611271033011 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000755000175000017500000000000012143273450033011 5ustar ebourgebourg././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/Item.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000644000175000017500000000412311714611271033013 0ustar ebourgebourg ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/Contact.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000644000175000017500000000327411714611271033021 0ustar ebourgebourg ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/classloader/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000755000175000017500000000000012143273450033011 5ustar ebourgebourg././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/classloader/Account.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000644000175000017500000000327411714611271033021 0ustar ebourgebourg ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/cache/infinispan/functional/Customer.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/test/resources/org/hibernate/test/c0000644000175000017500000000334611714611271033021 0ustar ebourgebourg libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/0000755000175000017500000000000011714611271025072 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/0000755000175000017500000000000011714611271026013 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/0000755000175000017500000000000011714611271026602 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/0000755000175000017500000000000011714611271030543 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/0000755000175000017500000000000011714611271031606 5ustar ebourgebourg././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001001311714611271032627 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.query; import java.util.Properties; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheException; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.infinispan.notifications.Listener; /** * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ @Listener public class QueryResultsRegionImpl extends BaseTransactionalDataRegion implements QueryResultsRegion { private boolean localOnly; public QueryResultsRegionImpl(CacheAdapter cacheAdapter, String name, Properties properties, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, null, transactionManager, factory); // If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes. // We use the Timestamps cache to manage invalidation localOnly = cacheAdapter.isClusteredInvalidation(); } public void evict(Object key) throws CacheException { if (localOnly) cacheAdapter.withFlags(FlagAdapter.CACHE_MODE_LOCAL).remove(key); else cacheAdapter.remove(key); } public void evictAll() throws CacheException { Transaction tx = suspend(); try { CacheHelper.sendEvictAllNotification(cacheAdapter, getAddress()); } finally { resume(tx); } } public Object get(Object key) throws CacheException { // If the region is not valid, skip cache store to avoid going remote to retrieve the query. // The aim of this is to maintain same logic/semantics as when state transfer was configured. // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround boolean skipCacheStore = false; if (!isValid()) skipCacheStore = true; if (!checkValid()) return null; // In Infinispan get doesn't acquire any locks, so no need to suspend the tx. // In the past, when get operations acquired locks, suspending the tx was a way // to avoid holding locks that would prevent updates. // Add a zero (or low) timeout option so we don't block // waiting for tx's that did a put to commit if (skipCacheStore) return get(key, true, FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT, FlagAdapter.SKIP_CACHE_STORE); else return get(key, true, FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT); } public void put(Object key, Object value) throws CacheException { if (checkValid()) { // Here we don't want to suspend the tx. If we do: // 1) We might be caching query results that reflect uncommitted // changes. No tx == no WL on cache node, so other threads // can prematurely see those query results // 2) No tx == immediate replication. More overhead, plus we // spread issue #1 above around the cluster // Add a zero (or quite low) timeout option so we don't block. // Ignore any TimeoutException. Basically we forego caching the // query result in order to avoid blocking. // Reads are done with suspended tx, so they should not hold the // lock for long. Not caching the query result is OK, since // any subsequent read will just see the old result with its // out-of-date timestamp; that result will be discarded and the // db query performed again. if (localOnly) cacheAdapter.withFlags(FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT, FlagAdapter.CACHE_MODE_LOCAL) .putAllowingTimeout(key, value); else cacheAdapter.withFlags(FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT) .putAllowingTimeout(key, value); } } }././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001446211714611271032643 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache.infinispan.access; import javax.transaction.Transaction; import org.hibernate.cache.CacheException; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.infinispan.impl.BaseRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Defines the strategy for transactional access to entity or collection data in a Infinispan instance. *

* The intent of this class is to encapsulate common code and serve as a delegate for * {@link EntityRegionAccessStrategy} and {@link CollectionRegionAccessStrategy} implementations. * * @author Brian Stansberry * @author Galder Zamarreño * @since 3.5 */ public class TransactionalAccessDelegate { private static final Log log = LogFactory.getLog(TransactionalAccessDelegate.class); protected final CacheAdapter cacheAdapter; protected final BaseRegion region; protected final PutFromLoadValidator putValidator; public TransactionalAccessDelegate(BaseRegion region, PutFromLoadValidator validator) { this.region = region; this.cacheAdapter = region.getCacheAdapter(); this.putValidator = validator; } public Object get(Object key, long txTimestamp) throws CacheException { if (!region.checkValid()) return null; Object val = cacheAdapter.get(key); if (val == null) putValidator.registerPendingPut(key); return val; } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { if (!region.checkValid()) return false; if (!putValidator.acquirePutFromLoadLock(key)) return false; try { cacheAdapter.putForExternalRead(key, value); } finally { putValidator.releasePutFromLoadLock(key); } return true; } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { // We ignore minimalPutOverride. Infinispan putForExternalRead is // already about as minimal as we can get; it will promptly return // if it discovers that the node we want to write to already exists return putFromLoad(key, value, txTimestamp, version); } public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } public SoftLock lockRegion() throws CacheException { return null; } public void unlockItem(Object key, SoftLock lock) throws CacheException { } public void unlockRegion(SoftLock lock) throws CacheException { } public boolean insert(Object key, Object value, Object version) throws CacheException { if (!region.checkValid()) return false; if (cacheAdapter.isClusteredInvalidation()) cacheAdapter.withFlags(FlagAdapter.CACHE_MODE_LOCAL).put(key, value); else cacheAdapter.put(key, value); return true; } public boolean afterInsert(Object key, Object value, Object version) throws CacheException { return false; } public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. cacheAdapter.put(key, value); return true; } public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { return false; } public void remove(Object key) throws CacheException { if (!putValidator.invalidateKey(key)) { throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName()); } // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. cacheAdapter.remove(key); } public void removeAll() throws CacheException { if (!putValidator.invalidateRegion()) { throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName()); } cacheAdapter.clear(); } public void evict(Object key) throws CacheException { if (!putValidator.invalidateKey(key)) { throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName()); } cacheAdapter.remove(key); } public void evictAll() throws CacheException { if (!putValidator.invalidateRegion()) { throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName()); } Transaction tx = region.suspend(); try { CacheHelper.sendEvictAllNotification(cacheAdapter, region.getAddress()); } finally { region.resume(tx); } } } ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000006211711714611271032643 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat, Inc or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache.infinispan.access; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheException; /** * Encapsulates logic to allow a {@link TransactionalAccessDelegate} to determine * whether a {@link TransactionalAccessDelegate#putFromLoad(Object, Object, long, Object, boolean)} * call should be allowed to update the cache. A putFromLoad has * the potential to store stale data, since the data may have been removed from the * database and the cache between the time when the data was read from the database * and the actual call to putFromLoad. *

* The expected usage of this class by a thread that read the cache and did * not find data is: * *

    *
  1. Call {@link #registerPendingPut(Object)}
  2. *
  3. Read the database
  4. *
  5. Call {@link #acquirePutFromLoadLock(Object)} *
  6. if above returns false, the thread should not cache the data; * only if above returns true, put data in the cache and...
  7. *
  8. then call {@link #releasePutFromLoadLock(Object)}
  9. *
*

* *

* The expected usage by a thread that is taking an action such that any pending * putFromLoad may have stale data and should not cache it is to either * call * *

    *
  • {@link #invalidateKey(Object)} (for a single key invalidation)
  • *
  • or {@link #invalidateRegion()} (for a general invalidation all pending puts)
  • *
*

* *

* This class also supports the concept of "naked puts", which are calls to * {@link #acquirePutFromLoadLock(Object)} without a preceding {@link #registerPendingPut(Object)} * call. *

* * @author Brian Stansberry * * @version $Revision: $ */ public class PutFromLoadValidator { /** * Period (in ms) after a removal during which a call to * {@link #acquirePutFromLoadLock(Object)} that hasn't been * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") * will return false. * will return false. */ public static final long NAKED_PUT_INVALIDATION_PERIOD = TimeUnit.SECONDS.toMillis(20); /** Period (in ms) after which a pending put is placed in the over-age queue */ private static final long PENDING_PUT_OVERAGE_PERIOD = TimeUnit.SECONDS.toMillis(5); /** Period (in ms) before which we stop trying to clean out pending puts */ private static final long PENDING_PUT_RECENT_PERIOD = TimeUnit.SECONDS.toMillis(2); /** Period (in ms) after which a pending put is never expected to come in and should be cleaned */ private static final long MAX_PENDING_PUT_DELAY = TimeUnit.SECONDS.toMillis(2 * 60); /** * Used to determine whether the owner of a pending put is a thread or a transaction */ private final TransactionManager transactionManager; private final long nakedPutInvalidationPeriod; private final long pendingPutOveragePeriod; private final long pendingPutRecentPeriod; private final long maxPendingPutDelay; /** * Registry of expected, future, isPutValid calls. If a key+owner is registered in this map, it * is not a "naked put" and is allowed to proceed. */ private final ConcurrentMap pendingPuts = new ConcurrentHashMap(); /** * List of pending puts. Used to ensure we don't leak memory via the pendingPuts map */ private final List> pendingQueue = new LinkedList>(); /** * Separate list of pending puts that haven't been resolved within PENDING_PUT_OVERAGE_PERIOD. * Used to ensure we don't leak memory via the pendingPuts map. Tracked separately from more * recent pending puts for efficiency reasons. */ private final List> overagePendingQueue = new LinkedList>(); /** Lock controlling access to pending put queues */ private final Lock pendingLock = new ReentrantLock(); private final ConcurrentMap recentRemovals = new ConcurrentHashMap(); /** * List of recent removals. Used to ensure we don't leak memory via the recentRemovals map */ private final List removalsQueue = new LinkedList(); /** * The time when the first element in removalsQueue will expire. No reason to do housekeeping on * the queue before this time. */ private volatile long earliestRemovalTimestamp; /** Lock controlling access to removalsQueue */ private final Lock removalsLock = new ReentrantLock(); /** * The time of the last call to regionRemoved(), plus NAKED_PUT_INVALIDATION_PERIOD. All naked * puts will be rejected until the current time is greater than this value. */ private volatile long invalidationTimestamp; /** * Creates a new PutFromLoadValidator. * * @param transactionManager * transaction manager to use to associate changes with a transaction; may be * null */ public PutFromLoadValidator(TransactionManager transactionManager) { this(transactionManager, NAKED_PUT_INVALIDATION_PERIOD, PENDING_PUT_OVERAGE_PERIOD, PENDING_PUT_RECENT_PERIOD, MAX_PENDING_PUT_DELAY); } /** * Constructor variant for use by unit tests; allows control of various timeouts by the test. */ protected PutFromLoadValidator(TransactionManager transactionManager, long nakedPutInvalidationPeriod, long pendingPutOveragePeriod, long pendingPutRecentPeriod, long maxPendingPutDelay) { this.transactionManager = transactionManager; this.nakedPutInvalidationPeriod = nakedPutInvalidationPeriod; this.pendingPutOveragePeriod = pendingPutOveragePeriod; this.pendingPutRecentPeriod = pendingPutRecentPeriod; this.maxPendingPutDelay = maxPendingPutDelay; } // ----------------------------------------------------------------- Public /** * Acquire a lock giving the calling thread the right to put data in the * cache for the given key. *

* NOTE: A call to this method that returns true * should always be matched with a call to {@link #releasePutFromLoadLock(Object)}. *

* * @param key the key * * @return true if the lock is acquired and the cache put * can proceed; false if the data should not be cached */ public boolean acquirePutFromLoadLock(Object key) { boolean valid = false; boolean locked = false; long now = System.currentTimeMillis(); // Important: Do cleanup before we acquire any locks so we // don't deadlock with invalidateRegion cleanOutdatedPendingPuts(now, true); try { PendingPutMap pending = pendingPuts.get(key); if (pending != null) { locked = pending.acquireLock(100, TimeUnit.MILLISECONDS); if (locked) { try { PendingPut toCancel = pending.remove(getOwnerForPut()); if (toCancel != null) { valid = !toCancel.completed; toCancel.completed = true; } } finally { if (!valid) { pending.releaseLock(); locked = false; } } } } else { // Key wasn't in pendingPuts, so either this is a "naked put" // or regionRemoved has been called. Check if we can proceed if (now > invalidationTimestamp) { Long removedTime = recentRemovals.get(key); if (removedTime == null || now > removedTime.longValue()) { // It's legal to proceed. But we have to record this key // in pendingPuts so releasePutFromLoadLock can find it. // To do this we basically simulate a normal "register // then acquire lock" pattern registerPendingPut(key); locked = acquirePutFromLoadLock(key); valid = locked; } } } } catch (Throwable t) { valid = false; if (locked) { PendingPutMap toRelease = pendingPuts.get(key); if (toRelease != null) { toRelease.releaseLock(); } } if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } } return valid; } /** * Releases the lock previously obtained by a call to * {@link #acquirePutFromLoadLock(Object)} that returned true. * * @param key the key */ public void releasePutFromLoadLock(Object key) { PendingPutMap pending = pendingPuts.get(key); if (pending != null) { if (pending.size() == 0) { pendingPuts.remove(key, pending); } pending.releaseLock(); } } /** * Invalidates any {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to * {@link #acquirePutFromLoadLock(Object)} will return false.

This method will block until any * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the given key * has released the lock. This allows the caller to be certain the putFromLoad will not execute after this method * returns, possibly caching stale data.

* * @param key key identifying data whose pending puts should be invalidated * @return true if the invalidation was successful; false if a problem occured (which the * caller should treat as an exception condition) */ public boolean invalidateKey(Object key) { boolean success = true; // Invalidate any pending puts PendingPutMap pending = pendingPuts.get(key); if (pending != null) { // This lock should be available very quickly, but we'll be // very patient waiting for it as callers should treat not // acquiring it as an exception condition if (pending.acquireLock(60, TimeUnit.SECONDS)) { try { pending.invalidate(); } finally { pending.releaseLock(); } } else { success = false; } } // Record when this occurred to invalidate later naked puts RecentRemoval removal = new RecentRemoval(key, this.nakedPutInvalidationPeriod); recentRemovals.put(key, removal.timestamp); // Don't let recentRemovals map become a memory leak RecentRemoval toClean = null; boolean attemptClean = removal.timestamp.longValue() > earliestRemovalTimestamp; removalsLock.lock(); try { removalsQueue.add(removal); if (attemptClean) { if (removalsQueue.size() > 1) { // we have at least one as we // just added it toClean = removalsQueue.remove(0); } earliestRemovalTimestamp = removalsQueue.get(0).timestamp.longValue(); } } finally { removalsLock.unlock(); } if (toClean != null) { Long cleaned = recentRemovals.get(toClean.key); if (cleaned != null && cleaned.equals(toClean.timestamp)) { cleaned = recentRemovals.remove(toClean.key); if (cleaned != null && cleaned.equals(toClean.timestamp) == false) { // Oops; removed the wrong timestamp; restore it recentRemovals.putIfAbsent(toClean.key, cleaned); } } } return success; } /** * Invalidates all {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to * {@link #acquirePutFromLoadLock(Object)} will return false.

This method will block until any * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the any key has * released the lock. This allows the caller to be certain the putFromLoad will not execute after this method returns, * possibly caching stale data.

* * @return true if the invalidation was successful; false if a problem occured (which the * caller should treat as an exception condition) */ public boolean invalidateRegion() { boolean ok = false; invalidationTimestamp = System.currentTimeMillis() + this.nakedPutInvalidationPeriod; try { // Acquire the lock for each entry to ensure any ongoing // work associated with it is completed before we return for (PendingPutMap entry : pendingPuts.values()) { if (entry.acquireLock(60, TimeUnit.SECONDS)) { try { entry.invalidate(); } finally { entry.releaseLock(); } } else { ok = false; } } removalsLock.lock(); try { recentRemovals.clear(); removalsQueue.clear(); ok = true; } finally { removalsLock.unlock(); } } catch (Exception e) { ok = false; } finally { earliestRemovalTimestamp = invalidationTimestamp; } return ok; } /** * Notifies this validator that it is expected that a database read followed by a subsequent {@link * #acquirePutFromLoadLock(Object)} call will occur. The intent is this method would be called following a cache miss * wherein it is expected that a database read plus cache put will occur. Calling this method allows the validator to * treat the subsequent acquirePutFromLoadLock as if the database read occurred when this method was * invoked. This allows the validator to compare the timestamp of this call against the timestamp of subsequent removal * notifications. A put that occurs without this call preceding it is "naked"; i.e the validator must assume the put is * not valid if any relevant removal has occurred within {@link #NAKED_PUT_INVALIDATION_PERIOD} milliseconds. * * @param key key that will be used for subsequent cache put */ public void registerPendingPut(Object key) { PendingPut pendingPut = new PendingPut(key, getOwnerForPut()); PendingPutMap pendingForKey = new PendingPutMap(pendingPut); for (;;) { PendingPutMap existing = pendingPuts.putIfAbsent(key, pendingForKey); if (existing != null) { if (existing.acquireLock(10, TimeUnit.SECONDS)) { try { existing.put(pendingPut); PendingPutMap doublecheck = pendingPuts.putIfAbsent(key, existing); if (doublecheck == null || doublecheck == existing) { break; } // else we hit a race and need to loop to try again } finally { existing.releaseLock(); } } else { // Can't get the lock; when we come back we'll be a "naked put" break; } } else { // normal case break; } } // Guard against memory leaks preventOutdatedPendingPuts(pendingPut); } // -------------------------------------------------------------- Protected /** Only for use by unit tests; may be removed at any time */ protected int getPendingPutQueueLength() { pendingLock.lock(); try { return pendingQueue.size(); } finally { pendingLock.unlock(); } } /** Only for use by unit tests; may be removed at any time */ protected int getOveragePendingPutQueueLength() { pendingLock.lock(); try { return overagePendingQueue.size(); } finally { pendingLock.unlock(); } } /** Only for use by unit tests; may be removed at any time */ protected int getRemovalQueueLength() { removalsLock.lock(); try { return removalsQueue.size(); } finally { removalsLock.unlock(); } } // ---------------------------------------------------------------- Private private Object getOwnerForPut() { Transaction tx = null; try { if (transactionManager != null) { tx = transactionManager.getTransaction(); } } catch (SystemException se) { throw new CacheException("Could not obtain transaction", se); } return tx == null ? Thread.currentThread() : tx; } private void preventOutdatedPendingPuts(PendingPut pendingPut) { pendingLock.lock(); try { pendingQueue.add(new WeakReference(pendingPut)); if (pendingQueue.size() > 1) { cleanOutdatedPendingPuts(pendingPut.timestamp, false); } } finally { pendingLock.unlock(); } } private void cleanOutdatedPendingPuts(long now, boolean lock) { PendingPut toClean = null; if (lock) { pendingLock.lock(); } try { // Clean items out of the basic queue long overaged = now - this.pendingPutOveragePeriod; long recent = now - this.pendingPutRecentPeriod; int pos = 0; while (pendingQueue.size() > pos) { WeakReference ref = pendingQueue.get(pos); PendingPut item = ref.get(); if (item == null || item.completed) { pendingQueue.remove(pos); } else if (item.timestamp < overaged) { // Potential leak; move to the overaged queued pendingQueue.remove(pos); overagePendingQueue.add(ref); } else if (item.timestamp >= recent) { // Don't waste time on very recent items break; } else if (pos > 2) { // Don't spend too much time getting nowhere break; } else { // Move on to the next item pos++; } } // Process the overage queue until we find an item to clean // or an incomplete item that hasn't aged out long mustCleanTime = now - this.maxPendingPutDelay; while (overagePendingQueue.size() > 0) { WeakReference ref = overagePendingQueue.get(0); PendingPut item = ref.get(); if (item == null || item.completed) { overagePendingQueue.remove(0); } else { if (item.timestamp < mustCleanTime) { overagePendingQueue.remove(0); toClean = item; } break; } } } finally { if (lock) { pendingLock.unlock(); } } // We've found a pendingPut that never happened; clean it up if (toClean != null) { PendingPutMap map = pendingPuts.get(toClean.key); if (map != null) { if (map.acquireLock(100, TimeUnit.MILLISECONDS)) { try { PendingPut cleaned = map.remove(toClean.owner); if (toClean.equals(cleaned) == false) { if (cleaned != null) { // Oops. Restore it. map.put(cleaned); } } else if (map.size() == 0) { pendingPuts.remove(toClean.key, map); } } finally { map.releaseLock(); } } else { // Something's gone wrong and the lock isn't being released. // We removed toClean from the queue and need to restore it // TODO this is pretty dodgy restorePendingPut(toClean); } } } } private void restorePendingPut(PendingPut toRestore) { pendingLock.lock(); try { // Give it a new lease on life so it's not out of order. We could // scan the queue and put toRestore back at the front, but then // we'll just immediately try removing it again; instead we // let it cycle through the queue again toRestore.refresh(); pendingQueue.add(new WeakReference(toRestore)); } finally { pendingLock.unlock(); } } /** * Lazy-initialization map for PendingPut. Optimized for the expected usual case where only a * single put is pending for a given key. * * This class is NOT THREAD SAFE. All operations on it must be performed with the lock held. */ private static class PendingPutMap { private PendingPut singlePendingPut; private Map fullMap; private final Lock lock = new ReentrantLock(); PendingPutMap(PendingPut singleItem) { this.singlePendingPut = singleItem; } public void put(PendingPut pendingPut) { if (singlePendingPut == null) { if (fullMap == null) { // initial put singlePendingPut = pendingPut; } else { fullMap.put(pendingPut.owner, pendingPut); } } else { // 2nd put; need a map fullMap = new HashMap(4); fullMap.put(singlePendingPut.owner, singlePendingPut); singlePendingPut = null; fullMap.put(pendingPut.owner, pendingPut); } } public PendingPut remove(Object ownerForPut) { PendingPut removed = null; if (fullMap == null) { if (singlePendingPut != null && singlePendingPut.owner.equals(ownerForPut)) { removed = singlePendingPut; singlePendingPut = null; } } else { removed = fullMap.remove(ownerForPut); } return removed; } public int size() { return fullMap == null ? (singlePendingPut == null ? 0 : 1) : fullMap.size(); } public boolean acquireLock(long time, TimeUnit unit) { try { return lock.tryLock(time, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } public void releaseLock() { lock.unlock(); } public void invalidate() { if (singlePendingPut != null) { singlePendingPut.completed = true; // Nullify to avoid leaking completed pending puts singlePendingPut = null; } else if (fullMap != null) { for (PendingPut pp : fullMap.values()) { pp.completed = true; } // Nullify to avoid leaking completed pending puts fullMap = null; } } } private static class PendingPut { private final Object key; private final Object owner; private long timestamp = System.currentTimeMillis(); private volatile boolean completed; private PendingPut(Object key, Object owner) { this.key = key; this.owner = owner; } private void refresh() { timestamp = System.currentTimeMillis(); } } private static class RecentRemoval { private final Object key; private final Long timestamp; private RecentRemoval(Object key, long nakedPutInvalidationPeriod) { this.key = key; timestamp = Long.valueOf(System.currentTimeMillis() + nakedPutInvalidationPeriod); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000002361411714611271032642 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.impl; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheException; import org.hibernate.cache.Region; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.util.AddressAdapter; import org.hibernate.cache.infinispan.util.AddressAdapterImpl; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Support for Infinispan {@link Region}s. Handles common "utility" methods for an underlying named * Cache. In other words, this implementation doesn't actually read or write data. Subclasses are * expected to provide core cache interaction appropriate to the semantics needed. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseRegion implements Region { private enum InvalidateState { INVALID, CLEARING, VALID }; private static final Log log = LogFactory.getLog(BaseRegion.class); private final String name; protected final CacheAdapter cacheAdapter; protected final AddressAdapter address; protected final Set currentView = new HashSet(); protected final TransactionManager transactionManager; protected final boolean replication; protected final Object invalidationMutex = new Object(); protected final AtomicReference invalidateState = new AtomicReference(InvalidateState.VALID); private final RegionFactory factory; public BaseRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) { this.cacheAdapter = cacheAdapter; this.name = name; this.transactionManager = transactionManager; this.replication = cacheAdapter.isClusteredReplication(); this.address = this.cacheAdapter.getAddress(); this.cacheAdapter.addListener(this); this.factory = factory; } public void start() { if (address != null) { synchronized (currentView) { List view = cacheAdapter.getMembers(); if (view != null) { currentView.addAll(view); establishInternalNodes(); } } } } /** * Calls to this method must be done from synchronized (currentView) blocks only!! */ private void establishInternalNodes() { Transaction tx = suspend(); try { for (AddressAdapter member : currentView) { CacheHelper.initInternalEvict(cacheAdapter, member); } } finally { resume(tx); } } public String getName() { return name; } public CacheAdapter getCacheAdapter() { return cacheAdapter; } public long getElementCountInMemory() { if (checkValid()) { Set keySet = cacheAdapter.keySet(); int size = cacheAdapter.size(); if (CacheHelper.containsEvictAllNotification(keySet, address)) size--; return size; } return 0; } /** * Not supported. * * @return -1 */ public long getElementCountOnDisk() { return -1; } /** * Not supported. * * @return -1 */ public long getSizeInMemory() { return -1; } public int getTimeout() { return 600; // 60 seconds } public long nextTimestamp() { return factory.nextTimestamp(); } public Map toMap() { if (checkValid()) { // If copying causes issues, provide a lazily loaded Map Map map = new HashMap(); Set entries = cacheAdapter.toMap().entrySet(); for (Map.Entry entry : entries) { Object key = entry.getKey(); if (!CacheHelper.isEvictAllNotification(key)) { map.put(key, entry.getValue()); } } return map; } return Collections.EMPTY_MAP; } public void destroy() throws CacheException { try { cacheAdapter.stop(); // cacheAdapter.clear(); } finally { cacheAdapter.removeListener(this); } } public boolean contains(Object key) { if (!checkValid()) return false; // Reads are non-blocking in Infinispan, so not sure of the necessity of passing ZERO_LOCK_ACQUISITION_TIMEOUT return cacheAdapter.withFlags(FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT).containsKey(key); } public AddressAdapter getAddress() { return address; } public boolean checkValid() { boolean valid = isValid(); if (!valid) { synchronized (invalidationMutex) { if (invalidateState.compareAndSet(InvalidateState.INVALID, InvalidateState.CLEARING)) { Transaction tx = suspend(); try { cacheAdapter.withFlags(FlagAdapter.CACHE_MODE_LOCAL, FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT).clear(); invalidateState.compareAndSet(InvalidateState.CLEARING, InvalidateState.VALID); } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("Could not invalidate region: " + e.getLocalizedMessage()); } } finally { resume(tx); } } } valid = isValid(); } return valid; } protected boolean isValid() { return invalidateState.get() == InvalidateState.VALID; } /** * Performs a Infinispan get(Fqn, Object) * * @param key The key of the item to get * @param suppressTimeout should any TimeoutException be suppressed? * @param flagAdapters flags to add to the get invocation * @return The retrieved object * @throws CacheException issue managing transaction or talking to cache */ protected Object get(Object key, boolean suppressTimeout, FlagAdapter... flagAdapters) throws CacheException { CacheAdapter localCacheAdapter = cacheAdapter; if (flagAdapters != null && flagAdapters.length > 0) localCacheAdapter = cacheAdapter.withFlags(flagAdapters); if (suppressTimeout) return localCacheAdapter.getAllowingTimeout(key); else return localCacheAdapter.get(key); } public Object getOwnerForPut() { Transaction tx = null; try { if (transactionManager != null) { tx = transactionManager.getTransaction(); } } catch (SystemException se) { throw new CacheException("Could not obtain transaction", se); } return tx == null ? Thread.currentThread() : tx; } /** * Tell the TransactionManager to suspend any ongoing transaction. * * @return the transaction that was suspended, or null if * there wasn't one */ public Transaction suspend() { Transaction tx = null; try { if (transactionManager != null) { tx = transactionManager.suspend(); } } catch (SystemException se) { throw new CacheException("Could not suspend transaction", se); } return tx; } /** * Tell the TransactionManager to resume the given transaction * * @param tx * the transaction to suspend. May be null. */ public void resume(Transaction tx) { try { if (tx != null) transactionManager.resume(tx); } catch (Exception e) { throw new CacheException("Could not resume transaction", e); } } @CacheEntryModified public void entryModified(CacheEntryModifiedEvent event) { handleEvictAllModification(event); } protected boolean handleEvictAllModification(CacheEntryModifiedEvent event) { if (!event.isPre() && (replication || event.isOriginLocal()) && CacheHelper.isEvictAllNotification(event.getKey(), event.getValue())) { if (log.isTraceEnabled()) log.trace("Set invalid state because marker cache entry was put: {0}", event); invalidateState.set(InvalidateState.INVALID); return true; } return false; } @CacheEntryInvalidated public void entryInvalidated(CacheEntryInvalidatedEvent event) { if (log.isTraceEnabled()) log.trace("Cache entry invalidated: {0}", event); handleEvictAllInvalidation(event); } protected boolean handleEvictAllInvalidation(CacheEntryInvalidatedEvent event) { if (!event.isPre() && CacheHelper.isEvictAllNotification(event.getKey())) { if (log.isTraceEnabled()) log.trace("Set invalid state because marker cache entry was invalidated: {0}", event); invalidateState.set(InvalidateState.INVALID); return true; } return false; } @ViewChanged public void viewChanged(ViewChangedEvent event) { synchronized (currentView) { List view = AddressAdapterImpl.toAddressAdapter(event.getNewMembers()); if (view != null) { currentView.addAll(view); establishInternalNodes(); } } } }././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000213411714611271032634 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.impl; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheException; import org.hibernate.cache.GeneralDataRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.util.CacheAdapter; /** * Support for Infinispan {@link GeneralDataRegion} implementors. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion { public BaseGeneralDataRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, transactionManager, factory); } public void evict(Object key) throws CacheException { cacheAdapter.evict(key); } public void evictAll() throws CacheException { cacheAdapter.clear(); } public Object get(Object key) throws CacheException { return cacheAdapter.get(key); } public void put(Object key, Object value) throws CacheException { cacheAdapter.put(key, value); } }././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/ClassLoaderAwareCache.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001517011714611271032640 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.impl; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.infinispan.AbstractDelegatingAdvancedCache; import org.infinispan.AdvancedCache; import org.infinispan.commands.VisitableCommand; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.base.CommandInterceptor; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.stats.Stats; /** * @author Paul Ferraro */ public class ClassLoaderAwareCache extends AbstractDelegatingAdvancedCache { final WeakReference classLoaderRef; public ClassLoaderAwareCache(AdvancedCache cache, ClassLoader classLoader) { super(cache); this.classLoaderRef = new WeakReference(classLoader); cache.removeInterceptor(ClassLoaderAwareCommandInterceptor.class); cache.addInterceptor(new ClassLoaderAwareCommandInterceptor(), 0); } @Override public Stats getStats() { return this.getAdvancedCache().getStats(); } @Override public void stop() { super.stop(); this.classLoaderRef.clear(); } @Override public void addListener(Object listener) { super.addListener(new ClassLoaderAwareListener(listener, this)); } void setContextClassLoader(final ClassLoader classLoader) { PrivilegedAction action = new PrivilegedAction() { @Override public Void run() { Thread.currentThread().setContextClassLoader(classLoader); return null; } }; AccessController.doPrivileged(action); } private class ClassLoaderAwareCommandInterceptor extends CommandInterceptor { @Override protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ClassLoaderAwareCache.this.setContextClassLoader(ClassLoaderAwareCache.this.classLoaderRef.get()); try { return super.handleDefault(ctx, command); } finally { ClassLoaderAwareCache.this.setContextClassLoader(classLoader); } } } static final Map, Event.Type> events = new HashMap, Event.Type>(); static { events.put(CacheEntryActivated.class, Event.Type.CACHE_ENTRY_ACTIVATED); events.put(CacheEntryCreated.class, Event.Type.CACHE_ENTRY_CREATED); events.put(CacheEntryEvicted.class, Event.Type.CACHE_ENTRY_EVICTED); events.put(CacheEntryInvalidated.class, Event.Type.CACHE_ENTRY_INVALIDATED); events.put(CacheEntryLoaded.class, Event.Type.CACHE_ENTRY_LOADED); events.put(CacheEntryModified.class, Event.Type.CACHE_ENTRY_MODIFIED); events.put(CacheEntryPassivated.class, Event.Type.CACHE_ENTRY_PASSIVATED); events.put(CacheEntryRemoved.class, Event.Type.CACHE_ENTRY_REMOVED); events.put(CacheEntryVisited.class, Event.Type.CACHE_ENTRY_VISITED); } @Listener public static class ClassLoaderAwareListener { private final Object listener; private final Map> methods = new EnumMap>(Event.Type.class); private final ClassLoaderAwareCache cache; public ClassLoaderAwareListener(Object listener, ClassLoaderAwareCache cache) { this.listener = listener; this.cache = cache; for (Method method : listener.getClass().getMethods()) { for (Map.Entry, Event.Type> entry : events.entrySet()) { Class annotation = entry.getKey(); if (method.isAnnotationPresent(annotation)) { List methods = this.methods.get(entry.getValue()); if (methods == null) { methods = new LinkedList(); this.methods.put(entry.getValue(), methods); } methods.add(method); } } } } @CacheEntryActivated @CacheEntryCreated @CacheEntryEvicted @CacheEntryInvalidated @CacheEntryLoaded @CacheEntryModified @CacheEntryPassivated @CacheEntryRemoved @CacheEntryVisited public void event(Event event) throws Throwable { List methods = this.methods.get(event.getType()); if (methods != null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ClassLoader visible = (ClassLoader) cache.classLoaderRef.get(); cache.setContextClassLoader(visible); try { for (Method method : this.methods.get(event.getType())) { try { method.invoke(this.listener, event); } catch (InvocationTargetException e) { throw e.getCause(); } } } finally { cache.setContextClassLoader(classLoader); } } } public int hashCode() { return this.listener.hashCode(); } public boolean equals(Object object) { if (object == null) return false; if (object instanceof ClassLoaderAwareCache.ClassLoaderAwareListener) { @SuppressWarnings("unchecked") ClassLoaderAwareListener listener = (ClassLoaderAwareListener) object; return this.listener.equals(listener.listener); } return this.listener.equals(object); } } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000203511714611271032634 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.impl; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.TransactionalDataRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; /** * Support for Inifinispan {@link TransactionalDataRegion} implementors. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseTransactionalDataRegion extends BaseRegion implements TransactionalDataRegion { private final CacheDataDescription metadata; public BaseTransactionalDataRegion(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, transactionManager, factory); this.metadata = metadata; } public CacheDataDescription getCacheDataDescription() { return metadata; } public boolean isTransactionAware() { return transactionManager != null; } }././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000022400000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000377211714611271032645 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.tm; import java.util.Properties; import javax.transaction.TransactionManager; import org.hibernate.cfg.Settings; import org.hibernate.transaction.TransactionManagerLookup; /** * HibernateTransactionManagerLookup. * * @author Galder Zamarreño * @since 3.5 */ public class HibernateTransactionManagerLookup implements org.infinispan.transaction.lookup.TransactionManagerLookup { private final TransactionManagerLookup hibernateLookup; private final Properties properties; public HibernateTransactionManagerLookup(Settings settings, Properties properties) { if (settings != null) this.hibernateLookup = settings.getTransactionManagerLookup(); else this.hibernateLookup = null; this.properties = properties; } public TransactionManager getTransactionManager() throws Exception { return hibernateLookup == null ? null : hibernateLookup.getTransactionManager(properties); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000530111714611271032633 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.entity; import org.hibernate.cache.CacheException; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate; /** * Transactional entity region access for Infinispan. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class TransactionalAccess implements EntityRegionAccessStrategy { private final EntityRegionImpl region; private final TransactionalAccessDelegate delegate; TransactionalAccess(EntityRegionImpl region) { this.region = region; this.delegate = new TransactionalAccessDelegate(region, region.getPutFromLoadValidator()); } public void evict(Object key) throws CacheException { delegate.evict(key); } public void evictAll() throws CacheException { delegate.evictAll(); } public Object get(Object key, long txTimestamp) throws CacheException { return delegate.get(key, txTimestamp); } public EntityRegion getRegion() { return this.region; } public boolean insert(Object key, Object value, Object version) throws CacheException { return delegate.insert(key, value, version); } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version); } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version, minimalPutOverride); } public void remove(Object key) throws CacheException { delegate.remove(key); } public void removeAll() throws CacheException { delegate.removeAll(); } public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { return delegate.update(key, value, currentVersion, previousVersion); } public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } public SoftLock lockRegion() throws CacheException { return null; } public void unlockItem(Object key, SoftLock lock) throws CacheException { } public void unlockRegion(SoftLock lock) throws CacheException { } public boolean afterInsert(Object key, Object value, Object version) throws CacheException { return false; } public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { return false; } }././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000306711714611271032642 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.entity; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.infinispan.notifications.Listener; /** * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ @Listener public class EntityRegionImpl extends BaseTransactionalDataRegion implements EntityRegion { public EntityRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, metadata, transactionManager, factory); } public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { if (AccessType.READ_ONLY.equals(accessType)) { return new ReadOnlyAccess(this); } else if (AccessType.TRANSACTIONAL.equals(accessType)) { return new TransactionalAccess(this); } throw new CacheException("Unsupported access type [" + accessType.getName() + "]"); } public PutFromLoadValidator getPutFromLoadValidator() { return new PutFromLoadValidator(transactionManager); } }././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000327711714611271032645 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.entity; import org.hibernate.cache.CacheException; import org.hibernate.cache.access.SoftLock; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A specialization of {@link TransactionalAccess} that ensures we never update data. Infinispan * access is always transactional. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class ReadOnlyAccess extends TransactionalAccess { private static final Log log = LogFactory.getLog(ReadOnlyAccess.class); ReadOnlyAccess(EntityRegionImpl region) { super(region); } public SoftLock lockItem(Object key, Object version) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } public SoftLock lockRegion() throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } public void unlockItem(Object key, SoftLock lock) throws CacheException { log.error("Illegal attempt to edit read only item"); } public void unlockRegion(SoftLock lock) throws CacheException { log.error("Illegal attempt to edit read only item"); } @Override public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000413311714611271032635 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.collection; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate; /** * Transactional collection region access for Infinispan. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class TransactionalAccess implements CollectionRegionAccessStrategy { private final CollectionRegionImpl region; private final TransactionalAccessDelegate delegate; TransactionalAccess(CollectionRegionImpl region) { this.region = region; this.delegate = new TransactionalAccessDelegate(region, region.getPutFromLoadValidator()); } public void evict(Object key) throws CacheException { delegate.evict(key); } public void evictAll() throws CacheException { delegate.evictAll(); } public Object get(Object key, long txTimestamp) throws CacheException { return delegate.get(key, txTimestamp); } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version); } public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version, minimalPutOverride); } public void remove(Object key) throws CacheException { delegate.remove(key); } public void removeAll() throws CacheException { delegate.removeAll(); } public CollectionRegion getRegion() { return region; } public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } public SoftLock lockRegion() throws CacheException { return null; } public void unlockItem(Object key, SoftLock lock) throws CacheException { } public void unlockRegion(SoftLock lock) throws CacheException { } }././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000312411714611271032634 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.collection; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.infinispan.notifications.Listener; /** * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ @Listener public class CollectionRegionImpl extends BaseTransactionalDataRegion implements CollectionRegion { public CollectionRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, metadata, transactionManager, factory); } public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { if (AccessType.READ_ONLY.equals(accessType)) { return new ReadOnlyAccess(this); } else if (AccessType.TRANSACTIONAL.equals(accessType)) { return new TransactionalAccess(this); } throw new CacheException("Unsupported access type [" + accessType.getName() + "]"); } public PutFromLoadValidator getPutFromLoadValidator() { return new PutFromLoadValidator(transactionManager); } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/ReadOnlyAccess.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000253211714611271032636 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.collection; import org.hibernate.cache.CacheException; import org.hibernate.cache.access.SoftLock; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This defines the strategy for transactional access to collection data in a * Infinispan instance. *

* The read-only access to a Infinispan really is still transactional, just with * the extra semantic or guarantee that we will not update data. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class ReadOnlyAccess extends TransactionalAccess { private static final Log log = LogFactory.getLog(ReadOnlyAccess.class); ReadOnlyAccess(CollectionRegionImpl region) { super(region); } public SoftLock lockItem(Object key, Object version) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } public SoftLock lockRegion() throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only region"); } public void unlockItem(Object key, SoftLock lock) throws CacheException { log.error("Illegal attempt to edit read only item"); } public void unlockRegion(SoftLock lock) throws CacheException { log.error("Illegal attempt to edit read only item"); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampTypeOverrides.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000405411714611271032637 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.timestamp; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.TypeOverrides; import org.infinispan.config.Configuration; import org.infinispan.config.Configuration.CacheMode; import org.infinispan.eviction.EvictionStrategy; /** * TimestampTypeOverrides. * * @author Galder Zamarreño * @since 3.5 */ public class TimestampTypeOverrides extends TypeOverrides { @Override public void validateInfinispanConfiguration(Configuration configuration) throws CacheException { CacheMode cacheMode = configuration.getCacheMode(); if (cacheMode.equals(CacheMode.INVALIDATION_ASYNC) || cacheMode.equals(CacheMode.INVALIDATION_SYNC)) { throw new CacheException("Timestamp cache cannot be configured with invalidation"); } EvictionStrategy strategy = configuration.getEvictionStrategy(); if (!strategy.equals(EvictionStrategy.NONE)) { throw new CacheException("Timestamp cache cannot be configured with eviction"); } } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001147211714611271032641 0ustar ebourgebourgpackage org.hibernate.cache.infinispan.timestamp; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheException; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.TimestampsRegion; import org.hibernate.cache.infinispan.impl.BaseGeneralDataRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheHelper; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; /** * Defines the behavior of the timestamps cache region for Infinispan. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ @Listener public class TimestampsRegionImpl extends BaseGeneralDataRegion implements TimestampsRegion { private Map localCache = new ConcurrentHashMap(); public TimestampsRegionImpl(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) { super(cacheAdapter, name, transactionManager, factory); cacheAdapter.addListener(this); populateLocalCache(); } @Override public void evict(Object key) throws CacheException { // TODO Is this a valid operation on a timestamps cache? cacheAdapter.remove(key); } public void evictAll() throws CacheException { // TODO Is this a valid operation on a timestamps cache? Transaction tx = suspend(); try { CacheHelper.sendEvictAllNotification(cacheAdapter, getAddress()); } finally { resume(tx); } } public Object get(Object key) throws CacheException { Object value = localCache.get(key); // If the region is not valid, skip cache store to avoid going remote to retrieve the query. // The aim of this is to maintain same logic/semantics as when state transfer was configured. // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround boolean skipCacheStore = false; if (!isValid()) skipCacheStore = true; if (value == null && checkValid()) { if (skipCacheStore) value = get(key, false, FlagAdapter.SKIP_CACHE_STORE); else value = get(key, false); if (value != null) localCache.put(key, value); } return value; } public void put(Object key, Object value) throws CacheException { // Don't hold the JBC node lock throughout the tx, as that // prevents reads and other updates Transaction tx = suspend(); try { // We ensure ASYNC semantics (JBCACHE-1175) and make sure previous // value is not loaded from cache store cos it's not needed. cacheAdapter.withFlags(FlagAdapter.FORCE_ASYNCHRONOUS).put(key, value); } catch (Exception e) { throw new CacheException(e); } finally { resume(tx); } } @Override public void destroy() throws CacheException { localCache.clear(); cacheAdapter.removeListener(this); super.destroy(); } /** * Monitors cache events and updates the local cache * * @param event */ @CacheEntryModified public void nodeModified(CacheEntryModifiedEvent event) { if (!handleEvictAllModification(event) && !event.isPre()) { localCache.put(event.getKey(), event.getValue()); } } /** * Monitors cache events and updates the local cache * * @param event */ @CacheEntryRemoved public void nodeRemoved(CacheEntryRemovedEvent event) { if (event.isPre()) return; localCache.remove(event.getKey()); } @Override protected boolean handleEvictAllModification(CacheEntryModifiedEvent event) { boolean result = super.handleEvictAllModification(event); if (result) { localCache.clear(); } return result; } @Override protected boolean handleEvictAllInvalidation(CacheEntryInvalidatedEvent event) { boolean result = super.handleEvictAllInvalidation(event); if (result) { localCache.clear(); } return result; } /** * Brings all data from the distributed cache into our local cache. */ private void populateLocalCache() { Set children = cacheAdapter.keySet(); for (Object key : children) get(key); } }././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000755000175000017500000000000012143273450032632 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheHelper.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000703211714611271032636 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat, Inc. and/or it's affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors.  All third-party contributions are * distributed under license by Red Hat, Inc. and/or it's affiliates. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache.infinispan.util; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Helper for dealing with Infinisan cache instances. * * @author Galder Zamarreño * @since 3.5 */ public class CacheHelper { private static final Log log = LogFactory.getLog(CacheHelper.class); /** * Disallow external instantiation of CacheHelper. */ private CacheHelper() { } public static void initInternalEvict(CacheAdapter cache, AddressAdapter member) { EvictAll eKey = new EvictAll(member == null ? NoAddress.INSTANCE : member); cache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).put(eKey, Internal.INIT); } public static void sendEvictAllNotification(CacheAdapter cache, AddressAdapter member) { EvictAll eKey = new EvictAll(member == null ? NoAddress.INSTANCE : member); cache.put(eKey, Internal.EVICT); } public static boolean isEvictAllNotification(Object key) { return key instanceof EvictAll; } public static boolean containsEvictAllNotification(Set keySet, AddressAdapter member) { EvictAll eKey = new EvictAll(member == null ? NoAddress.INSTANCE : member); return keySet.contains(eKey); } public static boolean isEvictAllNotification(Object key, Object value) { return key instanceof EvictAll && value == Internal.EVICT; } private static class EvictAll implements Externalizable { AddressAdapter member; EvictAll(AddressAdapter member) { this.member = member; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof EvictAll)) return false; EvictAll ek = (EvictAll) obj; return ek.member.equals(member); } @Override public int hashCode() { int result = 17; result = 31 * result + member.hashCode(); return result; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { member = (AddressAdapter) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(member); } } private enum NoAddress implements AddressAdapter { INSTANCE; } private enum Internal { INIT, EVICT; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheAdapterImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001562511714611271032645 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.util; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.cache.CacheException; import org.infinispan.Cache; import org.infinispan.config.Configuration; import org.infinispan.context.Flag; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * CacheAdapterImpl. * * @author Galder Zamarreño * @since 3.5 */ public class CacheAdapterImpl implements CacheAdapter { private static final Log log = LogFactory.getLog(CacheAdapterImpl.class); private final Cache cache; private CacheAdapterImpl(Cache cache) { this.cache = cache; } public static CacheAdapter newInstance(Cache cache) { return new CacheAdapterImpl(cache); } public boolean isClusteredInvalidation() { return isClusteredInvalidation(cache.getConfiguration().getCacheMode()); } public boolean isClusteredReplication() { return isClusteredReplication(cache.getConfiguration().getCacheMode()); } public boolean isSynchronous() { return isSynchronous(cache.getConfiguration().getCacheMode()); } public Set keySet() { return cache.keySet(); } public CacheAdapter withFlags(FlagAdapter... flagAdapters) { Flag[] flags = FlagAdapter.toFlags(flagAdapters); return newInstance(cache.getAdvancedCache().withFlags(flags)); } public Object get(Object key) throws CacheException { try { return cache.get(key); } catch (Exception e) { throw new CacheException(e); } } public Object getAllowingTimeout(Object key) throws CacheException { try { return getFailSilentCache().get(key); } catch (TimeoutException ignored) { // ignore it return null; } catch (Exception e) { throw new CacheException(e); } } public void put(Object key, Object value) throws CacheException { try { // No previous value interest, so apply flags that avoid remote lookups. getSkipRemoteGetLoadCache().put(key, value); } catch (Exception e) { throw new CacheException(e); } } public void putAllowingTimeout(Object key, Object value) throws CacheException { try { // No previous value interest, so apply flags that avoid remote lookups. getFailSilentCacheSkipRemotes().put(key, value); } catch (TimeoutException allowed) { // ignore it } catch (Exception e) { throw new CacheException(e); } } public void putForExternalRead(Object key, Object value) throws CacheException { try { // No previous value interest, so apply flags that avoid remote lookups. getFailSilentCacheSkipRemotes().putForExternalRead(key, value); } catch (Exception e) { throw new CacheException(e); } } public void remove(Object key) throws CacheException { try { // No previous value interest, so apply flags that avoid remote lookups. getSkipRemoteGetLoadCache().remove(key); } catch (Exception e) { throw new CacheException(e); } } public void evict(Object key) throws CacheException { try { cache.evict(key); } catch (Exception e) { throw new CacheException(e); } } public void clear() throws CacheException { try { cache.clear(); } catch (Exception e) { throw new CacheException(e); } } public void stop() { if (log.isTraceEnabled()) log.trace("Stop " + cache); cache.stop(); } private static boolean isClusteredInvalidation(Configuration.CacheMode cacheMode) { return cacheMode == Configuration.CacheMode.INVALIDATION_ASYNC || cacheMode == Configuration.CacheMode.INVALIDATION_SYNC; } private static boolean isClusteredReplication(Configuration.CacheMode cacheMode) { return cacheMode == Configuration.CacheMode.REPL_ASYNC || cacheMode == Configuration.CacheMode.REPL_SYNC; } private static boolean isSynchronous(Configuration.CacheMode cacheMode) { return cacheMode == Configuration.CacheMode.REPL_SYNC || cacheMode == Configuration.CacheMode.INVALIDATION_SYNC || cacheMode == Configuration.CacheMode.DIST_SYNC; } public void addListener(Object listener) { cache.addListener(listener); } public AddressAdapter getAddress() { RpcManager rpc = cache.getAdvancedCache().getRpcManager(); if (rpc != null) { return AddressAdapterImpl.newInstance(rpc.getTransport().getAddress()); } return null; } public List getMembers() { RpcManager rpc = cache.getAdvancedCache().getRpcManager(); if (rpc != null) { return AddressAdapterImpl.toAddressAdapter(rpc.getTransport().getMembers()); } return null; } public RpcManager getRpcManager() { return cache.getAdvancedCache().getRpcManager(); } public int size() { return cache.size(); } public Map toMap() { return cache; } public void removeListener(Object listener) { cache.removeListener(listener); } public boolean containsKey(Object key) { return cache.containsKey(key); } public Configuration getConfiguration() { return cache.getConfiguration(); } private Cache getFailSilentCache() { return cache.getAdvancedCache().withFlags(Flag.FAIL_SILENTLY); } private Cache getSkipRemoteGetLoadCache() { return cache.getAdvancedCache().withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP); } private Cache getFailSilentCacheSkipRemotes() { return cache.getAdvancedCache().withFlags( Flag.FAIL_SILENTLY, Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP); } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheAdapter.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001340311714611271032635 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.util; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.cache.CacheException; import org.infinispan.Cache; import org.infinispan.config.Configuration; import org.infinispan.util.concurrent.TimeoutException; /** * Infinispan cache abstraction. * * @author Galder Zamarreño * @since 3.5 */ public interface CacheAdapter { /** * Is this cache participating in a cluster with invalidation? * * @return true if the cache is configured for synchronous/asynchronous invalidation; false otherwise. */ boolean isClusteredInvalidation(); /** * Is this cache participating in a cluster with replication? * * @return true if the cache is configured for synchronous/asynchronous invalidation; false otherwise. */ boolean isClusteredReplication(); /** * Is this cache configured for synchronous communication? * * @return true if the cache is configured for synchronous communication; false otherwise. */ boolean isSynchronous(); /** * Set of keys of this cache. * * @return Set containing keys stored in this cache. */ Set keySet(); /** * A builder-style method that adds flags to any cache API call. * * @param flagAdapters a set of flags to apply. See the {@link FlagAdapter} documentation. * @return a cache on which a real operation is to be invoked. */ CacheAdapter withFlags(FlagAdapter... flagAdapters); /** * Method to check whether a certain key exists in this cache. * * @param key key to look up. * @return true if key is present, false otherwise. */ boolean containsKey(Object key); /** * Performs an get(Object) on the cache, wrapping any exception in a {@link CacheException}. * * @param key key to retrieve * @throws CacheException */ Object get(Object key) throws CacheException; /** * Performs an get(Object) on the cache ignoring any {@link TimeoutException} * and wrapping any other exception in a {@link CacheException}. * * @param key key to retrieve * @throws CacheException */ Object getAllowingTimeout(Object key) throws CacheException; /** * Performs a put(Object, Object) on the cache, * wrapping any exception in a {@link CacheException}. * * @param key key whose value will be modified * @param value data to store in the cache entry * @throws CacheException */ void put(Object key, Object value) throws CacheException; /** * Performs a put(Object, Object) on the cache ignoring * any {@link TimeoutException} and wrapping any exception in a * {@link CacheException}. * * @param key key whose value will be modified * @param value data to store in the cache entry * @throws CacheException */ void putAllowingTimeout(Object key, Object value) throws CacheException; /** * See {@link Cache#putForExternalRead(Object, Object)} for detailed documentation. * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws CacheException */ void putForExternalRead(Object key, Object value) throws CacheException; /** * Performs a remove(Object), wrapping any exception in * a {@link CacheException}. * * @param key key to be removed * @throws CacheException */ void remove(Object key) throws CacheException; /** * Evict the given key from memory. * * @param key to evict. */ void evict(Object key) throws CacheException; /** * Clear the cache. * * @throws CacheException */ void clear() throws CacheException; /** * Stops the cache. */ void stop(); /** * Add listener to this cache. * * @param listener to be added to cache. */ void addListener(Object listener); /** * Get local cluster address. * * @return Address representing local address. */ AddressAdapter getAddress(); /** * Get cluster members. * * @return List of cluster member Address instances */ List getMembers(); /** * Size of cache. * * @return number of cache entries. */ int size(); /** * This method returns a Map view of the cache. * * @return Map view of cache. */ Map toMap(); /** * Remove listener from cache instance. * * @param listener to be removed. */ void removeListener(Object listener); /** * Get cache configuration. * * @return Configuration instance associated with this cache. */ Configuration getConfiguration(); } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/AddressAdapterImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000516611714611271032644 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.util; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; import org.infinispan.remoting.transport.Address; /** * AddressAdapterImpl. * * @author Galder Zamarreño * @since 3.5 */ public class AddressAdapterImpl implements AddressAdapter, Externalizable { private Address address; private AddressAdapterImpl(Address address) { this.address = address; } static AddressAdapter newInstance(Address address) { return new AddressAdapterImpl(address); } public static List toAddressAdapter(List

ispnAddresses) { List addresses = new ArrayList(ispnAddresses.size()); for (Address address : ispnAddresses) { addresses.add(AddressAdapterImpl.newInstance(address)); } return addresses; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { address = (Address) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(address); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof AddressAdapterImpl)) return false; AddressAdapterImpl other = (AddressAdapterImpl) obj; return other.address.equals(address); } @Override public int hashCode() { int result = 17; result = 31 * result + address.hashCode(); return result; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/FlagAdapter.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000433211714611271032636 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.util; import org.hibernate.cache.CacheException; import org.infinispan.context.Flag; /** * FlagAdapter. * * @author Galder Zamarreño * @since 3.5 */ public enum FlagAdapter { ZERO_LOCK_ACQUISITION_TIMEOUT, CACHE_MODE_LOCAL, FORCE_ASYNCHRONOUS, FORCE_SYNCHRONOUS, SKIP_CACHE_STORE, SKIP_CACHE_LOAD; Flag toFlag() { switch(this) { case ZERO_LOCK_ACQUISITION_TIMEOUT: return Flag.ZERO_LOCK_ACQUISITION_TIMEOUT; case CACHE_MODE_LOCAL: return Flag.CACHE_MODE_LOCAL; case FORCE_ASYNCHRONOUS: return Flag.FORCE_ASYNCHRONOUS; case FORCE_SYNCHRONOUS: return Flag.FORCE_SYNCHRONOUS; case SKIP_CACHE_STORE: return Flag.SKIP_CACHE_STORE; case SKIP_CACHE_LOAD: return Flag.SKIP_CACHE_LOAD; default: throw new CacheException("Unmatched Infinispan flag " + this); } } static Flag[] toFlags(FlagAdapter[] adapters) { Flag[] flags = new Flag[adapters.length]; for (int i = 0; i < adapters.length; i++) { flags[i] = adapters[i].toFlag(); } return flags; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/AddressAdapter.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000226411714611271032640 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or its affiliates, and * individual contributors as indicated by the @author tags. See the * copyright.txt file in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan.util; /** * AddressAdapter. * * @author Galder Zamarreño * @since 3.5 */ public interface AddressAdapter { } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000004466411714611271032652 0ustar ebourgebourgpackage org.hibernate.cache.infinispan; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.transaction.TransactionManager; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.TimestampsRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.infinispan.collection.CollectionRegionImpl; import org.hibernate.cache.infinispan.entity.EntityRegionImpl; import org.hibernate.cache.infinispan.impl.ClassLoaderAwareCache; import org.hibernate.cache.infinispan.query.QueryResultsRegionImpl; import org.hibernate.cache.infinispan.timestamp.TimestampsRegionImpl; import org.hibernate.cache.infinispan.timestamp.TimestampTypeOverrides; import org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cfg.Settings; import org.hibernate.util.PropertiesHelper; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.config.Configuration; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A {@link RegionFactory} for Infinispan-backed cache * regions. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class InfinispanRegionFactory implements RegionFactory { private static final Log log = LogFactory.getLog(InfinispanRegionFactory.class); private static final String PREFIX = "hibernate.cache.infinispan."; private static final String CONFIG_SUFFIX = ".cfg"; private static final String STRATEGY_SUFFIX = ".eviction.strategy"; private static final String WAKE_UP_INTERVAL_SUFFIX = ".eviction.wake_up_interval"; private static final String MAX_ENTRIES_SUFFIX = ".eviction.max_entries"; private static final String LIFESPAN_SUFFIX = ".expiration.lifespan"; private static final String MAX_IDLE_SUFFIX = ".expiration.max_idle"; // private static final String STATISTICS_SUFFIX = ".statistics"; /** * Classpath or filesystem resource containing Infinispan configurations the factory should use. * * @see #DEF_INFINISPAN_CONFIG_RESOURCE */ public static final String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg"; public static final String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics"; private static final String ENTITY_KEY = "entity"; /** * Name of the configuration that should be used for entity caches. * * @see #DEF_ENTITY_RESOURCE */ public static final String ENTITY_CACHE_RESOURCE_PROP = PREFIX + ENTITY_KEY + CONFIG_SUFFIX; private static final String COLLECTION_KEY = "collection"; /** * Name of the configuration that should be used for collection caches. * No default value, as by default we try to use the same Infinispan cache * instance we use for entity caching. * * @see #ENTITY_CACHE_RESOURCE_PROP * @see #DEF_ENTITY_RESOURCE */ public static final String COLLECTION_CACHE_RESOURCE_PROP = PREFIX + COLLECTION_KEY + CONFIG_SUFFIX; private static final String TIMESTAMPS_KEY = "timestamps"; /** * Name of the configuration that should be used for timestamp caches. * * @see #DEF_TIMESTAMPS_RESOURCE */ public static final String TIMESTAMPS_CACHE_RESOURCE_PROP = PREFIX + TIMESTAMPS_KEY + CONFIG_SUFFIX; private static final String QUERY_KEY = "query"; /** * Name of the configuration that should be used for query caches. * * @see #DEF_QUERY_RESOURCE */ public static final String QUERY_CACHE_RESOURCE_PROP = PREFIX + QUERY_KEY + CONFIG_SUFFIX; /** * Default value for {@link #INFINISPAN_CONFIG_RESOURCE_PROP}. Specifies the "infinispan-configs.xml" file in this package. */ public static final String DEF_INFINISPAN_CONFIG_RESOURCE = "org/hibernate/cache/infinispan/builder/infinispan-configs.xml"; /** * Default value for {@link #ENTITY_CACHE_RESOURCE_PROP}. */ public static final String DEF_ENTITY_RESOURCE = "entity"; /** * Default value for {@link #TIMESTAMPS_CACHE_RESOURCE_PROP}. */ public static final String DEF_TIMESTAMPS_RESOURCE = "timestamps"; /** * Default value for {@link #QUERY_CACHE_RESOURCE_PROP}. */ public static final String DEF_QUERY_RESOURCE = "local-query"; private EmbeddedCacheManager manager; private final Map typeOverrides = new HashMap(); private final Set definedConfigurations = new HashSet(); private org.infinispan.transaction.lookup.TransactionManagerLookup transactionManagerlookup; private TransactionManager transactionManager; /** * Create a new instance using the default configuration. */ public InfinispanRegionFactory() { } /** * Create a new instance using conifguration properties in props. * * @param props * Environmental properties; currently unused. */ public InfinispanRegionFactory(Properties props) { } /** {@inheritDoc} */ public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { if (log.isDebugEnabled()) log.debug("Building collection cache region [" + regionName + "]"); Cache cache = getCache(regionName, COLLECTION_KEY, properties); CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache); CollectionRegionImpl region = new CollectionRegionImpl(cacheAdapter, regionName, metadata, transactionManager, this); region.start(); return region; } /** {@inheritDoc} */ public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { if (log.isDebugEnabled()) log.debug("Building entity cache region [" + regionName + "]"); Cache cache = getCache(regionName, ENTITY_KEY, properties); CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache); EntityRegionImpl region = new EntityRegionImpl(cacheAdapter, regionName, metadata, transactionManager, this); region.start(); return region; } /** * {@inheritDoc} */ public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { if (log.isDebugEnabled()) log.debug("Building query results cache region [" + regionName + "]"); String cacheName = typeOverrides.get(QUERY_KEY).getCacheName(); // If region name is not default one, lookup a cache for that region name if (!regionName.equals("org.hibernate.cache.StandardQueryCache")) cacheName = regionName; Cache cache = getCache(cacheName, QUERY_KEY, properties); CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache); QueryResultsRegionImpl region = new QueryResultsRegionImpl(cacheAdapter, regionName, properties, transactionManager, this); region.start(); return region; } /** * {@inheritDoc} */ public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { if (log.isDebugEnabled()) log.debug("Building timestamps cache region [" + regionName + "]"); Cache cache = getCache(regionName, TIMESTAMPS_KEY, properties); CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache); TimestampsRegionImpl region = createTimestampsRegion(cacheAdapter, regionName); region.start(); return region; } protected TimestampsRegionImpl createTimestampsRegion(CacheAdapter cacheAdapter, String regionName) { return new TimestampsRegionImpl(cacheAdapter, regionName, transactionManager, this); } protected TransactionManager getTransactionManager() { return transactionManager; } /** * {@inheritDoc} */ public boolean isMinimalPutsEnabledByDefault() { return true; } @Override public AccessType getDefaultAccessType() { return AccessType.TRANSACTIONAL; } /** * {@inheritDoc} */ public long nextTimestamp() { return System.currentTimeMillis() / 100; } public void setCacheManager(EmbeddedCacheManager manager) { this.manager = manager; } public EmbeddedCacheManager getCacheManager() { return manager; } /** * {@inheritDoc} */ public void start(Settings settings, Properties properties) throws CacheException { log.debug("Starting Infinispan region factory"); try { transactionManagerlookup = new HibernateTransactionManagerLookup(settings, properties); transactionManager = transactionManagerlookup.getTransactionManager(); manager = createCacheManager(properties); initGenericDataTypeOverrides(); Enumeration keys = properties.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); int prefixLoc = -1; if ((prefixLoc = key.indexOf(PREFIX)) != -1) { dissectProperty(prefixLoc, key, properties); } } defineGenericDataTypeCacheConfigurations(settings, properties); } catch (CacheException ce) { throw ce; } catch (Throwable t) { throw new CacheException("Unable to start region factory", t); } } /** * {@inheritDoc} */ public void stop() { log.debug("Stopping Infinispan CacheManager"); manager.stop(); } /** * Returns an unmodifiable map containing configured entity/collection type configuration overrides. * This method should be used primarily for testing/checking purpouses. * * @return an unmodifiable map. */ public Map getTypeOverrides() { return Collections.unmodifiableMap(typeOverrides); } public Set getDefinedConfigurations() { return Collections.unmodifiableSet(definedConfigurations); } protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { try { String configLoc = PropertiesHelper.getString(INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE); EmbeddedCacheManager manager = new DefaultCacheManager(configLoc, false); String globalStats = PropertiesHelper.extractPropertyValue(INFINISPAN_GLOBAL_STATISTICS_PROP, properties); if (globalStats != null) { manager.getGlobalConfiguration().setExposeGlobalJmxStatistics(Boolean.parseBoolean(globalStats)); } manager.start(); return manager; } catch (IOException e) { throw new CacheException("Unable to create default cache manager", e); } } private Map initGenericDataTypeOverrides() { TypeOverrides entityOverrides = new TypeOverrides(); entityOverrides.setCacheName(DEF_ENTITY_RESOURCE); typeOverrides.put(ENTITY_KEY, entityOverrides); TypeOverrides collectionOverrides = new TypeOverrides(); collectionOverrides.setCacheName(DEF_ENTITY_RESOURCE); typeOverrides.put(COLLECTION_KEY, collectionOverrides); TypeOverrides timestampOverrides = new TimestampTypeOverrides(); timestampOverrides.setCacheName(DEF_TIMESTAMPS_RESOURCE); typeOverrides.put(TIMESTAMPS_KEY, timestampOverrides); TypeOverrides queryOverrides = new TypeOverrides(); queryOverrides.setCacheName(DEF_QUERY_RESOURCE); typeOverrides.put(QUERY_KEY, queryOverrides); return typeOverrides; } private void dissectProperty(int prefixLoc, String key, Properties properties) { TypeOverrides cfgOverride = null; int suffixLoc = -1; if (!key.equals(INFINISPAN_CONFIG_RESOURCE_PROP) && (suffixLoc = key.indexOf(CONFIG_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setCacheName(PropertiesHelper.extractPropertyValue(key, properties)); } else if ((suffixLoc = key.indexOf(STRATEGY_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setEvictionStrategy(PropertiesHelper.extractPropertyValue(key, properties)); } else if ((suffixLoc = key.indexOf(WAKE_UP_INTERVAL_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setEvictionWakeUpInterval(Long.parseLong(PropertiesHelper.extractPropertyValue(key, properties))); } else if ((suffixLoc = key.indexOf(MAX_ENTRIES_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setEvictionMaxEntries(PropertiesHelper.getInt(key, properties, -1)); } else if ((suffixLoc = key.indexOf(LIFESPAN_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setExpirationLifespan(Long.parseLong(PropertiesHelper.extractPropertyValue(key, properties))); } else if ((suffixLoc = key.indexOf(MAX_IDLE_SUFFIX)) != -1) { cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); cfgOverride.setExpirationMaxIdle(Long.parseLong(PropertiesHelper.extractPropertyValue(key, properties))); } // else if ((suffixLoc = key.indexOf(STATISTICS_SUFFIX)) != -1) { // cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); // cfgOverride.setExposeStatistics(Boolean.parseBoolean(PropertiesHelper.extractPropertyValue(key, properties))); // } } private TypeOverrides getOrCreateConfig(int prefixLoc, String key, int suffixLoc) { String name = key.substring(prefixLoc + PREFIX.length(), suffixLoc); TypeOverrides cfgOverride = typeOverrides.get(name); if (cfgOverride == null) { cfgOverride = new TypeOverrides(); typeOverrides.put(name, cfgOverride); } return cfgOverride; } private void defineGenericDataTypeCacheConfigurations(Settings settings, Properties properties) throws CacheException { String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY}; for (String type : defaultGenericDataTypes) { TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties); String cacheName = override.getCacheName(); Configuration newCacheCfg = override.createInfinispanConfiguration(); // Apply overrides Configuration cacheConfig = manager.defineConfiguration(cacheName, cacheName, newCacheCfg); // Configure transaction manager cacheConfig = configureTransactionManager(cacheConfig, cacheName, properties); manager.defineConfiguration(cacheName, cacheName, cacheConfig); definedConfigurations.add(cacheName); override.validateInfinispanConfiguration(cacheConfig); } } private Cache getCache(String regionName, String typeKey, Properties properties) { TypeOverrides regionOverride = typeOverrides.get(regionName); if (!definedConfigurations.contains(regionName)) { String templateCacheName = null; Configuration regionCacheCfg = null; if (regionOverride != null) { if (log.isDebugEnabled()) log.debug("Cache region specific configuration exists: " + regionOverride); regionOverride = overrideStatisticsIfPresent(regionOverride, properties); regionCacheCfg = regionOverride.createInfinispanConfiguration(); String cacheName = regionOverride.getCacheName(); if (cacheName != null) // Region specific override with a given cache name templateCacheName = cacheName; else // Region specific override without cache name, so template cache name is generic for data type. templateCacheName = typeOverrides.get(typeKey).getCacheName(); } else { // No region specific overrides, template cache name is generic for data type. templateCacheName = typeOverrides.get(typeKey).getCacheName(); regionCacheCfg = typeOverrides.get(typeKey).createInfinispanConfiguration(); } // Configure transaction manager regionCacheCfg = configureTransactionManager(regionCacheCfg, templateCacheName, properties); // Apply overrides manager.defineConfiguration(regionName, templateCacheName, regionCacheCfg); definedConfigurations.add(regionName); } Cache cache = manager.getCache(regionName); if (!cache.getStatus().allowInvocations()) { cache.start(); } return createCacheWrapper(cache.getAdvancedCache()); } protected ClassLoaderAwareCache createCacheWrapper(AdvancedCache cache) { return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()); } private Configuration configureTransactionManager(Configuration regionOverrides, String templateCacheName, Properties properties) { // Get existing configuration to verify whether a tm was configured or not. Configuration templateConfig = manager.defineConfiguration(templateCacheName, new Configuration()); String ispnTmLookupClassName = templateConfig.getTransactionManagerLookupClass(); String hbTmLookupClassName = org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup.class.getName(); if (ispnTmLookupClassName != null && !ispnTmLookupClassName.equals(hbTmLookupClassName)) { log.debug("Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " + "class than Hibernate [" + hbTmLookupClassName + "]"); } else { regionOverrides.setTransactionManagerLookup(transactionManagerlookup); } return regionOverrides; } private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Properties properties) { String globalStats = PropertiesHelper.extractPropertyValue(INFINISPAN_GLOBAL_STATISTICS_PROP, properties); if (globalStats != null) { override.setExposeStatistics(Boolean.parseBoolean(globalStats)); } return override; } } ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/JndiInfinispanRegionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000000705411714611271032642 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.hibernate.cache.CacheException; import org.hibernate.cache.RegionFactory; import org.hibernate.util.NamingHelper; import org.hibernate.util.PropertiesHelper; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A {@link RegionFactory} for Infinispan-backed cache * regions that finds its cache manager in JNDI rather than creating one itself. * * @author Galder Zamarreño * @since 3.5 */ public class JndiInfinispanRegionFactory extends InfinispanRegionFactory { private static final Log log = LogFactory.getLog(JndiInfinispanRegionFactory.class); /** * Specifies the JNDI name under which the {@link EmbeddedCacheManager} to use is bound. * There is no default value -- the user must specify the property. */ public static final String CACHE_MANAGER_RESOURCE_PROP = "hibernate.cache.infinispan.cachemanager"; public JndiInfinispanRegionFactory() { super(); } public JndiInfinispanRegionFactory(Properties props) { super(props); } @Override protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { String name = PropertiesHelper.getString(CACHE_MANAGER_RESOURCE_PROP, properties, null); if (name == null) throw new CacheException("Configuration property " + CACHE_MANAGER_RESOURCE_PROP + " not set"); return locateCacheManager(name, NamingHelper.getJndiProperties(properties)); } private EmbeddedCacheManager locateCacheManager(String jndiNamespace, Properties jndiProperties) { Context ctx = null; try { ctx = new InitialContext(jndiProperties); return (EmbeddedCacheManager) ctx.lookup(jndiNamespace); } catch (NamingException ne) { String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]"; log.info(msg, ne); throw new CacheException( msg ); } finally { if (ctx != null) { try { ctx.close(); } catch( NamingException ne ) { log.info("Unable to release initial context", ne); } } } } @Override public void stop() { // Do not attempt to stop a cache manager because it wasn't created by this region factory. } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.javalibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/java/org/hibernate/cache/infin0000644000175000017500000001232511714611271032637 0ustar ebourgebourg/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat, Inc. and/or it's affiliates, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.hibernate.cache.infinispan; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.hibernate.cache.CacheException; import org.infinispan.config.Configuration; import org.infinispan.eviction.EvictionStrategy; /** * This class represents Infinispan cache parameters that can be configured via hibernate configuration properties * for either general entity/collection/query/timestamp data type caches and overrides for individual entity or * collection caches. Configuration these properties override previously defined properties in XML file. * * @author Galder Zamarreño * @since 3.5 */ public class TypeOverrides { private final Set overridden = new HashSet(); private String cacheName; private EvictionStrategy evictionStrategy; private long evictionWakeUpInterval; private int evictionMaxEntries; private long expirationLifespan; private long expirationMaxIdle; private boolean isExposeStatistics; public String getCacheName() { return cacheName; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } public EvictionStrategy getEvictionStrategy() { return evictionStrategy; } public void setEvictionStrategy(String evictionStrategy) { markAsOverriden("evictionStrategy"); this.evictionStrategy = EvictionStrategy.valueOf(uc(evictionStrategy)); } public long getEvictionWakeUpInterval() { return evictionWakeUpInterval; } public void setEvictionWakeUpInterval(long evictionWakeUpInterval) { markAsOverriden("evictionWakeUpInterval"); this.evictionWakeUpInterval = evictionWakeUpInterval; } public int getEvictionMaxEntries() { return evictionMaxEntries; } public void setEvictionMaxEntries(int evictionMaxEntries) { markAsOverriden("evictionMaxEntries"); this.evictionMaxEntries = evictionMaxEntries; } public long getExpirationLifespan() { return expirationLifespan; } public void setExpirationLifespan(long expirationLifespan) { markAsOverriden("expirationLifespan"); this.expirationLifespan = expirationLifespan; } public long getExpirationMaxIdle() { return expirationMaxIdle; } public void setExpirationMaxIdle(long expirationMaxIdle) { markAsOverriden("expirationMaxIdle"); this.expirationMaxIdle = expirationMaxIdle; } public boolean isExposeStatistics() { return isExposeStatistics; } public void setExposeStatistics(boolean isExposeStatistics) { markAsOverriden("isExposeStatistics"); this.isExposeStatistics = isExposeStatistics; } public Configuration createInfinispanConfiguration() { Configuration cacheCfg = new Configuration(); if (overridden.contains("evictionStrategy")) cacheCfg.setEvictionStrategy(evictionStrategy); if (overridden.contains("evictionWakeUpInterval")) cacheCfg.setEvictionWakeUpInterval(evictionWakeUpInterval); if (overridden.contains("evictionMaxEntries")) cacheCfg.setEvictionMaxEntries(evictionMaxEntries); if (overridden.contains("expirationLifespan")) cacheCfg.setExpirationLifespan(expirationLifespan); if (overridden.contains("expirationMaxIdle")) cacheCfg.setExpirationMaxIdle(expirationMaxIdle); if (overridden.contains("isExposeStatistics")) cacheCfg.setExposeJmxStatistics(isExposeStatistics); return cacheCfg; } public void validateInfinispanConfiguration(Configuration configuration) throws CacheException { // no-op } @Override public String toString() { return new StringBuilder().append(getClass().getSimpleName()).append('{') .append("cache=").append(cacheName) .append(", strategy=").append(evictionStrategy) .append(", wakeUpInterval=").append(evictionWakeUpInterval) .append(", maxEntries=").append(evictionMaxEntries) .append(", lifespan=").append(expirationLifespan) .append(", maxIdle=").append(expirationMaxIdle) .append('}').toString(); } private String uc(String s) { return s == null ? null : s.toUpperCase(Locale.ENGLISH); } private void markAsOverriden(String fieldName) { overridden.add(fieldName); } } libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/0000755000175000017500000000000011714611271027104 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/0000755000175000017500000000000011714611271027673 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/0000755000175000017500000000000011714611271031634 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/0000755000175000017500000000000011714611271032677 5ustar ebourgebourg././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/infinispan/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/0000755000175000017500000000000011714611271032677 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/infinispan/builder/libhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/0000755000175000017500000000000012143273450032677 5ustar ebourgebourg././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/infinispan/builder/infinispan-configs.xmllibhibernate3-java-3.6.10.Final/project/hibernate-infinispan/src/main/resources/org/hibernate/cache/0000644000175000017500000001535211714611271032707 0ustar ebourgebourg libhibernate3-java-3.6.10.Final/project/lgpl.txt0000644000175000017500000006347411714611271020777 0ustar ebourgebourg GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libhibernate3-java-3.6.10.Final/project/pom.xml0000644000175000017500000000657011714611271020607 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent 3.6.10.Final hibernate-parent/pom.xml org.hibernate hibernate pom Hibernate Core Aggregator Aggregator of the Hibernate Core modules. true hibernate-parent hibernate-core hibernate-testing hibernate-testsuite hibernate-ehcache hibernate-jbosscache hibernate-oscache hibernate-swarmcache hibernate-c3p0 hibernate-proxool hibernate-envers hibernate-jdbc3-testing hibernate-infinispan install org.apache.maven.plugins maven-release-plugin 2.0-beta-9 true org.apache.maven.plugins maven-javadoc-plugin 2.5 jdk6-modules disableJDK6Modules !true hibernate-entitymanager hibernate-jdbc4-testing docs disableDistribution !true hibernate-documentation hibernate-distribution libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/0000755000175000017500000000000012143273450024070 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/build.xml0000644000175000017500000000176511714611271025722 0ustar ebourgebourg Processing JPA annotations for metamodel generation libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/pom.xml0000644000175000017500000002360711714611271025415 0ustar ebourgebourg 4.0.0 org.hibernate hibernate-parent 3.6.10.Final ../hibernate-parent/pom.xml org.hibernate hibernate-entitymanager jar Hibernate Entity Manager Hibernate Entity Manager ${project.groupId} hibernate-core ${project.version} cglib cglib javassist javassist org.hibernate.javax.persistence hibernate-jpa-2.0-api javax.validation validation-api true org.hibernate hibernate-validator test ${project.groupId} hibernate-testing ${project.version} test org.jboss.shrinkwrap shrinkwrap-api 1.0.0-alpha-6 test org.jboss.shrinkwrap shrinkwrap-impl-base 1.0.0-alpha-6 test ${project.groupId} hibernate-jpamodelgen 1.0.0.Final test org.hibernate.javax.persistence hibernate-jpa-2.0-api true src/test/resources true src/test/bundles ../bundles org.jboss.maven.plugins maven-injection-plugin ${project.version} org.hibernate.ejb.Version getVersionString org.apache.maven.plugins maven-antrun-plugin process_annotations process-test-sources ${project.build.directory}/generated-src/jpamodelgen run org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 org.apache.maven.plugins maven-surefire-plugin **/*TestCase.java doc org.jboss.maven.plugins maven-jdocbook-plugin master.xml ${basedir}/src/main/docbook en ${basedir}/src/main/docbook/en/images make-doc package resources generate jaxb 1.5 javax.xml.bind jaxb-api 2.1 test com.sun.xml.bind jaxb-impl 2.1.3 test libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/0000755000175000017500000000000011714611271024657 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/0000755000175000017500000000000011714611271025636 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/0000755000175000017500000000000012143273450026557 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/0000755000175000017500000000000011714611271027346 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/0000755000175000017500000000000011714611271031307 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/0000755000175000017500000000000011714611271032047 5ustar ebourgebourg././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/tuple/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/tuple/TupleCriteriaTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000632011714611271032734 0ustar ebourgebourgpackage org.hibernate.ejb.criteria.tuple; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Tuple; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Root; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Customer; import org.hibernate.ejb.metamodel.Customer_; /** * @author Emmanuel Bernard */ public class TupleCriteriaTest extends AbstractMetamodelSpecificTest { public void testArray() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Customer c1 = new Customer(); c1.setId( "c1" ); c1.setAge( 18 ); c1.setName( "Bob" ); em.persist( c1 ); em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(Object[].class); Root c = q.from(Customer.class); q.select( cb.array( c.get(Customer_.name), c.get(Customer_.age) ) ); List result = em.createQuery(q).getResultList(); assertEquals( 1, result.size() ); assertEquals( c1.getName(), result.get( 0 )[0] ); assertEquals( c1.getAge(), result.get( 0 )[1] ); em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Customer" ).executeUpdate(); em.getTransaction().commit(); em.close(); } public void testTuple() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Customer c1 = new Customer(); c1.setId( "c1" ); c1.setAge( 18 ); c1.setName( "Bob" ); em.persist( c1 ); em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createTupleQuery(); Root customerRoot = criteria.from( Customer.class ); Path namePath = customerRoot.get( Customer_.name ); Path agePath = customerRoot.get( Customer_.age ); agePath.alias( "age" ); criteria.multiselect( namePath, agePath ); List results = em.createQuery( criteria ).getResultList(); assertEquals( 1, results.size() ); Object resultElement = results.get( 0 ); assertTrue( "Check result 'row' as Tuple", Tuple.class.isInstance( resultElement ) ); Tuple resultElementTuple = (Tuple) resultElement; Object[] tupleArray = resultElementTuple.toArray(); assertEquals( 2, tupleArray.length ); assertEquals( tupleArray[0], resultElementTuple.get( 0 ) ); assertEquals( resultElementTuple.get( namePath ), resultElementTuple.get( 0 ) ); assertEquals( tupleArray[1], resultElementTuple.get( 1 ) ); assertEquals( resultElementTuple.get( agePath ), resultElementTuple.get( 1 ) ); assertEquals( resultElementTuple.get( agePath ), resultElementTuple.get( "age" ) ); em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Customer" ).executeUpdate(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/MultiTypedBasicAttributesEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000407011714611271032734 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * An entity with multiple attributes of basic type for use in testing using those types/attributes * in queries. * * @author Steve Ebersole */ @Entity @Table(name="ENT_W_MANY_COLS") public class MultiTypedBasicAttributesEntity { @Id @GeneratedValue( generator = "increment" ) @GenericGenerator( name = "increment", strategy = "increment" ) private Long id; private byte[] someBytes; private Byte[] someWrappedBytes; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getSomeBytes() { return someBytes; } public void setSomeBytes(byte[] someBytes) { this.someBytes = someBytes; } public Byte[] getSomeWrappedBytes() { return someWrappedBytes; } public void setSomeWrappedBytes(Byte[] someWrappedBytes) { this.someWrappedBytes = someWrappedBytes; } }././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/components/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/components/Name.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000355311714611271032741 0ustar ebourgebourg/* * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA\ */ package org.hibernate.ejb.criteria.components; import java.io.Serializable; import javax.persistence.Embeddable; import javax.persistence.Column; /** * The name component * * @author alan.oleary */ @Embeddable public class Name implements Serializable { private static final long serialVersionUID = 8381969086665589013L; private String firstName; private String lastName; public Name() { } public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Column(name = "FIRST_NAME", nullable = false) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "LAST_NAME", nullable = false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/components/Client.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000331011714611271032730 0ustar ebourgebourg/* * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA\ */ package org.hibernate.ejb.criteria.components; import java.io.Serializable; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; /** * The client domain entity * */ @Entity public class Client implements Serializable { private int id; private Name name; public Client() { } public Client(int id, Name name) { this.id = id; this.name = name; } public Client(int id, String firstName, String lastName) { this( id, new Name( firstName, lastName ) ); } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @Embedded public Name getName() { return name; } public void setName(Name name) { this.name = name; } } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/components/ComponentCriteriaTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000611211714611271032733 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.components; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.criteria.Expression; import org.hibernate.ejb.test.TestCase; /** * * @author alan.oleary */ public class ComponentCriteriaTest extends TestCase { public Class[] getAnnotatedClasses() { return new Class[] { Client.class }; } public void testEmbeddableInPath() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Client client = new Client( 111, "steve", "ebersole" ); em.persist(client); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Client.class); Root root = cq.from(Client.class); cq.where(cb.equal(root.get("name").get("firstName"), client.getName().getFirstName())); List list = em.createQuery(cq).getResultList(); assertEquals(1, list.size()); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Client" ).executeUpdate(); em.getTransaction().commit(); em.close(); } public void testParameterizedFunctions() { // HHH-4586 EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); // lower CriteriaQuery cq = cb.createQuery( Client.class ); Root root = cq.from( Client.class ); cq.where( cb.equal( cb.lower( root.get( Client_.name ).get( Name_.lastName ) ),"test" ) ); em.createQuery( cq ).getResultList(); // upper cq = cb.createQuery( Client.class ); root = cq.from( Client.class ); cq.where( cb.equal( cb.upper( root.get( Client_.name ).get( Name_.lastName ) ),"test" ) ); em.createQuery( cq ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/paths/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/paths/ImplicitJoinTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000453011714611271032735 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.paths; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Root; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.LineItem; import org.hibernate.ejb.metamodel.LineItem_; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Order_; /** * TODO : javadoc * * @author Steve Ebersole */ public class ImplicitJoinTest extends AbstractMetamodelSpecificTest { public void testImplicitJoinFromExplicitCollectionJoin() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Order.class ); Root orderRoot = criteria.from( Order.class ); Join lineItemsJoin = orderRoot.join( Order_.lineItems ); criteria.where( criteriaBuilder.lt( lineItemsJoin.get( LineItem_.quantity ), 2 ) ); criteria.select( orderRoot ).distinct( true ); TypedQuery query = em.createQuery( criteria ); query.getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/paths/AbstractPathImplTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000363011714611271032735 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.paths; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Order; /** * @author Michael Rudolf */ public class AbstractPathImplTest extends AbstractMetamodelSpecificTest { public void testGetNonExistingAttributeViaName() { EntityManager em = getOrCreateEntityManager(); try { CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery criteria = criteriaBuilder.createQuery( Order.class ); Root orderRoot = criteria.from( Order.class ); orderRoot.get( "nonExistingAttribute" ); fail(); } catch ( IllegalArgumentException e ) { // success } finally { em.close(); } } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/ParameterTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000635411714611271032743 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Root; import org.hibernate.ejb.test.TestCase; /** * @author Steve Ebersole */ public class ParameterTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { MultiTypedBasicAttributesEntity.class }; } public void testPrimitiveArrayParameterBinding() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder() .createQuery( MultiTypedBasicAttributesEntity.class ); Root rootEntity = criteria.from( MultiTypedBasicAttributesEntity.class ); Path someBytesPath = rootEntity.get( "someBytes" ); ParameterExpression param = em.getCriteriaBuilder().parameter( byte[].class, "theBytes" ); criteria.where( em.getCriteriaBuilder().equal( someBytesPath, param ) ); TypedQuery query = em.createQuery( criteria ); query.setParameter( param, new byte[] { 1,1,1 } ); query.getResultList(); em.getTransaction().commit(); em.close(); } public void testNonPrimitiveArrayParameterBinding() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder() .createQuery( MultiTypedBasicAttributesEntity.class ); Root rootEntity = criteria.from( MultiTypedBasicAttributesEntity.class ); Path thePath = rootEntity.get( "someWrappedBytes" ); ParameterExpression param = em.getCriteriaBuilder().parameter( Byte[].class, "theBytes" ); criteria.where( em.getCriteriaBuilder().equal( thePath, param ) ); TypedQuery query = em.createQuery( criteria ); query.setParameter( param, new Byte[] { Byte.valueOf((byte)1), Byte.valueOf((byte)1), Byte.valueOf((byte)1) } ); query.getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/QueryBuilderTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000001716111714611271032741 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import org.hibernate.ejb.criteria.predicate.ComparisonPredicate; import org.hibernate.ejb.metamodel.Address; import org.hibernate.ejb.metamodel.Alias; import org.hibernate.ejb.metamodel.Country; import org.hibernate.ejb.metamodel.CreditCard; import org.hibernate.ejb.metamodel.Customer; import org.hibernate.ejb.metamodel.Info; import org.hibernate.ejb.metamodel.LineItem; import org.hibernate.ejb.metamodel.MetamodelImpl; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Phone; import org.hibernate.ejb.metamodel.Product; import org.hibernate.ejb.metamodel.ShelfLife; import org.hibernate.ejb.metamodel.Spouse; import org.hibernate.ejb.test.TestCase; /** * TODO : javadoc * * @author Steve Ebersole */ public class QueryBuilderTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { Address.class, Alias.class, Country.class, CreditCard.class, Customer.class, Info.class, LineItem.class, Order.class, Phone.class, Product.class, ShelfLife.class, Spouse.class }; } public void testEqualityComparisonLiteralConversion() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery cquery = cb.createQuery( Integer.class ); Root product = cquery.from( Product.class ); EntityType Product_ = mm.entity( Product.class ); cquery.select( cb.toInteger( product.get( Product_.getSingularAttribute("quantity", Integer.class)) ) ); ComparisonPredicate predicate = (ComparisonPredicate) cb.equal( product.get( Product_.getSingularAttribute( "partNumber", Long.class ) ), 373767373 ); assertEquals( Long.class, predicate.getRightHandOperand().getJavaType() ); cquery.where( predicate ); em.createQuery( cquery ).getResultList(); predicate = (ComparisonPredicate) cb.ge( cb.length( product.get( Product_.getSingularAttribute( "name", String.class ) ) ), 4L ); assertEquals( Integer.class, predicate.getRightHandOperand().getJavaType() ); cquery.where( predicate ); em.createQuery( cquery ).getResultList(); em.getTransaction().commit(); em.close(); } public void testEqualityComparisonEntityConversion() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Address address = new Address( "Street Id", "Fake Street", "Fake City", "Fake State", "Fake Zip" ); Phone phone1 = new Phone( "1", "555", "0001", address ); Phone phone2 = new Phone( "2", "555", "0002", address ); Phone phone3 = new Phone( "3", "555", "0003", address ); Phone phone4 = new Phone( "4", "555", "0004" ); Collection phones = new ArrayList( 3 ); phones.add( phone1 ); phones.add( phone2 ); phones.add( phone3 ); address.setPhones( phones ); em.persist( address ); em.persist( phone4 ); em.getTransaction().commit(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); EntityType Phone_ = mm.entity( Phone.class ); CriteriaQuery cquery = cb.createQuery( Phone.class ); Root phone = cquery.from( Phone.class ); ComparisonPredicate predicate = (ComparisonPredicate) cb.equal( phone.get( Phone_.getSingularAttribute( "address", Address.class ) ), address ); cquery.where( predicate ); List results = em.createQuery( cquery ).getResultList(); assertEquals( 3, results.size() ); em.getTransaction().commit(); em.close(); } public void testTypeConversion() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); EntityType Product_ = mm.entity( Product.class ); // toFloat CriteriaQuery floatQuery = cb.createQuery( Float.class ); Root product = floatQuery.from( Product.class ); floatQuery.select( cb.toFloat( product.get(Product_.getSingularAttribute("quantity", Integer.class)) ) ); em.createQuery( floatQuery ).getResultList(); // toDouble CriteriaQuery doubleQuery = cb.createQuery(Double.class); product = doubleQuery.from( Product.class ); doubleQuery.select( cb.toDouble( product.get(Product_.getSingularAttribute("quantity", Integer.class)) ) ); em.createQuery( doubleQuery ).getResultList(); em.getTransaction().commit(); em.close(); } public void testConstructor() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery cquery = cb.createQuery(Customer.class); Root customer = cquery.from(Customer.class); EntityType Customer_ = customer.getModel(); cquery.select( cb.construct( Customer.class, customer.get(Customer_.getSingularAttribute("id", String.class)), customer.get(Customer_.getSingularAttribute("name", String.class)) ) ); TypedQuery tq = em.createQuery(cquery); tq.getResultList(); em.getTransaction().commit(); em.close(); } public void testDateTimeFunctions() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery dateQuery = cb.createQuery(java.sql.Date.class); dateQuery.from( Customer.class ); dateQuery.select( cb.currentDate() ); em.createQuery( dateQuery ).getResultList(); CriteriaQuery timeQuery = cb.createQuery(java.sql.Time.class); timeQuery.from( Customer.class ); timeQuery.select( cb.currentTime() ); em.createQuery( timeQuery ).getResultList(); CriteriaQuery tsQuery = cb.createQuery(java.sql.Timestamp.class); tsQuery.from( Customer.class ); tsQuery.select( cb.currentTimestamp() ); em.createQuery( tsQuery ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/subquery/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/subquery/CorrelatedSubqueryTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000001275011714611271032740 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.subquery; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Customer; import org.hibernate.ejb.metamodel.Customer_; import org.hibernate.ejb.metamodel.LineItem; import org.hibernate.ejb.metamodel.LineItem_; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Order_; import org.hibernate.testing.junit.SkipForDialect; /** * TODO : javadoc * * @author Steve Ebersole */ public class CorrelatedSubqueryTest extends AbstractMetamodelSpecificTest { public void testBasicCorrelation() { CriteriaBuilder builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Customer.class ); Root customer = criteria.from( Customer.class ); criteria.select( customer ); Subquery orderSubquery = criteria.subquery( Order.class ); Root customerCorrelationRoot = orderSubquery.correlate( customer ); Join customerOrderCorrelationJoin = customerCorrelationRoot.join( Customer_.orders ); orderSubquery.select( customerOrderCorrelationJoin ); criteria.where( builder.not( builder.exists( orderSubquery ) ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } public void testRestrictedCorrelation() { CriteriaBuilder builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Order.class ); Root orderRoot = criteria.from( Order.class ); criteria.select( orderRoot ); // create correlated subquery Subquery customerSubquery = criteria.subquery( Customer.class ); Root orderRootCorrelation = customerSubquery.correlate( orderRoot ); Join orderCustomerJoin = orderRootCorrelation.join( Order_.customer ); customerSubquery.where( builder.like( orderCustomerJoin.get( Customer_.name ), "%Caruso" ) ) .select( orderCustomerJoin ); criteria.where( builder.exists( customerSubquery ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } @SkipForDialect(value=SybaseASE15Dialect.class, jiraKey="HHH-3032") public void testCorrelationExplicitSelectionCorrelation() { CriteriaBuilder builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery customerCriteria = builder.createQuery( Customer.class ); Root customer = customerCriteria.from( Customer.class ); Join o = customer.join( Customer_.orders ); Subquery sq = customerCriteria.subquery(Order.class); Join sqo = sq.correlate(o); Join sql = sqo.join(Order_.lineItems); sq.where( builder.gt(sql.get( LineItem_.quantity), 3) ); // use the correlation itself as the subquery selection (initially caused problems wrt aliases) sq.select(sqo); customerCriteria.select(customer).distinct(true); customerCriteria.where(builder.exists(sq)); em.createQuery( customerCriteria ).getResultList(); em.getTransaction().commit(); em.close(); } public void testRestrictedCorrelationNoExplicitSelection() { CriteriaBuilder builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Order.class ); Root orderRoot = criteria.from( Order.class ); criteria.select( orderRoot ); // create correlated subquery Subquery customerSubquery = criteria.subquery( Customer.class ); Root orderRootCorrelation = customerSubquery.correlate( orderRoot ); Join orderCustomerJoin = orderRootCorrelation.join( "customer" ); customerSubquery.where( builder.like( orderCustomerJoin.get( "name" ), "%Caruso" ) ); criteria.where( builder.exists( customerSubquery ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/subquery/UncorrelatedSubqueryTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000500111714611271032727 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.subquery; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Customer; import org.hibernate.ejb.metamodel.Customer_; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Order_; /** * TODO : javadoc * * @author Steve Ebersole */ public class UncorrelatedSubqueryTest extends AbstractMetamodelSpecificTest { public void testEqualAll() { CriteriaBuilder builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Customer.class ); Root customerRoot = criteria.from( Customer.class ); Join orderJoin = customerRoot.join( Customer_.orders ); criteria.select( customerRoot ); Subquery subCriteria = criteria.subquery( Double.class ); Root subqueryOrderRoot = subCriteria.from( Order.class ); subCriteria.select( builder.min( subqueryOrderRoot.get( Order_.totalPrice ) ) ); criteria.where( builder.equal( orderJoin.get( "totalPrice" ), builder.all( subCriteria ) ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/CriteriaCompilingTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000001241111714611271032732 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.ejb.metamodel.Address; import org.hibernate.ejb.metamodel.Alias; import org.hibernate.ejb.metamodel.Country; import org.hibernate.ejb.metamodel.CreditCard; import org.hibernate.ejb.metamodel.Customer; import org.hibernate.ejb.metamodel.Info; import org.hibernate.ejb.metamodel.LineItem; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Phone; import org.hibernate.ejb.metamodel.Product; import org.hibernate.ejb.metamodel.ShelfLife; import org.hibernate.ejb.metamodel.Spouse; import org.hibernate.ejb.test.TestCase; import org.hibernate.ejb.test.callbacks.RemoteControl; import org.hibernate.ejb.test.callbacks.Television; import org.hibernate.ejb.test.callbacks.VideoSystem; import org.hibernate.ejb.test.inheritance.Fruit; import org.hibernate.ejb.test.inheritance.Strawberry; /** * TODO : javadoc * * @author Steve Ebersole */ public class CriteriaCompilingTest extends TestCase { public Class[] getAnnotatedClasses() { return new Class[] { Customer.class, Alias.class, Phone.class, Address.class, Country.class, CreditCard.class, Info.class, Spouse.class, LineItem.class, Order.class, Product.class, ShelfLife.class, // @Inheritance Fruit.class, Strawberry.class, // @MappedSuperclass VideoSystem.class, Television.class, RemoteControl.class }; } public void testJustSimpleRootCriteria() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // First w/o explicit selection... CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Customer.class ); criteria.from( Customer.class ); em.createQuery( criteria ).getResultList(); // Now with... criteria = em.getCriteriaBuilder().createQuery( Customer.class ); Root root = criteria.from( Customer.class ); criteria.select( root ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } public void testSimpleJoinCriteria() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // String based... CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Order.class ); Root root = criteria.from( Order.class ); root.join( "lineItems" ); criteria.select( root ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } public void testSimpleFetchCriteria() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // String based... CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Order.class ); Root root = criteria.from( Order.class ); root.fetch( "lineItems" ); criteria.select( root ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } public void testSerialization() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Order.class ); Root root = criteria.from( Order.class ); root.fetch( "lineItems" ); criteria.select( root ); criteria = serializeDeserialize( criteria ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } private T serializeDeserialize(T object) { T serializedObject = null; try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( object ); out.close(); byte[] serialized = stream.toByteArray(); stream.close(); ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream( byteIn ); serializedObject = (T) in.readObject(); in.close(); byteIn.close(); } catch (Exception e) { fail("Unable to serialize / deserialize the object: " + e.getMessage() ); } return serializedObject; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032731 5ustar ebourgebourg././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/AggregationResultTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000001414511714611271032740 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import junit.framework.AssertionFailedError; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Product; import org.hibernate.ejb.metamodel.Product_; /** * TODO : javadoc * * @author Steve Ebersole */ public class AggregationResultTest extends AbstractMetamodelSpecificTest { private CriteriaBuilder builder; @Override public void setUp() throws Exception { super.setUp(); builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Product product = new Product(); product.setId( "product1" ); product.setPrice( 1.23d ); product.setQuantity( 1000 ); product.setPartNumber( Integer.MAX_VALUE + 1 ); product.setRating( 1.999f ); product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) ); product.setSomeBigDecimal( BigDecimal.valueOf( 987654.321 ) ); em.persist( product ); em.getTransaction().commit(); em.close(); } @Override public void tearDown() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Product" ).executeUpdate(); em.getTransaction().commit(); em.close(); super.tearDown(); } /** * Sum of Longs should return a Long */ public void testSumOfLongs() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Long.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.partNumber ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( Long.class, sumResult ); em.getTransaction().commit(); em.close(); } /** * Sum of Integers should return an Integer; note that this is distinctly different than JPAQL */ public void testSumOfIntegers() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Integer.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.quantity ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( Integer.class, sumResult ); em.getTransaction().commit(); em.close(); } /** * Sum of Doubles should return a Double */ public void testSumOfDoubles() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Double.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.price ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( Double.class, sumResult ); em.getTransaction().commit(); em.close(); } /** * Sum of Floats should return a Float; note that this is distinctly different than JPAQL */ public void testSumOfFloats() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Float.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.rating ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( Float.class, sumResult ); em.getTransaction().commit(); em.close(); } /** * Sum of BigInteger should return a BigInteger */ public void testSumOfBigIntegers() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( BigInteger.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.someBigInteger ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( BigInteger.class, sumResult ); em.getTransaction().commit(); em.close(); } /** * Sum of BigDecimal should return a BigDecimal */ public void testSumOfBigDecimals() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( BigDecimal.class ); Root productRoot = criteria.from( Product.class ); criteria.select( builder.sum( productRoot.get( Product_.someBigDecimal ) ) ); Object sumResult = em.createQuery( criteria ).getSingleResult(); assertReturnType( BigDecimal.class, sumResult ); em.getTransaction().commit(); em.close(); } public void assertReturnType(Class expectedType, Object value) { if ( value != null && ! expectedType.isInstance( value ) ) { throw new AssertionFailedError( "Result value was not of expected type: expected [" + expectedType.getName() + "] but found [" + value.getClass().getName() + "]" ); } } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/CastTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000534011714611271032735 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Product; public class CastTest extends AbstractMetamodelSpecificTest { private static final int QUANTITY = 2; public void testCastToString() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Product product = new Product(); product.setId( "product1" ); product.setPrice( 1.23d ); product.setQuantity( QUANTITY ); product.setPartNumber( ((long)Integer.MAX_VALUE) + 1 ); product.setRating( 1.999f ); product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) ); product.setSomeBigDecimal( BigDecimal.valueOf( 987654.321 ) ); em.persist( product ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery( Product.class ); Root root = criteria.from( Product.class ); criteria.where( builder.equal(root.get("quantity").as(String.class), builder.literal(String.valueOf(QUANTITY))) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Product" ).executeUpdate(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/ExpressionsTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000002541011714611271032735 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.Query; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Phone; import org.hibernate.ejb.metamodel.Product; import org.hibernate.ejb.metamodel.Product_; import org.hibernate.ejb.test.mapping.Phone_; import org.hibernate.impl.AbstractQueryImpl; /** * Tests that various expressions operate as expected * * @author Steve Ebersole */ public class ExpressionsTest extends AbstractMetamodelSpecificTest { private CriteriaBuilder builder; @Override public void setUp() throws Exception { super.setUp(); builder = factory.getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Product product = new Product(); product.setId( "product1" ); product.setPrice( 1.23d ); product.setQuantity( 2 ); product.setPartNumber( ((long)Integer.MAX_VALUE) + 1 ); product.setRating( 1.999f ); product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) ); product.setSomeBigDecimal( BigDecimal.valueOf( 987654.321 ) ); em.persist( product ); em.getTransaction().commit(); em.close(); } public void testEmptyConjunction() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.and() ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testEmptyConjunctionIsTrue() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.isTrue( builder.and() ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testEmptyConjunctionIsFalse() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.isFalse( builder.and() ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 0, result.size() ); em.getTransaction().commit(); em.close(); } public void testEmptyDisjunction() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.disjunction() ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 0, result.size() ); em.getTransaction().commit(); em.close(); } public void testEmptyDisjunctionIsTrue() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.isTrue( builder.disjunction() ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 0, result.size() ); em.getTransaction().commit(); em.close(); } public void testEmptyDisjunctionIsFalse() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); criteria.from( Product.class ); criteria.where( builder.isFalse( builder.disjunction() ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testDiff() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Integer.class ); criteria.from( Product.class ); criteria.select( builder.diff( builder.literal( 5 ), builder.literal( 2 ) ) ); Integer result = em.createQuery( criteria ).getSingleResult(); assertEquals( Integer.valueOf( 3 ), result ); em.getTransaction().commit(); em.close(); } public void testDiffWithQuotient() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Number.class ); criteria.from( Product.class ); criteria.select( builder.quot( builder.diff( builder.literal( BigDecimal.valueOf( 2.0 ) ), builder.literal( BigDecimal.valueOf( 1.0 ) ) ), BigDecimal.valueOf( 2.0 ) ) ); Number result = em.createQuery( criteria ).getSingleResult(); assertEquals(0.5d, result.doubleValue(), 0.1d); em.getTransaction().commit(); em.close(); } public void testSumWithQuotient() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Number.class ); criteria.from( Product.class ); criteria.select( builder.quot( builder.sum( builder.literal( BigDecimal.valueOf( 0.0 ) ), builder.literal( BigDecimal.valueOf( 1.0 ) ) ), BigDecimal.valueOf( 2.0 ) ) ); Number result = em.createQuery( criteria ).getSingleResult(); assertEquals(0.5d, result.doubleValue(), 0.1d); em.getTransaction().commit(); em.close(); } public void testQuotientAndMultiply() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Number.class ); criteria.from( Product.class ); criteria.select( builder.quot( builder.prod( builder.literal( BigDecimal.valueOf( 10.0 ) ), builder.literal( BigDecimal.valueOf( 5.0 ) ) ), BigDecimal.valueOf( 2.0 ) ) ); Number result = em.createQuery( criteria ).getSingleResult(); assertEquals(25.0d, result.doubleValue(), 0.1d); criteria.select( builder.prod( builder.quot( builder.literal( BigDecimal.valueOf( 10.0 ) ), builder.literal( BigDecimal.valueOf( 5.0 ) ) ), BigDecimal.valueOf( 2.0 ) ) ); result = em.createQuery( criteria ).getSingleResult(); assertEquals(4.0d, result.doubleValue(), 0.1d); em.getTransaction().commit(); em.close(); } public void testParameterReuse() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Product.class ); Root from = criteria.from( Product.class ); ParameterExpression param = em.getCriteriaBuilder().parameter( String.class ); Predicate predicate = em.getCriteriaBuilder().equal( from.get( Product_.id ), param ); Predicate predicate2 = em.getCriteriaBuilder().equal( from.get( Product_.name ), param ); criteria.where( em.getCriteriaBuilder().or( predicate, predicate2 ) ); assertEquals( 1, criteria.getParameters().size() ); TypedQuery query = em.createQuery( criteria ); int hqlParamCount = countGeneratedParameters( query.unwrap( Query.class ) ); assertEquals( 1, hqlParamCount ); query.setParameter( param, "abc" ).getResultList(); em.getTransaction().commit(); em.close(); } private int countGeneratedParameters(Query query) { AbstractQueryImpl hqlQueryImpl = (AbstractQueryImpl) query; return hqlQueryImpl.getParameterMetadata().getNamedParameterNames().size(); } public void testInExplicitTupleList() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); Root from = criteria.from( Product.class ); criteria.where( from.get( Product_.partNumber ).in( Collections.singletonList( ((long)Integer.MAX_VALUE) + 1 ) ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testInExplicitTupleListVarargs() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); Root from = criteria.from( Product.class ); criteria.where( from.get( Product_.partNumber ).in( ((long)Integer.MAX_VALUE) + 1 ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testInExpressionVarargs() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Product.class ); Root from = criteria.from( Product.class ); criteria.where( from.get( Product_.partNumber ).in( from.get( Product_.partNumber ) ) ); List result = em.createQuery( criteria ).getResultList(); assertEquals( 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testJoinedElementCollectionValuesInTupleList() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = builder.createQuery( Phone.class ); Root from = criteria.from( Phone.class ); criteria.where( from.join( "types" ) .in( Collections.singletonList( Phone.Type.WORK ) ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/BasicCriteriaUsageTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000517211714611271032740 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import javax.persistence.EntityManager; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Root; import javax.persistence.criteria.Predicate; import org.hibernate.ejb.test.TestCase; /** * TODO : javadoc * * @author Steve Ebersole */ public class BasicCriteriaUsageTest extends TestCase { public Class[] getAnnotatedClasses() { return new Class[] { Wall.class }; } public void testParameterCollection() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Wall.class ); Root from = criteria.from( Wall.class ); ParameterExpression param = em.getCriteriaBuilder().parameter( String.class ); SingularAttribute colorAttribute = em.getMetamodel() .entity( Wall.class ) .getDeclaredSingularAttribute( "color" ); assertNotNull( "metamodel returned null singular attribute", colorAttribute ); Predicate predicate = em.getCriteriaBuilder().equal( from.get( colorAttribute ), param ); criteria.where( predicate ); assertEquals( 1, criteria.getParameters().size() ); em.getTransaction().commit(); em.close(); } public void testTrivialCompilation() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery criteria = em.getCriteriaBuilder().createQuery( Wall.class ); criteria.from( Wall.class ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/PredicateTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000001630011714611271032733 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.ejb.metamodel.Customer_; import org.hibernate.ejb.metamodel.Order; import org.hibernate.ejb.metamodel.Order_; /** * Test the various predicates. * * @author Steve Ebersole * @author Hardy Ferentschik */ public class PredicateTest extends AbstractMetamodelSpecificTest { private EntityManager em; private CriteriaBuilder builder; public void setUp() throws Exception { super.setUp(); builder = factory.getCriteriaBuilder(); em = getOrCreateEntityManager(); createTestOrders(); em.getTransaction().begin(); } public void tearDown() throws Exception { em.getTransaction().commit(); em.close(); super.tearDown(); } public void testEmptyConjunction() { // yes this is a retarded case, but explicitly allowed in the JPA spec CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); orderCriteria.where( builder.isTrue( builder.conjunction() ) ); em.createQuery( orderCriteria ).getResultList(); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 3 ); } public void testEmptyDisjunction() { // yes this is a retarded case, but explicitly allowed in the JPA spec CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); orderCriteria.where( builder.isFalse( builder.disjunction() ) ); em.createQuery( orderCriteria ).getResultList(); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 3 ); } /** * Check simple not. */ public void testSimpleNot() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); orderCriteria.where( builder.not( builder.equal( orderRoot.get( "id" ), "order-1" ) ) ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 2 ); } /** * Check complicated not. */ public void testComplicatedNotOr() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); Predicate p1 = builder.equal( orderRoot.get( "id" ), "order-1" ); Predicate p2 = builder.equal( orderRoot.get( "id" ), "order-2" ); orderCriteria.where( builder.not( builder.or( p1, p2 ) ) ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 1 ); Order order = orders.get( 0 ); assertEquals( "order-3", order.getId() ); } /** * Check complicated not. */ public void testNotMultipleOr() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); Predicate p1 = builder.equal( orderRoot.get( "id" ), "order-1" ); Predicate p2 = builder.equal( orderRoot.get( "id" ), "order-2" ); Predicate p3 = builder.equal( orderRoot.get( "id" ), "order-3" ); orderCriteria.where( builder.not( builder.or( p1, p2, p3 ) ) ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 0 ); } /** * Check complicated not. */ public void testComplicatedNotAnd() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); Predicate p1 = builder.equal( orderRoot.get( "id" ), "order-1" ); Predicate p2 = builder.equal( orderRoot.get( "id" ), "order-2" ); orderCriteria.where( builder.not( builder.and( p1, p2 ) ) ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 3 ); } private void createTestOrders() { em.getTransaction().begin(); em.persist( new Order( "order-1", 1.0d ) ); em.persist( new Order( "order-2", 10.0d ) ); em.persist( new Order( "order-3", new char[]{'r','u'} ) ); em.getTransaction().commit(); } /** * Check predicate for field which has simple char array type (char[]). */ public void testCharArray() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); Predicate p = builder.equal( orderRoot.get( "domen" ), new char[]{'r','u'} ); orderCriteria.where( p ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 1 ); } /** * Check predicate for field which has simple char array type (byte[]). */ public void testByteArray() { CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); orderCriteria.select( orderRoot ); Predicate p = builder.equal( orderRoot.get( "number" ), new byte[]{'1','2'} ); orderCriteria.where( p ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 0 ); } public void testQuotientConversion() { EntityManager em = getOrCreateEntityManager(); CriteriaQuery orderCriteria = builder.createQuery( Order.class ); Root orderRoot = orderCriteria.from( Order.class ); Long longValue = 999999999L; Path doublePath = orderRoot.get( Order_.totalPrice ); Path integerPath = orderRoot.get( Order_.customer ).get( Customer_.age ); orderCriteria.select( orderRoot ); Predicate p = builder.ge( builder.quot( integerPath, doublePath ), longValue ); orderCriteria.where( p ); List orders = em.createQuery( orderCriteria ).getResultList(); assertTrue( orders.size() == 0 ); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/criteria/basic/Wall.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/crit0000644000175000017500000000430411714611271032734 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.ManyToOne; import javax.persistence.JoinColumn; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table( name = "crit_basic_wall" ) public class Wall { private Long id; private long width; private long height; private String color; private Wall left; private Wall right; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getWidth() { return width; } public void setWidth(long width) { this.width = width; } public long getHeight() { return height; } public void setHeight(long height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } @ManyToOne @JoinColumn(name = "left_id") public Wall getLeft() { return left; } public void setLeft(Wall left) { this.left = left; } @ManyToOne @JoinColumn(name = "right_id") public Wall getRight() { return right; } public void setRight(Wall right) { this.right = right; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000755000175000017500000000000012143273450032716 5ustar ebourgebourg././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Order.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000724011714611271032723 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "ORDER_TABLE") public class Order implements java.io.Serializable { private String id; private double totalPrice; private Customer customer; private CreditCard creditCard; private LineItem sampleLineItem; private Collection lineItems = new java.util.ArrayList(); private char[] domen; private byte[] number; public Order() { } public Order(String id, double totalPrice) { this.id = id; this.totalPrice = totalPrice; } public Order(String id, Customer customer) { this.id = id; this.customer = customer; } public Order(String id, char[] domen) { this.id = id; this.domen = domen; } public Order(String id) { this.id = id; } //==================================================================== // getters and setters for State fields @Id @Column(name = "ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "TOTALPRICE") public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double price) { this.totalPrice = price; } //==================================================================== // getters and setters for Association fields // MANYx1 @ManyToOne @JoinColumn( name = "FK4_FOR_CUSTOMER_TABLE") public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } //1x1 @OneToOne(mappedBy = "order") public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard cc) { this.creditCard = cc; } // 1x1 @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "FK0_FOR_LINEITEM_TABLE") public LineItem getSampleLineItem() { return sampleLineItem; } public void setSampleLineItem(LineItem l) { this.sampleLineItem = l; } //1xMANY @OneToMany(cascade = CascadeType.ALL, mappedBy = "order") public Collection getLineItems() { return lineItems; } public void setLineItems(Collection c) { this.lineItems = c; } public char[] getDomen() { return domen; } public void setDomen(char[] d) { domen = d; } public byte[] getNumber() { return number; } public void setNumber(byte[] n) { number = n; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Info.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000517611714611271032731 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "INFO_TABLE") public class Info implements java.io.Serializable { private String id; private String street; private String city; private String state; private String zip; private Spouse spouse; public Info() { } public Info(String v1, String v2, String v3, String v4, String v5) { id = v1; street = v2; city = v3; state = v4; zip = v5; } public Info( String v1, String v2, String v3, String v4, String v5, Spouse v6) { id = v1; street = v2; city = v3; state = v4; zip = v5; spouse = v6; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "INFOSTREET") public String getStreet() { return street; } public void setStreet(String v) { street = v; } @Column(name = "INFOSTATE") public String getState() { return state; } public void setState(String v) { state = v; } @Column(name = "INFOCITY") public String getCity() { return city; } public void setCity(String v) { city = v; } @Column(name = "INFOZIP") public String getZip() { return zip; } public void setZip(String v) { zip = v; } @OneToOne(mappedBy = "info") @JoinTable( name = "INFO_SPOUSE_TABLE" ) public Spouse getSpouse() { return spouse; } public void setSpouse(Spouse v) { this.spouse = v; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Customer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000001041511714611271032721 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "CUSTOMER_TABLE") public class Customer implements java.io.Serializable { private String id; private String name; private Integer age; private Address home; private Address work; private Country country; private Spouse spouse; private Collection creditCards = new java.util.ArrayList(); private Collection orders = new java.util.ArrayList(); private Collection aliases = new java.util.ArrayList(); private Collection aliasesNoop = new java.util.ArrayList(); public Customer() { } public Customer(String id, String name) { this.id = id; this.name = name; } public Customer(String id, String name, Country country) { this.id = id; this.name = name; this.country = country; } public Customer(String id, String name, Address home, Address work, Country country) { this.id = id; this.name = name; this.home = home; this.work = work; this.country = country; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { this.id = v; } @Column(name = "NAME") public String getName() { return name; } public void setName(String v) { this.name = v; } @Column(name = "AGE") public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Embedded public Country getCountry() { return country; } public void setCountry(Country v) { this.country = v; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK6_FOR_CUSTOMER_TABLE") public Address getHome() { return home; } public void setHome(Address v) { this.home = v; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK5_FOR_CUSTOMER_TABLE") public Address getWork() { return work; } public void setWork(Address v) { this.work = v; } @OneToOne(cascade = CascadeType.ALL, mappedBy = "customer") public Spouse getSpouse() { return spouse; } public void setSpouse(Spouse v) { this.spouse = v; } @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer") public Collection getCreditCards() { return creditCards; } public void setCreditCards(Collection v) { this.creditCards = v; } @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer") public Collection getOrders() { return orders; } public void setOrders(Collection v) { this.orders = v; } @ManyToMany(cascade = CascadeType.ALL, mappedBy = "customers") public Collection getAliases() { return aliases; } public void setAliases(Collection v) { this.aliases = v; } @ManyToMany(cascade = CascadeType.ALL, mappedBy = "customersNoop") public Collection getAliasesNoop() { return aliasesNoop; } public void setAliasesNoop(Collection v) { this.aliasesNoop = v; } }././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Address.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000560211714611271032723 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "ADDRESS") public class Address implements java.io.Serializable { private String id; private String street; private String city; private String state; private String zip; private Collection phones = new java.util.ArrayList(); public Address() { } public Address(String id, String street, String city, String state, String zip) { this.id = id; this.street = street; this.city = city; this.state = state; this.zip = zip; } public Address(String id, String street, String city, String state, String zip, Collection phones) { this.id = id; this.street = street; this.city = city; this.state = state; this.zip = zip; this.phones = phones; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "STREET") public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @Column(name = "CITY") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name = "STATE") public String getState() { return state; } public void setState(String state) { this.state = state; } @Column(name = "ZIP") public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } @OneToMany(cascade = CascadeType.ALL, mappedBy = "address") public Collection getPhones() { return phones; } public void setPhones(Collection phones) { this.phones = phones; } }././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Product.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000001031711714611271032722 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "PRODUCT_TABLE") @SecondaryTable(name = "PRODUCT_DETAILS", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID")) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "PRODUCT_TYPE", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("Product") public class Product implements java.io.Serializable { private String id; private String name; private double price; private float rating; private int quantity; private long partNumber; private BigInteger someBigInteger; private BigDecimal someBigDecimal; private String wareHouse; private ShelfLife shelfLife; public Product() { } public Product(String id, String name, double price, int quantity, long partNumber) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; this.partNumber = partNumber; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "PRICE") public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Column(name = "QUANTITY") public int getQuantity() { return quantity; } public void setQuantity(int v) { this.quantity = v; } @Column(name = "PNUM") public long getPartNumber() { return partNumber; } public void setPartNumber(long v) { this.partNumber = v; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public BigInteger getSomeBigInteger() { return someBigInteger; } public void setSomeBigInteger(BigInteger someBigInteger) { this.someBigInteger = someBigInteger; } public BigDecimal getSomeBigDecimal() { return someBigDecimal; } public void setSomeBigDecimal(BigDecimal someBigDecimal) { this.someBigDecimal = someBigDecimal; } @Column(name = "WHOUSE", nullable = true, table = "PRODUCT_DETAILS") public String getWareHouse() { return wareHouse; } public void setWareHouse(String v) { this.wareHouse = v; } @Embedded @AttributeOverrides({ @AttributeOverride(name = "inceptionDate", column = @Column(name = "INCEPTION", nullable = true)), @AttributeOverride(name = "soldDate", column = @Column(name = "SOLD", nullable = true)) }) public ShelfLife getShelfLife() { return shelfLife; } public void setShelfLife(ShelfLife v) { this.shelfLife = v; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Phone.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000500611714611271032721 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "PHONE_TABLE") public class Phone implements java.io.Serializable { public enum Type { LAND_LINE, CELL, FAX, WORK, HOME } private String id; private String area; private String number; private Address address; private Set types; public Phone() { } public Phone(String v1, String v2, String v3) { id = v1; area = v2; number = v3; } public Phone(String v1, String v2, String v3, Address v4) { id = v1; area = v2; number = v3; address = v4; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "AREA") public String getArea() { return area; } public void setArea(String v) { area = v; } @Column(name = "PHONE_NUMBER") public String getNumber() { return number; } public void setNumber(String v) { number = v; } @ManyToOne @JoinColumn(name = "FK_FOR_ADDRESS") public Address getAddress() { return address; } public void setAddress(Address a) { address = a; } @ElementCollection public Set getTypes() { return types; } public void setTypes(Set types) { this.types = types; } }././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/LineItem.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000440111714611271032717 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "LINEITEM_TABLE") public class LineItem implements java.io.Serializable { private String id; private int quantity; private Order order; private Product product; public LineItem() { } public LineItem(String v1, int v2, Order v3, Product v4) { id = v1; quantity = v2; order = v3; product = v4; } public LineItem(String v1, int v2) { id = v1; quantity = v2; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "QUANTITY") public int getQuantity() { return quantity; } public void setQuantity(int v) { quantity = v; } @ManyToOne @JoinColumn(name = "FK1_FOR_ORDER_TABLE") public Order getOrder() { return order; } public void setOrder(Order v) { order = v; } @ManyToOne @JoinColumn(name = "FK_FOR_PRODUCT_TABLE") public Product getProduct() { return product; } public void setProduct(Product v) { product = v; } }././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/AbstractMetamodelSpecificTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000300611714611271032717 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import org.hibernate.ejb.test.TestCase; /** * TODO : javadoc * * @author Steve Ebersole */ public abstract class AbstractMetamodelSpecificTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { Address.class, Alias.class, Country.class, CreditCard.class, Customer.class, Info.class, LineItem.class, Order.class, Phone.class, Product.class, ShelfLife.class, Spouse.class, VersionedEntity.class }; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Spouse.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000601511714611271032722 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "SPOUSE_TABLE") public class Spouse implements java.io.Serializable { private String id; private String first; private String maiden; private String last; private String sNumber; private Info info; private Customer customer; public Spouse() { } public Spouse( String v1, String v2, String v3, String v4, String v5, Info v6) { id = v1; first = v2; maiden = v3; last = v4; sNumber = v5; info = v6; } public Spouse( String v1, String v2, String v3, String v4, String v5, Info v6, Customer v7) { id = v1; first = v2; maiden = v3; last = v4; sNumber = v5; info = v6; customer = v7; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "FIRSTNAME") public String getFirstName() { return first; } public void setFirstName(String v) { first = v; } @Column(name = "MAIDENNAME") public String getMaidenName() { return maiden; } public void setMaidenName(String v) { maiden = v; } @Column(name = "LASTNAME") public String getLastName() { return last; } public void setLastName(String v) { last = v; } @Column(name = "SOCSECNUM") public String getSocialSecurityNumber() { return sNumber; } public void setSocialSecurityNumber(String v) { sNumber = v; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK_FOR_INFO_TABLE") public Info getInfo() { return info; } public void setInfo(Info v) { info = v; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK7_FOR_CUSTOMER_TABLE") public Customer getCustomer() { return customer; } public void setCustomer(Customer v) { customer = v; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/ShelfLife.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000332711714611271032725 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.sql.Date; import javax.persistence.Basic; import javax.persistence.Embeddable; @Embeddable public class ShelfLife implements java.io.Serializable { private Date inceptionDate; private Date soldDate; public ShelfLife() { } public ShelfLife(Date inceptionDate, Date soldDate) { this.inceptionDate = inceptionDate; this.soldDate = soldDate; } @Basic public Date getInceptionDate() { return inceptionDate; } public void setInceptionDate(Date inceptionDate) { this.inceptionDate = inceptionDate; } @Basic public Date getSoldDate() { return soldDate; } public void setSoldDate(Date soldDate) { this.soldDate = soldDate; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/CreditCard.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000636611714611271032733 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "CREDITCARD_TABLE") public class CreditCard implements java.io.Serializable { private String id; private String number; private String type; private String expires; private boolean approved; private double balance; private Order order; private Customer customer; public CreditCard() { } public CreditCard( String v1, String v2, String v3, String v4, boolean v5, double v6, Order v7, Customer v8) { id = v1; number = v2; type = v3; expires = v4; approved = v5; balance = v6; order = v7; customer = v8; } public CreditCard( String v1, String v2, String v3, String v4, boolean v5, double v6) { id = v1; number = v2; type = v3; expires = v4; approved = v5; balance = v6; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String v) { id = v; } @Column(name = "CREDITCARD_NUMBER") public String getNumber() { return number; } public void setNumber(String v) { number = v; } @Column(name = "TYPE") public String getType() { return type; } public void setType(String v) { type = v; } @Column(name = "EXPIRES") public String getExpires() { return expires; } public void setExpires(String v) { expires = v; } @Column(name = "APPROVED") public boolean getApproved() { return approved; } public void setApproved(boolean v) { approved = v; } @Column(name = "BALANCE") public double getBalance() { return balance; } public void setBalance(double v) { balance = v; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK_FOR_ORDER_TABLE") public Order getOrder() { return order; } public void setOrder(Order v) { order = v; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK3_FOR_CUSTOMER_TABLE") public Customer getCustomer() { return customer; } public void setCustomer(Customer v) { customer = v; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Country.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000314511714611271032723 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.Basic; import javax.persistence.Embeddable; /** * TODO : javadoc * * @author Steve Ebersole */ @Embeddable public class Country implements java.io.Serializable { private String country; private String code; public Country() { } public Country(String v1, String v2) { country = v1; code = v2; } @Basic public String getCountry() { return country; } public void setCountry(String v) { country = v; } @Basic public String getCode() { return code; } public void setCode(String v) { code = v; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/Alias.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000645711714611271032734 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Table(name = "ALIAS_TABLE") public class Alias implements java.io.Serializable { private String id; private String alias; private Customer customerNoop; private Collection customersNoop = new java.util.ArrayList(); private Collection customers = new java.util.ArrayList(); public Alias() { } public Alias(String id, String alias) { this.id = id; this.alias = alias; } @Id @Column(name = "ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "ALIAS") public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FK1_FOR_CUSTOMER_TABLE", insertable = false, updatable = false) public Customer getCustomerNoop() { return customerNoop; } public void setCustomerNoop(Customer customerNoop) { this.customerNoop = customerNoop; } @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "FKS_ANOOP_CNOOP", joinColumns = @JoinColumn( name = "FK2_FOR_ALIAS_TABLE", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn( name = "FK8_FOR_CUSTOMER_TABLE", referencedColumnName = "ID") ) public Collection getCustomersNoop() { return customersNoop; } public void setCustomersNoop(Collection customersNoop) { this.customersNoop = customersNoop; } @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "FKS_ALIAS_CUSTOMER", joinColumns = @JoinColumn( name = "FK_FOR_ALIAS_TABLE", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn( name = "FK_FOR_CUSTOMER_TABLE", referencedColumnName = "ID") ) public Collection getCustomers() { return customers; } public void setCustomers(Collection customers) { this.customers = customers; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/EmbeddedTypeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000501011714611271032714 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.EntityManager; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.SingularAttribute; import org.hibernate.ejb.test.TestCase; /** * TODO : javadoc * * @author Steve Ebersole */ public class EmbeddedTypeTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { Product.class, ShelfLife.class, VersionedEntity.class }; } public void testSingularAttributeAccessByName() { // HHH-4702 EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); SingularAttribute soldDate_ = em.getMetamodel().embeddable( ShelfLife.class ) .getSingularAttribute( "soldDate" ); assertEquals( java.sql.Date.class, soldDate_.getBindableJavaType()); assertEquals( java.sql.Date.class, soldDate_.getType().getJavaType() ); assertEquals( java.sql.Date.class, soldDate_.getJavaType() ); em.getTransaction().commit(); em.close(); } public void testVersionAttributeMetadata() { // HHH-5821 EntityManager em = getOrCreateEntityManager(); EntityType metadata = em.getMetamodel().entity( VersionedEntity.class ); assertNotNull( metadata.getDeclaredVersion( int.class ) ); assertTrue( metadata.getDeclaredVersion( int.class ).isVersion() ); assertEquals( 3, metadata.getDeclaredSingularAttributes().size() ); assertTrue( metadata.getDeclaredSingularAttributes().contains( metadata.getDeclaredVersion( int.class ) ) ); em.close(); } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/metamodel/VersionedEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/meta0000644000175000017500000000316111714611271032721 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.metamodel; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; /** * @author Steve Ebersole */ @Entity public class VersionedEntity { private String id; private String name; private int version; @Id public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Version public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/inheritance/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/inheritance/InheritanceTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000213311714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.inheritance; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class InheritanceTest extends TestCase { public void testFind() throws Exception { EntityManager firstSession = getOrCreateEntityManager( ); Strawberry u = new Strawberry(); u.setSize( 12l ); firstSession.getTransaction().begin(); firstSession.persist(u); firstSession.getTransaction().commit(); Long newId = u.getId(); firstSession.clear(); firstSession.getTransaction().begin(); // 1. Strawberry result1 = firstSession.find(Strawberry.class, newId); assertNotNull( result1 ); // 2. Strawberry result2 = (Strawberry) firstSession.find(Fruit.class, newId); System.out.println("2. result is:" + result2); firstSession.getTransaction().commit(); firstSession.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Fruit.class, Strawberry.class }; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/inheritance/Strawberry.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000056411714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.inheritance; import javax.persistence.Column; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Strawberry extends Fruit { private Long size; @Column(name="size_") public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/inheritance/Fruit.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000077511714611271032762 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.inheritance; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity @Inheritance(strategy = InheritanceType.JOINED) public abstract class Fruit { Long id; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Customer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000146211714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "CUSTOMER_TABLE") @Inheritance(strategy = InheritanceType.JOINED) public class Customer extends Person { private Employee salesperson; private String comments; @OneToOne @JoinColumn(name = "salesperson") public Employee getSalesperson() { return salesperson; } public void setSalesperson(Employee salesperson) { this.salesperson = salesperson; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CountryNameCheckerListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000125011714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.util.ArrayList; import java.util.List; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; /** * @author Emmanuel Bernard */ public class CountryNameCheckerListener { private List countries = new ArrayList(); { countries.add( "France" ); countries.add( "Netherland" ); } @PrePersist @PreUpdate public void testCountryName(Object object) { if ( object instanceof Translation ) { Translation tr = (Translation) object; if ( ! countries.contains( tr.getInto() ) ) { throw new IllegalArgumentException( "Not a country name: " + tr.getInto() ); } } } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/RemoteControl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000147011714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * @author Emmanuel Bernard */ @Entity public class RemoteControl { private Integer id; private Date creationDate; @Basic @Temporal(TemporalType.TIMESTAMP) public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @PrePersist private void init() { creationDate = new Date(); } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CountryChecker.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000067011714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.persistence.EntityListeners; /** * @author Emmanuel Bernard */ @EntityListeners(CountryNameCheckerListener.class) @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CountryChecker { } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbackAndDirtyTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000560411714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class CallbackAndDirtyTest extends TestCase { public void testDirtyButNotDirty() throws Exception { EntityManager manager = getOrCreateEntityManager(); manager.getTransaction().begin(); Employee mark = new Employee(); mark.setName( "Mark" ); mark.setTitle( "internal sales" ); mark.setSex( 'M' ); mark.setAddress( "buckhead" ); mark.setZip( "30305" ); mark.setCountry( "USA" ); Customer joe = new Customer(); joe.setName( "Joe" ); joe.setSex( 'M' ); joe.setAddress( "San Francisco" ); joe.setZip( "XXXXX" ); joe.setCountry( "USA" ); joe.setComments( "Very demanding" ); joe.setSalesperson( mark ); Person yomomma = new Person(); yomomma.setName( "mum" ); yomomma.setSex( 'F' ); manager.persist( mark ); manager.persist( joe ); manager.persist( yomomma ); long[] ids = {mark.getId(), joe.getId(), yomomma.getId()}; manager.getTransaction().commit(); manager.getTransaction().begin(); assertEquals( manager.createQuery( "select p.address, p.name from Person p order by p.name" ).getResultList().size(), 3 ); assertEquals( manager.createQuery( "select p from Person p where p.class = Customer" ).getResultList().size(), 1 ); manager.getTransaction().commit(); manager.getTransaction().begin(); List customers = manager.createQuery( "select c from Customer c left join fetch c.salesperson" ).getResultList(); for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) { Customer c = (Customer) iter.next(); assertEquals( c.getSalesperson().getName(), "Mark" ); } assertEquals( customers.size(), 1 ); manager.getTransaction().commit(); manager.getTransaction().begin(); customers = manager.createQuery( "select c from Customer c" ).getResultList(); for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) { Customer c = (Customer) iter.next(); assertEquals( c.getSalesperson().getName(), "Mark" ); } assertEquals( customers.size(), 1 ); manager.getTransaction().commit(); manager.getTransaction().begin(); mark = manager.find( Employee.class, new Long( ids[0] ) ); joe = (Customer) manager.find( Customer.class, new Long( ids[1] ) ); yomomma = manager.find( Person.class, new Long( ids[2] ) ); mark.setZip( "30306" ); assertEquals( 1, manager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() ); manager.remove( mark ); manager.remove( joe ); manager.remove( yomomma ); assertTrue( manager.createQuery( "select p from Person p" ).getResultList().isEmpty() ); manager.getTransaction().commit(); manager.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Customer.class, Employee.class, Person.class }; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbacksTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001476411714611271032765 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.ejb.test.Cat; import org.hibernate.ejb.test.Kitten; import org.hibernate.ejb.test.TestCase; import org.hibernate.testing.junit.FailureExpected; /** * @author Emmanuel Bernard */ @SuppressWarnings("unchecked") public class CallbacksTest extends TestCase { public void testCallbackMethod() throws Exception { EntityManager em = getOrCreateEntityManager(); Cat c = new Cat(); c.setName( "Kitty" ); c.setDateOfBirth( new Date( 90, 11, 15 ) ); em.getTransaction().begin(); em.persist( c ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); c = em.find( Cat.class, c.getId() ); assertFalse( c.getAge() == 0 ); c.setName( "Tomcat" ); //update this entity em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); c = em.find( Cat.class, c.getId() ); assertEquals( "Tomcat", c.getName() ); em.getTransaction().commit(); em.close(); } public void testEntityListener() throws Exception { EntityManager em = getOrCreateEntityManager(); Cat c = new Cat(); c.setName( "Kitty" ); c.setLength( 12 ); c.setDateOfBirth( new Date( 90, 11, 15 ) ); em.getTransaction().begin(); int previousVersion = c.getManualVersion(); em.persist( c ); em.getTransaction().commit(); em.getTransaction().begin(); c = em.find( Cat.class, c.getId() ); assertNotNull( c.getLastUpdate() ); assertTrue( previousVersion < c.getManualVersion() ); assertEquals( 12, c.getLength() ); previousVersion = c.getManualVersion(); c.setName( "new name" ); em.getTransaction().commit(); em.getTransaction().begin(); c = em.find( Cat.class, c.getId() ); assertTrue( previousVersion < c.getManualVersion() ); em.getTransaction().commit(); em.close(); } public void testPostPersist() throws Exception { EntityManager em = getOrCreateEntityManager(); Cat c = new Cat(); em.getTransaction().begin(); c.setLength( 23 ); c.setAge( 2 ); c.setName( "Beetle" ); c.setDateOfBirth( new Date() ); em.persist( c ); em.getTransaction().commit(); em.close(); List ids = Cat.getIdList(); Object id = Cat.getIdList().get( ids.size() - 1 ); assertNotNull( id ); } //Not a test since the spec did not make the proper change on listeners public void listenerAnnotation() throws Exception { EntityManager em = getOrCreateEntityManager(); Translation tl = new Translation(); em.getTransaction().begin(); tl.setInto( "France" ); em.persist( tl ); tl = new Translation(); tl.setInto( "Bimboland" ); try { em.persist( tl ); em.flush(); fail( "Annotations annotated by a listener not used" ); } catch (IllegalArgumentException e) { //success } finally { em.getTransaction().rollback(); em.close(); } } public void testPrePersistOnCascade() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Television tv = new Television(); RemoteControl rc = new RemoteControl(); em.persist( tv ); em.flush(); tv.setControl( rc ); tv.init(); em.flush(); assertNotNull( rc.getCreationDate() ); em.getTransaction().rollback(); em.close(); } public void testCallBackListenersHierarchy() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Television tv = new Television(); em.persist( tv ); tv.setName( "Myaio" ); tv.init(); em.flush(); assertEquals( 1, tv.counter ); em.getTransaction().rollback(); em.close(); assertEquals( 5, tv.communication ); assertTrue( tv.isLast ); } public void testException() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Rythm r = new Rythm(); try { em.persist( r ); em.flush(); fail("should have raised an ArythmeticException:"); } catch (ArithmeticException e) { //success } catch( Exception e ) { fail("should have raised an ArythmeticException:" + e.getClass() ); } em.getTransaction().rollback(); em.close(); } public void testIdNullSetByPrePersist() throws Exception { Plant plant = new Plant(); plant.setName( "Origuna plantula gigantic" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( plant ); em.flush(); em.getTransaction().rollback(); em.close(); } @FailureExpected(message = "collection change does not trigger an event", jiraKey = "EJB-288") public void testPostUpdateCollection() throws Exception { // create a cat EntityManager em = getOrCreateEntityManager(); Cat cat = new Cat(); em.getTransaction().begin(); cat.setLength( 23 ); cat.setAge( 2 ); cat.setName( "Beetle" ); cat.setDateOfBirth( new Date() ); em.persist( cat ); em.getTransaction().commit(); // assert it is persisted List ids = Cat.getIdList(); Object id = Cat.getIdList().get( ids.size() - 1 ); assertNotNull( id ); // add a kitten to the cat - triggers PostCollectionRecreateEvent int postVersion = Cat.postVersion; em.getTransaction().begin(); Kitten kitty = new Kitten(); kitty.setName("kitty"); List kittens = new ArrayList(); kittens.add(kitty); cat.setKittens(kittens); em.getTransaction().commit(); assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion); // add another kitten - triggers PostCollectionUpdateEvent. postVersion = Cat.postVersion; em.getTransaction().begin(); Kitten tom = new Kitten(); tom.setName("Tom"); cat.getKittens().add(tom); em.getTransaction().commit(); assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion); // delete a kitty - triggers PostCollectionUpdateEvent postVersion = Cat.postVersion; em.getTransaction().begin(); cat.getKittens().remove(tom); em.getTransaction().commit(); assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion); // delete and recreate kittens - triggers PostCollectionRemoveEvent and PostCollectionRecreateEvent) postVersion = Cat.postVersion; em.getTransaction().begin(); cat.setKittens(new ArrayList()); em.getTransaction().commit(); assertEquals("Post version should have been incremented.", postVersion + 2, Cat.postVersion); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Cat.class, Translation.class, Television.class, RemoteControl.class, Rythm.class, Plant.class, Kitten.class }; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/VideoSystem.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000122511714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.EntityListeners; import javax.persistence.ExcludeSuperclassListeners; import javax.persistence.MappedSuperclass; import javax.persistence.PreUpdate; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ @ExcludeSuperclassListeners @EntityListeners({FirstOneListener.class, IncreaseListener.class}) @MappedSuperclass public class VideoSystem extends CommunicationSystem { public transient int counter = 0; @PreUpdate public void increase() { isFirst = false; isLast = false; communication++; } @PrePersist public void prepareEntity() { counter++; } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/ExceptionListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000043211714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ public class ExceptionListener { @PrePersist public void raiseException(Object e) { throw new ArithmeticException( "1/0 impossible" ); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Rythm.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000072211714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Entity; import javax.persistence.EntityListeners; /** * @author Emmanuel Bernard */ @Entity @EntityListeners(ExceptionListener.class) public class Rythm { @Id @GeneratedValue private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/FirstOneListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000055011714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.PreUpdate; /** * @author Emmanuel Bernard */ public class FirstOneListener { @PreUpdate public void firstOne(CommunicationSystem object) { if ( !object.isFirst ) throw new IllegalStateException(); object.isFirst = true; object.isLast = false; object.communication++; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/IncreaseListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000045511714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.PreUpdate; /** * @author Emmanuel Bernard */ public class IncreaseListener { @PreUpdate public void increate(CommunicationSystem object) { object.communication++; object.isFirst = false; object.isLast = false; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Plant.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000120011714611271032742 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.Id; import javax.persistence.Entity; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ @Entity public class Plant { @Id private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @PrePersist private void defineId() { //some (stupid) id generation if ( name.length() > 5 ) { setId( name.substring( 0, 5 ) ); } else { setId( name ); } } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CommunicationSystem.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000066611714611271032761 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; /** * @author Emmanuel Bernard */ @MappedSuperclass @EntityListeners(IncreaseListener.class) public class CommunicationSystem { public int communication = 0; public boolean isFirst = true; public boolean isLast; public void init() { communication = 0; isFirst = true; isLast = false; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Translation.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000117211714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "Translatn") @CountryChecker public class Translation { private Integer id; private String into; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name = "country_into") public String getInto() { return into; } public void setInto(String into) { this.into = into; } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Television.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000233611714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PreUpdate; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ @Entity @EntityListeners({IncreaseListener.class}) public class Television extends VideoSystem { private Integer id; private RemoteControl control; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @OneToOne(cascade = CascadeType.ALL) public RemoteControl getControl() { return control; } public void setControl(RemoteControl control) { this.control = control; } public String getName() { return name; } public void setName(String name) { this.name = name; } @PreUpdate public void isLast() { if ( isLast ) throw new IllegalStateException(); isFirst = false; isLast = true; communication++; } @PrePersist public void prepareEntity() { //override a super method annotated with the same // event for it not to be called counter++; } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Employee.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000222511714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "EMPLOYEE_TABLE") @Inheritance(strategy = InheritanceType.JOINED) public class Employee extends Person { private String title; private BigDecimal salary; private Employee manager; /** * @return Returns the title. */ public String getTitle() { return title; } /** * @param title The title to set. */ public void setTitle(String title) { this.title = title; } @OneToOne @JoinColumn(name = "manager") public Employee getManager() { return manager; } /** * @param manager The manager to set. */ public void setManager(Employee manager) { this.manager = manager; } /** * @return Returns the salary. */ public BigDecimal getSalary() { return salary; } /** * @param salary The salary to set. */ public void setSalary(BigDecimal salary) { this.salary = salary; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/Person.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000227311714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.callbacks; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "PERSON_TABLE") @Inheritance(strategy = InheritanceType.JOINED) public class Person { private long id; private String name; private String address; private String zip; private String country; private char sex; @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public String getName() { return name; } public void setName(String identity) { this.name = identity; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/query/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/query/ComponentJoinsTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000447611714611271032764 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA\ */ package org.hibernate.ejb.test.query; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; import org.hibernate.ejb.criteria.components.Client; /** * Tests related to specifying joins on components (embedded values). * * @author Steve Ebersole */ public class ComponentJoinsTest extends TestCase { public Class[] getAnnotatedClasses() { return new Class[] { Client.class }; } public void testComponentJoins() { // Just checking proper query construction and syntax checking via database query parser... EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // use it in WHERE em.createQuery( "select c from Client c join c.name as n where n.lastName like '%'" ).getResultList(); // use it in SELECT em.createQuery( "select n.lastName from Client c join c.name as n" ).getResultList(); em.createQuery( "select n from Client c join c.name as n" ).getResultList(); // use it in ORDER BY em.createQuery( "select n from Client c join c.name as n order by n.lastName" ).getResultList(); em.createQuery( "select n from Client c join c.name as n order by c" ).getResultList(); em.createQuery( "select n from Client c join c.name as n order by n" ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/query/QueryTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000004370011714611271032755 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.query; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TemporalType; import javax.persistence.Tuple; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; import org.hibernate.ejb.test.TestCase; import org.hibernate.ejb.test.Wallet; /** * @author Emmanuel Bernard */ public class QueryTest extends TestCase { public void testPagedQuery() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item = new Item( "Mouse", "Micro$oft mouse" ); em.persist( item ); item = new Item( "Computer", "Apple II" ); em.persist( item ); Query q = em.createQuery( "select i from " + Item.class.getName() + " i where i.name like :itemName" ); q.setParameter( "itemName", "%" ); q.setMaxResults( 1 ); q.getSingleResult(); q = em.createQuery( "select i from Item i where i.name like :itemName" ); q.setParameter( "itemName", "%" ); q.setFirstResult( 1 ); q.setMaxResults( 1 ); em.getTransaction().rollback(); em.close(); } public void testAggregationReturnType() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item = new Item( "Mouse", "Micro$oft mouse" ); em.persist( item ); item = new Item( "Computer", "Apple II" ); em.persist( item ); Query q = em.createQuery( "select count(i) from Item i where i.name like :itemName" ); q.setParameter( "itemName", "%" ); assertTrue( q.getSingleResult() instanceof Long ); em.getTransaction().rollback(); em.close(); } public void testParameterList() throws Exception { final Item item = new Item( "Mouse", "Micro$oft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in :names" ); //test hint in value and string q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); List params = new ArrayList(); params.add( item.getName() ); q.setParameter( "names", params ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); q = em.createQuery( "select item from Item item where item.name in :names" ); //test hint in value and string q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); params.add( item2.getName() ); q.setParameter( "names", params ); result = q.getResultList(); assertNotNull( result ); assertEquals( 2, result.size() ); q = em.createQuery( "select item from Item item where item.name in ?1" ); params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( "1", params ); result = q.getResultList(); assertNotNull( result ); assertEquals( 2, result.size() ); em.remove( result.get( 0 ) ); em.remove( result.get( 1 ) ); em.getTransaction().commit(); em.close(); } public void testParameterListInExistingParens() throws Exception { final Item item = new Item( "Mouse", "Micro$oft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in (:names)" ); //test hint in value and string q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); List params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( "names", params ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 2, result.size() ); q = em.createQuery( "select item from Item item where item.name in ( \n :names \n)\n" ); //test hint in value and string q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( "names", params ); result = q.getResultList(); assertNotNull( result ); assertEquals( 2, result.size() ); q = em.createQuery( "select item from Item item where item.name in ( ?1 )" ); params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( "1", params ); result = q.getResultList(); assertNotNull( result ); assertEquals( 2, result.size() ); em.remove( result.get( 0 ) ); em.remove( result.get( 1 ) ); em.getTransaction().commit(); em.close(); } // public void testDistinct() throws Exception { // Item item = new Item("Mouse", "Micro_oft mouse"); // Distributor fnac = new Distributor(); // fnac.setName("Fnac"); // item.addDistributor(fnac); // Distributor auchan = new Distributor(); // auchan.setName("Auchan"); // item.addDistributor(auchan); // // EntityManager em = getOrCreateEntityManager(); // em.getTransaction().begin(); // em.persist(fnac); // em.persist(auchan); // em.persist(item); // em.getTransaction().commit(); // // em.getTransaction().begin(); // Query q = em.createQuery("select distinct item from Item item join fetch item.distributors"); // List result = q.getResultList(); // assertNotNull(result); // assertEquals( 1, result.size() ); // item = (Item) result.get(0); // item.getDistributors().clear(); // em.flush(); // int deleted = em.createQuery("delete from Item").executeUpdate(); // assertEquals( 1, deleted ); // deleted = em.createQuery("delete from Distributor").executeUpdate(); // assertEquals( 2, deleted ); // em.getTransaction().commit(); // // em.close(); // } public void testEscapeCharacter() throws Exception { final Item item = new Item( "Mouse", "Micro_oft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.descr like 'Microk_oft mouse' escape 'k' " ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); int deleted = em.createQuery( "delete from Item" ).executeUpdate(); assertEquals( 2, deleted ); em.getTransaction().commit(); em.close(); } public void testNativeQueryByEntity() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); item = (Item) em.createNativeQuery( "select * from Item", Item.class ).getSingleResult(); assertNotNull( item ); assertEquals( "Micro$oft mouse", item.getDescr() ); em.remove( item ); em.getTransaction().commit(); em.close(); } public void testNativeQueryByResultSet() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); item = (Item) em.createNativeQuery( "select name as itemname, descr as itemdescription from Item", "getItem" ) .getSingleResult(); assertNotNull( item ); assertEquals( "Micro$oft mouse", item.getDescr() ); em.remove( item ); em.getTransaction().commit(); em.close(); } public void testExplicitPositionalParameter() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.getTransaction().commit(); em.getTransaction().begin(); Query query = em.createQuery( "select w from " + Wallet.class.getName() + " w where w.brand in ?1" ); List brands = new ArrayList(); brands.add( "Lacoste" ); query.setParameter( 1, brands ); w = (Wallet) query.getSingleResult(); assertNotNull( w ); query = em.createQuery( "select w from " + Wallet.class.getName() + " w where w.marketEntrance = ?1" ); query.setParameter( 1, new Date(), TemporalType.DATE ); //assertNull( query.getSingleResult() ); assertEquals( 0, query.getResultList().size() ); em.remove( w ); em.getTransaction().commit(); em.close(); } public void testPositionalParameterForms() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.getTransaction().commit(); em.getTransaction().begin(); // first using jpa-style positional parameter Query query = em.createQuery( "select w from Wallet w where w.brand = ?1" ); query.setParameter( 1, "Lacoste" ); w = (Wallet) query.getSingleResult(); assertNotNull( w ); // next using jpa-style positional parameter, but as a name (which is how Hibernate core treats these query = em.createQuery( "select w from Wallet w where w.brand = ?1" ); query.setParameter( "1", "Lacoste" ); w = (Wallet) query.getSingleResult(); assertNotNull( w ); // finally using hql-style positional parameter query = em.createQuery( "select w from Wallet w where w.brand = ?" ); query.setParameter( 1, "Lacoste" ); w = (Wallet) query.getSingleResult(); assertNotNull( w ); em.remove( w ); em.getTransaction().commit(); em.close(); } public void testPositionalParameterWithUserError() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.flush(); try { Query query = em.createQuery( "select w from Wallet w where w.brand = ?1 and w.model = ?3" ); query.setParameter( 1, "Lacoste" ); query.setParameter( 2, "Expensive" ); query.getResultList(); fail("The query should fail due to a user error in parameters"); } catch ( IllegalArgumentException e ) { //success } finally { em.getTransaction().rollback(); em.close(); } } public void testNativeQuestionMarkParameter() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.getTransaction().commit(); em.getTransaction().begin(); Query query = em.createNativeQuery( "select * from Wallet w where w.brand = ?", Wallet.class ); query.setParameter( 1, "Lacoste" ); w = (Wallet) query.getSingleResult(); assertNotNull( w ); em.remove( w ); em.getTransaction().commit(); em.close(); } public void testNativeQueryWithPositionalParameter() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query query = em.createNativeQuery( "select * from Item where name = ?1", Item.class ); query.setParameter( 1, "Mouse" ); item = (Item) query.getSingleResult(); assertNotNull( item ); assertEquals( "Micro$oft mouse", item.getDescr() ); query = em.createNativeQuery( "select * from Item where name = ?", Item.class ); query.setParameter( 1, "Mouse" ); item = (Item) query.getSingleResult(); assertNotNull( item ); assertEquals( "Micro$oft mouse", item.getDescr() ); em.remove( item ); em.getTransaction().commit(); em.close(); } public void testDistinct() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.createQuery( "delete Item" ).executeUpdate(); em.createQuery( "delete Distributor" ).executeUpdate(); Distributor d1 = new Distributor(); d1.setName( "Fnac" ); Distributor d2 = new Distributor(); d2.setName( "Darty" ); Item item = new Item( "Mouse", "Micro$oft mouse" ); item.getDistributors().add( d1 ); item.getDistributors().add( d2 ); em.persist( d1 ); em.persist( d2 ); em.persist( item ); em.flush(); em.clear(); Query q = em.createQuery( "select distinct i from Item i left join fetch i.distributors" ); item = (Item) q.getSingleResult() ; //assertEquals( 1, distinctResult.size() ); //item = (Item) distinctResult.get( 0 ); assertTrue( Hibernate.isInitialized( item.getDistributors() ) ); assertEquals( 2, item.getDistributors().size() ); em.getTransaction().rollback(); em.close(); } public void testIsNull() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Distributor d1 = new Distributor(); d1.setName( "Fnac" ); Distributor d2 = new Distributor(); d2.setName( "Darty" ); Item item = new Item( "Mouse", null ); Item item2 = new Item( "Mouse2", "dd" ); item.getDistributors().add( d1 ); item.getDistributors().add( d2 ); em.persist( d1 ); em.persist( d2 ); em.persist( item ); em.persist( item2 ); em.flush(); em.clear(); Query q = em.createQuery( "select i from Item i where i.descr = :descr or (i.descr is null and cast(:descr as string) is null)" ); //Query q = em.createQuery( "select i from Item i where (i.descr is null and :descr is null) or (i.descr = :descr"); q.setParameter( "descr", "dd" ); List result = q.getResultList(); assertEquals( 1, result.size() ); q.setParameter( "descr", null ); result = q.getResultList(); assertEquals( 1, result.size() ); //item = (Item) distinctResult.get( 0 ); em.getTransaction().rollback(); em.close(); } public void testUpdateQuery() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.flush(); em.clear(); assertEquals( 1, em.createNativeQuery( "update Item set descr = 'Logitech Mouse' where name = 'Mouse'" ).executeUpdate() ); item = em.find( Item.class, item.getName() ); assertEquals( "Logitech Mouse", item.getDescr() ); em.remove( item ); em.getTransaction().rollback(); em.close(); } public void testUnavailableNamedQuery() throws Exception { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); try { em.createNamedQuery( "wrong name" ); fail("Wrong named query should raise an exception"); } catch (IllegalArgumentException e) { //success } em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); em.remove( em.find( Item.class, item.getName() ) ); em.getTransaction().commit(); em.close(); } public void testTypedNamedNativeQuery() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); item = em.createNamedQuery( "nativeItem1", Item.class ).getSingleResult(); item = em.createNamedQuery( "nativeItem2", Item.class ).getSingleResult(); assertNotNull( item ); assertEquals( "Micro$oft mouse", item.getDescr() ); em.remove( item ); em.getTransaction().commit(); em.close(); } public void testTypedScalarQueries() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item = new Item( "Mouse", "Micro$oft mouse" ); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Object[] itemData = em.createQuery( "select i.name,i.descr from Item i", Object[].class ).getSingleResult(); assertEquals( 2, itemData.length ); assertEquals( String.class, itemData[0].getClass() ); assertEquals( String.class, itemData[1].getClass() ); Tuple itemTuple = em.createQuery( "select i.name,i.descr from Item i", Tuple.class ).getSingleResult(); assertEquals( 2, itemTuple.getElements().size() ); assertEquals( String.class, itemTuple.get( 0 ).getClass() ); assertEquals( String.class, itemTuple.get( 1 ).getClass() ); Item itemView = em.createQuery( "select new Item(i.name,i.descr) from Item i", Item.class ).getSingleResult(); assertNotNull( itemView ); assertEquals( "Micro$oft mouse", itemView.getDescr() ); em.remove( item ); em.getTransaction().commit(); em.close(); } @Override public Class[] getAnnotatedClasses() { return new Class[]{ Item.class, Distributor.class, Wallet.class }; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/MergeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001315711714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class MergeTest extends TestCase { public void testMergeWithIndexColumn() { Race race = new Race(); race.competitors.add( new Competitor( "Name" ) ); race.competitors.add( new Competitor() ); race.competitors.add( new Competitor() ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( race ); em.flush(); em.clear(); race.competitors.add( new Competitor() ); race.competitors.remove( 2 ); race.competitors.remove( 1 ); race.competitors.get( 0 ).setName( "Name2" ); race = em.merge( race ); em.flush(); em.clear(); race = em.find( Race.class, race.id ); assertEquals( 2, race.competitors.size() ); assertEquals( "Name2", race.competitors.get( 0 ).getName() ); em.getTransaction().rollback(); em.close(); } public void testMergeManyToMany() { Competition competition = new Competition(); competition.getCompetitors().add( new Competitor( "Name" ) ); competition.getCompetitors().add( new Competitor() ); competition.getCompetitors().add( new Competitor() ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( competition ); em.flush(); em.clear(); competition.getCompetitors().add( new Competitor() ); competition.getCompetitors().remove( 2 ); competition.getCompetitors().remove( 1 ); competition.getCompetitors().get( 0 ).setName( "Name2" ); competition = em.merge( competition ); em.flush(); em.clear(); competition = em.find( Competition.class, competition.getId() ); assertEquals( 2, competition.getCompetitors().size() ); // we cannot assume that the order in the list is maintained - HHH-4516 String changedCompetitorName; if ( competition.getCompetitors().get( 0 ).getName() != null ) { changedCompetitorName = competition.getCompetitors().get( 0 ).getName(); } else { changedCompetitorName = competition.getCompetitors().get( 1 ).getName(); } assertEquals( "Name2", changedCompetitorName ); em.getTransaction().rollback(); em.close(); } public void testMergeManyToManyWithDeference() { Competition competition = new Competition(); competition.getCompetitors().add( new Competitor( "Name" ) ); competition.getCompetitors().add( new Competitor() ); competition.getCompetitors().add( new Competitor() ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( competition ); em.flush(); em.clear(); List newComp = new ArrayList(); newComp.add( competition.getCompetitors().get( 0 ) ); newComp.add( new Competitor() ); newComp.get( 0 ).setName( "Name2" ); competition.setCompetitors( newComp ); competition = em.merge( competition ); em.flush(); em.clear(); competition = em.find( Competition.class, competition.getId() ); assertEquals( 2, competition.getCompetitors().size() ); // we cannot assume that the order in the list is maintained - HHH-4516 String changedCompetitorName; if ( competition.getCompetitors().get( 0 ).getName() != null ) { changedCompetitorName = competition.getCompetitors().get( 0 ).getName(); } else { changedCompetitorName = competition.getCompetitors().get( 1 ).getName(); } assertEquals( "Name2", changedCompetitorName ); em.getTransaction().rollback(); em.close(); } public void testRemoveAndMerge() { Race race = new Race(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( race ); em.flush(); em.clear(); race = em.find( Race.class, race.id ); em.remove( race ); try { race = em.merge( race ); em.flush(); fail( "Should raise an IllegalArgumentException" ); } catch ( IllegalArgumentException e ) { //all good } catch ( Exception e ) { fail( "Should raise an IllegalArgumentException" ); } em.getTransaction().rollback(); em.close(); } public void testConcurrentMerge() { Race race = new Race(); race.name = "Derby"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( race ); em.flush(); em.getTransaction().commit(); em.close(); race.name = "Magnicourt"; em = getOrCreateEntityManager(); em.getTransaction().begin(); Race race2 = em.find( Race.class, race.id ); race2.name = "Mans"; race = em.merge( race ); em.flush(); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); race2 = em.find( Race.class, race.id ); assertEquals( "Last commit win in merge", "Magnicourt", race2.name ); em.remove( race2 ); em.getTransaction().commit(); em.close(); } public void testMergeUnidirectionalOneToMany() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Empire roman = new Empire(); em.persist( roman ); em.flush(); em.clear(); roman = em.find( Empire.class, roman.getId() ); Colony gaule = new Colony(); roman.getColonies().add( gaule ); em.merge( roman ); em.flush(); em.clear(); roman = em.find( Empire.class, roman.getId() ); assertEquals( 1, roman.getColonies().size() ); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Race.class, Competitor.class, Competition.class, Empire.class, Colony.class }; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/FlushModeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000364411714611271032760 0ustar ebourgebourg//$Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.emops; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class FlushModeTest extends TestCase { public void testCreateEMFlushMode() throws Exception { Map properties = new HashMap(); properties.put( "org.hibernate.flushMode", "manual" ); EntityManager em = createEntityManager( properties ); em.getTransaction().begin(); Dress dress = new Dress(); dress.name = "long dress"; em.persist( dress ); em.getTransaction().commit(); em.clear(); assertNull( em.find( Dress.class, dress.name ) ); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Race.class, Competitor.class, Dress.class }; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Dog.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000061611714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity @Inheritance( strategy = InheritanceType.JOINED ) public class Dog extends Pet { private int numBones; public int getNumBones() { return numBones; } public void setNumBones(int numBones) { this.numBones = numBones; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Colony.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000056611714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Colony { @Id @GeneratedValue private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Dress.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000033011714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Id; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Dress { @Id public String name; } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Empire.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000135011714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.OneToMany; import javax.persistence.CascadeType; /** * @author Emmanuel Bernard */ @Entity public class Empire { @Id @GeneratedValue private Long id; @OneToMany(cascade= CascadeType.ALL ) private Set colonies = new HashSet(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Set getColonies() { return colonies; } public void setColonies(Set colonies) { this.colonies = colonies; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Competition.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000204611714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import java.util.Collection; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.ManyToMany; import javax.persistence.CascadeType; import javax.persistence.FetchType; import javax.persistence.JoinTable; import javax.persistence.JoinColumn; /** * @author Emmanuel Bernard */ @Entity public class Competition { @Id @GeneratedValue private Integer id; @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY) @JoinTable(name="competition_competitor") @JoinColumn private List competitors = new ArrayList(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List getCompetitors() { return competitors; } public void setCompetitors(List competitors) { this.competitors = competitors; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Race.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000144011714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderColumn; /** * @author Emmanuel Bernard */ @Entity public class Race { @Id @GeneratedValue public Integer id; @OrderColumn( name="index_" ) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN }) public List competitors = new ArrayList(); public String name; } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/CascadePersistTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000402211714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; import org.hibernate.Session; import org.hibernate.stat.Statistics; /** * @author Emmanuel Bernard */ public class CascadePersistTest extends TestCase { public void testLazyCollectionsStayLazyOnPersist() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); //initialize A a = new A(); a.setName( "name1" ); em.persist( a ); a = new A(); a.setName( "name2" ); em.persist( a ); a = new A(); a.setName( "name3" ); em.persist( a ); em.flush(); a = em.find( A.class, 1 ); for ( int i = 0; i < 3; i++ ) { B1 b1 = new B1(); b1.setA( a ); em.persist( b1 ); } for ( int i = 0; i < 3; i++ ) { B2 b2 = new B2(); b2.setA( a ); em.persist( b2 ); } for ( int i = 0; i < 3; i++ ) { B3 b3 = new B3(); b3.setA( a ); em.persist( b3 ); } for ( int i = 0; i < 3; i++ ) { B4 b4 = new B4(); b4.setA( a ); em.persist( b4 ); } em.flush(); B1 b1 = em.find( B1.class, 1 ); for ( int i = 0; i < 2; i++ ) { C1 c1 = new C1(); c1.setB1( b1 ); em.persist( c1 ); } B2 b2 = em.find( B2.class, 1 ); for ( int i = 0; i < 4; i++ ) { C2 c2 = new C2(); c2.setB2( b2 ); em.persist( c2 ); } em.flush(); em.clear(); //test a = em.find( A.class, 1 ); C2 c2 = new C2(); for ( B2 anotherB2 : a.getB2List() ) { if ( anotherB2.getId() == 1 ) { anotherB2.getC2List().add( c2 ); c2.setB2( anotherB2 ); } } Statistics statistics = em.unwrap(Session.class).getSessionFactory().getStatistics(); statistics.setStatisticsEnabled( true ); statistics.clear(); em.persist( c2 ); long loaded = statistics.getEntityLoadCount(); assertEquals( 0, loaded ); em.flush(); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ A.class, B1.class, B2.class, B3.class, B4.class, C1.class, C2.class }; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/C2.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000134411714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class C2 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "b2Id" ) private B2 b2; public B2 getB2() { return b2; } public void setB2(B2 b2) { this.b2 = b2; } public int getId() { return id; } public void setId(int id) { this.id = id; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/A.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000340111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class A { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; private String name; @OneToMany( fetch = FetchType.LAZY, mappedBy = "a", cascade = {CascadeType.PERSIST} ) private Set b1List; @OneToMany( fetch = FetchType.LAZY, mappedBy = "a", cascade = {CascadeType.PERSIST} ) private Set b2List; @OneToMany( fetch = FetchType.LAZY, mappedBy = "a", cascade = {CascadeType.PERSIST} ) private Set b3List; @OneToMany( fetch = FetchType.LAZY, mappedBy = "a", cascade = {CascadeType.PERSIST} ) private Set b4List; public int getId() { return id; } public void setId(int id) { this.id = id; } public Set getB1List() { if ( b1List == null ) b1List = new HashSet(); return b1List; } public void setB1List(Set list) { b1List = list; } public Set getB2List() { if ( b2List == null ) b2List = new HashSet(); return b2List; } public void setB2List(Set list) { b2List = list; } public Set getB3List() { return b3List; } public void setB3List(Set list) { if ( b3List == null ) b3List = new HashSet(); b3List = list; } public Set getB4List() { return b4List; } public void setB4List(Set list) { if ( b4List == null ) b4List = new HashSet(); b4List = list; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/C1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000134411714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class C1 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "b1Id" ) private B1 b1; public B1 getB1() { return b1; } public void setB1(B1 b1) { this.b1 = b1; } public int getId() { return id; } public void setId(int id) { this.id = id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/B3.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000133111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class B3 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "aId" ) private A a; public int getId() { return id; } public void setId(int id) { this.id = id; } public A getA() { return a; } public void setA(A a) { this.a = a; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/B2.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000210511714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class B2 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "aId" ) private A a; @OneToMany( fetch = FetchType.LAZY, mappedBy = "b2", cascade = {CascadeType.PERSIST} ) private Set c2List; public A getA() { return a; } public void setA(A a) { this.a = a; } public Set getC2List() { if ( c2List == null ) c2List = new HashSet(); return c2List; } public void setC2List(Set list) { c2List = list; } public int getId() { return id; } public void setId(int id) { this.id = id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/B1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000210511714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class B1 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "aId" ) private A a; @OneToMany( fetch = FetchType.LAZY, mappedBy = "b1", cascade = {CascadeType.PERSIST} ) private Set c1List; public int getId() { return id; } public void setId(int id) { this.id = id; } public A getA() { return a; } public void setA(A a) { this.a = a; } public Set getC1List() { if ( c1List == null ) c1List = new HashSet(); return c1List; } public void setC1List(Set list) { c1List = list; } }././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/cascade/B4.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000133111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class B4 { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int id; @ManyToOne( fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST} ) @JoinColumn( name = "aId" ) private A a; public int getId() { return id; } public void setId(int id) { this.id = id; } public A getA() { return a; } public void setA(A a) { this.a = a; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RemoveTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000513011714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import org.hibernate.StaleObjectStateException; import org.hibernate.ejb.test.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.OptimisticLockException; import java.util.Map; /** * @author Emmanuel Bernard */ public class RemoveTest extends TestCase { private static final Logger log = LoggerFactory.getLogger(RemoveTest.class); public void testRemove() { Race race = new Race(); race.competitors.add( new Competitor() ); race.competitors.add( new Competitor() ); race.competitors.add( new Competitor() ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( race ); em.flush(); em.remove( race ); em.flush(); em.getTransaction().rollback(); em.close(); } public void testRemoveAndFind() { Race race = new Race(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( race ); em.remove( race ); assertNull( em.find( Race.class, race.id ) ); em.getTransaction().rollback(); em.close(); } public void testUpdatedAndRemove() throws Exception { Music music = new Music(); music.setName( "Classical" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( music ); em.getTransaction().commit(); em.clear(); EntityManager em2 = factory.createEntityManager(); try { em2.getTransaction().begin(); //read music from 2nd EM music = em2.find( Music.class, music.getId() ); } catch (Exception e) { em2.getTransaction().rollback(); em2.close(); throw e; } //change music em = getOrCreateEntityManager(); em.getTransaction().begin(); em.find( Music.class, music.getId() ).setName( "Rap" ); em.getTransaction().commit(); try { em2.remove( music ); //remove changed music em2.flush(); fail("should have an optimistic lock exception"); } catch( OptimisticLockException e ) { log.debug("success"); } finally { em2.getTransaction().rollback(); em2.close(); } //clean em.getTransaction().begin(); em.remove( em.find( Music.class, music.getId() ) ); em.getTransaction().commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Race.class, Competitor.class, Music.class }; } public Map getConfig() { Map cfg = super.getConfig(); cfg.put( "hibernate.jdbc.batch_size", "0"); return cfg; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Music.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000124711714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Version; import javax.persistence.Id; import javax.persistence.Entity; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Music { @Id @GeneratedValue private Integer id; private String name; @Version private Integer version; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Pet.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000145511714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity @Inheritance( strategy = InheritanceType.JOINED ) public class Pet implements java.io.Serializable { private int id; private String name; private double weight; @Id @GeneratedValue( strategy = GenerationType.AUTO ) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Mail.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000067711714611271032763 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Mail { @Id private Long id; private String from; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RefreshTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000140311714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class RefreshTest extends TestCase { public void testRefreshNonManaged() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Race race = new Race(); em.persist( race ); em.flush(); em.clear(); try { em.refresh( race ); fail("Refresh should fail on a non managed entity"); } catch( IllegalArgumentException e) { //success } em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Race.class, Competitor.class }; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/GetReferenceTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000172711714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class GetReferenceTest extends TestCase { public void testWrongIdType() throws Exception { EntityManager em = getOrCreateEntityManager(); try { Competitor c = em.getReference( Competitor.class, new String("30") ); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } catch ( Exception e ) { fail("Wrong exception: " + e ); } try { Mail c = em.getReference( Mail.class, 1 ); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } catch ( Exception e ) { fail("Wrong exception: " + e ); } em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Competitor.class, Race.class, Mail.class }; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Cat.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000056011714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity @Inheritance( strategy = InheritanceType.JOINED ) public class Cat extends Pet { int lives; public int getLives() { return lives; } public void setLives(int lives) { this.lives = lives; } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/FlushTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000577311714611271032765 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import java.util.Collection; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import javax.persistence.Query; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class FlushTest extends TestCase { private static Set names= new HashSet(); static { names.add("Toonses"); names.add("Sox"); names.add("Winnie"); names.add("Junior"); } //Test for EJBTHREE-722 public void testFlushOnDetached() throws Exception { EntityManager manager = getOrCreateEntityManager( ); manager.getTransaction().begin(); Pet p1 = createCat("Toonses", 15.0, 9, manager); manager.flush(); manager.clear(); Pet p2 = createCat("Sox", 10.0, 5, manager); manager.flush(); manager.clear(); Pet p3 = createDog("Winnie", 70.0, 5, manager); manager.flush(); manager.clear(); Pet p4 = createDog("Junior", 11.0, 1, manager); manager.flush(); manager.clear(); Decorate d1 = createDecorate("Test", p1, manager); manager.flush(); manager.clear(); Decorate d2 = createDecorate("Test2", p2, manager); manager.flush(); manager.clear(); List l = findByWeight(14.0, manager); manager.flush(); manager.clear(); for (Object o : l) { assertTrue( names.contains( ( (Pet) o).getName() ) ); } Collection founds = getDecorate(manager); manager.flush(); manager.clear(); for (Decorate value : founds) { assertTrue( names.contains( value.getPet().getName() ) ); } manager.getTransaction().rollback(); manager.close(); } public Dog createDog(String name, double weight, int bones, EntityManager manager) { Dog dog = new Dog(); dog.setName(name); dog.setWeight(weight); dog.setNumBones(bones); manager.persist(dog); return dog; } public Cat createCat(String name, double weight, int lives, EntityManager manager) { Cat cat = new Cat(); cat.setName(name); cat.setWeight(weight); cat.setLives(lives); manager.persist(cat); return cat; } public List findByWeight(double weight, EntityManager manager) { return manager.createQuery( "select p from Pet p where p.weight < :weight").setParameter( "weight", weight).getResultList(); } public Decorate createDecorate(String name, Pet pet, EntityManager manager) { Decorate dec = new Decorate(); dec.setName(name); dec.setPet(pet); manager.persist(dec); return dec; } public Collection getDecorate(EntityManager manager) { Collection founds = new ArrayList(); Query query = manager.createQuery("SELECT o FROM Decorate o"); List list = query.getResultList(); for (Object obj : list) { if (obj instanceof Decorate) { Decorate decorate = (Decorate) obj; founds.add( decorate ); decorate.getPet().getName(); //load } } return founds; } public Class[] getAnnotatedClasses() { return new Class[] { Pet.class, Dog.class, Cat.class, Decorate.class }; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Decorate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000144611714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Decorate implements java.io.Serializable { private int id; private String name; private Pet pet; public Decorate() { super(); } @Id @GeneratedValue( strategy = GenerationType.AUTO ) public int getId() { return id; } public String getName() { return name; } @OneToOne( fetch = FetchType.LAZY ) public Pet getPet() { return pet; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setPet(Pet pet) { this.pet = pet; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/Competitor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000114311714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.emops; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Competitor { @Id @GeneratedValue public Integer id; private String name; public Competitor() { } public Competitor(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lob/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000314611714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.lob; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Blob; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import org.hibernate.Hibernate; import org.hibernate.dialect.Dialect; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class BlobTest extends TestCase { public void testBlobSerialization() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Map image = new HashMap(); image.put( "meta", "metadata" ); image.put( "data", "imagedata" ); ImageReader reader = new ImageReader(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( image ); reader.setImage( (Blob) Hibernate.createBlob( baos.toByteArray() ) ); em.persist( reader ); em.getTransaction().commit(); em.close(); //useless but y'a know em = getOrCreateEntityManager(); em.getTransaction().begin(); reader = em.find( ImageReader.class, reader.getId() ); ObjectInputStream ois = new ObjectInputStream( reader.getImage().getBinaryStream() ); image = (HashMap) ois.readObject(); assertTrue( image.containsKey( "meta" ) ); em.getTransaction().commit(); em.close(); } @Override public boolean appliesTo(Dialect dialect) { return dialect.supportsExpectedLobUsagePattern(); } public Class[] getAnnotatedClasses() { return new Class[]{ ImageReader.class }; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lob/ImageReader.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000147611714611271032761 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.lob; import java.io.Serializable; import java.sql.Blob; import java.sql.Clob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; /** * @author Emmanuel Bernard */ @Entity public class ImageReader implements Serializable { private long id; private Blob image; private Clob text; @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } @Lob @Column(name = "bin_img") public Blob getImage() { return image; } public void setImage(Blob image) { this.image = image; } @Lob @Column(name = "img_text") public Clob getText() { return text; } public void setText(Clob text) { this.text = text; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/transaction/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/transaction/Book.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000136511714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.transaction; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Version; /** * @author Emmanuel Bernard */ @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.TABLE) public Integer id; public String name; @Version public Integer version; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000002063411714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.transaction; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import javax.persistence.TransactionRequiredException; import org.hibernate.Session; import org.hibernate.ejb.HibernateEntityManagerFactory; import org.hibernate.ejb.test.TestCase; import org.hibernate.stat.Statistics; /** * @author Emmanuel Bernard */ public class FlushAndTransactionTest extends TestCase { public void testAlwaysTransactionalOperations() throws Exception { Book book = new Book(); book.name = "Le petit prince"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( book ); em.getTransaction().commit(); try { em.flush(); fail( "flush has to be inside a Tx" ); } catch ( TransactionRequiredException e ) { //success } try { em.lock( book, LockModeType.READ ); fail( "lock has to be inside a Tx" ); } catch ( TransactionRequiredException e ) { //success } em.getTransaction().begin(); em.remove( em.find( Book.class, book.id ) ); em.getTransaction().commit(); em.close(); } // public void testTransactionalOperationsWhenTransactional() throws Exception { // Book book = new Book(); // book.name = "Le petit prince"; // EntityManager em = getEntityManager( PersistenceContextType.TRANSACTION ); // try { // em.persist( book ); // fail("flush has to be inside a Tx"); // } // catch (TransactionRequiredException e) { // //success // } // try { // em.refresh( book ); // fail("refresh has to be inside a Tx"); // } // catch (TransactionRequiredException e) { // //success // } // try { // em.remove( book ); // fail("refresh has to be inside a Tx"); // } // catch (TransactionRequiredException e) { // //success // } // em.close(); // } public void testTransactionalOperationsWhenExtended() throws Exception { Book book = new Book(); book.name = "Le petit prince"; EntityManager em = getOrCreateEntityManager(); Statistics stats = ( ( HibernateEntityManagerFactory ) factory ).getSessionFactory().getStatistics(); stats.clear(); stats.setStatisticsEnabled( true ); em.persist( book ); assertEquals( 0, stats.getEntityInsertCount() ); em.getTransaction().begin(); em.flush(); em.getTransaction().commit(); assertEquals( 1, stats.getEntityInsertCount() ); em.clear(); book.name = "Le prince"; book = em.merge( book ); em.refresh( book ); assertEquals( 0, stats.getEntityUpdateCount() ); em.getTransaction().begin(); em.flush(); em.getTransaction().commit(); assertEquals( 0, stats.getEntityUpdateCount() ); book.name = "Le prince"; em.getTransaction().begin(); em.find( Book.class, book.id ); em.getTransaction().commit(); assertEquals( 1, stats.getEntityUpdateCount() ); em.remove( book ); assertEquals( 0, stats.getEntityDeleteCount() ); em.getTransaction().begin(); em.flush(); em.getTransaction().commit(); assertEquals( 1, stats.getEntityDeleteCount() ); em.close(); stats.setStatisticsEnabled( false ); } public void testMergeWhenExtended() throws Exception { Book book = new Book(); book.name = "Le petit prince"; EntityManager em = getOrCreateEntityManager(); Statistics stats = ( ( HibernateEntityManagerFactory ) factory ).getSessionFactory().getStatistics(); em.getTransaction().begin(); em.persist( book ); assertEquals( 0, stats.getEntityInsertCount() ); em.getTransaction().commit(); em.clear(); //persist and clear stats.clear(); stats.setStatisticsEnabled( true ); Book bookReloaded = em.find( Book.class, book.id ); book.name = "Le prince"; assertEquals( "Merge should use the available entiies in the PC", em.merge( book ), bookReloaded ); assertEquals( book.name, bookReloaded.name ); assertEquals( 0, stats.getEntityDeleteCount() ); assertEquals( 0, stats.getEntityInsertCount() ); assertEquals( "Updates should have been queued", 0, stats.getEntityUpdateCount() ); em.getTransaction().begin(); Book bookReReloaded = em.find( Book.class, bookReloaded.id ); assertEquals( "reload should return the object in PC", bookReReloaded, bookReloaded ); assertEquals( bookReReloaded.name, bookReloaded.name ); em.getTransaction().commit(); assertEquals( 0, stats.getEntityDeleteCount() ); assertEquals( 0, stats.getEntityInsertCount() ); assertEquals( "Work on Tx should flush", 1, stats.getEntityUpdateCount() ); em.getTransaction().begin(); em.remove( bookReReloaded ); em.getTransaction().commit(); em.close(); stats.setStatisticsEnabled( false ); } public void testCloseAndTransaction() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Book book = new Book(); book.name = "Java for Dummies"; em.close(); assertFalse( em.isOpen() ); try { em.flush(); fail( "direct action on a closed em should fail" ); } catch ( IllegalStateException e ) { //success em.getTransaction().rollback(); } } public void testTransactionCommitDoesNotFlush() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Book book = new Book(); book.name = "Java for Dummies"; em.persist( book ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); List result = em.createQuery( "select book from Book book where book.name = :title" ). setParameter( "title", book.name ).getResultList(); assertEquals( "EntityManager.commit() should trigger a flush()", 1, result.size() ); em.getTransaction().commit(); em.close(); } public void testTransactionAndContains() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Book book = new Book(); book.name = "Java for Dummies"; em.persist( book ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); List result = em.createQuery( "select book from Book book where book.name = :title" ). setParameter( "title", book.name ).getResultList(); assertEquals( "EntityManager.commit() should trigger a flush()", 1, result.size() ); assertTrue( em.contains( result.get( 0 ) ) ); em.getTransaction().commit(); assertTrue( em.contains( result.get( 0 ) ) ); em.close(); } public void testRollbackOnlyOnPersistenceException() throws Exception { Book book = new Book(); book.name = "Stolen keys"; book.id = null; //new Integer( 50 ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( book ); em.flush(); em.clear(); book.setName( "kitty kid" ); em.merge( book ); em.flush(); em.clear(); book.setName( "kitty kid2" ); //non updated version em.merge( book ); em.flush(); fail( "optimistic locking exception" ); } catch ( PersistenceException e ) { //success } try { em.getTransaction().commit(); fail( "Commit should be rollbacked" ); } catch ( RollbackException e ) { //success } finally { em.close(); } } public void testRollbackExceptionOnOptimisticLockException() throws Exception { Book book = new Book(); book.name = "Stolen keys"; book.id = null; //new Integer( 50 ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( book ); em.flush(); em.clear(); book.setName( "kitty kid" ); em.merge( book ); em.flush(); em.clear(); book.setName( "kitty kid2" ); //non updated version em.unwrap( Session.class ).update( book ); try { em.getTransaction().commit(); fail( "Commit should be rollbacked" ); } catch ( RollbackException e ) { assertTrue( "During flush a StateStateException is wrapped into a OptimisticLockException", e.getCause() instanceof OptimisticLockException ); } finally { em.close(); } } public void testRollbackClearPC() throws Exception { Book book = new Book(); book.name = "Stolen keys"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( book ); em.getTransaction().commit(); em.getTransaction().begin(); book.name = "Recovered keys"; em.merge( book ); em.getTransaction().rollback(); assertEquals( "Stolen keys", em.find( Book.class, book.id ).name ); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Book.class }; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Item.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000372311714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SqlResultSetMapping; /** * @author Gavin King */ @Entity(name = "Item") @SqlResultSetMapping(name = "getItem", entities = @EntityResult(entityClass = org.hibernate.ejb.test.Item.class, fields = { @FieldResult(name = "name", column = "itemname"), @FieldResult(name = "descr", column = "itemdescription") }) ) @NamedNativeQueries({ @NamedNativeQuery( name = "nativeItem1", query = "select name as itemname, descr as itemdescription from Item", resultSetMapping = "getItem" ), @NamedNativeQuery( name = "nativeItem2", query = "select * from Item", resultClass = Item.class ) }) //@Cache(region="Item", usage=NONSTRICT_READ_WRITE) public class Item implements Serializable { private String name; private String descr; private Set distributors = new HashSet(); public Item() { } public Item(String name, String desc) { this.name = name; this.descr = desc; } @Column(length = 200) public String getDescr() { return descr; } public void setDescr(String desc) { this.descr = desc; } @Id @Column(length = 30) public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany public Set getDistributors() { return distributors; } public void setDistributors(Set distributors) { this.distributors = distributors; } public void addDistributor(Distributor d) { if ( distributors == null ) distributors = new HashSet(); distributors.add( d ); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000011714611271032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/cachemodes/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000022400000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/cachemodes/SharedCacheModesTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001323511714611271032755 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.cachemodes; import javax.persistence.CacheRetrieveMode; import javax.persistence.CacheStoreMode; import javax.persistence.EntityManager; import javax.persistence.Query; import org.hibernate.CacheMode; import org.hibernate.Session; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.ejb.HibernateQuery; import org.hibernate.ejb.test.TestCase; import org.hibernate.impl.AbstractQueryImpl; /** * TODO : javadoc * * @author Steve Ebersole */ public class SharedCacheModesTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { SimpleEntity.class }; } // this is all i can do for now testing-wise since I did not implement @Cacheable first ;) public void testEntityManagerCacheModes() { EntityManager em; Session session; em = getOrCreateEntityManager(); session = ( (HibernateEntityManager) em ).getSession(); // defaults... assertEquals( CacheStoreMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheRetrieveMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheMode.NORMAL, session.getCacheMode() ); // overrides... em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH ); assertEquals( CacheStoreMode.REFRESH, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, session.getCacheMode() ); em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS ); assertEquals( CacheStoreMode.BYPASS, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.GET, session.getCacheMode() ); em.setProperty( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS ); assertEquals( CacheRetrieveMode.BYPASS, em.getProperties().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheMode.IGNORE, session.getCacheMode() ); em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE ); assertEquals( CacheStoreMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.PUT, session.getCacheMode() ); em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH ); assertEquals( CacheStoreMode.REFRESH, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, session.getCacheMode() ); } public void testQueryCacheModes() { EntityManager em = getOrCreateEntityManager(); Query jpaQuery = em.createQuery( "from SimpleEntity" ); AbstractQueryImpl hibQuery = (AbstractQueryImpl) ( (HibernateQuery) jpaQuery ).getHibernateQuery(); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE ); assertEquals( CacheStoreMode.USE, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.NORMAL, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS ); assertEquals( CacheStoreMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.GET, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH ); assertEquals( CacheStoreMode.REFRESH, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.REFRESH, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.IGNORE, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.USE, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.PUT, hibQuery.getCacheMode() ); } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/cachemodes/SimpleEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000277611714611271032765 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.cachemodes; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity public class SimpleEntity { private Long id; private String name; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000023100000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ExplicitlyCacheableEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000302011714611271032744 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.annotation; import javax.persistence.Cacheable; import javax.persistence.Entity; import javax.persistence.Id; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Cacheable public class ExplicitlyCacheableEntity { private Long id; private String name; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ConfigurationTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001210011714611271032743 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.annotation; import java.util.Properties; import javax.persistence.SharedCacheMode; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.impl.NoCachingRegionFactory; import org.hibernate.cfg.Environment; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.testing.junit.UnitTestCase; import org.hibernate.mapping.PersistentClass; /** * TODO : javadoc * * @author Steve Ebersole */ public class ConfigurationTest extends UnitTestCase { public ConfigurationTest(String string) { super( string ); } public void testSharedCacheModeNone() { Ejb3Configuration config = buildConfiguration( SharedCacheMode.NONE ); PersistentClass pc = config.getClassMapping( ExplicitlyCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( ExplicitlyNonCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( NoCacheableAnnotationEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); } public void testSharedCacheModeUnspecified() { Ejb3Configuration config = buildConfiguration( SharedCacheMode.UNSPECIFIED ); PersistentClass pc = config.getClassMapping( ExplicitlyCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( ExplicitlyNonCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( NoCacheableAnnotationEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); } public void testSharedCacheModeAll() { Ejb3Configuration config = buildConfiguration( SharedCacheMode.ALL ); PersistentClass pc = config.getClassMapping( ExplicitlyCacheableEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( ExplicitlyNonCacheableEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( NoCacheableAnnotationEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); } public void testSharedCacheModeEnable() { Ejb3Configuration config = buildConfiguration( SharedCacheMode.ENABLE_SELECTIVE ); PersistentClass pc = config.getClassMapping( ExplicitlyCacheableEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( ExplicitlyNonCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( NoCacheableAnnotationEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); } public void testSharedCacheModeDisable() { Ejb3Configuration config = buildConfiguration( SharedCacheMode.DISABLE_SELECTIVE ); PersistentClass pc = config.getClassMapping( ExplicitlyCacheableEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( ExplicitlyNonCacheableEntity.class.getName() ); assertNull( pc.getCacheConcurrencyStrategy() ); pc = config.getClassMapping( NoCacheableAnnotationEntity.class.getName() ); assertNotNull( pc.getCacheConcurrencyStrategy() ); } private Ejb3Configuration buildConfiguration(SharedCacheMode mode) { Properties properties = new Properties(); properties.put( AvailableSettings.SHARED_CACHE_MODE, mode ); properties.put( Environment.CACHE_REGION_FACTORY, CustomRegionFactory.class.getName() ); Ejb3Configuration config = new Ejb3Configuration(); config.setProperties( properties ); config.addAnnotatedClass( ExplicitlyCacheableEntity.class ); config.addAnnotatedClass( ExplicitlyNonCacheableEntity.class ); config.addAnnotatedClass( NoCacheableAnnotationEntity.class ); config.buildMappings(); return config; } public static class CustomRegionFactory extends NoCachingRegionFactory { public CustomRegionFactory(Properties properties) { super( properties ); } @Override public AccessType getDefaultAccessType() { return AccessType.READ_WRITE; } } } ././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/NoCacheableAnnotationEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000300711714611271032751 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.annotation; import javax.persistence.Cacheable; import javax.persistence.Entity; import javax.persistence.Id; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity public class NoCacheableAnnotationEntity { private Long id; private String name; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }././@LongLink0000000000000000000000000000023400000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ExplicitlyNonCacheableEntity.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000303311714611271032750 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cacheable.annotation; import javax.persistence.Cacheable; import javax.persistence.Entity; import javax.persistence.Id; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity @Cacheable(false) public class ExplicitlyNonCacheableEntity { private Long id; private String name; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000022700000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersistenceUnitInfoAdapter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000572411714611271032761 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.ejb3configuration; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Properties; import javax.persistence.SharedCacheMode; import javax.persistence.ValidationMode; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.sql.DataSource; import org.hibernate.ejb.HibernatePersistence; /** * TODO : javadoc * * @author Steve Ebersole */ public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo { private Properties properties; public String getPersistenceUnitName() { return "persistenceUnitAdapter"; } public String getPersistenceProviderClassName() { return HibernatePersistence.class.getName(); } public PersistenceUnitTransactionType getTransactionType() { return null; } public DataSource getJtaDataSource() { return null; } public DataSource getNonJtaDataSource() { return null; } public List getMappingFileNames() { return Collections.emptyList(); } public List getJarFileUrls() { return Collections.emptyList(); } public URL getPersistenceUnitRootUrl() { return null; } public List getManagedClassNames() { return Collections.emptyList(); } public boolean excludeUnlistedClasses() { return false; } public SharedCacheMode getSharedCacheMode() { return null; } public ValidationMode getValidationMode() { return null; } public Properties getProperties() { if ( properties == null ) { properties = new Properties(); } return properties; } public String getPersistenceXMLSchemaVersion() { return null; } public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } public void addTransformer(ClassTransformer transformer) { } public ClassLoader getNewTempClassLoader() { return Thread.currentThread().getContextClassLoader(); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000024700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/IdentifierGeneratorStrategyProviderTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000422311714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration.id; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import junit.framework.TestCase; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; /** * @author Emmanuel Bernard */ public class IdentifierGeneratorStrategyProviderTest extends TestCase { public void testIdentifierGeneratorStrategyProvider() { Ejb3Configuration conf = new Ejb3Configuration(); conf.setProperty( AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER, FunkyIdentifierGeneratorProvider.class.getName() ); conf.addAnnotatedClass( Cable.class ); final EntityManagerFactory entityManagerFactory = conf.buildEntityManagerFactory(); final EntityManager entityManager = entityManagerFactory.createEntityManager(); try { entityManager.persist( new Cable() ); entityManager.flush(); fail("FunkyException should have been thrown when the id is generated"); } catch ( FunkyException e ) { entityManager.close(); entityManagerFactory.close(); } } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/FunkyException.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000225411714611271032754 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration.id; /** * @author Emmanuel Bernard */ public class FunkyException extends RuntimeException { } ././@LongLink0000000000000000000000000000024000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/FunkyIdentifierGeneratorProvider.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000302011714611271032744 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration.id; import java.util.HashMap; import java.util.Map; import org.hibernate.ejb.cfg.spi.IdentifierGeneratorStrategyProvider; /** * @author Emmanuel Bernard */ public class FunkyIdentifierGeneratorProvider implements IdentifierGeneratorStrategyProvider { public Map> getStrategies() { final HashMap> result = new HashMap>( 1 ); result.put( "funky", FunkyIdGenerator.class ); return result; } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/FunkyIdGenerator.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000301111714611271032744 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration.id; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.IdentifierGenerator; import org.hibernate.mapping.IdGenerator; /** * @author Emmanuel Bernard */ public class FunkyIdGenerator implements IdentifierGenerator { public Serializable generate(SessionImplementor session, Object object) throws HibernateException { throw new FunkyException(); } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/id/Cable.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000316411714611271032755 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration.id; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; /** * @author Emmanuel Bernard */ @Entity public class Cable { @Id @GeneratedValue(generator = "fnk") @GenericGenerator( name = "fnk", strategy = "funky") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } private Integer id; public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; } ././@LongLink0000000000000000000000000000022700000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersisterClassProviderTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000004747211714611271032767 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration; import java.io.Serializable; import java.util.Comparator; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.MappingException; import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.entry.CacheEntryStructure; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.engine.CascadeStyle; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.ValueInclusion; import org.hibernate.id.IdentifierGenerator; import org.hibernate.metadata.ClassMetadata; import org.hibernate.persister.PersisterClassProvider; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.type.Type; import org.hibernate.type.VersionType; /** * @author Emmanuel Bernard */ public class PersisterClassProviderTest extends junit.framework.TestCase { public void testPersisterClassProvider() { Ejb3Configuration conf = new Ejb3Configuration(); conf.setProperty( AvailableSettings.PERSISTER_CLASS_PROVIDER, GoofyPersisterClassProvider.class.getName() ); conf.addAnnotatedClass( Bell.class ); try { final EntityManagerFactory entityManagerFactory = conf.buildEntityManagerFactory(); entityManagerFactory.close(); } catch ( PersistenceException e ) { assertNotNull( e.getCause() ); assertNotNull( e.getCause().getCause() ); assertEquals( GoofyException.class, e.getCause().getCause().getClass() ); } } public static class GoofyPersisterClassProvider implements PersisterClassProvider { public Class getEntityPersisterClass(String entityName) { return GoofyProvider.class; } public Class getCollectionPersisterClass(String collectionPersister) { return null; } } public static class GoofyProvider implements EntityPersister { public GoofyProvider(org.hibernate.mapping.PersistentClass persistentClass, org.hibernate.cache.access.EntityRegionAccessStrategy strategy, org.hibernate.engine.SessionFactoryImplementor sf, org.hibernate.engine.Mapping mapping) { throw new GoofyException(); } public void postInstantiate() throws MappingException { //To change body of implemented methods use File | Settings | File Templates. } public SessionFactoryImplementor getFactory() { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getRootEntityName() { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getEntityName() { return null; //To change body of implemented methods use File | Settings | File Templates. } public EntityMetamodel getEntityMetamodel() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isSubclassEntityName(String entityName) { return false; //To change body of implemented methods use File | Settings | File Templates. } public Serializable[] getPropertySpaces() { return new Serializable[0]; //To change body of implemented methods use File | Settings | File Templates. } public Serializable[] getQuerySpaces() { return new Serializable[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasProxy() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasCollections() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasMutableProperties() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasSubselectLoadableCollections() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasCascades() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isMutable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isInherited() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isIdentifierAssignedByInsert() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Type getPropertyType(String propertyName) throws MappingException { return null; //To change body of implemented methods use File | Settings | File Templates. } public int[] findDirty(Object[] currentState, Object[] previousState, Object owner, SessionImplementor session) { return new int[0]; //To change body of implemented methods use File | Settings | File Templates. } public int[] findModified(Object[] old, Object[] current, Object object, SessionImplementor session) { return new int[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasIdentifierProperty() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean canExtractIdOutOfEntity() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isVersioned() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Comparator getVersionComparator() { return null; //To change body of implemented methods use File | Settings | File Templates. } public VersionType getVersionType() { return null; //To change body of implemented methods use File | Settings | File Templates. } public int getVersionProperty() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasNaturalIdentifier() { return false; //To change body of implemented methods use File | Settings | File Templates. } public int[] getNaturalIdentifierProperties() { return new int[0]; //To change body of implemented methods use File | Settings | File Templates. } public Object[] getNaturalIdentifierSnapshot(Serializable id, SessionImplementor session) { return new Object[0]; //To change body of implemented methods use File | Settings | File Templates. } public IdentifierGenerator getIdentifierGenerator() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasLazyProperties() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Object load(Serializable id, Object optionalObject, LockMode lockMode, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object load(Serializable id, Object optionalObject, LockOptions lockOptions, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void lock(Serializable id, Object version, Object object, LockMode lockMode, SessionImplementor session) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public void lock(Serializable id, Object version, Object object, LockOptions lockOptions, SessionImplementor session) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public void insert(Serializable id, Object[] fields, Object object, SessionImplementor session) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public Serializable insert(Object[] fields, Object object, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void delete(Serializable id, Object version, Object object, SessionImplementor session) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public void update(Serializable id, Object[] fields, int[] dirtyFields, boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object object, Object rowId, SessionImplementor session) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public Type[] getPropertyTypes() { return new Type[0]; //To change body of implemented methods use File | Settings | File Templates. } public String[] getPropertyNames() { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyInsertability() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public ValueInclusion[] getPropertyInsertGenerationInclusions() { return new ValueInclusion[0]; //To change body of implemented methods use File | Settings | File Templates. } public ValueInclusion[] getPropertyUpdateGenerationInclusions() { return new ValueInclusion[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyUpdateability() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyCheckability() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyNullability() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyVersionability() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean[] getPropertyLaziness() { return new boolean[0]; //To change body of implemented methods use File | Settings | File Templates. } public CascadeStyle[] getPropertyCascadeStyles() { return new CascadeStyle[0]; //To change body of implemented methods use File | Settings | File Templates. } public Type getIdentifierType() { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getIdentifierPropertyName() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isCacheInvalidationRequired() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isLazyPropertiesCacheable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasCache() { return false; //To change body of implemented methods use File | Settings | File Templates. } public EntityRegionAccessStrategy getCacheAccessStrategy() { return null; //To change body of implemented methods use File | Settings | File Templates. } public CacheEntryStructure getCacheEntryStructure() { return null; //To change body of implemented methods use File | Settings | File Templates. } public ClassMetadata getClassMetadata() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isBatchLoadable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isSelectBeforeUpdateRequired() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Object[] getDatabaseSnapshot(Serializable id, SessionImplementor session) throws HibernateException { return new Object[0]; //To change body of implemented methods use File | Settings | File Templates. } public Object getCurrentVersion(Serializable id, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object forceVersionIncrement(Serializable id, Object currentVersion, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public EntityMode guessEntityMode(Object object) { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isInstrumented(EntityMode entityMode) { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasInsertGeneratedProperties() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasUpdateGeneratedProperties() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isVersionPropertyGenerated() { return false; //To change body of implemented methods use File | Settings | File Templates. } public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public void afterReassociate(Object entity, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public Object createProxy(Serializable id, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Boolean isTransient(Object object, SessionImplementor session) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object[] getPropertyValuesToInsert(Object object, Map mergeMap, SessionImplementor session) throws HibernateException { return new Object[0]; //To change body of implemented methods use File | Settings | File Templates. } public void processInsertGeneratedProperties(Serializable id, Object entity, Object[] state, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public void processUpdateGeneratedProperties(Serializable id, Object entity, Object[] state, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public Class getMappedClass(EntityMode entityMode) { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean implementsLifecycle(EntityMode entityMode) { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean implementsValidatable(EntityMode entityMode) { return false; //To change body of implemented methods use File | Settings | File Templates. } public Class getConcreteProxyClass(EntityMode entityMode) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setPropertyValues(Object object, Object[] values, EntityMode entityMode) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public void setPropertyValue(Object object, int i, Object value, EntityMode entityMode) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public Object[] getPropertyValues(Object object, EntityMode entityMode) throws HibernateException { return new Object[0]; //To change body of implemented methods use File | Settings | File Templates. } public Object getPropertyValue(Object object, int i, EntityMode entityMode) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object getPropertyValue(Object object, String propertyName, EntityMode entityMode) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Serializable getIdentifier(Object entity, SessionImplementor session) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setIdentifier(Object entity, Serializable id, EntityMode entityMode) throws HibernateException { //To change body of implemented methods use File | Settings | File Templates. } public void setIdentifier(Object entity, Serializable id, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public Object getVersion(Object object, EntityMode entityMode) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object instantiate(Serializable id, SessionImplementor session) { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isInstance(Object object, EntityMode entityMode) { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean hasUninitializedLazyProperties(Object object, EntityMode entityMode) { return false; //To change body of implemented methods use File | Settings | File Templates. } public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, EntityMode entityMode) { //To change body of implemented methods use File | Settings | File Templates. } public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session) { //To change body of implemented methods use File | Settings | File Templates. } public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode) { return null; //To change body of implemented methods use File | Settings | File Templates. } } public static class GoofyException extends RuntimeException { } } ././@LongLink0000000000000000000000000000022700000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/SessionFactoryObserverTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000450211714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration; import javax.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.hibernate.SessionFactoryObserver; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; /** * @author Emmanuel Bernard */ public class SessionFactoryObserverTest extends junit.framework.TestCase { public void testSessionFactoryObserverProperty() { Ejb3Configuration conf = new Ejb3Configuration(); conf.setProperty( AvailableSettings.SESSION_FACTORY_OBSERVER, GoofySessionFactoryObserver.class.getName() ); conf.addAnnotatedClass( Bell.class ); try { final EntityManagerFactory entityManagerFactory = conf.buildEntityManagerFactory(); entityManagerFactory.close(); fail("GoofyException should have been thrown"); } catch ( GoofyException e ) { //success } } public static class GoofySessionFactoryObserver implements SessionFactoryObserver { public void sessionFactoryCreated(SessionFactory factory) { } public void sessionFactoryClosed(SessionFactory factory) { throw new GoofyException(); } } public static class GoofyException extends RuntimeException { } }././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/InterceptorTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001176111714611271032757 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.ejb3configuration; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; /** * @author Emmanuel Bernard */ public class InterceptorTest extends TestCase { public void testInjectedInterceptor() { configuration.setInterceptor( new ExceptionInterceptor() ); EntityManagerFactory emf = configuration.createEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setName( "Laptop" ); try { em.getTransaction().begin(); em.persist( i ); em.getTransaction().commit(); } catch (IllegalStateException e) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } finally { if ( em.getTransaction() != null && em.getTransaction().isActive() ) em.getTransaction().rollback(); em.close(); emf.close(); } } public void testConfiguredInterceptor() { configuration.setProperty( AvailableSettings.INTERCEPTOR, ExceptionInterceptor.class.getName() ); EntityManagerFactory emf = configuration.createEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setName( "Laptop" ); try { em.getTransaction().begin(); em.persist( i ); em.getTransaction().commit(); fail( "No interceptor" ); } catch (IllegalStateException e) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } finally { if ( em.getTransaction() != null && em.getTransaction().isActive() ) em.getTransaction().rollback(); em.close(); emf.close(); } } public void testConfiguredSessionInterceptor() { configuration.setProperty( AvailableSettings.SESSION_INTERCEPTOR, LocalExceptionInterceptor.class.getName() ); configuration.setProperty( "aaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbb" ); EntityManagerFactory emf = configuration.createEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setName( "Laptop" ); try { em.getTransaction().begin(); em.persist( i ); em.getTransaction().commit(); fail( "No interceptor" ); } catch (IllegalStateException e) { assertEquals( LocalExceptionInterceptor.LOCAL_EXCEPTION_MESSAGE, e.getMessage() ); } finally { if ( em.getTransaction() != null && em.getTransaction().isActive() ) em.getTransaction().rollback(); em.close(); emf.close(); } } public void testEmptyCreateEntityManagerFactoryAndPropertyUse() { configuration.setProperty( AvailableSettings.INTERCEPTOR, ExceptionInterceptor.class.getName() ); EntityManagerFactory emf = configuration.createEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setName( "Laptop" ); try { em.getTransaction().begin(); em.persist( i ); em.getTransaction().commit(); fail( "No interceptor" ); } catch (IllegalStateException e) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } finally { if ( em.getTransaction() != null && em.getTransaction().isActive() ) em.getTransaction().rollback(); em.close(); emf.close(); } } public void testOnLoadCallInInterceptor() { configuration.setInterceptor( new ExceptionInterceptor(true) ); EntityManagerFactory emf = configuration.createEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setName( "Laptop" ); em.getTransaction().begin(); em.persist( i ); em.flush(); em.clear(); try { em.find(Item.class, i.getName() ); fail( "No interceptor" ); } catch (IllegalStateException e) { assertEquals( ExceptionInterceptor.EXCEPTION_MESSAGE, e.getMessage() ); } finally { if ( em.getTransaction() != null && em.getTransaction().isActive() ) em.getTransaction().rollback(); em.close(); emf.close(); } } public Class[] getAnnotatedClasses() { return new Class[]{ Item.class, Distributor.class }; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/TestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000673011714611271032757 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.ejb3configuration; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.persistence.Persistence; import org.hibernate.cfg.Environment; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; /** * @author Emmanuel Bernard */ public abstract class TestCase extends junit.framework.TestCase { protected Ejb3Configuration configuration; private Class lastTestClass; public TestCase() { super(); } public TestCase(String name) { super( name ); } public void setUp() { if ( configuration == null || lastTestClass != getClass() ) { buildConfiguration(); lastTestClass = getClass(); } //factory = new HibernatePersistence().createEntityManagerFactory( getConfig() ); } protected boolean recreateSchema() { return true; } private void buildConfiguration() { configuration = new Ejb3Configuration(); configuration.addProperties( loadProperties() ); if ( recreateSchema() ) { configuration.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); } for ( Class clazz : getAnnotatedClasses() ) { configuration.addAnnotatedClass( clazz ); } for ( Map.Entry entry : getCachedClasses().entrySet() ) { configuration.setProperty( AvailableSettings.CLASS_CACHE_PREFIX + "." + entry.getKey().getName(), entry.getValue() ); } for ( Map.Entry entry : getCachedCollections().entrySet() ) { configuration.setProperty( AvailableSettings.COLLECTION_CACHE_PREFIX + "." + entry.getKey(), entry.getValue() ); } } public abstract Class[] getAnnotatedClasses(); public Map getCachedClasses() { return new HashMap(); } public Map getCachedCollections() { return new HashMap(); } public static Properties loadProperties() { Properties props = new Properties(); InputStream stream = Persistence.class.getResourceAsStream( "/hibernate.properties" ); if ( stream != null ) { try { props.load( stream ); } catch (Exception e) { throw new RuntimeException( "could not load hibernate.properties" ); } finally { try { stream.close(); } catch (IOException ioe) { } } } return props; } @Override protected void tearDown() throws Exception { super.tearDown(); configuration = null; //avoid side effects } } ././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/EntityManagerSerializationTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000531511714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ejb3configuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.ejb.test.Cat; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; import org.hibernate.ejb.test.Kitten; import org.hibernate.ejb.test.Wallet; /** * @author Emmanuel Bernard */ public class EntityManagerSerializationTest extends org.hibernate.ejb.test.TestCase { public void testSerialization() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( factory ); out.close(); byte[] serialized = stream.toByteArray(); stream.close(); ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream( byteIn ); EntityManagerFactory serializedFactory = (EntityManagerFactory) in.readObject(); in.close(); byteIn.close(); EntityManager em = serializedFactory.createEntityManager(); //em.getTransaction().begin(); //em.setFlushMode( FlushModeType.NEVER ); Cat cat = new Cat(); cat.setAge( 3 ); cat.setDateOfBirth( new Date() ); cat.setLength( 22 ); cat.setName( "Kitty" ); em.persist( cat ); Item item = new Item(); item.setName( "Train Ticket" ); item.setDescr( "Paris-London" ); em.persist( item ); //em.getTransaction().commit(); //em.getTransaction().begin(); item.setDescr( "Paris-Bruxelles" ); //em.getTransaction().commit(); //fake the in container work ( (HibernateEntityManager) em ).getSession().disconnect(); stream = new ByteArrayOutputStream(); out = new ObjectOutputStream( stream ); out.writeObject( em ); out.close(); serialized = stream.toByteArray(); stream.close(); byteIn = new ByteArrayInputStream( serialized ); in = new ObjectInputStream( byteIn ); em = (EntityManager) in.readObject(); in.close(); byteIn.close(); //fake the in container work em.getTransaction().begin(); item = em.find( Item.class, item.getName() ); item.setDescr( item.getDescr() + "-Amsterdam" ); cat = (Cat) em.createQuery( "select c from " + Cat.class.getName() + " c" ).getSingleResult(); cat.setLength( 34 ); em.flush(); em.remove( item ); em.remove( cat ); em.flush(); em.getTransaction().commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Item.class, Distributor.class, Wallet.class, Cat.class, Kitten.class }; } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ProgrammaticConfTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000427411714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ejb3configuration; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.cfg.Environment; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.ejb.test.Cat; import org.hibernate.ejb.test.Kitten; import org.hibernate.util.ConfigHelper; /** * @author Emmanuel Bernard */ public class ProgrammaticConfTest extends junit.framework.TestCase { public void testProgrammaticAPI() throws Exception { Ejb3Configuration conf = new Ejb3Configuration(); conf.addAnnotatedClass( Cat.class ); conf.addAnnotatedClass( Kitten.class ); conf.addProperties(getProperties()); EntityManagerFactory emf = conf.buildEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Cat cat = new Cat(); cat.setAge( 23 ); cat.setDateOfBirth( new Date() ); cat.setLength( 32 ); cat.setName( "Tomy" ); em.getTransaction().begin(); em.persist( cat ); em.flush(); assertNotNull( em.find(Cat.class, cat.getId() ) ); em.getTransaction().rollback(); emf.close(); } public void testProgrammaticCfg() throws Exception { Ejb3Configuration conf = new Ejb3Configuration(); conf.configure( "org/hibernate/ejb/test/ejb3configuration/hibernate.cfg.xml" ); conf.addProperties(getProperties()); EntityManagerFactory emf = conf.buildEntityManagerFactory(); EntityManager em = emf.createEntityManager(); Cat cat = new Cat(); cat.setAge( 23 ); cat.setDateOfBirth( new Date() ); cat.setLength( 32 ); cat.setName( "Tomy" ); em.getTransaction().begin(); em.persist( cat ); em.flush(); assertNotNull( em.find(Cat.class, cat.getId() ) ); em.getTransaction().rollback(); emf.close(); } protected Properties getProperties() throws IOException { Properties properties = new Properties( ); InputStream stream = ConfigHelper.getResourceAsStream("/hibernate.properties"); try { properties.load(stream); } finally { try{ stream.close(); } catch (IOException ioe){ } } properties.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); return properties; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/Bell.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000250011714611271032746 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ejb.test.ejb3configuration; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Bell { @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } private Integer id; } ././@LongLink0000000000000000000000000000022600000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/LocalExceptionInterceptor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000112211714611271032745 0ustar ebourgebourg//$ package org.hibernate.ejb.test.ejb3configuration; import java.io.Serializable; import org.hibernate.type.Type; import org.hibernate.CallbackException; /** * @author Emmanuel Bernard */ public class LocalExceptionInterceptor extends ExceptionInterceptor { public static final String LOCAL_EXCEPTION_MESSAGE = "Session-scoped interceptor enabled"; public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { if (allowSave) return false; throw new IllegalStateException( LOCAL_EXCEPTION_MESSAGE ); } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ExceptionInterceptor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000213011714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ejb3configuration; import java.io.Serializable; import java.util.Iterator; import org.hibernate.CallbackException; import org.hibernate.EntityMode; import org.hibernate.Interceptor; import org.hibernate.Transaction; import org.hibernate.EmptyInterceptor; import org.hibernate.type.Type; /** * @author Emmanuel Bernard */ public class ExceptionInterceptor extends EmptyInterceptor { public static final String EXCEPTION_MESSAGE = "Interceptor enabled"; protected boolean allowSave = false; public ExceptionInterceptor() { this.allowSave = false; } public ExceptionInterceptor(boolean allowSave) { this.allowSave = allowSave; } public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { throw new IllegalStateException( EXCEPTION_MESSAGE ); } public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { if (allowSave) return false; throw new IllegalStateException( EXCEPTION_MESSAGE ); } } ././@LongLink0000000000000000000000000000023300000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ConfigurationObjectSettingTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000002266311714611271032762 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.ejb3configuration; import java.util.Collections; import java.util.Map; import javax.persistence.SharedCacheMode; import javax.persistence.ValidationMode; import org.hibernate.HibernateException; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.ejb.packaging.PersistenceMetadata; /** * Test passing along various config settings that take objects other than strings as values. * * @author Steve Ebersole */ public class ConfigurationObjectSettingTest extends junit.framework.TestCase { public void testContainerBootstrapSharedCacheMode() { // first, via the integration vars PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter(); { // as object Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( empty, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } { // as string Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( empty, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } // next, via the PUI PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() { @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.ENABLE_SELECTIVE; } }; { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( adapter, null ); assertEquals( SharedCacheMode.ENABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } // via both, integration vars should take precedence { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( adapter, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } } public void testContainerBootstrapValidationMode() { // first, via the integration vars PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter(); { // as object Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( empty, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK ) ); assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } { // as string Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( empty, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name() ) ); assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } // next, via the PUI PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() { @Override public ValidationMode getValidationMode() { return ValidationMode.CALLBACK; } }; { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( adapter, null ); assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } // via both, integration vars should take precedence { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( adapter, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.NONE ) ); assertEquals( ValidationMode.NONE.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } } public void testContainerBootstrapValidationFactory() { final Object token = new Object(); PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter(); Ejb3Configuration cfg = new Ejb3Configuration(); try { cfg.configure( adapter, Collections.singletonMap( AvailableSettings.VALIDATION_FACTORY, token ) ); fail( "Was expecting error as token did not implement ValidatorFactory" ); } catch ( HibernateException e ) { // probably the condition we want but unfortunately the exception is not specific // and the pertinent info is in a cause } } public void testStandaloneBootstrapSharedCacheMode() { // first, via the integration vars PersistenceMetadata metadata = new PersistenceMetadata(); { // as object Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } { // as string Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } // next, via the PM metadata.setSharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE.name() ); { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, null ); assertEquals( SharedCacheMode.ENABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } // via both, integration vars should take precedence { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) ); } } public void testStandaloneBootstrapValidationMode() { // first, via the integration vars PersistenceMetadata metadata = new PersistenceMetadata(); { // as object Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK ) ); assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } { // as string Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name() ) ); assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } // next, via the PUI metadata.setValidationMode( ValidationMode.AUTO.name() ); { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, null ); assertEquals( ValidationMode.AUTO.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } // via both, integration vars should take precedence { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure( metadata, Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.NONE ) ); assertEquals( ValidationMode.NONE.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) ); } } public void testStandaloneBootstrapValidationFactory() { final Object token = new Object(); PersistenceMetadata metadata = new PersistenceMetadata(); Ejb3Configuration cfg = new Ejb3Configuration(); try { cfg.configure( metadata, Collections.singletonMap( AvailableSettings.VALIDATION_FACTORY, token ) ); fail( "Was expecting error as token did not implement ValidatorFactory" ); } catch ( HibernateException e ) { // probably the condition we want but unfortunately the exception is not specific // and the pertinent info is in a cause } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/Instrument.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000305711714611271032756 0ustar ebourgebourg// $Id:$ /* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.ejb.test.exception; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PrePersist; /** * @author Hardy Ferentschik */ @Entity public class Instrument { @Id @GeneratedValue private int id; private String name; private Type type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } @PrePersist public void prePersist() { throw new RuntimeException( "Instrument broken." ); } public enum Type { WIND, STRINGS, PERCUSSION } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/Music.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000145111714611271032752 0ustar ebourgebourg// $Id$ package org.hibernate.ejb.test.exception; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Version; /** * @author Emmanuel Bernard */ @Entity @SuppressWarnings("serial") public class Music implements Serializable { private Integer id; private Integer version; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Version public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/ExceptionTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000716311714611271032760 0ustar ebourgebourg// $Id$ package org.hibernate.ejb.test.exception; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.cfg.Environment; import org.hibernate.ejb.test.TestCase; import org.hibernate.exception.ConstraintViolationException; /** * @author Emmanuel Bernard */ @SuppressWarnings("unchecked") public class ExceptionTest extends TestCase { private final Logger log = LoggerFactory.getLogger( ExceptionTest.class ); public void testOptimisticLockingException() throws Exception { EntityManager em = getOrCreateEntityManager(); EntityManager em2 = factory.createEntityManager(); em.getTransaction().begin(); Music music = new Music(); music.setName( "Old Country" ); em.persist( music ); em.getTransaction().commit(); try { em2.getTransaction().begin(); Music music2 = em2.find( Music.class, music.getId() ); music2.setName( "HouseMusic" ); em2.getTransaction().commit(); } catch ( Exception e ) { em2.getTransaction().rollback(); throw e; } finally { em2.close(); } em.getTransaction().begin(); music.setName( "Rock" ); try { em.flush(); fail( "Should raise an optimistic lock exception" ); } catch ( OptimisticLockException e ) { //success assertEquals( music, e.getEntity() ); } catch ( Exception e ) { fail( "Should raise an optimistic lock exception" ); } finally { em.getTransaction().rollback(); em.close(); } } public void testEntityNotFoundException() throws Exception { EntityManager em = getOrCreateEntityManager(); Music music = em.getReference( Music.class, -1 ); try { music.getName(); fail( "Non existent entity should raise an exception when state is accessed" ); } catch ( EntityNotFoundException e ) { log.debug( "success" ); } finally { em.close(); } } public void testConstraintViolationException() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Music music = new Music(); music.setName( "Jazz" ); em.persist( music ); Musician lui = new Musician(); lui.setName( "Lui Armstrong" ); lui.setFavouriteMusic( music ); em.persist( lui ); em.getTransaction().commit(); try { em.getTransaction().begin(); String hqlDelete = "delete Music where name = :name"; em.createQuery( hqlDelete ).setParameter( "name", "Jazz" ).executeUpdate(); em.getTransaction().commit(); fail(); } catch ( PersistenceException e ) { Throwable t = e.getCause(); assertTrue( "Should be a constraint violation", t instanceof ConstraintViolationException ); em.getTransaction().rollback(); } finally { em.close(); } } // HHH-4676 public void testInterceptor() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Instrument instrument = new Instrument(); instrument.setName( "Guitar" ); try { em.persist( instrument ); fail( "Commit should have failed." ); } catch ( RuntimeException e ) { assertTrue( em.getTransaction().getRollbackOnly() ); } em.close(); } @Override public Map getConfig() { Map config = super.getConfig(); config.put( Environment.BATCH_VERSIONED_DATA, "false" ); return config; } public Class[] getAnnotatedClasses() { return new Class[] { Music.class, Musician.class, Instrument.class }; } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/Musician.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000146511714611271032757 0ustar ebourgebourg// $Id$ package org.hibernate.ejb.test.exception; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * @author Hardy Ferentschik */ @Entity @SuppressWarnings("serial") public class Musician implements Serializable { private Integer id; private String name; private Music favouriteMusic; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne public Music getFavouriteMusic() { return favouriteMusic; } public void setFavouriteMusic(Music favouriteMusic) { this.favouriteMusic = favouriteMusic; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Distributor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000151111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Distributor implements Serializable { private Integer id; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof Distributor ) ) return false; final Distributor distributor = (Distributor) o; if ( !name.equals( distributor.name ) ) return false; return true; } public int hashCode() { return name.hashCode(); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/MyNamingStrategy.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000044211714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import org.hibernate.cfg.EJB3NamingStrategy; /** * @author Emmanuel Bernard */ public class MyNamingStrategy extends EJB3NamingStrategy { @Override public String tableName(String tableName) { return "tbl_" + super.tableName( tableName ); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001434311714611271032756 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.testing.junit.functional.annotations.HibernateTestCase; /** * A base class for all ejb tests. * * @author Emmanuel Bernard * @author Hardy Ferentschik */ public abstract class TestCase extends HibernateTestCase { private static final Logger log = LoggerFactory.getLogger( TestCase.class ); protected static EntityManagerFactory factory; private EntityManager em; private ArrayList isolatedEms = new ArrayList(); public TestCase() { super(); } public TestCase(String name) { super( name ); } public void tearDown() throws Exception { super.tearDown(); } @Override protected void buildConfiguration() throws Exception { Ejb3Configuration ejbconfig = new Ejb3Configuration(); TestCase.cfg = ejbconfig.getHibernateConfiguration(); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); } cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); for ( String mappingFile : getMappings() ) { cfg.addResource( mappingFile ); } factory = ejbconfig.createEntityManagerFactory( getConfig() ); } private void cleanUnclosed(EntityManager em) { if ( em == null ) { return; } if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); log.warn( "You left an open transaction! Fix your test case. For now, we are closing it for you." ); } if ( em.isOpen() ) { // as we open an EM before the test runs, it will still be open if the test uses a custom EM. // or, the person may have forgotten to close. So, do not raise a "fail", but log the fact. em.close(); log.warn( "The EntityManager is not closed. Closing it." ); } } protected void handleUnclosedResources() { cleanUnclosed( this.em ); for ( Iterator iter = isolatedEms.iterator(); iter.hasNext(); ) { cleanUnclosed( ( EntityManager ) iter.next() ); } cfg = null; } protected void closeResources() { if ( factory != null ) { factory.close(); } } protected EntityManager getOrCreateEntityManager() { if ( em == null || !em.isOpen() ) { em = factory.createEntityManager(); } return em; } protected EntityManager createIsolatedEntityManager() { EntityManager isolatedEm = factory.createEntityManager(); isolatedEms.add( isolatedEm ); return isolatedEm; } protected EntityManager createIsolatedEntityManager(Map props) { EntityManager isolatedEm = factory.createEntityManager(props); isolatedEms.add( isolatedEm ); return isolatedEm; } /** * always reopen a new EM and clse the existing one */ protected EntityManager createEntityManager(Map properties) { if ( em != null && em.isOpen() ) { em.close(); } em = factory.createEntityManager( properties ); return em; } public String[] getEjb3DD() { return new String[] { }; } public Map getCachedClasses() { return new HashMap(); } public Map getCachedCollections() { return new HashMap(); } public static Properties loadProperties() { Properties props = new Properties(); InputStream stream = Persistence.class.getResourceAsStream( "/hibernate.properties" ); if ( stream != null ) { try { props.load( stream ); } catch ( Exception e ) { throw new RuntimeException( "could not load hibernate.properties" ); } finally { try { stream.close(); } catch ( IOException ioe ) { } } } props.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); return props; } public Map getConfig() { Map config = loadProperties(); ArrayList classes = new ArrayList(); classes.addAll( Arrays.asList( getAnnotatedClasses() ) ); config.put( AvailableSettings.LOADED_CLASSES, classes ); for ( Map.Entry entry : getCachedClasses().entrySet() ) { config.put( AvailableSettings.CLASS_CACHE_PREFIX + "." + entry.getKey().getName(), entry.getValue() ); } for ( Map.Entry entry : getCachedCollections().entrySet() ) { config.put( AvailableSettings.COLLECTION_CACHE_PREFIX + "." + entry.getKey(), entry.getValue() ); } if ( getEjb3DD().length > 0 ) { ArrayList dds = new ArrayList(); dds.addAll( Arrays.asList( getEjb3DD() ) ); config.put( AvailableSettings.XML_FILE_NAMES, dds ); } addConfigOptions( config ); return config; } protected void addConfigOptions(Map options) { } @Override public void runBare() throws Throwable { if ( !appliesTo( Dialect.getDialect() ) ) { return; } super.runBare(); } public boolean appliesTo(Dialect dialect) { return true; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Kitten.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000170111714611271032750 0ustar ebourgebourg// $Id$ package org.hibernate.ejb.test; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Hardy Ferentschik */ @SuppressWarnings("serial") @Entity public class Kitten { private Integer id; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Constructs a String with all attributes * in name = value format. * * @return a String representation * of this object. */ public String toString() { final String TAB = " "; String retValue = ""; retValue = "Kitten ( " + super.toString() + TAB + "id = " + this.id + TAB + "name = " + this.name + TAB + " )"; return retValue; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/Bottom.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000317411714611271032756 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cascade.multilevel; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "BOTTOM") public class Bottom { @Id @GeneratedValue private Long id; @OneToOne(mappedBy = "bottom") private Middle middle; Long getId() { return id; } void setId(Long id) { this.id = id; } Middle getMiddle() { return middle; } void setMiddle(Middle middle) { this.middle = middle; } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/Middle.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000374011714611271032755 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cascade.multilevel; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "MIDDLE") public class Middle { @Id private Long id; @ManyToOne private Top top; @OneToOne(cascade = { CascadeType.ALL }) @JoinColumn(name = "BOTTOM_ID") private Bottom bottom; private Middle() { } public Middle(Long i) { this.id = i; } Long getId() { return id; } void setId(Long id) { this.id = id; } Top getTop() { return top; } void setTop(Top top) { this.top = top; } Bottom getBottom() { return bottom; } void setBottom(Bottom bottom) { this.bottom = bottom; bottom.setMiddle(this); } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/Top.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000370711714611271032760 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cascade.multilevel; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "TOP") public class Top { @Id @GeneratedValue private Long id; @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "top") List middles; Long getId() { return id; } void setId(Long id) { this.id = id; } List getMiddles() { if (middles == null) { middles = new ArrayList(); } return middles; } void setMiddles(List middles) { this.middles = middles; } void addMiddle(Middle middle) { this.getMiddles().add(middle); middle.setTop(this); } } ././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/MultiLevelCascadeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000473611714611271032763 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.cascade.multilevel; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.hibernate.ejb.test.TestCase; public class MultiLevelCascadeTest extends TestCase { public void test() { EntityManager em = getOrCreateEntityManager( ); EntityTransaction tx = em.getTransaction(); tx.begin(); Top top = new Top(); em.persist( top ); // Flush 1 em.flush(); Middle middle = new Middle( 1l ); top.addMiddle( middle ); middle.setTop( top ); Bottom bottom = new Bottom(); middle.setBottom( bottom ); bottom.setMiddle( middle ); Middle middle2 = new Middle( 2l ); top.addMiddle(middle2); middle2.setTop( top ); Bottom bottom2 = new Bottom(); middle2.setBottom( bottom2 ); bottom2.setMiddle( middle2 ); // Flush 2 em.flush(); tx.commit(); em.close(); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); top = em.find(Top.class, top.getId()); assertEquals(2, top.getMiddles().size()); for (Middle loadedMiddle : top.getMiddles()) { assertSame(top, loadedMiddle.getTop()); assertNotNull(loadedMiddle.getBottom()); } em.remove( top ); em.close(); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { Top.class, Middle.class, Bottom.class }; } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/DetachAndContainsTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000335311714611271032755 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import java.util.Collection; import java.util.ArrayList; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.OneToMany; import javax.persistence.ManyToOne; import javax.persistence.EntityManager; import static javax.persistence.CascadeType.*; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class DetachAndContainsTest extends TestCase { public void testDetach() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Tooth tooth = new Tooth(); Mouth mouth = new Mouth(); em.persist( mouth ); em.persist( tooth ); tooth.mouth = mouth; mouth.teeth = new ArrayList(); mouth.teeth.add( tooth ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); mouth = em.find( Mouth.class, mouth.id ); assertNotNull( mouth ); assertEquals( 1, mouth.teeth.size() ); tooth = mouth.teeth.iterator().next(); em.detach( mouth ); assertFalse( em.contains( tooth ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.find( Mouth.class, mouth.id ) ); em.getTransaction().commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Mouth.class, Tooth.class }; } @Entity public static class Mouth { @Id @GeneratedValue public Integer id; @OneToMany(mappedBy = "mouth", cascade = { DETACH, REMOVE } ) public Collection teeth; } @Entity public static class Tooth { @Id @GeneratedValue public Integer id; public String type; @ManyToOne public Mouth mouth; } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Conference.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000362611714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "portal_pk_conference") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) @DiscriminatorValue("X") @org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true) public class Conference implements Serializable { private Long id; private Date date; private ExtractionDocumentInfo extractionDocument; @OneToOne(mappedBy = "conference", cascade = CascadeType.ALL) public ExtractionDocumentInfo getExtractionDocument() { return extractionDocument; } public void setExtractionDocument(ExtractionDocumentInfo extractionDocument) { this.extractionDocument = extractionDocument; } public Conference() { date = new Date(); } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "c_date", nullable = false) public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public boolean equals(Object o) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; final Conference that = (Conference) o; return !( date != null ? !date.equals( that.date ) : that.date != null ); } public int hashCode() { return ( date != null ? date.hashCode() : 0 ); } }././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Song.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000121411714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * @author Emmanuel Bernard */ @Entity public class Song { @Id @GeneratedValue private Long id; @ManyToOne(fetch = FetchType.LAZY, optional = false) private Author author; public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/FetchTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001503711714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.util.ArrayList; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Query; import org.hibernate.Hibernate; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class FetchTest extends TestCase { public void testCascadeAndFetchCollection() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Troop disney = new Troop(); disney.setName( "Disney" ); Soldier mickey = new Soldier(); mickey.setName( "Mickey" ); disney.addSoldier( mickey ); em.persist( disney ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Troop troop = em.find( Troop.class, disney.getId() ); assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) ); em.getTransaction().commit(); assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) ); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); troop = em.find( Troop.class, disney.getId() ); em.remove( troop ); //Fail because of HHH-1187 em.getTransaction().commit(); em.close(); } public void testCascadeAndFetchEntity() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Troop disney = new Troop(); disney.setName( "Disney" ); Soldier mickey = new Soldier(); mickey.setName( "Mickey" ); disney.addSoldier( mickey ); em.persist( disney ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Soldier soldier = em.find( Soldier.class, mickey.getId() ); assertFalse( Hibernate.isInitialized( soldier.getTroop() ) ); em.getTransaction().commit(); assertFalse( Hibernate.isInitialized( soldier.getTroop() ) ); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Troop troop = em.find( Troop.class, disney.getId() ); em.remove( troop ); //Fail because of HHH-1187 em.getTransaction().commit(); em.close(); } public void testTwoLevelDeepPersist() throws Exception { EntityTransaction tx; EntityManager em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); Conference jbwBarcelona = new Conference(); jbwBarcelona.setDate( new Date() ); ExtractionDocumentInfo info = new ExtractionDocumentInfo(); info.setConference( jbwBarcelona ); jbwBarcelona.setExtractionDocument( info ); info.setLastModified( new Date() ); ExtractionDocument doc = new ExtractionDocument(); doc.setDocumentInfo( info ); info.setDocuments( new ArrayList() ); info.getDocuments().add( doc ); doc.setBody( new byte[]{'c', 'f'} ); em.persist( jbwBarcelona ); tx.commit(); em.close(); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); jbwBarcelona = em.find( Conference.class, jbwBarcelona.getId() ); assertTrue( Hibernate.isInitialized( jbwBarcelona ) ); assertTrue( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument() ) ); assertFalse( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument().getDocuments() ) ); em.flush(); assertTrue( Hibernate.isInitialized( jbwBarcelona ) ); assertTrue( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument() ) ); assertFalse( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument().getDocuments() ) ); em.remove( jbwBarcelona ); tx.commit(); em.close(); } public void testTwoLevelDeepPersistOnManyToOne() throws Exception { EntityTransaction tx; EntityManager em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); Grandson gs = new Grandson(); gs.setParent( new Son() ); gs.getParent().setParent( new Parent() ); em.persist( gs ); tx.commit(); em.close(); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); gs = em.find( Grandson.class, gs.getId() ); em.flush(); assertTrue( Hibernate.isInitialized( gs.getParent() ) ); assertFalse( Hibernate.isInitialized( gs.getParent().getParent() ) ); em.remove( gs ); tx.commit(); em.close(); } public void testPerfCascadeAndFetchEntity() throws Exception { EntityManager em = getOrCreateEntityManager(); //init data em.getTransaction().begin(); int loop = 50; for ( int i = 0; i < loop ; i++ ) { Troop disney = new Troop(); disney.setName( "Disney" ); Soldier mickey = new Soldier(); mickey.setName( "Mickey" ); disney.addSoldier( mickey ); em.persist( disney ); } em.getTransaction().commit(); em.close(); //Warm up loop em = getOrCreateEntityManager(); em.getTransaction().begin(); for ( int i = 0; i < loop ; i++ ) { //Soldier soldier = em.find( Soldier.class, new Integer(i) ); Troop troop = em.find( Troop.class, new Integer( i ) ); //( ( HibernateEntityManager ) em ).getSession().evict(soldier); } long l11 = System.currentTimeMillis(); Query query = em.createQuery( "SELECT count(t) FROM Soldier t" ); query.getSingleResult(); long l2 = System.currentTimeMillis(); System.out.println( "Query1 " + ( l2 - l11 ) ); em.getTransaction().commit(); em.close(); //do not evict for ( int j = 0; j < 10 ; j++ ) { em = getOrCreateEntityManager(); em.getTransaction().begin(); for ( int i = 0; i < loop ; i++ ) { Troop troop = em.find( Troop.class, new Integer( i ) ); ( (HibernateEntityManager) em ).getSession().evict( troop ); } l11 = System.currentTimeMillis(); query = em.createQuery( "SELECT count(t) FROM Soldier t" ); query.getSingleResult(); l2 = System.currentTimeMillis(); System.out.println( "Query " + ( l2 - l11 ) ); em.getTransaction().commit(); em.close(); //evict em = getOrCreateEntityManager(); em.getTransaction().begin(); for ( int i = 0; i < loop ; i++ ) { //Soldier soldier = em.find( Soldier.class, new Integer(i) ); Troop troop = em.find( Troop.class, new Integer( i ) ); //( ( HibernateEntityManager ) em ).getSession().evict(troop); } l11 = System.currentTimeMillis(); query = em.createQuery( "SELECT count(t) FROM Soldier t" ); query.getSingleResult(); l2 = System.currentTimeMillis(); System.out.println( "Query " + ( l2 - l11 ) ); em.getTransaction().commit(); } em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Troop.class, Soldier.class, Conference.class, ExtractionDocument.class, ExtractionDocumentInfo.class, Parent.class, Son.class, Grandson.class }; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/DeleteOrphanTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000451211714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.hibernate.Hibernate; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class DeleteOrphanTest extends TestCase { public void testDeleteOrphan() throws Exception { EntityTransaction tx; EntityManager em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); Troop disney = new Troop(); disney.setName( "Disney" ); Soldier mickey = new Soldier(); mickey.setName( "Mickey" ); disney.addSoldier( mickey ); em.persist( disney ); tx.commit(); em.close(); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); Troop troop = em.find( Troop.class, disney.getId() ); Hibernate.initialize( troop.getSoldiers() ); tx.commit(); em.close(); Soldier soldier = troop.getSoldiers().iterator().next(); troop.getSoldiers().remove( soldier ); troop = (Troop) unserialize( serialize( troop ) ); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); em.merge( troop ); tx.commit(); em.close(); em = getOrCreateEntityManager(); tx = em.getTransaction(); tx.begin(); soldier = em.find( Soldier.class, mickey.getId() ); assertNull( "delete-orphan should work", soldier ); troop = em.find( Troop.class, disney.getId() ); em.remove( troop ); tx.commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Troop.class, Soldier.class }; } private byte[] serialize(Object object) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( object ); out.close(); byte[] serialized = stream.toByteArray(); stream.close(); return serialized; } private Object unserialize(byte[] serialized) throws IOException, ClassNotFoundException { ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream( byteIn ); Object result = in.readObject(); in.close(); byteIn.close(); return result; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Soldier.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000226311714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * @author Emmanuel Bernard */ @Entity public class Soldier implements Serializable { private Integer id; private String name; private Troop troop; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) @JoinColumn(name = "troop_fk") public Troop getTroop() { return troop; } public void setTroop(Troop troop) { this.troop = troop; } public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof Soldier ) ) return false; final Soldier soldier = (Soldier) o; if ( !name.equals( soldier.name ) ) return false; return true; } public int hashCode() { return name.hashCode(); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/FetchTest2.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000260111714611271032750 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; public class FetchTest2 extends TestCase { public void testProxyTransientStuff() throws Exception { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Troop2 disney = new Troop2(); disney.setName( "Disney" ); Soldier2 mickey = new Soldier2(); mickey.setName( "Mickey" ); mickey.setTroop( disney ); em.persist( disney ); em.persist( mickey ); em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); Soldier2 soldier = em.find( Soldier2.class, mickey.getId() ); soldier.getTroop().getId(); try { em.flush(); } catch (IllegalStateException e) { fail( "Should not raise an exception" ); } em.getTransaction().commit(); em.close(); em = factory.createEntityManager(); em.getTransaction().begin(); //load troop wo a proxy disney = em.find( Troop2.class, disney.getId() ); soldier = em.find( Soldier2.class, mickey.getId() ); try { em.flush(); } catch (IllegalStateException e) { fail( "Should not raise an exception" ); } em.remove( soldier ); em.remove( disney ); em.getTransaction().commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Troop2.class, Soldier2.class }; } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/ExtractionDocumentInfo.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000532111714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.persistence.Table; import javax.persistence.Transient; /** * @author Emmanuel Bernard */ @Entity @Table(name = "portal_pk_docs_extraction_info") //@Cache(usage = READ_WRITE) @org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true) public class ExtractionDocumentInfo implements Serializable { private Long id; private Date lastModified; private Conference conference; private List documents; public ExtractionDocumentInfo() { lastModified = new Date(); } public ExtractionDocumentInfo(Conference conference) { this.conference = conference; lastModified = new Date(); documents = new ArrayList(); documents.add( new ExtractionDocument( this ) ); } @Transient public ExtractionDocument getDocument() { if ( documents.isEmpty() ) { documents.add( new ExtractionDocument( this ) ); } Iterator iterator = documents.iterator(); return iterator.next(); } @Transient public byte[] getBody() { return getDocument().getBody(); } public void setBody(byte[] body) { getDocument().setBody( body ); } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToMany(mappedBy = "documentInfo", cascade = CascadeType.ALL) public List getDocuments() { return documents; } public void setDocuments(List documents) { this.documents = documents; } @ManyToOne @JoinColumn(name = "conference_id") public Conference getConference() { return conference; } public void setConference(Conference conference) { this.conference = conference; } @Column(name = "last_modified", nullable = false) public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof ExtractionDocumentInfo ) ) return false; final ExtractionDocumentInfo newsInfo = (ExtractionDocumentInfo) o; return id.equals( newsInfo.id ); } public int hashCode() { return id.hashCode(); } @PreRemove public void preRemove() { getConference().setExtractionDocument( null ); } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Student.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000210311714611271032745 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import org.hibernate.annotations.AccessType; @Entity @AccessType("field") public class Student { @Id @GeneratedValue Long id; String name; @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST}) private Teacher primaryTeacher; @OneToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST}) private Teacher favoriteTeacher; public Student() { } public Teacher getFavoriteTeacher() { return favoriteTeacher; } public void setFavoriteTeacher(Teacher lifeCover) { this.favoriteTeacher = lifeCover; } public Teacher getPrimaryTeacher() { return primaryTeacher; } public void setPrimaryTeacher(Teacher relativeTo) { this.primaryTeacher = relativeTo; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/CascadeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000400611714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.hibernate.ejb.test.TestCase; /** * @author Max Rydahl Andersen */ public class CascadeTest extends TestCase { public void testCascade() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Teacher teacher = null; teacher = new Teacher(); Student student = new Student(); teacher.setFavoriteStudent(student); student.setFavoriteTeacher(teacher); teacher.getStudents().add(student); student.setPrimaryTeacher(teacher); em.persist( teacher ); em.getTransaction().commit(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Teacher foundTeacher = (Teacher) em.createQuery( "select t from Teacher as t" ).getSingleResult(); System.out.println(foundTeacher); System.out.println(foundTeacher.getFavoriteStudent()); for (Student fstudent : foundTeacher.getStudents()) { System.out.println(fstudent); System.out.println(fstudent.getFavoriteTeacher()); System.out.println(fstudent.getPrimaryTeacher()); } em.getTransaction().commit(); // here *alot* of flushes occur on an object graph that has *Zero* changes. em.close(); } public void testNoCascadeAndMerge() throws Exception { Song e1 = new Song(); Author e2 = new Author(); e1.setAuthor(e2); EntityManager em = getOrCreateEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(e2); em.persist(e1); tx.commit(); em.close(); em = getOrCreateEntityManager(); e1 = em.find(Song.class, e1.getId()); e2 = null; tx = em.getTransaction(); tx.begin(); em.merge(e1); //em.refresh(e1); tx.commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Teacher.class, Student.class, Song.class, Author.class }; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Teacher.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000236211714611271032754 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import org.hibernate.annotations.AccessType; @Entity @AccessType("field") public class Teacher { @Id @GeneratedValue Long id; String name; @OneToMany(mappedBy="primaryTeacher", cascade={CascadeType.MERGE, CascadeType.PERSIST}) private Set students = new HashSet(); @OneToOne(mappedBy="favoriteTeacher", cascade={CascadeType.MERGE, CascadeType.PERSIST}) private Student favoriteStudent; public Teacher() { } public Student getFavoriteStudent() { return favoriteStudent; } public void setFavoriteStudent( Student contributionOrBenefitParameters) { this.favoriteStudent = contributionOrBenefitParameters; } public Set getStudents() { return students; } public void setStudents( Set todoCollection) { this.students = todoCollection; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/ExtractionDocument.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000246211714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Proxy; /** * @author Emmanuel Bernard */ @Entity @Table(name = "portal_pk_docs_extraction") //@Cache(usage = READ_WRITE) @org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true) @Proxy public class ExtractionDocument implements Serializable { private Long id; private byte[] body; private ExtractionDocumentInfo documentInfo; public ExtractionDocument() { } public ExtractionDocument(ExtractionDocumentInfo documentInfo) { this.documentInfo = documentInfo; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToOne @JoinColumn(name = "document_info_id") public ExtractionDocumentInfo getDocumentInfo() { return documentInfo; } public void setDocumentInfo(ExtractionDocumentInfo documentInfo) { this.documentInfo = documentInfo; } @Column(nullable = false) public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Troop2.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000111211714611271032744 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Troop2 implements Serializable { /* FAILS: */ @Id @GeneratedValue private Integer id; private String name; /* WORKS: @Id @GeneratedValue */ public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Soldier2.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000215611714611271032755 0ustar ebourgebourgpackage org.hibernate.ejb.test.cascade; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * @author Emmanuel Bernard */ @Entity public class Soldier2 implements Serializable { private Integer id; private String name; private Troop2 troop; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "troop_fk") public Troop2 getTroop() { return troop; } public void setTroop(Troop2 troop) { this.troop = troop; } public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof Soldier2 ) ) return false; final Soldier2 soldier = (Soldier2) o; if ( !name.equals( soldier.name ) ) return false; return true; } public int hashCode() { return name.hashCode(); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Parent.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000064711714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "family_parent") public class Parent { @Id @GeneratedValue private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Grandson.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000123611714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * @author Emmanuel Bernard */ @Entity public class Grandson { @Id @GeneratedValue private Integer id; @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) private Son parent; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Son getParent() { return parent; } public void setParent(Son parent) { this.parent = parent; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Son.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000124011714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * @author Emmanuel Bernard */ @Entity public class Son { @Id @GeneratedValue public Integer id; @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) public Parent parent; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Troop.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000236311714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import org.hibernate.annotations.OrderBy; /** * @author Emmanuel Bernard */ @Entity public class Troop implements Serializable { private Integer id; private String name; private Set soldiers; @OneToMany(mappedBy = "troop", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) @OrderBy(clause = "name desc") @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) public Set getSoldiers() { return soldiers; } public void setSoldiers(Set soldiers) { this.soldiers = soldiers; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void addSoldier(Soldier s) { if ( soldiers == null ) soldiers = new HashSet(); soldiers.add( s ); s.setTroop( this ); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Author.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000042411714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Author { @Id @GeneratedValue private Long id; } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/AssociationTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000265211714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.association; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class AssociationTest extends TestCase { public void testBidirOneToOne() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); String id = "10"; Incident i = em.find( Incident.class, id ); if ( i == null ) { i = new Incident( id ); IncidentStatus ist = new IncidentStatus( id ); i.setIncidentStatus( ist ); ist.setIncident( i ); em.persist( i ); } em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); em.remove( em.find(Incident.class, id) ); em.getTransaction().commit(); em.close(); } public void testMergeAndBidirOneToOne() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Oven oven = new Oven(); Kitchen kitchen = new Kitchen(); em.persist( oven ); em.persist( kitchen ); kitchen.setOven( oven ); oven.setKitchen( kitchen ); em.flush(); em.clear(); //oven = em.find(Oven.class, oven.getId() ); oven = em.merge( oven ); em.flush(); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Incident.class, IncidentStatus.class, Kitchen.class, Oven.class }; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/Kitchen.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000110411714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.association; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; /** * @author Emmanuel Bernard */ @Entity public class Kitchen { @Id @GeneratedValue private Long id; @OneToOne(mappedBy = "kitchen") private Oven oven; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Oven getOven() { return oven; } public void setOven(Oven oven) { this.oven = oven; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/IncidentStatus.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000117711714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.association; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; /** * @author Emmanuel Bernard */ @Entity public class IncidentStatus { @Id String id; @OneToOne(mappedBy = "incidentStatus") Incident incident; public IncidentStatus() { } public IncidentStatus(String id) { this.id = id; } public Incident getIncident() { return incident; } public void setIncident(Incident incident) { this.incident = incident; } @Override public String toString() { return "IncidentStatus " + id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/Oven.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000127111714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.association; import javax.persistence.Entity; import javax.persistence.OneToOne; import javax.persistence.JoinColumn; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.FetchType; /** * @author Emmanuel Bernard */ @Entity public class Oven { @Id @GeneratedValue private Long id; @OneToOne(fetch= FetchType.LAZY) @JoinColumn private Kitchen kitchen; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Kitchen getKitchen() { return kitchen; } public void setKitchen(Kitchen kitchen) { this.kitchen = kitchen; } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/association/Incident.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000134011714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.association; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; /** * @author Emmanuel Bernard */ @Entity public class Incident { @Id String id; @OneToOne(cascade = CascadeType.ALL) IncidentStatus incidentStatus; public Incident() { } public Incident(String id) { this.id = id; } public IncidentStatus getIncidentStatus() { return incidentStatus; } public void setIncidentStatus(IncidentStatus incidentStatus) { this.incidentStatus = incidentStatus; } @Override public String toString() { return "Incident: " + id + " " + incidentStatus; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/NoOpListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000046211714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import org.hibernate.event.PreInsertEventListener; import org.hibernate.event.PreInsertEvent; /** * @author Emmanuel Bernard */ public class NoOpListener implements PreInsertEventListener { public boolean onPreInsert(PreInsertEvent event) { return false; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/hibernateFilters/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000024000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/hibernateFilters/EntityManagerWithFilteredSessionTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000330111714611271032746 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.hibernateFilters; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.ejb.test.TestCase; /** * @author Steve Ebersole */ public class EntityManagerWithFilteredSessionTest extends TestCase { @Override public Class[] getAnnotatedClasses() { return new Class[] { Account.class }; } public void testTypedQueryCreation() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.unwrap( Session.class ).enableFilter( "byRegion" ).setParameter( "region", "US" ); em.createQuery( "from Account", Account.class ).getResultList(); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/hibernateFilters/Account.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000420411714611271032751 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.hibernateFilters; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.ParamDef; /** * @author Steve Ebersole */ @Entity @FilterDef( name="byRegion", parameters = {@ParamDef(name = "region", type = "string")}) @Filter( name = "byRegion", condition = "region_cd = :region" ) public class Account { private Long id; private String name; private String regionCode; @Id @GeneratedValue( generator = "increment" ) @GenericGenerator( name = "increment", strategy = "increment" ) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Column( name = "region_cd" ) public String getRegionCode() { return regionCode; } public void setRegionCode(String regionCode) { this.regionCode = regionCode; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/StaticMetadataTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001402111714611271032747 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.util.Set; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.EmbeddableType; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.Type; import org.hibernate.ejb.test.TestCase; /** * @author Steve Ebersole */ public class StaticMetadataTest extends TestCase { public void testInjections() throws Exception { // Address (embeddable) assertNotNull( Address_.address1 ); assertNotNull( Address_.address2 ); assertNotNull( Address_.city ); final EmbeddableType
addressType = ( EmbeddableType
) House_.address.getType(); assertEquals( addressType.getDeclaredSingularAttribute( "address1" ), Address_.address1 ); assertEquals( addressType.getDeclaredSingularAttribute( "address2" ), Address_.address2 ); assertTrue( Address_.address1.isOptional() ); assertFalse( Address_.address2.isOptional() ); // Animal (mapped superclass) assertNotNull( Animal_.id ); assertTrue( Animal_.id.isId() ); assertEquals( Long.class, Animal_.id.getJavaType() ); assertNotNull( Animal_.legNbr ); // assertEquals( Integer.class, Animal_.legNbr.getJavaType() ); assertEquals( int.class, Animal_.legNbr.getJavaType() ); // Cat (hierarchy) assertNotNull( Cat_.id ); assertNotNull( Cat_.id.isId() ); assertEquals( Animal.class, Cat_.id.getJavaMember().getDeclaringClass() ); assertNotNull( Cat_.nickname ); // FoodItem assertNotNull( FoodItem_.version ); assertTrue( FoodItem_.version.isVersion() ); // Fridge assertNotNull( Fridge_.id ); assertTrue( Fridge_.id.isId() ); assertEquals( Long.class, Fridge_.id.getJavaType() ); assertNotNull( Fridge_.temperature ); assertEquals( "temperature", Fridge_.temperature.getName() ); assertEquals( Fridge.class, Fridge_.temperature.getDeclaringType().getJavaType() ); // assertEquals( Integer.class, Fridge_.temperature.getJavaType() ); // assertEquals( Integer.class, Fridge_.temperature.getBindableJavaType() ); // assertEquals( Integer.class, Fridge_.temperature.getType().getJavaType() ); assertEquals( int.class, Fridge_.temperature.getJavaType() ); assertEquals( int.class, Fridge_.temperature.getBindableJavaType() ); assertEquals( int.class, Fridge_.temperature.getType().getJavaType() ); assertEquals( Bindable.BindableType.SINGULAR_ATTRIBUTE, Fridge_.temperature.getBindableType() ); assertEquals( Type.PersistenceType.BASIC, Fridge_.temperature.getType().getPersistenceType() ); assertEquals( Attribute.PersistentAttributeType.BASIC, Fridge_.temperature.getPersistentAttributeType() ); assertFalse( Fridge_.temperature.isId() ); assertFalse( Fridge_.temperature.isOptional() ); assertFalse( Fridge_.temperature.isAssociation() ); assertFalse( Fridge_.temperature.isCollection() ); assertFalse( Fridge_.brand.isOptional() ); // House (embedded id) assertNotNull( House_.key ); assertTrue( House_.key.isId() ); assertEquals( Attribute.PersistentAttributeType.EMBEDDED, House_.key.getPersistentAttributeType() ); assertNotNull( House_.address ); assertEquals( Attribute.PersistentAttributeType.EMBEDDED, House_.address.getPersistentAttributeType() ); assertFalse( House_.address.isCollection() ); assertFalse( House_.address.isAssociation() ); assertNotNull( House_.rooms ); assertTrue( House_.rooms.isAssociation() ); assertTrue( House_.rooms.isCollection() ); assertEquals( Attribute.PersistentAttributeType.ELEMENT_COLLECTION, House_.rooms.getPersistentAttributeType() ); assertEquals( Room.class, House_.rooms.getBindableJavaType() ); assertEquals( Bindable.BindableType.PLURAL_ATTRIBUTE, House_.rooms.getBindableType() ); assertEquals( Set.class, House_.rooms.getJavaType() ); assertEquals( PluralAttribute.CollectionType.SET, House_.rooms.getCollectionType() ); assertEquals( Type.PersistenceType.EMBEDDABLE, House_.rooms.getElementType().getPersistenceType() ); assertNotNull( House_.roomsByName ); assertEquals( String.class, House_.roomsByName.getKeyJavaType() ); assertEquals( Type.PersistenceType.BASIC, House_.roomsByName.getKeyType().getPersistenceType() ); assertEquals( PluralAttribute.CollectionType.MAP, House_.roomsByName.getCollectionType() ); assertNotNull( House_.roomsBySize ); assertEquals( Type.PersistenceType.EMBEDDABLE, House_.roomsBySize.getElementType().getPersistenceType() ); assertEquals( PluralAttribute.CollectionType.LIST, House_.roomsBySize.getCollectionType() ); // Person (mapped id) assertNotNull( Person_.firstName ); assertNotNull( Person_.lastName ); assertTrue( Person_.firstName.isId() ); assertTrue( Person_.lastName.isId() ); assertTrue( Person_.lastName.isId() ); //Garden List as bag assertNotNull( Garden_.flowers ); } @Override public Class[] getAnnotatedClasses() { return new Class[] { Fridge.class, FoodItem.class, Person.class, House.class, Dog.class, Cat.class, Cattish.class, Feline.class, Garden.class, Flower.class }; } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Flower.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000300611714611271032750 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Flower { private Long id; private String name; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Cattish.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000262511714611271032756 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.MappedSuperclass; /** * @author Emmanuel Bernard */ @MappedSuperclass public class Cattish extends Feline { private long hoursOfSleep; public long getHoursOfSleep() { return hoursOfSleep; } public void setHoursOfSleep(long hoursOfSleep) { this.hoursOfSleep = hoursOfSleep; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SubThing.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000254111714611271032753 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; /** * @author Emmanuel Bernard */ //not an entity but in between mapped superclass and entity public class SubThing extends Thing { private String blah; public String getBlah() { return blah; } public void setBlah(String blah) { this.blah = blah; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Garden.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000345311714611271032756 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.util.List; import java.util.ArrayList; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; /** * @author Emmanuel Bernard */ @Entity public class Garden { private Long id; private String name; private List flowers = new ArrayList(); @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany public List getFlowers() { return flowers; } public void setFlowers(List flowers) { this.flowers = flowers; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Address.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000332511714611271032754 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Embeddable; import javax.persistence.Basic; /** * @author Emmanuel Bernard */ @Embeddable public class Address { private String address1; private String address2; private String city; @Basic(optional = true) public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } @Basic(optional = false) public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Dog.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000251311714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Dog extends Animal { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Room.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000301711714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.math.BigDecimal; import javax.persistence.Embeddable; /** * @author Emmanuel Bernard */ @Embeddable public class Room { private BigDecimal length; private BigDecimal width; public BigDecimal getLength() { return length; } public void setLength(BigDecimal length) { this.length = length; } public BigDecimal getWidth() { return width; } public void setWidth(BigDecimal width) { this.width = width; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/House.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000520611714611271032754 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.io.Serializable; import java.util.Set; import java.util.Map; import java.util.List; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.ElementCollection; import javax.persistence.CollectionTable; import javax.persistence.MapKeyColumn; import javax.persistence.OrderColumn; /** * @author Emmanuel Bernard */ @Entity(name="org.hibernate.ejb.test.metadata.House") public class House { private Key key; private Address address; private Set rooms; private Map roomsByName; private List roomsBySize; @ElementCollection @OrderColumn(name = "size_order") public List getRoomsBySize() { return roomsBySize; } public void setRoomsBySize(List roomsBySize) { this.roomsBySize = roomsBySize; } @ElementCollection @MapKeyColumn(name="room_name") public Map getRoomsByName() { return roomsByName; } public void setRoomsByName(Map roomsByName) { this.roomsByName = roomsByName; } @ElementCollection public Set getRooms() { return rooms; } public void setRooms(Set rooms) { this.rooms = rooms; } @EmbeddedId public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public static class Key implements Serializable { private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimpleMedicalHistory.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000101411714611271032745 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * @author Emmanuel Bernard */ @Entity public class SimpleMedicalHistory implements Serializable { @Temporal(TemporalType.DATE) Date lastupdate; @Id @JoinColumn(name = "FK") @OneToOne SimplePerson patient; } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Thing.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000303311714611271032750 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.MappedSuperclass; import javax.persistence.Version; /** * @author Emmanuel Bernard */ @MappedSuperclass public class Thing { private Double weight; private Long version; public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } @Version public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/DeskWithRawType.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000230111714611271032745 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; /** * @author Emmanuel Bernard */ @Entity public class DeskWithRawType implements java.io.Serializable { @Id protected String id; @Basic protected String name; public DeskWithRawType() { } @ManyToMany(targetEntity = EmployeeWithRawType.class, cascade = CascadeType.ALL) @JoinTable(name = "DESK_EMPL", joinColumns = @JoinColumn( name = "DESK_FK", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn( name = "EMPL_FK", referencedColumnName = "ID") ) protected Collection employees = new java.util.ArrayList(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection getEmployees() { return employees; } public void setEmployees(Collection employees) { this.employees = employees; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Feline.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000252511714611271032755 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Feline extends Animal { private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/WithGenericCollection.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000502511714611271032753 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.util.Collection; import java.util.List; import java.util.ArrayList; import javax.persistence.*; /** * This class has a List of mapped entity objects that are themselves parameterized. * This class was added for JIRA issue #HHH- * * @author Kahli Burke */ @Entity @Table(name = "WITH_GENERIC_COLLECTION") public class WithGenericCollection implements java.io.Serializable { @Id @Column(name = "ID") private String id; @Basic(optional=false) private double d; @ManyToOne(optional=false) @JoinColumn(name="PARENT_ID", insertable=false, updatable=false) private WithGenericCollection parent = null; @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name="PARENT_ID") private List> children = new ArrayList>(); public WithGenericCollection() { } //==================================================================== // getters and setters for State fields public String getId() { return id; } public void setId(String id) { this.id = id; } public void setD(double d) { this.d = d; } public double getD() { return d; } public List> getChildren() { return children; } public void setChildren(List> children) { this.children = children; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/FoodItem.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000330311714611271032750 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Version; /** * @author Emmanuel Bernard */ @Entity public class FoodItem { private Long id; private String name; private Long version; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Version public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Being.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000024311714611271032750 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import javax.persistence.MappedSuperclass; /** * @author Emmanuel Bernard */ @MappedSuperclass public class Being { } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Cat.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000255011714611271032753 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Cat extends Cattish { private String nickname; public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/JoinedManyToOneOwner.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000322511714611271032753 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; /** * An entity that defines a @ManyToOne @JoinTable *

* See HHH-4720 for details * * @author Steve Ebersole */ @Entity public class JoinedManyToOneOwner { private Long id; private House house; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinTable( name = "SOME_OTHER_TABLE" ) public House getHouse() { return house; } public void setHouse(House house) { this.house = house; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Fridge.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000337711714611271032763 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Basic; /** * @author Emmanuel Bernard */ @Entity public class Fridge { private Long id; private String brand; private int temperature; //dimensions @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Basic(optional = false) public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getTemperature() { return temperature; } public void setTemperature(int temperature) { this.temperature = temperature; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/EmployeeWithRawType.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000164311714611271032755 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; /** * @author Emmanuel Bernard */ @Entity public class EmployeeWithRawType implements java.io.Serializable { @Id protected String id; @Basic protected String name; @ManyToMany(targetEntity = DeskWithRawType.class, mappedBy = "employees", cascade = CascadeType.ALL) protected Collection desks = new java.util.ArrayList(); public EmployeeWithRawType() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection getDesks() { return desks; } public void setDesks(Collection desks) { this.desks = desks; } }././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Parent.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000266611714611271032763 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import java.util.Set; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; /** * @author Emmanuel Bernard */ @Entity @Table(name="ejb_parent") public class Parent { @Embeddable public static class Relatives { private Set siblings; @OneToMany @JoinColumn(name="siblings_fk") public Set getSiblings() { return siblings; } public void setSiblings(Set siblings) { this.siblings = siblings; } } private Integer id; private String name; private Set children; private Relatives siblings; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany @JoinColumn(name="parent_fk", nullable = false) public Set getChildren() { return children; } public void setChildren(Set children) { this.children = children; } //@Transient @Embedded public Relatives getSiblings() { return siblings; } public void setSiblings(Relatives siblings) { this.siblings = siblings; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Person.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000550111714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.io.Serializable; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @IdClass(Person.PersonPK.class) @Entity(name="Homosapien") public class Person { private String firstName; private String lastName; private Short age; @Id public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Id public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } public static class PersonPK implements Serializable { private String firstName; private String lastName; @Id public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Id public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } PersonPK personPK = ( PersonPK ) o; if ( firstName != null ? !firstName.equals( personPK.firstName ) : personPK.firstName != null ) { return false; } if ( lastName != null ? !lastName.equals( personPK.lastName ) : personPK.lastName != null ) { return false; } return true; } @Override public int hashCode() { int result = firstName != null ? firstName.hashCode() : 0; result = 31 * result + ( lastName != null ? lastName.hashCode() : 0 ); return result; } } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Animal.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000306011714611271032750 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import javax.persistence.MappedSuperclass; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @MappedSuperclass public class Animal extends SubThing { private Long id; private int legNbr; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getLegNbr() { return legNbr; } public void setLegNbr(int legNbr) { this.legNbr = legNbr; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimplePerson.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000030511714611271032747 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class SimplePerson { @Id String ssn; } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/MetadataTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000004027711714611271032763 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.metadata; import java.util.Set; import javax.persistence.EntityManagerFactory; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.Type; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.EmbeddableType; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.MappedSuperclassType; import javax.persistence.metamodel.IdentifiableType; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.ejb.metamodel.MetamodelImpl; import org.hibernate.ejb.test.TestCase; import org.hibernate.engine.SessionFactoryImplementor; /** * @author Emmanuel Bernard */ public class MetadataTest extends TestCase { public void testBaseOfService() throws Exception { EntityManagerFactory emf = factory; assertNotNull( emf.getMetamodel() ); final EntityType entityType = emf.getMetamodel().entity( Fridge.class ); assertNotNull( entityType ); } @SuppressWarnings({ "unchecked" }) public void testBuildingMetamodelWithParameterizedCollection() { AnnotationConfiguration cfg = new AnnotationConfiguration( ); configure( cfg ); cfg.addAnnotatedClass( WithGenericCollection.class ); cfg.buildMappings(); SessionFactoryImplementor sfi = (SessionFactoryImplementor) cfg.buildSessionFactory(); MetamodelImpl.buildMetamodel( cfg.getClassMappings(), sfi ); } public void testLogicalManyToOne() throws Exception { final EntityType entityType = factory.getMetamodel().entity( JoinedManyToOneOwner.class ); final SingularAttribute attr = entityType.getDeclaredSingularAttribute( "house" ); assertEquals( Attribute.PersistentAttributeType.MANY_TO_ONE, attr.getPersistentAttributeType() ); assertEquals( House.class, attr.getBindableJavaType() ); final EntityType houseType = factory.getMetamodel().entity( House.class ); assertEquals( houseType.getBindableJavaType(), attr.getBindableJavaType() ); } public void testEntity() throws Exception { final EntityType fridgeType = factory.getMetamodel().entity( Fridge.class ); assertEquals( Fridge.class, fridgeType.getBindableJavaType() ); assertEquals( Bindable.BindableType.ENTITY_TYPE, fridgeType.getBindableType() ); SingularAttribute wrapped = fridgeType.getDeclaredSingularAttribute( "temperature", Integer.class ); assertNotNull( wrapped ); SingularAttribute primitive = fridgeType.getDeclaredSingularAttribute( "temperature", int.class ); assertNotNull( primitive ); assertNotNull( fridgeType.getDeclaredSingularAttribute( "temperature" ) ); assertNotNull( fridgeType.getDeclaredAttribute( "temperature" ) ); final SingularAttribute id = fridgeType.getDeclaredId( Long.class ); assertNotNull( id ); assertTrue( id.isId() ); try { fridgeType.getDeclaredId( java.util.Date.class ); fail( "expecting failure" ); } catch ( IllegalArgumentException ignore ) { // expected result } final SingularAttribute id2 = fridgeType.getId( Long.class ); assertNotNull( id2 ); assertEquals( Fridge.class.getSimpleName(), fridgeType.getName() ); assertEquals( Long.class, fridgeType.getIdType().getJavaType() ); assertTrue( fridgeType.hasSingleIdAttribute() ); assertFalse( fridgeType.hasVersionAttribute() ); assertEquals( Type.PersistenceType.ENTITY, fridgeType.getPersistenceType() ); assertEquals( 3, fridgeType.getDeclaredAttributes().size() ); final EntityType houseType = factory.getMetamodel().entity( House.class ); assertEquals( House.class.getName(), houseType.getName() ); assertTrue( houseType.hasSingleIdAttribute() ); final SingularAttribute houseId = houseType.getDeclaredId( House.Key.class ); assertNotNull( houseId ); assertTrue( houseId.isId() ); assertEquals( Attribute.PersistentAttributeType.EMBEDDED, houseId.getPersistentAttributeType() ); final EntityType personType = factory.getMetamodel().entity( Person.class ); assertFalse( personType.hasSingleIdAttribute() ); final Set> ids = personType.getIdClassAttributes(); assertNotNull( ids ); assertEquals( 2, ids.size() ); for (SingularAttribute localId : ids) { assertTrue( localId.isId() ); } final EntityType foodType = factory.getMetamodel().entity( FoodItem.class ); assertTrue( foodType.hasVersionAttribute() ); final SingularAttribute version = foodType.getVersion( Long.class ); assertNotNull( version ); assertTrue( version.isVersion() ); assertEquals( 3, foodType.getDeclaredAttributes().size() ); } public void testBasic() throws Exception { final EntityType entityType = factory.getMetamodel().entity( Fridge.class ); final SingularAttribute singularAttribute = entityType.getDeclaredSingularAttribute( "temperature", Integer.class ); // assertEquals( Integer.class, singularAttribute.getBindableJavaType() ); // assertEquals( Integer.class, singularAttribute.getType().getJavaType() ); assertEquals( int.class, singularAttribute.getBindableJavaType() ); assertEquals( int.class, singularAttribute.getType().getJavaType() ); assertEquals( Bindable.BindableType.SINGULAR_ATTRIBUTE, singularAttribute.getBindableType() ); assertFalse( singularAttribute.isId() ); assertFalse( singularAttribute.isOptional() ); assertFalse( entityType.getDeclaredSingularAttribute( "brand", String.class ).isOptional() ); assertEquals( Type.PersistenceType.BASIC, singularAttribute.getType().getPersistenceType() ); final Attribute attribute = entityType.getDeclaredAttribute( "temperature" ); assertNotNull( attribute ); assertEquals( "temperature", attribute.getName() ); assertEquals( Fridge.class, attribute.getDeclaringType().getJavaType() ); assertEquals( Attribute.PersistentAttributeType.BASIC, attribute.getPersistentAttributeType() ); // assertEquals( Integer.class, attribute.getJavaType() ); assertEquals( int.class, attribute.getJavaType() ); assertFalse( attribute.isAssociation() ); assertFalse( attribute.isCollection() ); boolean found = false; for (Attribute attr : entityType.getDeclaredAttributes() ) { if ("temperature".equals( attr.getName() ) ) { found = true; break; } } assertTrue( found ); } public void testEmbeddable() throws Exception { final EntityType entityType = factory.getMetamodel().entity( House.class ); final SingularAttribute address = entityType.getDeclaredSingularAttribute( "address", Address.class ); assertNotNull( address ); assertEquals( Attribute.PersistentAttributeType.EMBEDDED, address.getPersistentAttributeType() ); assertFalse( address.isCollection() ); assertFalse( address.isAssociation() ); final EmbeddableType

addressType = (EmbeddableType
) address.getType(); assertEquals( Type.PersistenceType.EMBEDDABLE, addressType.getPersistenceType() ); assertEquals( 3, addressType.getDeclaredAttributes().size() ); assertTrue( addressType.getDeclaredSingularAttribute( "address1" ).isOptional() ); assertFalse( addressType.getDeclaredSingularAttribute( "address2" ).isOptional() ); final EmbeddableType
directType = factory.getMetamodel().embeddable( Address.class ); assertNotNull( directType ); assertEquals( Type.PersistenceType.EMBEDDABLE, directType.getPersistenceType() ); } public void testCollection() throws Exception { final EntityType entiytype = factory.getMetamodel().entity( Garden.class ); final Set> attributes = entiytype.getPluralAttributes(); assertEquals( 1, attributes.size() ); PluralAttribute flowers = attributes.iterator().next(); assertTrue( flowers instanceof ListAttribute ); } public void testElementCollection() throws Exception { final EntityType entityType = factory.getMetamodel().entity( House.class ); final SetAttribute rooms = entityType.getDeclaredSet( "rooms", Room.class ); assertNotNull( rooms ); assertTrue( rooms.isAssociation() ); assertTrue( rooms.isCollection() ); assertEquals( Attribute.PersistentAttributeType.ELEMENT_COLLECTION, rooms.getPersistentAttributeType() ); assertEquals( Room.class, rooms.getBindableJavaType() ); assertEquals( Bindable.BindableType.PLURAL_ATTRIBUTE, rooms.getBindableType() ); assertEquals( Set.class, rooms.getJavaType() ); assertEquals( PluralAttribute.CollectionType.SET, rooms.getCollectionType() ); assertEquals( 3, entityType.getDeclaredPluralAttributes().size() ); assertEquals( Type.PersistenceType.EMBEDDABLE, rooms.getElementType().getPersistenceType() ); final MapAttribute roomsByName = entityType.getDeclaredMap( "roomsByName", String.class, Room.class ); assertNotNull( roomsByName ); assertEquals( String.class, roomsByName.getKeyJavaType() ); assertEquals( Type.PersistenceType.BASIC, roomsByName.getKeyType().getPersistenceType() ); assertEquals( PluralAttribute.CollectionType.MAP, roomsByName.getCollectionType() ); final ListAttribute roomsBySize = entityType.getDeclaredList( "roomsBySize", Room.class ); assertNotNull( roomsBySize ); assertEquals( Type.PersistenceType.EMBEDDABLE, roomsBySize.getElementType().getPersistenceType() ); assertEquals( PluralAttribute.CollectionType.LIST, roomsBySize.getCollectionType() ); } public void testHierarchy() { final EntityType cat = factory.getMetamodel().entity( Cat.class ); assertNotNull( cat ); assertEquals( 7, cat.getAttributes().size() ); assertEquals( 1, cat.getDeclaredAttributes().size() ); ensureProperMember(cat.getDeclaredAttributes()); assertTrue( cat.hasVersionAttribute() ); assertEquals( "version", cat.getVersion(Long.class).getName() ); verifyDeclaredVersionNotPresent( cat ); verifyDeclaredIdNotPresentAndIdPresent(cat); assertEquals( Type.PersistenceType.MAPPED_SUPERCLASS, cat.getSupertype().getPersistenceType() ); MappedSuperclassType cattish = (MappedSuperclassType) cat.getSupertype(); assertEquals( 6, cattish.getAttributes().size() ); assertEquals( 1, cattish.getDeclaredAttributes().size() ); ensureProperMember(cattish.getDeclaredAttributes()); assertTrue( cattish.hasVersionAttribute() ); assertEquals( "version", cattish.getVersion(Long.class).getName() ); verifyDeclaredVersionNotPresent( cattish ); verifyDeclaredIdNotPresentAndIdPresent(cattish); assertEquals( Type.PersistenceType.ENTITY, cattish.getSupertype().getPersistenceType() ); EntityType feline = (EntityType) cattish.getSupertype(); assertEquals( 5, feline.getAttributes().size() ); assertEquals( 1, feline.getDeclaredAttributes().size() ); ensureProperMember(feline.getDeclaredAttributes()); assertTrue( feline.hasVersionAttribute() ); assertEquals( "version", feline.getVersion(Long.class).getName() ); verifyDeclaredVersionNotPresent( feline ); verifyDeclaredIdNotPresentAndIdPresent(feline); assertEquals( Type.PersistenceType.MAPPED_SUPERCLASS, feline.getSupertype().getPersistenceType() ); MappedSuperclassType animal = (MappedSuperclassType) feline.getSupertype(); assertEquals( 4, animal.getAttributes().size() ); assertEquals( 2, animal.getDeclaredAttributes().size() ); ensureProperMember(animal.getDeclaredAttributes()); assertTrue( animal.hasVersionAttribute() ); assertEquals( "version", animal.getVersion(Long.class).getName() ); verifyDeclaredVersionNotPresent( animal ); assertEquals( "id", animal.getId(Long.class).getName() ); final SingularAttribute id = animal.getDeclaredId( Long.class ); assertEquals( "id", id.getName() ); assertNotNull( id.getJavaMember() ); assertEquals( Type.PersistenceType.MAPPED_SUPERCLASS, animal.getSupertype().getPersistenceType() ); MappedSuperclassType thing = (MappedSuperclassType) animal.getSupertype(); assertEquals( 2, thing.getAttributes().size() ); assertEquals( 2, thing.getDeclaredAttributes().size() ); ensureProperMember(thing.getDeclaredAttributes()); final SingularAttribute weight = thing.getDeclaredSingularAttribute( "weight", Double.class ); assertEquals( Double.class, weight.getJavaType() ); assertEquals( "version", thing.getVersion(Long.class).getName() ); final SingularAttribute version = thing.getDeclaredVersion( Long.class ); assertEquals( "version", version.getName() ); assertNotNull( version.getJavaMember() ); assertNull( thing.getId( Long.class ) ); assertNull( thing.getSupertype() ); } public void testBackrefAndGenerics() throws Exception { final EntityType parent = factory.getMetamodel().entity( Parent.class ); assertNotNull( parent ); final SetAttribute children = parent.getSet( "children" ); assertNotNull( children ); assertEquals( 1, parent.getPluralAttributes().size() ); assertEquals( 4, parent.getAttributes().size() ); final EntityType child = factory.getMetamodel().entity( Child.class ); assertNotNull( child ); assertEquals( 2, child.getAttributes().size() ); final SingularAttribute attribute = parent.getSingularAttribute( "siblings", Parent.Relatives.class ); final EmbeddableType siblings = (EmbeddableType) attribute.getType(); assertNotNull(siblings); final SetAttribute siblingsCollection = siblings.getSet( "siblings" ); assertNotNull( siblingsCollection ); final Type collectionElement = siblingsCollection.getElementType(); assertNotNull( collectionElement ); assertEquals( collectionElement, child ); } private void ensureProperMember(Set attributes) { //we do not update the set so we are safe @SuppressWarnings( "unchecked" ) final Set> safeAttributes = ( Set> ) attributes; for (Attribute attribute : safeAttributes ) { final String name = attribute.getJavaMember().getName(); assertNotNull( attribute.getJavaMember() ); assertTrue( name.toLowerCase().endsWith( attribute.getName().toLowerCase() ) ); } } private void verifyDeclaredIdNotPresentAndIdPresent(IdentifiableType type) { assertEquals( "id", type.getId(Long.class).getName() ); try { type.getDeclaredId(Long.class); fail("Should not have a declared id"); } catch (IllegalArgumentException e) { //success } } private void verifyDeclaredVersionNotPresent(IdentifiableType type) { try { type.getDeclaredVersion(Long.class); fail("Should not have a declared version"); } catch (IllegalArgumentException e) { //success } } //todo test plural @Override public Class[] getAnnotatedClasses() { return new Class[]{ Fridge.class, FoodItem.class, Person.class, House.class, Dog.class, Cat.class, Cattish.class, Feline.class, Garden.class, Flower.class, JoinedManyToOneOwner.class, Parent.class, Child.class }; } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SecondMetadataTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000150711714611271032754 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class SecondMetadataTest extends TestCase { public void testBaseOfService() throws Exception { EntityManagerFactory emf = factory; assertNotNull( emf.getMetamodel() ); assertNotNull( emf.getMetamodel().entity( DeskWithRawType.class ) ); assertNotNull( emf.getMetamodel().entity( EmployeeWithRawType.class ) ); assertNotNull( emf.getMetamodel().entity( SimpleMedicalHistory.class ) ); assertNotNull( emf.getMetamodel().entity( SimplePerson.class ) ); } @Override public Class[] getAnnotatedClasses() { return new Class[] { DeskWithRawType.class, EmployeeWithRawType.class, SimpleMedicalHistory.class, SimplePerson.class }; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/Child.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000104711714611271032753 0ustar ebourgebourgpackage org.hibernate.ejb.test.metadata; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name="ejb_child") public class Child extends Being { private Integer id; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/Article.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000204211714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.GeneratedValue; import javax.persistence.CascadeType; import javax.persistence.ManyToOne; import javax.persistence.JoinColumn; /** * @author Emmanuel Bernard */ @Entity @Table(name = "ITEM") @org.hibernate.annotations.BatchSize(size = 10) public class Article { private Integer id; private String name; private Article nextArticle; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="poopoo") public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "NEXT_MESSAGE_ID") public Article getNextArticle() { return nextArticle; } public void setNextArticle(Article nextArticle) { this.nextArticle = nextArticle; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/Address.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000154311714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; /** * @author Emmanuel Bernard */ public class Address { private String street; private String city; private String state; private String zip; public Address() { } public Address(String street, String city, String state, String zip) { this.street = street; this.city = city; this.state = state; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } }././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/CounterListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000113011714611271032744 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.PreRemove; /** * @author Emmanuel Bernard */ public class CounterListener { public static int insert; public static int update; public static int delete; @PrePersist public void increaseInsert(Object object) { insert++; } @PreUpdate public void increaseUpdate(Object object) { update++; } @PreRemove public void increaseDelete(Object object) { delete++; } public static void reset() { insert = 0; update = 0; delete = 0; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/XmlAttributeOverrideTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000341611714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class XmlAttributeOverrideTest extends TestCase { public void testAttributeOverriding() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Employee e = new Employee(); e.setId(Long.valueOf(100)); e.setName("Bubba"); e.setHomeAddress(new Address("123 Main St", "New York", "NY", "11111")); e.setMailAddress(new Address("P.O. Box 123", "New York", "NY", "11111")); em.persist(e); em.flush(); em.getTransaction().rollback(); em.close(); } public void testDefaultEventListener() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CounterListener.reset(); Employee e = new Employee(); e.setId(Long.valueOf(100)); e.setName("Bubba"); e.setHomeAddress(new Address("123 Main St", "New York", "NY", "11111")); e.setMailAddress(new Address("P.O. Box 123", "New York", "NY", "11111")); em.persist(e); em.flush(); em.clear(); em.find( Employee.class, e.getId() ).setName( "Bibo" ); em.flush(); em.clear(); em.remove( em.find( Employee.class, e.getId() ) ); em.flush(); em.getTransaction().rollback(); em.close(); assertEquals( 1, CounterListener.insert ); assertEquals( 1, CounterListener.update ); assertEquals( 1, CounterListener.delete ); } public Class[] getAnnotatedClasses() { return new Class[0]; } @Override public String[] getEjb3DD() { return new String[] { "org/hibernate/ejb/test/xml/orm3.xml" }; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/Article.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000205611714611271032754 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.GeneratedValue; import javax.persistence.CascadeType; import javax.persistence.ManyToOne; import javax.persistence.JoinColumn; /** * @author Emmanuel Bernard */ @Entity @Table(name = "ITEM") @org.hibernate.annotations.BatchSize(size = 10) public class Article { private Integer id; private String name; private Article nextArticle; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="poopoo") public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "NEXT_MESSAGE_ID") public Article getNextArticle() { return nextArticle; } public void setNextArticle(Article nextArticle) { this.nextArticle = nextArticle; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/Address.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000155711714611271032761 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; /** * @author Emmanuel Bernard */ public class Address { private String street; private String city; private String state; private String zip; public Address() { } public Address(String street, String city, String state, String zip) { this.street = street; this.city = city; this.state = state; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } }././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/XmlAttributeOverrideTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000170311714611271032752 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class XmlAttributeOverrideTest extends TestCase { public void testAttributeOverriding() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Employee e = new Employee(); e.setId(Long.valueOf(100)); e.setName("Bubba"); e.setHomeAddress(new Address("123 Main St", "New York", "NY", "11111")); e.setMailAddress(new Address("P.O. Box 123", "New York", "NY", "11111")); em.persist(e); em.flush(); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[0]; } @Override public String[] getEjb3DD() { return new String[] { "org/hibernate/ejb/test/xml/sequences/orm3.xml" }; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/Lighter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000025211714611271032750 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; /** * @author Emmanuel Bernard */ public class Lighter { public String name; public String power; } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/Light.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000025011714611271032746 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; /** * @author Emmanuel Bernard */ public class Light { public String name; public String power; } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/Employee.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000320311714611271032747 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Employee { @Id Long id; String name; /* @Embedded @AttributeOverrides({ @AttributeOverride(name = "street", column = @Column(name = "HA_street")), @AttributeOverride(name = "city", column = @Column(name = "HA_city")), @AttributeOverride(name = "state", column = @Column(name = "HA_state")), @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) */ Address homeAddress; /* @Embedded @AttributeOverrides({ @AttributeOverride(name = "street", column = @Column(name = "MA_street")), @AttributeOverride(name = "city", column = @Column(name = "MA_city")), @AttributeOverride(name = "state", column = @Column(name = "MA_state")), @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) */ Address mailAddress; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getHomeAddress() { return homeAddress; } public void setHomeAddress(Address homeAddress) { this.homeAddress = homeAddress; } public Address getMailAddress() { return mailAddress; } public void setMailAddress(Address mailAddress) { this.mailAddress = mailAddress; } }././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/sequences/XmlTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000137011714611271032752 0ustar ebourgebourg//$Id: $ package org.hibernate.ejb.test.xml.sequences; import javax.persistence.EntityManager; import org.hibernate.dialect.Dialect; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class XmlTest extends TestCase { public void testXmlMappingCorrectness() throws Exception { EntityManager em = getOrCreateEntityManager(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[0]; } @Override public boolean appliesTo(Dialect dialect) { return dialect.supportsSequences(); } @Override public String[] getEjb3DD() { return new String[] { "org/hibernate/ejb/test/xml/sequences/orm.xml", "org/hibernate/ejb/test/xml/sequences/orm2.xml", }; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/Lighter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000023611714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; /** * @author Emmanuel Bernard */ public class Lighter { public String name; public String power; } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/Light.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000023411714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; /** * @author Emmanuel Bernard */ public class Light { public String name; public String power; } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/Employee.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000316711714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Employee { @Id Long id; String name; /* @Embedded @AttributeOverrides({ @AttributeOverride(name = "street", column = @Column(name = "HA_street")), @AttributeOverride(name = "city", column = @Column(name = "HA_city")), @AttributeOverride(name = "state", column = @Column(name = "HA_state")), @AttributeOverride(name = "zip", column = @Column(name = "HA_zip")) }) */ Address homeAddress; /* @Embedded @AttributeOverrides({ @AttributeOverride(name = "street", column = @Column(name = "MA_street")), @AttributeOverride(name = "city", column = @Column(name = "MA_city")), @AttributeOverride(name = "state", column = @Column(name = "MA_state")), @AttributeOverride(name = "zip", column = @Column(name = "MA_zip")) }) */ Address mailAddress; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getHomeAddress() { return homeAddress; } public void setHomeAddress(Address homeAddress) { this.homeAddress = homeAddress; } public Address getMailAddress() { return mailAddress; } public void setMailAddress(Address mailAddress) { this.mailAddress = mailAddress; } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/xml/XmlTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000111111714611271032743 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.xml; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class XmlTest extends TestCase { public void testXmlMappingCorrectness() throws Exception { EntityManager em = getOrCreateEntityManager(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[0]; } @Override public String[] getEjb3DD() { return new String[] { "org/hibernate/ejb/test/xml/orm.xml", "org/hibernate/ejb/test/xml/orm2.xml", }; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagingTestCase.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000003330111714611271032751 0ustar ebourgebourg// $Id$ /* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.ejb.test.packaging; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.Archives; import org.jboss.shrinkwrap.api.exporter.ExplodedExporter; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.hibernate.ejb.test.Cat; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; import org.hibernate.ejb.test.Kitten; import org.hibernate.ejb.test.pack.cfgxmlpar.Morito; import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer; import org.hibernate.ejb.test.pack.defaultpar.IncrementListener; import org.hibernate.ejb.test.pack.defaultpar.Lighter; import org.hibernate.ejb.test.pack.defaultpar.Money; import org.hibernate.ejb.test.pack.defaultpar.Mouse; import org.hibernate.ejb.test.pack.defaultpar.OtherIncrementListener; import org.hibernate.ejb.test.pack.defaultpar.Version; import org.hibernate.ejb.test.pack.defaultpar_1_0.ApplicationServer1; import org.hibernate.ejb.test.pack.defaultpar_1_0.IncrementListener1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Money1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Mouse1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Version1; import org.hibernate.ejb.test.pack.excludehbmpar.Caipirinha; import org.hibernate.ejb.test.pack.explodedpar.Carpet; import org.hibernate.ejb.test.pack.explodedpar.Elephant; import org.hibernate.ejb.test.pack.externaljar.Scooter; import org.hibernate.ejb.test.pack.spacepar.Bug; import org.hibernate.ejb.test.pack.various.Airplane; import org.hibernate.ejb.test.pack.various.Seat; /** * @author Hardy Ferentschik */ public abstract class PackagingTestCase extends TestCase { protected static ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); protected static ClassLoader bundleClassLoader; protected static File targetDir; static { // get a URL reference to something we now is part of the classpath (us) URL myUrl = originalClassLoader.getResource( PackagingTestCase.class.getName().replace( '.', '/' ) + ".class" ); File myPath = new File( myUrl.getFile() ); // navigate back to '/target' targetDir = myPath .getParentFile() // target/classes/org/hibernate/ejb/test/packaging .getParentFile() // target/classes/org/hibernate/ejb/test .getParentFile() // target/classes/org/hibernate/ejb .getParentFile() // target/classes/org/hibernate .getParentFile() // target/classes/org .getParentFile() // target/classes/ .getParentFile(); // target File testPackagesDir = new File( targetDir, "bundles" ); try { bundleClassLoader = new URLClassLoader( new URL[] { testPackagesDir.toURL() }, originalClassLoader ); } catch ( MalformedURLException e ) { fail( "Unable to build custom class loader" ); } targetDir = new File( targetDir, "packages" ); targetDir.mkdirs(); } @Override protected void setUp() throws Exception { // add the bundle class loader in order for ShrinkWrap to build the test package Thread.currentThread().setContextClassLoader( bundleClassLoader ); super.setUp(); } @Override public void tearDown() throws Exception { super.tearDown(); // reset the classloader Thread.currentThread().setContextClassLoader( originalClassLoader ); } protected void addPackageToClasspath(File... files) throws MalformedURLException { List urlList = new ArrayList(); for ( File file : files ) { urlList.add( file.toURL() ); } URLClassLoader classLoader = new URLClassLoader( urlList.toArray( new URL[urlList.size()] ), originalClassLoader ); Thread.currentThread().setContextClassLoader( classLoader ); } protected void addPackageToClasspath(URL... urls) throws MalformedURLException { List urlList = new ArrayList(); urlList.addAll( Arrays.asList( urls ) ); URLClassLoader classLoader = new URLClassLoader( urlList.toArray( new URL[urlList.size()] ), originalClassLoader ); Thread.currentThread().setContextClassLoader( classLoader ); } protected File buildDefaultPar() { String fileName = "defaultpar.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( ApplicationServer.class, Lighter.class, Money.class, Mouse.class, OtherIncrementListener.class, IncrementListener.class, Version.class ); ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" ); archive.addResource( "defaultpar/META-INF/orm.xml", path ); path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "defaultpar/META-INF/persistence.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar/Mouse.hbm.xml" ); archive.addResource( "defaultpar/org/hibernate/ejb/test/pack/defaultpar/Mouse.hbm.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar/package-info.class" ); archive.addResource( "org/hibernate/ejb/test/pack/defaultpar/package-info.class", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildDefaultPar_1_0() { String fileName = "defaultpar_1_0.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( ApplicationServer1.class, Lighter1.class, Money1.class, Mouse1.class, IncrementListener1.class, Version1.class ); ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" ); archive.addResource( "defaultpar_1_0/META-INF/orm.xml", path ); path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "defaultpar_1_0/META-INF/persistence.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse.hbm.xml" ); archive.addResource( "defaultpar_1_0/org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse1.hbm.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/defaultpar_1_0/package-info.class" ); archive.addResource( "org/hibernate/ejb/test/pack/defaultpar_1_0/package-info.class", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildExplicitPar() { String fileName = "explicitpar.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Airplane.class, Seat.class, Cat.class, Kitten.class, Distributor.class, Item.class ); ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" ); archive.addResource( "explicitpar/META-INF/orm.xml", path ); path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "explicitpar/META-INF/persistence.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildExplodedPar() { String fileName = "explodedpar"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Elephant.class, Carpet.class ); ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "explodedpar/META-INF/persistence.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml" ); archive.addResource( "explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/explodedpar/package-info.class" ); archive.addResource( "org/hibernate/ejb/test/pack/explodedpar/package-info.class", path ); File testPackage = new File( targetDir, fileName ); archive.as( ExplodedExporter.class ).exportExploded( targetDir ); return testPackage; } protected File buildExcludeHbmPar() { String fileName = "excludehbmpar.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Caipirinha.class ); ArchivePath path = ArchivePaths.create( "META-INF/orm2.xml" ); archive.addResource( "excludehbmpar/META-INF/orm2.xml", path ); path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "excludehbmpar/META-INF/persistence.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/excludehbmpar/Mouse.hbm.xml" ); archive.addResource( "excludehbmpar/org/hibernate/ejb/test/pack/excludehbmpar/Mouse.hbm.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildCfgXmlPar() { String fileName = "cfgxmlpar.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Morito.class, Item.class ); ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "cfgxmlpar/META-INF/persistence.xml", path ); path = ArchivePaths.create( "org/hibernate/ejb/test/pack/cfgxmlpar/hibernate.cfg.xml" ); archive.addResource( "cfgxmlpar/org/hibernate/ejb/test/pack/cfgxmlpar/hibernate.cfg.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildSpacePar() { String fileName = "space par.par"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Bug.class ); ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "space par/META-INF/persistence.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildOverridenPar() { String fileName = "overridenpar.jar"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( org.hibernate.ejb.test.pack.overridenpar.Bug.class ); ArchivePath path = ArchivePaths.create( "META-INF/persistence.xml" ); archive.addResource( "overridenpar/META-INF/persistence.xml", path ); path = ArchivePaths.create( "overridenpar.properties" ); archive.addResource( "overridenpar/overridenpar.properties", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildExternalJar() { String fileName = "externaljar.jar"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addClasses( Scooter.class ); ArchivePath path = ArchivePaths.create( "META-INF/orm.xml" ); archive.addResource( "externaljar/META-INF/orm.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildWar() { String fileName = "war.war"; WebArchive archive = Archives.create( fileName, WebArchive.class ); archive.addClasses( org.hibernate.ejb.test.pack.war.ApplicationServer.class, org.hibernate.ejb.test.pack.war.IncrementListener.class, org.hibernate.ejb.test.pack.war.Lighter.class, org.hibernate.ejb.test.pack.war.Money.class, org.hibernate.ejb.test.pack.war.Mouse.class, org.hibernate.ejb.test.pack.war.OtherIncrementListener.class, org.hibernate.ejb.test.pack.war.Version.class ); ArchivePath path = ArchivePaths.create( "WEB-INF/classes/META-INF/orm.xml" ); archive.addResource( "war/WEB-INF/classes/META-INF/orm.xml", path ); path = ArchivePaths.create( "WEB-INF/classes/META-INF/persistence.xml" ); archive.addResource( "war/WEB-INF/classes/META-INF/persistence.xml", path ); path = ArchivePaths.create( "WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml" ); archive.addResource( "war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xml", path ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildNestedEar(File includeFile) { String fileName = "nestedjar.ear"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addResource( includeFile ); File testPackage = new File( targetDir, fileName ); archive.as( ZipExporter.class ).exportZip( testPackage, true ); return testPackage; } protected File buildNestedEarDir(File includeFile) { String fileName = "nesteddir.ear"; JavaArchive archive = Archives.create( fileName, JavaArchive.class ); archive.addResource( includeFile ); File testPackage = new File( targetDir, fileName ); archive.as( ExplodedExporter.class ).exportExploded( targetDir ); return testPackage; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/JarVisitorTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000003101711714611271032753 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.packaging; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Set; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.MappedSuperclass; import org.hibernate.ejb.packaging.ClassFilter; import org.hibernate.ejb.packaging.Entry; import org.hibernate.ejb.packaging.ExplodedJarVisitor; import org.hibernate.ejb.packaging.FileFilter; import org.hibernate.ejb.packaging.FileZippedJarVisitor; import org.hibernate.ejb.packaging.Filter; import org.hibernate.ejb.packaging.InputStreamZippedJarVisitor; import org.hibernate.ejb.packaging.JarProtocolVisitor; import org.hibernate.ejb.packaging.JarVisitor; import org.hibernate.ejb.packaging.JarVisitorFactory; import org.hibernate.ejb.packaging.PackageFilter; import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer; import org.hibernate.ejb.test.pack.explodedpar.Carpet; /** * @author Emmanuel Bernard * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class JarVisitorTest extends PackagingTestCase { public void testHttp() throws Exception { URL url = JarVisitorFactory.getJarURLFromURLEntry( new URL( "jar:http://www.ibiblio.org/maven/hibernate/jars/hibernate-annotations-3.0beta1.jar!/META-INF/persistence.xml" ), "/META-INF/persistence.xml" ); try { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); } catch ( IOException ie ) { //fail silently return; } JarVisitor visitor = JarVisitorFactory.getVisitor( url, getFilters() ); assertEquals( 0, visitor.getMatchingEntries()[0].size() ); assertEquals( 0, visitor.getMatchingEntries()[1].size() ); assertEquals( 0, visitor.getMatchingEntries()[2].size() ); } public void testInputStreamZippedJar() throws Exception { File defaultPar = buildDefaultPar(); addPackageToClasspath( defaultPar ); Filter[] filters = getFilters(); JarVisitor jarVisitor = new InputStreamZippedJarVisitor( defaultPar.toURL(), filters, "" ); assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() ); Set entries = jarVisitor.getMatchingEntries()[1]; assertEquals( 3, entries.size() ); Entry entry = new Entry( ApplicationServer.class.getName(), null ); assertTrue( entries.contains( entry ) ); entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null ); assertTrue( entries.contains( entry ) ); assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() ); assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } } public void testNestedJarProtocol() throws Exception { File defaultPar = buildDefaultPar(); File nestedEar = buildNestedEar( defaultPar ); File nestedEarDir = buildNestedEarDir( defaultPar ); addPackageToClasspath( nestedEar ); String jarFileName = nestedEar.toURL().toExternalForm() + "!/defaultpar.par"; Filter[] filters = getFilters(); JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" ); //TODO should we fix the name here to reach defaultpar rather than nestedjar ?? //assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() ); Set entries = jarVisitor.getMatchingEntries()[1]; assertEquals( 3, entries.size() ); Entry entry = new Entry( ApplicationServer.class.getName(), null ); assertTrue( entries.contains( entry ) ); entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null ); assertTrue( entries.contains( entry ) ); assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() ); assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } jarFileName = nestedEarDir.toURL().toExternalForm() + "!/defaultpar.par"; //JarVisitor jarVisitor = new ZippedJarVisitor( jarFileName, true, true ); filters = getFilters(); jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" ); //TODO should we fix the name here to reach defaultpar rather than nestedjar ?? //assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() ); entries = jarVisitor.getMatchingEntries()[1]; assertEquals( 3, entries.size() ); entry = new Entry( ApplicationServer.class.getName(), null ); assertTrue( entries.contains( entry ) ); entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null ); assertTrue( entries.contains( entry ) ); assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() ); assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } } public void testJarProtocol() throws Exception { File war = buildWar(); addPackageToClasspath( war ); String jarFileName = war.toURL().toExternalForm() + "!/WEB-INF/classes"; Filter[] filters = getFilters(); JarVisitor jarVisitor = new JarProtocolVisitor( new URL( jarFileName ), filters, "" ); assertEquals( "war", jarVisitor.getUnqualifiedJarName() ); Set entries = jarVisitor.getMatchingEntries()[1]; assertEquals( 3, entries.size() ); Entry entry = new Entry( org.hibernate.ejb.test.pack.war.ApplicationServer.class.getName(), null ); assertTrue( entries.contains( entry ) ); entry = new Entry( org.hibernate.ejb.test.pack.war.Version.class.getName(), null ); assertTrue( entries.contains( entry ) ); assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() ); assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } } public void testZippedJar() throws Exception { File defaultPar = buildDefaultPar(); addPackageToClasspath( defaultPar ); Filter[] filters = getFilters(); JarVisitor jarVisitor = new FileZippedJarVisitor( defaultPar.toURL(), filters, "" ); assertEquals( "defaultpar", jarVisitor.getUnqualifiedJarName() ); Set entries = jarVisitor.getMatchingEntries()[1]; assertEquals( 3, entries.size() ); Entry entry = new Entry( ApplicationServer.class.getName(), null ); assertTrue( entries.contains( entry ) ); entry = new Entry( org.hibernate.ejb.test.pack.defaultpar.Version.class.getName(), null ); assertTrue( entries.contains( entry ) ); assertNull( ( ( Entry ) entries.iterator().next() ).getInputStream() ); assertEquals( 2, jarVisitor.getMatchingEntries()[2].size() ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } } public void testExplodedJar() throws Exception { File explodedPar = buildExplodedPar(); addPackageToClasspath( explodedPar ); Filter[] filters = getFilters(); String dirPath = explodedPar.toURL().toExternalForm(); // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash? if ( dirPath.endsWith( "/" ) ) { dirPath = dirPath.substring( 0, dirPath.length() - 1 ); } JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, filters ); assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() ); Set[] entries = jarVisitor.getMatchingEntries(); assertEquals( 1, entries[1].size() ); assertEquals( 1, entries[0].size() ); assertEquals( 1, entries[2].size() ); Entry entry = new Entry( Carpet.class.getName(), null ); assertTrue( entries[1].contains( entry ) ); for ( Entry localEntry : ( Set ) jarVisitor.getMatchingEntries()[2] ) { assertNotNull( localEntry.getInputStream() ); localEntry.getInputStream().close(); } } public void testJarVisitorFactory() throws Exception{ //setting URL to accept vfs based protocol URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { public URLStreamHandler createURLStreamHandler(String protocol) { if("vfszip".equals(protocol) || "vfsfile".equals(protocol) ) return new URLStreamHandler() { protected URLConnection openConnection(URL u) throws IOException { return null; } }; return null; } }); URL jarUrl = new URL ("file:./target/packages/defaultpar.par"); JarVisitor jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null); assertEquals(FileZippedJarVisitor.class.getName(), jarVisitor.getClass().getName()); jarUrl = new URL ("file:./target/packages/explodedpar"); jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null); assertEquals(ExplodedJarVisitor.class.getName(), jarVisitor.getClass().getName()); jarUrl = new URL ("vfszip:./target/packages/defaultpar.par"); jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null); assertEquals(FileZippedJarVisitor.class.getName(), jarVisitor.getClass().getName()); jarUrl = new URL ("vfsfile:./target/packages/explodedpar"); jarVisitor = JarVisitorFactory.getVisitor(jarUrl, getFilters(), null); assertEquals(ExplodedJarVisitor.class.getName(), jarVisitor.getClass().getName()); } /** * EJB-230 */ public void testDuplicateFilterExplodedJarExpected() throws Exception { // File explodedPar = buildExplodedPar(); // addPackageToClasspath( explodedPar ); // // Filter[] filters = getFilters(); // Filter[] dupeFilters = new Filter[filters.length * 2]; // int index = 0; // for ( Filter filter : filters ) { // dupeFilters[index++] = filter; // } // filters = getFilters(); // for ( Filter filter : filters ) { // dupeFilters[index++] = filter; // } // String dirPath = explodedPar.toURL().toExternalForm(); // // TODO - shouldn't ExplodedJarVisitor take care of a trailing slash? // if ( dirPath.endsWith( "/" ) ) { // dirPath = dirPath.substring( 0, dirPath.length() - 1 ); // } // JarVisitor jarVisitor = new ExplodedJarVisitor( dirPath, dupeFilters ); // assertEquals( "explodedpar", jarVisitor.getUnqualifiedJarName() ); // Set[] entries = jarVisitor.getMatchingEntries(); // assertEquals( 1, entries[1].size() ); // assertEquals( 1, entries[0].size() ); // assertEquals( 1, entries[2].size() ); // for ( Entry entry : ( Set ) entries[2] ) { // InputStream is = entry.getInputStream(); // if ( is != null ) { // assertTrue( 0 < is.available() ); // is.close(); // } // } // for ( Entry entry : ( Set ) entries[5] ) { // InputStream is = entry.getInputStream(); // if ( is != null ) { // assertTrue( 0 < is.available() ); // is.close(); // } // } // // Entry entry = new Entry( Carpet.class.getName(), null ); // assertTrue( entries[1].contains( entry ) ); } private Filter[] getFilters() { return new Filter[] { new PackageFilter( false, null ) { public boolean accept(String javaElementName) { return true; } }, new ClassFilter( false, new Class[] { Entity.class, MappedSuperclass.class, Embeddable.class } ) { public boolean accept(String javaElementName) { return true; } }, new FileFilter( true ) { public boolean accept(String javaElementName) { return javaElementName.endsWith( "hbm.xml" ) || javaElementName.endsWith( "META-INF/orm.xml" ); } } }; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/Pasta.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000071711714611271032756 0ustar ebourgebourgpackage org.hibernate.ejb.test.packaging; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Pasta { @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id;} private Integer id; public String getType() { return type; } public void setType(String type) { this.type = type;} private String type; } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/CustomScanner.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000257211714611271032757 0ustar ebourgebourgpackage org.hibernate.ejb.test.packaging; import java.lang.annotation.Annotation; import java.net.URL; import java.util.Set; import org.hibernate.ejb.packaging.NamedInputStream; import org.hibernate.ejb.packaging.NativeScanner; import org.hibernate.ejb.packaging.Scanner; /** * @author Emmanuel Bernard */ public class CustomScanner implements Scanner { public static boolean isUsed = false; private Scanner scanner = new NativeScanner(); public static boolean isUsed() { return isUsed; } public static void resetUsed() { isUsed = false; } public Set getPackagesInJar(URL jartoScan, Set> annotationsToLookFor) { isUsed = true; return scanner.getPackagesInJar( jartoScan, annotationsToLookFor ); } public Set> getClassesInJar(URL jartoScan, Set> annotationsToLookFor) { isUsed = true; return scanner.getClassesInJar( jartoScan, annotationsToLookFor ); } public Set getFilesInJar(URL jartoScan, Set filePatterns) { isUsed = true; return scanner.getFilesInJar( jartoScan, filePatterns ); } public Set getFilesInClasspath(Set filePatterns) { isUsed = true; return scanner.getFilesInClasspath( filePatterns ); } public String getUnqualifiedJarName(URL jarUrl) { isUsed = true; return scanner.getUnqualifiedJarName( jarUrl ); } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/ScannerTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000757411714611271032766 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.packaging; import java.io.File; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.EntityManagerFactory; import javax.persistence.MappedSuperclass; import javax.persistence.Persistence; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.packaging.NamedInputStream; import org.hibernate.ejb.packaging.NativeScanner; import org.hibernate.ejb.packaging.Scanner; import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer; /** * @author Emmanuel Bernard * @author Hardy Ferentschik */ public class ScannerTest extends PackagingTestCase { public void testNativeScanner() throws Exception { File defaultPar = buildDefaultPar(); addPackageToClasspath( defaultPar ); Scanner scanner = new NativeScanner(); assertEquals( "defaultpar", scanner.getUnqualifiedJarName( defaultPar.toURL() ) ); Set> annotationsToLookFor = new HashSet>( 3 ); annotationsToLookFor.add( Entity.class ); annotationsToLookFor.add( MappedSuperclass.class ); annotationsToLookFor.add( Embeddable.class ); final Set> classes = scanner.getClassesInJar( defaultPar.toURL(), annotationsToLookFor ); assertEquals( 3, classes.size() ); assertTrue( classes.contains( ApplicationServer.class ) ); assertTrue( classes.contains( org.hibernate.ejb.test.pack.defaultpar.Version.class ) ); Set filePatterns = new HashSet( 2 ); filePatterns.add( "**/*.hbm.xml" ); filePatterns.add( "META-INF/orm.xml" ); final Set files = scanner.getFilesInJar( defaultPar.toURL(), filePatterns ); assertEquals( 2, files.size() ); for ( NamedInputStream file : files ) { assertNotNull( file.getStream() ); file.getStream().close(); } } public void testCustomScanner() throws Exception { File defaultPar = buildDefaultPar(); File explicitPar = buildExplicitPar(); addPackageToClasspath( defaultPar, explicitPar ); EntityManagerFactory emf; CustomScanner.resetUsed(); final HashMap integration = new HashMap(); emf = Persistence.createEntityManagerFactory( "defaultpar", integration ); assertTrue( ! CustomScanner.isUsed() ); emf.close(); CustomScanner.resetUsed(); emf = Persistence.createEntityManagerFactory( "manager1", integration ); assertTrue( CustomScanner.isUsed() ); emf.close(); CustomScanner.resetUsed(); integration.put( AvailableSettings.SCANNER, new CustomScanner() ); emf = Persistence.createEntityManagerFactory( "defaultpar", integration ); assertTrue( CustomScanner.isUsed() ); emf.close(); CustomScanner.resetUsed(); emf = Persistence.createEntityManagerFactory( "defaultpar", null ); assertTrue( ! CustomScanner.isUsed() ); emf.close(); } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/packaging/PackagedEntityManagerTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000003616311714611271032762 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.packaging; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceException; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.HibernateEntityManagerFactory; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; import org.hibernate.ejb.test.pack.cfgxmlpar.Morito; import org.hibernate.ejb.test.pack.defaultpar.ApplicationServer; import org.hibernate.ejb.test.pack.defaultpar.IncrementListener; import org.hibernate.ejb.test.pack.defaultpar.Lighter; import org.hibernate.ejb.test.pack.defaultpar.Money; import org.hibernate.ejb.test.pack.defaultpar.Mouse; import org.hibernate.ejb.test.pack.defaultpar.OtherIncrementListener; import org.hibernate.ejb.test.pack.defaultpar.Version; import org.hibernate.ejb.test.pack.defaultpar_1_0.ApplicationServer1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Mouse1; import org.hibernate.ejb.test.pack.defaultpar_1_0.Version1; import org.hibernate.ejb.test.pack.excludehbmpar.Caipirinha; import org.hibernate.ejb.test.pack.explodedpar.Carpet; import org.hibernate.ejb.test.pack.explodedpar.Elephant; import org.hibernate.ejb.test.pack.externaljar.Scooter; import org.hibernate.ejb.test.pack.spacepar.Bug; import org.hibernate.ejb.test.pack.various.Airplane; import org.hibernate.ejb.test.pack.various.Seat; import org.hibernate.engine.SessionImplementor; import org.hibernate.event.EventListeners; import org.hibernate.stat.Statistics; import org.hibernate.util.ConfigHelper; /** * In this test we verify that it is possible to bootstrap Hibernate/JPA from * various bundles (war, par, ...) using {@code Persistence.createEntityManagerFactory()} *

* Each test will before its run build the required bundle and place them into the classpath. * * @author Gavin King * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class PackagedEntityManagerTest extends PackagingTestCase { public void testDefaultPar() throws Exception { File testPackage = buildDefaultPar(); addPackageToClasspath( testPackage ); // run the test EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() ); EntityManager em = emf.createEntityManager(); ApplicationServer as = new ApplicationServer(); as.setName( "JBoss AS" ); Version v = new Version(); v.setMajor( 4 ); v.setMinor( 0 ); v.setMicro( 3 ); as.setVersion( v ); Mouse mouse = new Mouse(); mouse.setName( "mickey" ); em.getTransaction().begin(); em.persist( as ); em.persist( mouse ); assertEquals( 1, em.createNamedQuery( "allMouse" ).getResultList().size() ); Lighter lighter = new Lighter(); lighter.name = "main"; lighter.power = " 250 W"; em.persist( lighter ); em.flush(); em.remove( lighter ); em.remove( mouse ); assertNotNull( as.getId() ); em.remove( as ); em.getTransaction().commit(); em.close(); emf.close(); } public void testDefaultParForPersistence_1_0() throws Exception { File testPackage = buildDefaultPar_1_0(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar_1_0", new HashMap() ); EntityManager em = emf.createEntityManager(); ApplicationServer1 as = new ApplicationServer1(); as.setName( "JBoss AS" ); Version1 v = new Version1(); v.setMajor( 4 ); v.setMinor( 0 ); v.setMicro( 3 ); as.setVersion( v ); Mouse1 mouse = new Mouse1(); mouse.setName( "mickey" ); em.getTransaction().begin(); em.persist( as ); em.persist( mouse ); assertEquals( 1, em.createNamedQuery( "allMouse_1_0" ).getResultList().size() ); Lighter1 lighter = new Lighter1(); lighter.name = "main"; lighter.power = " 250 W"; em.persist( lighter ); em.flush(); em.remove( lighter ); em.remove( mouse ); assertNotNull( as.getId() ); em.remove( as ); em.getTransaction().commit(); em.close(); emf.close(); } public void testListenersDefaultPar() throws Exception { File testPackage = buildDefaultPar(); addPackageToClasspath( testPackage ); IncrementListener.reset(); OtherIncrementListener.reset(); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "defaultpar", new HashMap() ); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); ApplicationServer as = new ApplicationServer(); as.setName( "JBoss AS" ); Version v = new Version(); v.setMajor( 4 ); v.setMinor( 0 ); v.setMicro( 3 ); as.setVersion( v ); em.persist( as ); em.flush(); assertEquals( "Failure in default listeners", 1, IncrementListener.getIncrement() ); assertEquals( "Failure in XML overriden listeners", 1, OtherIncrementListener.getIncrement() ); Mouse mouse = new Mouse(); mouse.setName( "mickey" ); em.persist( mouse ); em.flush(); assertEquals( "Failure in @ExcludeDefaultListeners", 1, IncrementListener.getIncrement() ); assertEquals( 1, OtherIncrementListener.getIncrement() ); Money money = new Money(); em.persist( money ); em.flush(); assertEquals( "Failure in @ExcludeDefaultListeners", 2, IncrementListener.getIncrement() ); assertEquals( 1, OtherIncrementListener.getIncrement() ); em.getTransaction().rollback(); em.close(); emf.close(); } public void testExplodedPar() throws Exception { File testPackage = buildExplodedPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "explodedpar", new HashMap() ); EntityManager em = emf.createEntityManager(); org.hibernate.ejb.test.pack.explodedpar.Carpet carpet = new Carpet(); Elephant el = new Elephant(); el.setName( "Dumbo" ); carpet.setCountry( "Turkey" ); em.getTransaction().begin(); em.persist( carpet ); em.persist( el ); assertEquals( 1, em.createNamedQuery( "allCarpet" ).getResultList().size() ); assertNotNull( carpet.getId() ); em.remove( carpet ); em.getTransaction().commit(); em.close(); emf.close(); } public void testExcludeHbmPar() throws Exception { File testPackage = buildExcludeHbmPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = null; try { emf = Persistence.createEntityManagerFactory( "excludehbmpar", new HashMap() ); } catch ( PersistenceException e ) { Throwable nested = e.getCause(); if ( nested == null ) { throw e; } nested = nested.getCause(); if ( nested == null ) { throw e; } if ( !( nested instanceof ClassNotFoundException ) ) { throw e; } fail( "Try to process hbm file: " + e.getMessage() ); } EntityManager em = emf.createEntityManager(); Caipirinha s = new Caipirinha( "Strong" ); em.getTransaction().begin(); em.persist( s ); em.getTransaction().commit(); em.getTransaction().begin(); s = em.find( Caipirinha.class, s.getId() ); em.remove( s ); em.getTransaction().commit(); em.close(); emf.close(); } public void testCfgXmlPar() throws Exception { File testPackage = buildCfgXmlPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "cfgxmlpar", new HashMap() ); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setDescr( "Blah" ); i.setName( "factory" ); Morito m = new Morito(); m.setPower( "SuperStrong" ); em.getTransaction().begin(); em.persist( i ); em.persist( m ); em.getTransaction().commit(); em.getTransaction().begin(); i = em.find( Item.class, i.getName() ); em.remove( i ); em.remove( em.find( Morito.class, m.getId() ) ); em.getTransaction().commit(); em.close(); emf.close(); } public void testSpacePar() throws Exception { File testPackage = buildSpacePar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "space par", new HashMap() ); EntityManager em = emf.createEntityManager(); Bug bug = new Bug(); bug.setSubject( "Spaces in directory name don't play well on Windows" ); em.getTransaction().begin(); em.persist( bug ); em.flush(); em.remove( bug ); assertNotNull( bug.getId() ); em.getTransaction().rollback(); em.close(); emf.close(); } public void testOverridenPar() throws Exception { File testPackage = buildOverridenPar(); addPackageToClasspath( testPackage ); HashMap properties = new HashMap(); properties.put( AvailableSettings.JTA_DATASOURCE, null ); Properties p = new Properties(); p.load( ConfigHelper.getResourceAsStream( "/overridenpar.properties" ) ); properties.putAll( p ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "overridenpar", properties ); EntityManager em = emf.createEntityManager(); org.hibernate.ejb.test.pack.overridenpar.Bug bug = new org.hibernate.ejb.test.pack.overridenpar.Bug(); bug.setSubject( "Allow DS overriding" ); em.getTransaction().begin(); em.persist( bug ); em.flush(); em.remove( bug ); assertNotNull( bug.getId() ); em.getTransaction().rollback(); em.close(); emf.close(); } public void testListeners() throws Exception { File testPackage = buildExplicitPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() ); EntityManager em = emf.createEntityManager(); EventListeners eventListeners = em.unwrap( SessionImplementor.class ).getListeners(); assertEquals( "Explicit pre-insert event through hibernate.ejb.event.pre-insert does not work", eventListeners.getPreInsertEventListeners().length, eventListeners.getPreUpdateEventListeners().length + 1 ); em.close(); emf.close(); } public void testExtendedEntityManager() throws Exception { File testPackage = buildExplicitPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() ); EntityManager em = emf.createEntityManager(); Item item = new Item( "Mouse", "Micro$oft mouse" ); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); em.getTransaction().begin(); Item item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult(); assertNotNull( item1 ); assertSame( item, item1 ); item.setDescr( "Micro$oft wireless mouse" ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); em.getTransaction().begin(); item1 = em.find( Item.class, "Mouse" ); assertSame( item, item1 ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); item1 = em.find( Item.class, "Mouse" ); assertSame( item, item1 ); assertTrue( em.contains( item ) ); item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult(); assertNotNull( item1 ); assertSame( item, item1 ); assertTrue( em.contains( item ) ); em.getTransaction().begin(); assertTrue( em.contains( item ) ); em.remove( item ); em.remove( item ); //second remove should be a no-op em.getTransaction().commit(); em.close(); emf.close(); } public void testConfiguration() throws Exception { File testPackage = buildExplicitPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() ); Item item = new Item( "Mouse", "Micro$oft mouse" ); Distributor res = new Distributor(); res.setName( "Bruce" ); item.setDistributors( new HashSet() ); item.getDistributors().add( res ); Statistics stats = ( ( HibernateEntityManagerFactory ) emf ).getSessionFactory().getStatistics(); stats.clear(); stats.setStatisticsEnabled( true ); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist( res ); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.close(); assertEquals( 1, stats.getSecondLevelCachePutCount() ); assertEquals( 0, stats.getSecondLevelCacheHitCount() ); em = emf.createEntityManager(); em.getTransaction().begin(); Item second = em.find( Item.class, item.getName() ); assertEquals( 1, second.getDistributors().size() ); assertEquals( 1, stats.getSecondLevelCacheHitCount() ); em.getTransaction().commit(); em.close(); em = emf.createEntityManager(); em.getTransaction().begin(); second = em.find( Item.class, item.getName() ); assertEquals( 1, second.getDistributors().size() ); assertEquals( 3, stats.getSecondLevelCacheHitCount() ); for ( Distributor distro : second.getDistributors() ) { em.remove( distro ); } em.remove( second ); em.getTransaction().commit(); em.close(); stats.clear(); stats.setStatisticsEnabled( false ); emf.close(); } public void testExternalJar() throws Exception { File externalJar = buildExternalJar(); File testPackage = buildExplicitPar(); addPackageToClasspath( testPackage, externalJar ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() ); EntityManager em = emf.createEntityManager(); Scooter s = new Scooter(); s.setModel( "Abadah" ); s.setSpeed( 85l ); em.getTransaction().begin(); em.persist( s ); em.getTransaction().commit(); em.close(); em = emf.createEntityManager(); em.getTransaction().begin(); s = em.find( Scooter.class, s.getModel() ); assertEquals( new Long( 85 ), s.getSpeed() ); em.remove( s ); em.getTransaction().commit(); em.close(); emf.close(); } public void testORMFileOnMainAndExplicitJars() throws Exception { File testPackage = buildExplicitPar(); addPackageToClasspath( testPackage ); EntityManagerFactory emf = Persistence.createEntityManagerFactory( "manager1", new HashMap() ); EntityManager em = emf.createEntityManager(); Seat seat = new Seat(); seat.setNumber( "3B" ); Airplane plane = new Airplane(); plane.setSerialNumber( "75924418409052355" ); em.getTransaction().begin(); em.persist( seat ); em.persist( plane ); em.flush(); em.getTransaction().rollback(); em.close(); emf.close(); } }././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/LastUpdateListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000054411714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import java.util.Date; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; /** * @author Emmanuel Bernard */ public class LastUpdateListener { @PreUpdate @PrePersist public void setLastUpdate(Cat o) { o.setLastUpdate( new Date() ); o.setManualVersion( o.getManualVersion() + 1 ); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/instrument/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000023400000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/instrument/InterceptFieldClassFileTransformerTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000247111714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.instrument; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; /** * @author Emmanuel Bernard * @author Hardy Ferentschik */ public class InterceptFieldClassFileTransformerTest extends TestCase { /** * Tests that class file enhancement works. * * @throws Exception in case the test fails. */ public void testEnhancement() throws Exception { List entities = new ArrayList(); entities.add( "org.hibernate.ejb.test.instrument.Simple" ); // sanity check that the class is unmodified and does not contain getFieldHandler() try { org.hibernate.ejb.test.instrument.Simple.class.getDeclaredMethod( "getFieldHandler" ); fail(); } catch ( NoSuchMethodException nsme ) { // success } // use custom class loader which enhances the class InstrumentedClassLoader cl = new InstrumentedClassLoader( Thread.currentThread().getContextClassLoader() ); cl.setEntities( entities ); Class clazz = cl.loadClass( entities.get( 0 ) ); // javassist is our default byte code enhancer. Enhancing will eg add the method getFieldHandler() // see org.hibernate.bytecode.javassist.FieldTransformer Method method = clazz.getDeclaredMethod( "getFieldHandler" ); assertNotNull( method ); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/instrument/Simple.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000035711714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.instrument; /** * @author Emmanuel Bernard */ public class Simple { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/instrument/InstrumentedClassLoader.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000425611714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.instrument; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.IllegalClassFormatException; import java.util.List; import org.hibernate.ejb.instrument.InterceptFieldClassFileTransformer; /** * @author Emmanuel Bernard */ public class InstrumentedClassLoader extends ClassLoader { private List entities; public InstrumentedClassLoader(ClassLoader parent) { super( parent ); } @Override public Class loadClass(String name) throws ClassNotFoundException { if ( name != null && name.startsWith( "java.lang." ) ) return getParent().loadClass( name ); Class c = findLoadedClass( name ); if ( c != null ) return c; InputStream is = this.getResourceAsStream( name.replace( ".", "/" ) + ".class" ); if ( is == null ) throw new ClassNotFoundException( name ); byte[] buffer = new byte[409600]; byte[] originalClass = new byte[0]; int r = 0; try { r = is.read( buffer ); } catch (IOException e) { throw new ClassNotFoundException( name + " not found", e ); } while ( r >= buffer.length ) { byte[] temp = new byte[ originalClass.length + buffer.length ]; System.arraycopy( originalClass, 0, temp, 0, originalClass.length ); System.arraycopy( buffer, 0, temp, originalClass.length, buffer.length ); originalClass = temp; } if ( r != -1 ) { byte[] temp = new byte[ originalClass.length + r ]; System.arraycopy( originalClass, 0, temp, 0, originalClass.length ); System.arraycopy( buffer, 0, temp, originalClass.length, r ); originalClass = temp; } try { is.close(); } catch (IOException e) { throw new ClassNotFoundException( name + " not found", e ); } InterceptFieldClassFileTransformer t = new InterceptFieldClassFileTransformer( entities ); byte[] transformed = new byte[0]; try { transformed = t.transform( getParent(), name, null, null, originalClass ); } catch (IllegalClassFormatException e) { throw new ClassNotFoundException( name + " not found", e ); } return defineClass( name, transformed, 0, transformed.length ); } public void setEntities(List entities) { this.entities = entities; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/Book.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000107011714611271032747 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Book extends CopyrightableContent { private Long id; private String name; public Book() { super(); } public Book(Author a) { super(a); } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/GetIdentifierTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000330011714611271032745 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import javax.persistence.EntityManager; import javax.persistence.Persistence; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class GetIdentifierTest extends TestCase { public void testSimpleId() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Book book = new Book(); em.persist( book ); em.flush(); assertEquals( book.getId(), em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( book ) ); em.getTransaction().rollback(); em.close(); } public void testEmbeddedId() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Umbrella umbrella = new Umbrella(); umbrella.setId( new Umbrella.PK() ); umbrella.getId().setBrand( "Burberry" ); umbrella.getId().setModel( "Red Hat" ); em.persist( umbrella ); em.flush(); assertEquals( umbrella.getId(), em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( umbrella ) ); em.getTransaction().rollback(); em.close(); } public void testIdClass() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Sickness sick = new Sickness(); sick.setClassification( "H1N1" ); sick.setType("Flu"); em.persist( sick ); em.flush(); Sickness.PK id = new Sickness.PK(); id.setClassification( sick.getClassification() ); id.setType( sick.getType() ); assertEquals( id, em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier( sick ) ); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Book.class, Umbrella.class, Sickness.class, Author.class }; } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/CopyrightableContent.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000110411714611271032745 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; /** * @author Emmanuel Bernard */ @MappedSuperclass public abstract class CopyrightableContent { private Author author; public CopyrightableContent() { } public CopyrightableContent(Author author) { this.author = author; } @ManyToOne(fetch = FetchType.LAZY) private Author getAuthor() { return author; } private void setAuthor(Author author) { this.author = author; } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/PersistenceUtilHelperTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000667011714611271032762 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.util; import javax.persistence.spi.LoadState; import org.hibernate.ejb.util.PersistenceUtilHelper; /** * Tests for HHH-5094 and HHH-5334 * * @author Hardy Ferentschik */ public class PersistenceUtilHelperTest extends junit.framework.TestCase { private final PersistenceUtilHelper.MetadataCache cache = new PersistenceUtilHelper.MetadataCache(); public static class FieldAccessBean extends FieldAccessBeanBase { protected String protectedAccessProperty; private String privateAccessProperty; } public static class FieldAccessBeanBase { public String publicAccessProperty; } public static class MethodAccessBean extends MethodAccessBeanBase { private String protectedAccessProperty; private String privateAccessProperty; protected String getProtectedAccessPropertyValue() { return protectedAccessProperty; } private String getPrivateAccessPropertyValue() { return privateAccessProperty; } } public static class MethodAccessBeanBase { private String publicAccessProperty; public String getPublicAccessPropertyValue() { return publicAccessProperty; } } public void testIsLoadedWithReferencePublicField() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new FieldAccessBean(), "publicAccessProperty", cache ) ); } public void testIsLoadedWithReferencePublicMethod() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new MethodAccessBean(), "publicAccessPropertyValue", cache ) ); } public void testIsLoadedWithReferenceProtectedField() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new FieldAccessBean(), "protectedAccessProperty", cache ) ); } public void testIsLoadedWithReferenceProtectedMethod() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new MethodAccessBean(), "protectedAccessPropertyValue", cache ) ); } public void testIsLoadedWithReferencePrivateField() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new FieldAccessBean(), "privateAccessProperty", cache ) ); } public void testIsLoadedWithReferencePrivateMethod() { assertEquals( LoadState.UNKNOWN, PersistenceUtilHelper.isLoadedWithReference( new MethodAccessBean(), "privateAccessPropertyValue", cache ) ); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/Umbrella.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000253011714611271032751 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.EmbeddedId; /** * @author Emmanuel Bernard */ @Entity public class Umbrella { private PK id; private int size; @EmbeddedId public PK getId() { return id; } public void setId(PK id) { this.id = id; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public static class PK implements Serializable { private String model; private String brand; public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } PK pk = ( PK ) o; if ( brand != null ? !brand.equals( pk.brand ) : pk.brand != null ) { return false; } if ( model != null ? !model.equals( pk.model ) : pk.model != null ) { return false; } return true; } @Override public int hashCode() { int result = model != null ? model.hashCode() : 0; result = 31 * result + ( brand != null ? brand.hashCode() : 0 ); return result; } } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/IsLoadedTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000161411714611271032753 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class IsLoadedTest extends TestCase { public void testIsLoadedOnPrivateSuperclassProperty() { EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Author a = new Author(); Book book = new Book(a); em.persist( a ); em.persist( book ); em.flush(); em.clear(); book = em.find( Book.class, book.getId() ); assertTrue( em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded( book ) ); assertFalse( em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded( book, "author" ) ); em.getTransaction().rollback(); em.close(); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { Author.class, Book.class, CopyrightableContent.class }; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/Sickness.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000354411714611271032757 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import java.util.Date; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Temporal; import javax.persistence.Id; import javax.persistence.IdClass; /** * @author Emmanuel Bernard */ @Entity @IdClass(Sickness.PK.class) public class Sickness { private Date beginTime; private String type; private String classification; @Id public String getType() { return type; } public void setType(String type) { this.type = type; } @Id public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } @Temporal(javax.persistence.TemporalType.DATE) public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public static class PK implements Serializable { private String type; private String classification; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } PK pk = ( PK ) o; if ( classification != null ? !classification.equals( pk.classification ) : pk.classification != null ) { return false; } if ( type != null ? !type.equals( pk.type ) : pk.type != null ) { return false; } return true; } @Override public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + ( classification != null ? classification.hashCode() : 0 ); return result; } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/util/Author.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000062711714611271032756 0ustar ebourgebourgpackage org.hibernate.ejb.test.util; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name="tbl_Author") public class Author { @Id @GeneratedValue private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/beanvalidation/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/beanvalidation/BeanValidationTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000323711714611271032756 0ustar ebourgebourgpackage org.hibernate.ejb.test.beanvalidation; import java.math.BigDecimal; import javax.persistence.EntityManager; import javax.persistence.RollbackException; import javax.validation.ConstraintViolationException; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class BeanValidationTest extends TestCase { public void testBeanValidationIntegrationOnFlush() { CupHolder ch = new CupHolder(); ch.setRadius( new BigDecimal( "12" ) ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( ch ); em.flush(); fail("invalid object should not be persisted"); } catch ( ConstraintViolationException e ) { assertEquals( 1, e.getConstraintViolations().size() ); } assertTrue( "A constraint violation exception should mark the transaction for rollback", em.getTransaction().getRollbackOnly() ); em.getTransaction().rollback(); em.close(); } public void testBeanValidationIntegrationOnCommit() { CupHolder ch = new CupHolder(); ch.setRadius( new BigDecimal( "9" ) ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( ch ); em.flush(); try { ch.setRadius( new BigDecimal( "12" ) ); em.getTransaction().commit(); fail("invalid object should not be persisted"); } catch ( RollbackException e ) { final Throwable cve = e.getCause(); assertTrue( cve instanceof ConstraintViolationException ); assertEquals( 1, ( (ConstraintViolationException) cve ).getConstraintViolations().size() ); } em.close(); } @Override public Class[] getAnnotatedClasses() { return new Class[] { CupHolder.class }; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/beanvalidation/CupHolder.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000142011714611271032746 0ustar ebourgebourgpackage org.hibernate.ejb.test.beanvalidation; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; /** * @author Emmanuel Bernard */ @Entity public class CupHolder { @Id @GeneratedValue //@GeneratedValue(strategy = GenerationType.SEQUENCE) private Integer id; private BigDecimal radius; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Max( value = 10, message = "Radius way out") @NotNull public BigDecimal getRadius() { return radius; } public void setRadius(BigDecimal radius) { this.radius = radius; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Cat.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000753211714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PostUpdate; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Emmanuel Bernard */ @SuppressWarnings({"unchecked", "serial"}) @Entity @EntityListeners( LastUpdateListener.class ) public class Cat implements Serializable { private static final Logger log = LoggerFactory.getLogger(Cat.class); private static final List ids = new ArrayList(); // used for assertions public static int postVersion = 0; // used for assertions private Integer id; private String name; private Date dateOfBirth; private int age; private long length; private Date lastUpdate; private int manualVersion = 0; private List kittens; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public int getManualVersion() { return manualVersion; } public void setManualVersion(int manualVersion) { this.manualVersion = manualVersion; } @Transient public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Basic @Temporal( TemporalType.TIMESTAMP ) public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } @PostUpdate private void someLateUpdateWorking() { log.debug("PostUpdate for: {}", this.toString()); postVersion++; } @PostLoad public void calculateAge() { Calendar birth = new GregorianCalendar(); birth.setTime( dateOfBirth ); Calendar now = new GregorianCalendar(); now.setTime( new Date() ); int adjust = 0; if ( now.get( Calendar.DAY_OF_YEAR ) - birth.get( Calendar.DAY_OF_YEAR ) < 0 ) { adjust = -1; } age = now.get( Calendar.YEAR ) - birth.get( Calendar.YEAR ) + adjust; } @PostPersist public synchronized void addIdsToList() { ids.add( getId() ); } public static synchronized List getIdList() { return Collections.unmodifiableList( ids ); } public long getLength() { return length; } public void setLength(long length) { this.length = length; } @OneToMany(cascade = CascadeType.ALL) public List getKittens() { return kittens; } public void setKittens(List kittens) { this.kittens = kittens; } /** * Constructs a String with all attributes * in name = value format. * * @return a String representation * of this object. */ public String toString() { final String TAB = " "; String retValue = ""; retValue = "Cat ( " + super.toString() + TAB + "id = " + this.id + TAB + "name = " + this.name + TAB + "dateOfBirth = " + this.dateOfBirth + TAB + "age = " + this.age + TAB + "length = " + this.length + TAB + "lastUpdate = " + this.lastUpdate + TAB + "manualVersion = " + this.manualVersion + TAB + "postVersion = " + Cat.postVersion + TAB + "kittens = " + this.kittens + TAB + " )"; return retValue; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/QueryLockingTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000002045011714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.lock; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import org.hibernate.LockMode; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.QueryImpl; import org.hibernate.ejb.test.TestCase; import org.hibernate.impl.SessionImpl; /** * TODO : javadoc * * @author Steve Ebersole */ public class QueryLockingTest extends TestCase { @Override protected Class[] getAnnotatedClasses() { return new Class[] { Lockable.class }; } @Override @SuppressWarnings({ "unchecked" }) protected void addConfigOptions(Map options) { options.put( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); } public void testOverallLockMode() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); QueryImpl jpaQuery = em.createQuery( "from Lockable l" ).unwrap( QueryImpl.class ); org.hibernate.impl.QueryImpl hqlQuery = (org.hibernate.impl.QueryImpl) jpaQuery.getHibernateQuery(); assertEquals( LockMode.NONE, hqlQuery.getLockOptions().getLockMode() ); assertNull( hqlQuery.getLockOptions().getAliasSpecificLockMode( "l" ) ); assertEquals( LockMode.NONE, hqlQuery.getLockOptions().getEffectiveLockMode( "l" ) ); // NOTE : LockModeType.READ should map to LockMode.OPTIMISTIC jpaQuery.setLockMode( LockModeType.READ ); assertEquals( LockMode.OPTIMISTIC, hqlQuery.getLockOptions().getLockMode() ); assertNull( hqlQuery.getLockOptions().getAliasSpecificLockMode( "l" ) ); assertEquals( LockMode.OPTIMISTIC, hqlQuery.getLockOptions().getEffectiveLockMode( "l" ) ); jpaQuery.setHint( AvailableSettings.ALIAS_SPECIFIC_LOCK_MODE+".l", LockModeType.PESSIMISTIC_WRITE ); assertEquals( LockMode.OPTIMISTIC, hqlQuery.getLockOptions().getLockMode() ); assertEquals( LockMode.PESSIMISTIC_WRITE, hqlQuery.getLockOptions().getAliasSpecificLockMode( "l" ) ); assertEquals( LockMode.PESSIMISTIC_WRITE, hqlQuery.getLockOptions().getEffectiveLockMode( "l" ) ); em.getTransaction().commit(); em.close(); } public void testPessimisticForcedIncrementOverall() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable", Lockable.class ).setLockMode( LockModeType.PESSIMISTIC_FORCE_INCREMENT ).getSingleResult(); assertFalse( reread.getVersion().equals( initial ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } public void testPessimisticForcedIncrementSpecific() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable l", Lockable.class ) .setHint( AvailableSettings.ALIAS_SPECIFIC_LOCK_MODE+".l", LockModeType.PESSIMISTIC_FORCE_INCREMENT ) .getSingleResult(); assertFalse( reread.getVersion().equals( initial ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } public void testOptimisticForcedIncrementOverall() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable", Lockable.class ).setLockMode( LockModeType.OPTIMISTIC_FORCE_INCREMENT ).getSingleResult(); assertEquals( initial, reread.getVersion() ); em.getTransaction().commit(); em.close(); assertFalse( reread.getVersion().equals( initial ) ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } public void testOptimisticForcedIncrementSpecific() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable l", Lockable.class ) .setHint( AvailableSettings.ALIAS_SPECIFIC_LOCK_MODE+".l", LockModeType.OPTIMISTIC_FORCE_INCREMENT ) .getSingleResult(); assertEquals( initial, reread.getVersion() ); em.getTransaction().commit(); em.close(); assertFalse( reread.getVersion().equals( initial ) ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } public void testOptimisticOverall() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable", Lockable.class ) .setLockMode( LockModeType.OPTIMISTIC ) .getSingleResult(); assertEquals( initial, reread.getVersion() ); assertTrue( em.unwrap( SessionImpl.class ).getActionQueue().hasBeforeTransactionActions() ); em.getTransaction().commit(); em.close(); assertEquals( initial, reread.getVersion() ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } public void testOptimisticSpecific() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable lock = new Lockable( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); Integer initial = lock.getVersion(); assertNotNull( initial ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Lockable reread = em.createQuery( "from Lockable l", Lockable.class ) .setHint( AvailableSettings.ALIAS_SPECIFIC_LOCK_MODE+".l", LockModeType.OPTIMISTIC ) .getSingleResult(); assertEquals( initial, reread.getVersion() ); assertTrue( em.unwrap( SessionImpl.class ).getActionQueue().hasBeforeTransactionActions() ); em.getTransaction().commit(); em.close(); assertEquals( initial, reread.getVersion() ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove( em.getReference( Lockable.class, reread.getId() ) ); em.getTransaction().commit(); em.close(); } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/UnversionedLock.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000075611714611271032761 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.lock; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class UnversionedLock { @Id @GeneratedValue private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/Lockable.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000343111714611271032752 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.lock; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Version; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity public class Lockable { private Integer id; private Integer version; private String name; public Lockable() { } public Lockable(String name) { this.name = name; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Version public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/LockTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000007026211714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.lock; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.LockTimeoutException; import javax.persistence.OptimisticLockException; import javax.persistence.Query; import javax.persistence.QueryTimeoutException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.Oracle10gDialect; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.test.TestCase; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; /** * @author Emmanuel Bernard */ public class LockTest extends TestCase { private static final Log log = LogFactory.getLog( LockTest.class ); public void testFindWithTimeoutHint() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Lock lock = new Lock(); lock.setName( "name" ); em.persist( lock ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); Map properties = new HashMap(); properties.put( AvailableSettings.LOCK_TIMEOUT, 0L ); em.find( Lock.class, 1, LockModeType.PESSIMISTIC_WRITE, properties ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); lock = em.find( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); } public void testLockRead() throws Exception { Lock lock = new Lock(); lock.setName( "name" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.READ ); lock.setName( "surname" ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.find( Lock.class, lock.getId() ); assertEquals( "surname", lock.getName() ); em.remove( lock ); em.getTransaction().commit(); em.close(); } public void testLockOptimistic() throws Exception { Lock lock = new Lock(); lock.setName( "name" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.OPTIMISTIC ); lock.setName( "surname" ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.find( Lock.class, lock.getId() ); assertEquals( "surname", lock.getName() ); em.remove( lock ); em.getTransaction().commit(); em.close(); } public void testLockWrite() throws Exception { Lock lock = new Lock(); lock.setName( "second" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); Integer version = lock.getVersion(); em.lock( lock, LockModeType.WRITE ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); try { assertEquals( "should increase the version number EJB-106", 1, lock.getVersion() - version ); } finally { em.remove( lock ); em.getTransaction().commit(); } em.close(); } public void testLockWriteOnUnversioned() throws Exception { UnversionedLock lock = new UnversionedLock(); lock.setName( "second" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( UnversionedLock.class, lock.getId() ); try { // getting a READ (optimistic) lock on unversioned entity is not expected to work. // To get the same functionality as prior release, change the LockModeType.READ lock to: // em.lock(lock,LockModeType.PESSIMISTIC_READ); em.lock( lock, LockModeType.READ ); fail("expected OptimisticLockException exception"); } catch(OptimisticLockException expected) {} em.getTransaction().rollback(); // the previous code block can be rewritten as follows (to get the previous behavior) em.getTransaction().begin(); lock = em.getReference( UnversionedLock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_READ ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( UnversionedLock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); } public void testLockPessimisticForceIncrement() throws Exception { Lock lock = new Lock(); lock.setName( "force" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); Integer version = lock.getVersion(); em.lock( lock, LockModeType.PESSIMISTIC_FORCE_INCREMENT ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); try { assertEquals( "should increase the version number ", 1, lock.getVersion() - version ); } finally { em.remove( lock ); em.getTransaction().commit(); } em.close(); } public void testLockOptimisticForceIncrement() throws Exception { Lock lock = new Lock(); lock.setName( "force" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); Integer version = lock.getVersion(); em.lock( lock, LockModeType.OPTIMISTIC_FORCE_INCREMENT ); em.getTransaction().commit(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); try { assertEquals( "should increase the version number ", 1, lock.getVersion() - version ); } finally { em.remove( lock ); em.getTransaction().commit(); } em.close(); } public void testLockOptimisticForceIncrementDifferentEm() throws Exception { Lock lock = new Lock(); lock.setName( "force" ); EntityManager em1 = createIsolatedEntityManager(); em1.getTransaction().begin(); em1.persist( lock ); em1.getTransaction().commit(); em1.close(); EntityManager em2 = createIsolatedEntityManager(); em2.getTransaction().begin(); lock = em2.find( Lock.class, lock.getId(), LockModeType.OPTIMISTIC ); assertEquals( "lock mode should be OPTIMISTIC ", LockModeType.OPTIMISTIC, em2.getLockMode(lock) ); em2.lock( lock, LockModeType.OPTIMISTIC_FORCE_INCREMENT ); assertEquals( "lock mode should be OPTIMISTIC_FORCE_INCREMENT ", LockModeType.OPTIMISTIC_FORCE_INCREMENT, em2.getLockMode(lock) ); em2.getTransaction().commit(); em2.getTransaction().begin(); em2.remove( lock ); em2.getTransaction().commit(); em2.close(); } public void testContendedPessimisticLock() throws Exception { EntityManager em = getOrCreateEntityManager(); final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticWriteLock) if ( getDialect() instanceof HSQLDialect) { log.info("skipping testContendedPessimisticLock"); return; } Lock lock = new Lock(); Thread t = null; try { lock.setName( "testContendedPessimisticLock" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testContendedPessimisticLock: got write lock"); final CountDownLatch latch = new CountDownLatch(1); t = new Thread( new Runnable() { public void run() { try { em2.getTransaction().begin(); log.info("testContendedPessimisticLock: (BG) about to issue (PESSIMISTIC_READ) query against write-locked entity"); // we should block on the following read Query query = em2.createQuery( "select L from Lock_ L where L.id < 10000 "); query.setLockMode(LockModeType.PESSIMISTIC_READ); List resultList = query.getResultList(); resultList.get(0).getName(); // force entity to be read } finally { em2.getTransaction().commit(); latch.countDown(); // signal that we got the read lock } } } ); t.setDaemon( true ); t.setName("LockTest read lock"); t.start(); log.info("testContendedPessimisticLock: wait on BG thread"); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // latchSet should be false (timeout) because the background thread // shouldn't be able to get a read lock on write locked entity. log.info("testContendedPessimisticLock: BG thread completed transaction"); assertFalse( "shouldn't be able to get read lock while another transaction has write lock",latchSet ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testContendedPessimisticReadLockTimeout() throws Exception { EntityManager em = getOrCreateEntityManager(); final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testContendedPessimisticReadLockTimeout"); return; } Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testContendedPessimisticReadLockTimeout" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testContendedPessimisticReadLockTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info("testContendedPessimisticReadLockTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info("testContendedPessimisticReadLockTimeout: (BG) read write-locked entity"); Map props = new HashMap(); // timeout is in milliseconds props.put("javax.persistence.lock.timeout", new Integer(1000)); try { em2.lock( lock2, LockModeType.PESSIMISTIC_READ, props); } catch( LockTimeoutException e) { // success log.info("testContendedPessimisticReadLockTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { log.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName("Lock timeout Test (bg)"); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testContendedPessimisticWriteLockTimeout() throws Exception { EntityManager em = getOrCreateEntityManager(); final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testContendedPessimisticWriteLockTimeout"); return; } Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testContendedPessimisticWriteLockTimeout" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testContendedPessimisticWriteLockTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info("testContendedPessimisticWriteLockTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info("testContendedPessimisticWriteLockTimeout: (BG) read write-locked entity"); Map props = new HashMap(); // timeout is in milliseconds props.put("javax.persistence.lock.timeout", new Integer(1000)); try { em2.lock( lock2, LockModeType.PESSIMISTIC_WRITE, props); } catch( LockTimeoutException e) { // success log.info("testContendedPessimisticWriteLockTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { log.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName("Lock timeout Test (bg)"); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testContendedPessimisticWriteLockNoWait() throws Exception { EntityManager em = getOrCreateEntityManager(); final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testContendedPessimisticWriteLockNoWait"); return; } Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testContendedPessimisticWriteLockNoWait" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testContendedPessimisticWriteLockNoWait: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info("testContendedPessimisticWriteLockNoWait: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info("testContendedPessimisticWriteLockNoWait: (BG) read write-locked entity"); Map props = new HashMap(); // timeout of zero means no wait (for lock) props.put("javax.persistence.lock.timeout", new Integer(0)); try { em2.lock( lock2, LockModeType.PESSIMISTIC_WRITE, props); } catch( LockTimeoutException e) { // success log.info("testContendedPessimisticWriteLockNoWait: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { log.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName("Lock timeout Test (bg)"); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testQueryTimeout() throws Exception { EntityManager em = getOrCreateEntityManager(); final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testQueryTimeout"); return; } Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testQueryTimeout" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testQueryTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info( "testQueryTimeout: (BG) about to read write-locked entity" ); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info( "testQueryTimeout: (BG) read write-locked entity" ); try { // we should block on the following read Query query = em2.createQuery( "select L from Lock_ L where L.id < 10000 "); query.setLockMode( LockModeType.PESSIMISTIC_READ ); query.setHint( "javax.persistence.query.timeout", new Integer(500) ); // 1 sec timeout List resultList = query.getResultList(); String name = resultList.get(0).getName(); // force entity to be read log.info( "testQueryTimeout: name read =" + name ); } catch( QueryTimeoutException e) { // success log.info( "testQueryTimeout: (BG) got expected timeout exception" ); timedOut = true; } catch ( Throwable e) { log.info( "testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e ); } em2.getTransaction().commit(); return new Boolean( timedOut ); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName( "testQueryTimeout (bg)" ); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testQueryTimeoutEMProps() throws Exception { // TODO: replace dialect instanceof test with a Dialect.hasCapability if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testQueryTimeout"); return; } EntityManager em = getOrCreateEntityManager(); Map queryTimeoutProps = new HashMap(); queryTimeoutProps.put("javax.persistence.query.timeout", new Integer(500) ); // 1 sec timeout (should round up) final EntityManager em2 = createIsolatedEntityManager(queryTimeoutProps); Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testQueryTimeout" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testQueryTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info( "testQueryTimeout: (BG) about to read write-locked entity" ); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info( "testQueryTimeout: (BG) read write-locked entity" ); try { // we should block on the following read Query query = em2.createQuery( "select L from Lock_ L where L.id < 10000 "); query.setLockMode( LockModeType.PESSIMISTIC_READ ); List resultList = query.getResultList(); String name = resultList.get(0).getName(); // force entity to be read log.info( "testQueryTimeout: name read =" + name ); } catch( QueryTimeoutException e) { // success log.info( "testQueryTimeout: (BG) got expected timeout exception" ); timedOut = true; } catch ( Throwable e) { log.info( "testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e ); } em2.getTransaction().commit(); return new Boolean( timedOut ); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName( "testQueryTimeout (bg)" ); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public void testLockTimeoutEMProps() throws Exception { EntityManager em = getOrCreateEntityManager(); Map TimeoutProps = new HashMap(); TimeoutProps.put("javax.persistence.lock.timeout", new Integer(1000) ); // 1 second timeout final EntityManager em2 = createIsolatedEntityManager(TimeoutProps); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { log.info("skipping testLockTimeoutEMProps"); return; } Lock lock = new Lock(); Thread t = null; FutureTask bgTask = null; final CountDownLatch latch = new CountDownLatch(1); try { lock.setName( "testLockTimeoutEMProps" ); em.getTransaction().begin(); em.persist( lock ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read log.info("testLockTimeoutEMProps: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); log.info("testLockTimeoutEMProps: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read log.info("testLockTimeoutEMProps: (BG) read write-locked entity"); // em2 already has javax.persistence.lock.timeout of 1 second applied try { em2.lock( lock2, LockModeType.PESSIMISTIC_WRITE); } catch( LockTimeoutException e) { // success log.info("testLockTimeoutEMProps: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { log.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); } finally { latch.countDown(); // signal that we finished } } } ); t = new Thread(bgTask); t.setDaemon( true ); t.setName("Lock timeout Test (bg)"); t.start(); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // should return quickly on success assertTrue( "background test thread finished (lock timeout is broken)", latchSet); assertTrue( "background test thread timed out on lock attempt", bgTask.get().booleanValue() ); em.getTransaction().commit(); } finally { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); } if ( t != null) { // wait for background thread to finish before deleting entity t.join(); } em.getTransaction().begin(); lock = em.getReference( Lock.class, lock.getId() ); em.remove( lock ); em.getTransaction().commit(); em.close(); em2.close(); } } public Class[] getAnnotatedClasses() { return new Class[]{ Lock.class, UnversionedLock.class }; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/Lock.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000137511714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.lock; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Version; /** * @author Emmanuel Bernard */ @Entity(name="Lock_") public class Lock { private Integer id; private Integer version; private String name; public Lock() { } public Lock(String name) { this.name = name; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Version public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000011714611271032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/package-info.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000026411714611271032753 0ustar ebourgebourg@NamedQuery(name = "allMouse_1_0", query = "select m from ApplicationServer1 m") package org.hibernate.ejb.test.pack.defaultpar_1_0; import org.hibernate.annotations.NamedQuery;././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/Money1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000061111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Money1 { private Integer id; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }././@LongLink0000000000000000000000000000022600000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/OtherIncrementListener1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000062511714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; /** * @author Emmanuel Bernard */ public class OtherIncrementListener1 { private static int increment; public static int getIncrement() { return OtherIncrementListener1.increment; } public static void reset() { increment = 0; } public void increment(Object entity) { OtherIncrementListener1.increment++; } }././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/Lighter1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000025511714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; /** * @author Emmanuel Bernard */ public class Lighter1 { public String name; public String power; }././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/Version1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000133011714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; import javax.persistence.Embeddable; /** * @author Emmanuel Bernard */ @Embeddable public class Version1 { private static final String DOT = "."; private int major; private int minor; private int micro; public int getMajor() { return major; } public void setMajor(int major) { this.major = major; } public int getMinor() { return minor; } public void setMinor(int minor) { this.minor = minor; } public int getMicro() { return micro; } public void setMicro(int micro) { this.micro = micro; } public String toString() { return new StringBuffer( major ).append( DOT ).append( minor ).append( DOT ).append( micro ).toString(); } }././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000067011714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; import javax.persistence.ExcludeDefaultListeners; /** * @author Emmanuel Bernard */ @ExcludeDefaultListeners public class Mouse1 { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/IncrementListener1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000062611714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ public class IncrementListener1 { private static int increment; public static int getIncrement() { return increment; } public static void reset() { increment = 0; } @PrePersist public void increment(Object entity) { increment++; } }././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar_1_0/ApplicationServer1.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000123111714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar_1_0; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class ApplicationServer1 { private Integer id; private String name; private Version1 version; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Version1 getVersion() { return version; } public void setVersion(Version1 version) { this.version = version; } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/OtherIncrementListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000062011714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; /** * @author Emmanuel Bernard */ public class OtherIncrementListener { private static int increment; public static int getIncrement() { return OtherIncrementListener.increment; } public static void reset() { increment = 0; } public void increment(Object entity) { OtherIncrementListener.increment++; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/package-info.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000025511714611271032753 0ustar ebourgebourg@NamedQuery(name = "allMouse", query = "select m from ApplicationServer m") package org.hibernate.ejb.test.pack.defaultpar; import org.hibernate.annotations.NamedQuery; ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/ApplicationServer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000134011714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class ApplicationServer { private Integer id; private String name; private org.hibernate.ejb.test.pack.defaultpar.Version version; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Version getVersion() { return version; } public void setVersion(org.hibernate.ejb.test.pack.defaultpar.Version version) { this.version = version; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/Mouse.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000066411714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; import javax.persistence.ExcludeDefaultListeners; /** * @author Emmanuel Bernard */ @ExcludeDefaultListeners public class Mouse { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/Lighter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000025211714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; /** * @author Emmanuel Bernard */ public class Lighter { public String name; public String power; } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/Money.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000060611714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Money { private Integer id; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/Version.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000132411714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; import javax.persistence.Embeddable; /** * @author Emmanuel Bernard */ @Embeddable public class Version { private static final String DOT = "."; private int major; private int minor; private int micro; public int getMajor() { return major; } public void setMajor(int major) { this.major = major; } public int getMinor() { return minor; } public void setMinor(int minor) { this.minor = minor; } public int getMicro() { return micro; } public void setMicro(int micro) { this.micro = micro; } public String toString() { return new StringBuffer( major ).append( DOT ).append( minor ).append( DOT ).append( micro ).toString(); } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/defaultpar/IncrementListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000062311714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.defaultpar; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ public class IncrementListener { private static int increment; public static int getIncrement() { return increment; } public static void reset() { increment = 0; } @PrePersist public void increment(Object entity) { increment++; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explodedpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explodedpar/package-info.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000024211714611271032747 0ustar ebourgebourg@NamedQuery(name = "allCarpet", query = "select c from Carpet c") package org.hibernate.ejb.test.pack.explodedpar; import org.hibernate.annotations.NamedQuery; ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explodedpar/Elephant.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000055411714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.explodedpar; /** * @author Emmanuel Bernard */ public class Elephant { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explodedpar/Carpet.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000100511714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.explodedpar; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Carpet { private Integer id; private String country; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/cfgxmlpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/cfgxmlpar/Morito.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000076511714611271032761 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.cfgxmlpar; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Morito { private Integer id; private String power; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPower() { return power; } public void setPower(String power) { this.power = power; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explicitpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/explicitpar/Washer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000032211714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.explicitpar; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Washer { //No @id so picking it up should fail } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/excludehbmpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/excludehbmpar/Caipirinha.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000111311714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.excludehbmpar; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Caipirinha { private Integer id; private String name; public Caipirinha() { } public Caipirinha(String name) { this.name = name; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/externaljar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/externaljar/Scooter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000071211714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.externaljar; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Scooter { private String model; private Long speed; @Id public String getModel() { return model; } public void setModel(String model) { this.model = model; } public Long getSpeed() { return speed; } public void setSpeed(Long speed) { this.speed = speed; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/various/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/various/Airplane.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000045311714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.various; /** * @author Emmanuel Bernard */ public class Airplane { private String serialNumber; public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/various/Seat.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000037511714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.various; /** * @author Emmanuel Bernard */ public class Seat { private String number; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/OtherIncrementListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000061111714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; /** * @author Emmanuel Bernard */ public class OtherIncrementListener { private static int increment; public static int getIncrement() { return OtherIncrementListener.increment; } public static void reset() { increment = 0; } public void increment(Object entity) { OtherIncrementListener.increment++; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/package-info.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000024611714611271032753 0ustar ebourgebourg@NamedQuery(name = "allMouse", query = "select m from ApplicationServer m") package org.hibernate.ejb.test.pack.war; import org.hibernate.annotations.NamedQuery; ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/ApplicationServer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000121311714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class ApplicationServer { private Integer id; private String name; private Version version; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Version getVersion() { return version; } public void setVersion(Version version) { this.version = version; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/Mouse.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000065511714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; import javax.persistence.ExcludeDefaultListeners; /** * @author Emmanuel Bernard */ @ExcludeDefaultListeners public class Mouse { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/Lighter.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000024311714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; /** * @author Emmanuel Bernard */ public class Lighter { public String name; public String power; } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/Money.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000057711714611271032762 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Money { private Integer id; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/Version.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000131511714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; import javax.persistence.Embeddable; /** * @author Emmanuel Bernard */ @Embeddable public class Version { private static final String DOT = "."; private int major; private int minor; private int micro; public int getMajor() { return major; } public void setMajor(int major) { this.major = major; } public int getMinor() { return minor; } public void setMinor(int minor) { this.minor = minor; } public int getMicro() { return micro; } public void setMicro(int micro) { this.micro = micro; } public String toString() { return new StringBuffer( major ).append( DOT ).append( minor ).append( DOT ).append( micro ).toString(); } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/war/IncrementListener.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000061411714611271032752 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.war; import javax.persistence.PrePersist; /** * @author Emmanuel Bernard */ public class IncrementListener { private static int increment; public static int getIncrement() { return increment; } public static void reset() { increment = 0; } @PrePersist public void increment(Object entity) { increment++; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/spacepar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/spacepar/Bug.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000136311714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.spacepar; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Bug { @Id @GeneratedValue private Long id; private String subject; @Column(name="`comment`") private String comment; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/overridenpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/pack/overridenpar/Bug.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000136711714611271032760 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.pack.overridenpar; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public class Bug { @Id @GeneratedValue private Long id; private String subject; @Column(name="`comment`") private String comment; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/MergeTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000730611714611271032757 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ //$Id$ package org.hibernate.ejb.test.ops; import java.util.Map; import javax.persistence.EntityManager; import org.hibernate.cfg.Environment; import org.hibernate.ejb.EntityManagerFactoryImpl; import org.hibernate.ejb.test.TestCase; /** * @author Gavin King * @author Hardy Ferentschik */ public class MergeTest extends TestCase { public void testMergeTree() { clearCounts(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Node root = new Node( "root" ); Node child = new Node( "child" ); root.addChild( child ); em.persist( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 2 ); clearCounts(); root.setDescription( "The root node" ); child.setDescription( "The child node" ); Node secondChild = new Node( "second child" ); root.addChild( secondChild ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.merge( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 1 ); assertUpdateCount( 2 ); } public void testMergeTreeWithGeneratedId() { clearCounts(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); NumberedNode root = new NumberedNode( "root" ); NumberedNode child = new NumberedNode( "child" ); root.addChild( child ); em.persist( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 2 ); clearCounts(); root.setDescription( "The root node" ); child.setDescription( "The child node" ); NumberedNode secondChild = new NumberedNode( "second child" ); root.addChild( secondChild ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.merge( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 1 ); assertUpdateCount( 2 ); } private void clearCounts() { ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory().getStatistics().clear(); } private void assertInsertCount(int count) { int inserts = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory() .getStatistics() .getEntityInsertCount(); assertEquals( count, inserts ); } private void assertUpdateCount(int count) { int updates = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory() .getStatistics() .getEntityUpdateCount(); assertEquals( count, updates ); } @Override protected void addConfigOptions(Map options) { options.put( Environment.GENERATE_STATISTICS, "true" ); options.put( Environment.STATEMENT_BATCH_SIZE, "0" ); } @Override protected Class[] getAnnotatedClasses() { return new Class[0]; } @Override protected String[] getMappings() { return new String[] { "org/hibernate/ejb/test/ops/Node.hbm.xml" }; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Mammal.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000046411714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Mammal extends Animal { private int mamalNbr; public int getMamalNbr() { return mamalNbr; } public void setMamalNbr(int mamalNbr) { this.mamalNbr = mamalNbr; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Employer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000101411714611271032745 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import java.io.Serializable; import java.util.Collection; /** * Employer in a employer-Employee relationship * * @author Emmanuel Bernard */ public class Employer implements Serializable { private Integer id; private Collection employees; public Collection getEmployees() { return employees; } public Integer getId() { return id; } public void setEmployees(Collection set) { employees = set; } public void setId(Integer integer) { id = integer; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/PersistTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001445311714611271032760 0ustar ebourgebourg// $Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.ops; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import org.hibernate.cfg.Environment; import org.hibernate.ejb.EntityManagerFactoryImpl; import org.hibernate.ejb.test.TestCase; /** * @author Gavin King * @author Hardy Ferentschik */ public class PersistTest extends TestCase { public void testCreateTree() { clearCounts(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Node root = new Node( "root" ); Node child = new Node( "child" ); root.addChild( child ); em.persist( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 2 ); assertUpdateCount( 0 ); em = getOrCreateEntityManager(); em.getTransaction().begin(); root = ( Node ) em.find( Node.class, "root" ); Node child2 = new Node( "child2" ); root.addChild( child2 ); em.getTransaction().commit(); em.close(); assertInsertCount( 3 ); assertUpdateCount( 0 ); } public void testCreateTreeWithGeneratedId() { clearCounts(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); NumberedNode root = new NumberedNode( "root" ); NumberedNode child = new NumberedNode( "child" ); root.addChild( child ); em.persist( root ); em.getTransaction().commit(); em.close(); assertInsertCount( 2 ); assertUpdateCount( 0 ); em = getOrCreateEntityManager(); em.getTransaction().begin(); root = ( NumberedNode ) em.find( NumberedNode.class, root.getId() ); NumberedNode child2 = new NumberedNode( "child2" ); root.addChild( child2 ); em.getTransaction().commit(); em.close(); assertInsertCount( 3 ); assertUpdateCount( 0 ); } public void testCreateException() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Node dupe = new Node( "dupe" ); em.persist( dupe ); em.persist( dupe ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( dupe ); try { em.getTransaction().commit(); fail( "Cannot persist() twice the same entity" ); } catch ( Exception cve ) { //verify that an exception is thrown! } em.close(); Node nondupe = new Node( "nondupe" ); nondupe.addChild( dupe ); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( nondupe ); try { em.getTransaction().commit(); assertFalse( true ); } catch ( RollbackException e ) { //verify that an exception is thrown! } em.close(); } public void testCreateExceptionWithGeneratedId() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); NumberedNode dupe = new NumberedNode( "dupe" ); em.persist( dupe ); em.persist( dupe ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( dupe ); fail(); } catch ( PersistenceException poe ) { //verify that an exception is thrown! } em.getTransaction().rollback(); em.close(); NumberedNode nondupe = new NumberedNode( "nondupe" ); nondupe.addChild( dupe ); em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( nondupe ); fail(); } catch ( PersistenceException poe ) { //verify that an exception is thrown! } em.getTransaction().rollback(); em.close(); } public void testBasic() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Employer er = new Employer(); Employee ee = new Employee(); em.persist( ee ); Collection erColl = new ArrayList(); Collection eeColl = new ArrayList(); erColl.add( ee ); eeColl.add( er ); er.setEmployees( erColl ); ee.setEmployers( eeColl ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); er = ( Employer ) em.find( Employer.class, er.getId() ); assertNotNull( er ); assertNotNull( er.getEmployees() ); assertEquals( 1, er.getEmployees().size() ); Employee eeFromDb = ( Employee ) er.getEmployees().iterator().next(); assertEquals( ee.getId(), eeFromDb.getId() ); em.getTransaction().commit(); em.close(); } private void clearCounts() { ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory().getStatistics().clear(); } private void assertInsertCount(int count) { int inserts = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory() .getStatistics() .getEntityInsertCount(); assertEquals( count, inserts ); } private void assertUpdateCount(int count) { int updates = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory() .getStatistics() .getEntityUpdateCount(); assertEquals( count, updates ); } protected void addConfigOptions(Map options) { options.put( Environment.GENERATE_STATISTICS, "true" ); options.put( Environment.STATEMENT_BATCH_SIZE, "0" ); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { Node.class }; } protected String[] getMappings() { return new String[] { "org/hibernate/ejb/test/ops/Node.hbm.xml", "org/hibernate/ejb/test/ops/Employer.hbm.xml" }; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/FindTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000125711714611271032756 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class FindTest extends TestCase { public void testSubclassWrongId() throws Exception { Mammal mammal = new Mammal(); mammal.setMamalNbr( 2 ); mammal.setName( "Human" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( mammal ); em.flush(); assertNull( em.find(Reptile.class, 1l) ); em.getTransaction().rollback(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[] { Mammal.class, Reptile.class, Animal.class }; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Reptile.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000052011714611271032746 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.Entity; /** * @author Emmanuel Bernard */ @Entity public class Reptile extends Animal { private float temperature; public float getTemperature() { return temperature; } public void setTemperature(float temperature) { this.temperature = temperature; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/GetLoadTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001065111714611271032754 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ //$Id$ package org.hibernate.ejb.test.ops; import java.util.Map; import javax.persistence.EntityManager; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.cfg.Environment; import org.hibernate.ejb.EntityManagerFactoryImpl; import org.hibernate.ejb.test.TestCase; /** * @author Gavin King * @author Hardy Ferentschik */ public class GetLoadTest extends TestCase { public void testGetLoad() { clearCounts(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Session s = ( Session ) em.getDelegate(); Employer emp = new Employer(); s.persist( emp ); Node node = new Node( "foo" ); Node parent = new Node( "bar" ); parent.addChild( node ); s.persist( parent ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); s = ( Session ) em.getDelegate(); emp = ( Employer ) s.get( Employer.class, emp.getId() ); assertTrue( Hibernate.isInitialized( emp ) ); assertFalse( Hibernate.isInitialized( emp.getEmployees() ) ); node = ( Node ) s.get( Node.class, node.getName() ); assertTrue( Hibernate.isInitialized( node ) ); assertFalse( Hibernate.isInitialized( node.getChildren() ) ); assertFalse( Hibernate.isInitialized( node.getParent() ) ); assertNull( s.get( Node.class, "xyz" ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); s = ( Session ) em.getDelegate(); emp = ( Employer ) s.load( Employer.class, emp.getId() ); emp.getId(); assertFalse( Hibernate.isInitialized( emp ) ); node = ( Node ) s.load( Node.class, node.getName() ); assertEquals( node.getName(), "foo" ); assertFalse( Hibernate.isInitialized( node ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); s = ( Session ) em.getDelegate(); emp = ( Employer ) s.get( "org.hibernate.ejb.test.ops.Employer", emp.getId() ); assertTrue( Hibernate.isInitialized( emp ) ); node = ( Node ) s.get( "org.hibernate.ejb.test.ops.Node", node.getName() ); assertTrue( Hibernate.isInitialized( node ) ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); s = ( Session ) em.getDelegate(); emp = ( Employer ) s.load( "org.hibernate.ejb.test.ops.Employer", emp.getId() ); emp.getId(); assertFalse( Hibernate.isInitialized( emp ) ); node = ( Node ) s.load( "org.hibernate.ejb.test.ops.Node", node.getName() ); assertEquals( node.getName(), "foo" ); assertFalse( Hibernate.isInitialized( node ) ); em.getTransaction().commit(); em.close(); assertFetchCount( 0 ); } private void clearCounts() { ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory().getStatistics().clear(); } private void assertFetchCount(int count) { int fetches = ( int ) ( ( EntityManagerFactoryImpl ) factory ).getSessionFactory() .getStatistics() .getEntityFetchCount(); assertEquals( count, fetches ); } @Override protected void addConfigOptions(Map options) { options.put( Environment.GENERATE_STATISTICS, "true" ); options.put( Environment.STATEMENT_BATCH_SIZE, "0" ); } @Override protected Class[] getAnnotatedClasses() { return new Class[0]; } protected String[] getMappings() { return new String[] { "org/hibernate/ejb/test/ops/Node.hbm.xml", "org/hibernate/ejb/test/ops/Employer.hbm.xml" }; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Node.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000164111714611271032753 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import java.util.HashSet; import java.util.Set; /** * @author Gavin King */ public class Node { private String name; private Node parent; private Set children = new HashSet(); private String description; public Node() { } public Node(String name) { this.name = name; } public Set getChildren() { return children; } public void setChildren(Set children) { this.children = children; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } public Node addChild(Node child) { children.add( child ); child.setParent( this ); return this; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/MergeNewTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000241711714611271032755 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.EntityManager; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class MergeNewTest extends TestCase { public void testMergeNew() throws Exception { Workload load = new Workload(); load.name = "Cleaning"; load.load = 10; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); load = em.merge( load ); assertNotNull( load.id ); em.flush(); assertNotNull( load.id ); em.getTransaction().rollback(); em.close(); } public void testMergeAfterRemove() throws Exception { Workload load = new Workload(); load.name = "Cleaning"; load.load = 10; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); load = em.merge( load ); em.flush(); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); load = em.find( Workload.class, load.id ); em.remove( load ); em.flush(); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.merge( load ); em.flush(); em.getTransaction().commit(); em.close(); } public Class[] getAnnotatedClasses() { return new Class[]{ Workload.class }; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Workload.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000054711714611271032757 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Workload { @Id @GeneratedValue public Integer id; public String name; @Column(name="load_") public Integer load; } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Employee.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000103611714611271032751 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import java.io.Serializable; import java.util.Collection; /** * Employee in an Employer-Employee relationship * * @author Emmanuel Bernard */ public class Employee implements Serializable { private Integer id; private Collection employers; public Integer getId() { return id; } public void setId(Integer integer) { id = integer; } public Collection getEmployers() { return employers; } public void setEmployers(Collection employers) { this.employers = employers; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/Animal.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000074211714611271032754 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; /** * @author Emmanuel Bernard */ @Entity public abstract class Animal { private String name; private Long id; public String getName() { return name; } public void setName(String name) { this.name = name; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/ops/NumberedNode.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000050411714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.ops; /** * @author Gavin King */ public class NumberedNode extends Node { private long id; public NumberedNode() { super(); } public NumberedNode(String name) { super( name ); } public long getId() { return id; } public void setId(long id) { this.id = id; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/jee/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/jee/OrmVersionTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000001227011714611271032753 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.jee; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.persistence.SharedCacheMode; import javax.persistence.ValidationMode; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.sql.DataSource; import junit.framework.TestCase; import org.hibernate.InvalidMappingException; import org.hibernate.ejb.HibernatePersistence; /** * "smoke" tests for JEE bootstrapping of HEM via a {@link PersistenceUnitInfo} * * @author Steve Ebersole */ public class OrmVersionTest extends TestCase { public void testOrm1() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm1-test", "1.0" ) .addMappingFileName( "org/hibernate/ejb/test/jee/valid-orm-1.xml" ); HibernatePersistence hp = new HibernatePersistence(); EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, Collections.EMPTY_MAP ); emf.getMetamodel().entity( org.hibernate.ejb.test.pack.defaultpar_1_0.Lighter1.class ); // exception if not entity } public void testOrm2() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "orm2-test", "2.0" ) .addMappingFileName( "org/hibernate/ejb/test/jee/valid-orm-2.xml" ); HibernatePersistence hp = new HibernatePersistence(); EntityManagerFactory emf = hp.createContainerEntityManagerFactory( pui, Collections.EMPTY_MAP ); emf.getMetamodel().entity( org.hibernate.ejb.test.pack.defaultpar.Lighter.class ); // exception if not entity } public void testInvalidOrm1() { PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( "invalid-orm1-test", "1.0" ) .addMappingFileName( "org/hibernate/ejb/test/jee/invalid-orm-1.xml" ); HibernatePersistence hp = new HibernatePersistence(); try { hp.createContainerEntityManagerFactory( pui, Collections.EMPTY_MAP ); fail( "expecting 'invalid content' error" ); } catch ( InvalidMappingException expected ) { // expected condition } } public static class PersistenceUnitInfoImpl implements PersistenceUnitInfo { private final String name; private final String persistenceSchemaVersion; public PersistenceUnitInfoImpl(String name) { this( name, "2.0" ); } public PersistenceUnitInfoImpl(String name, String persistenceSchemaVersion) { this.name = name; this.persistenceSchemaVersion = persistenceSchemaVersion; } public String getPersistenceUnitName() { return name; } public String getPersistenceXMLSchemaVersion() { return persistenceSchemaVersion; } private final List mappingFileNames = new ArrayList(); public List getMappingFileNames() { return mappingFileNames; } private final List managedClassNames = new ArrayList(); private PersistenceUnitInfoImpl addMappingFileName(String mappingFileName) { mappingFileNames.add( mappingFileName ); return this; } public List getManagedClassNames() { return managedClassNames; } public String getPersistenceProviderClassName() { return null; } public PersistenceUnitTransactionType getTransactionType() { return PersistenceUnitTransactionType.RESOURCE_LOCAL; } public DataSource getJtaDataSource() { return null; } public DataSource getNonJtaDataSource() { return null; } private final List jarFileUrls = new ArrayList(); public List getJarFileUrls() { return jarFileUrls; } public URL getPersistenceUnitRootUrl() { return null; } public boolean excludeUnlistedClasses() { return false; } public SharedCacheMode getSharedCacheMode() { return null; } public ValidationMode getValidationMode() { return null; } private final Properties properties = new Properties(); public Properties getProperties() { return properties; } public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } public void addTransformer(ClassTransformer transformer) { } public ClassLoader getNewTempClassLoader() { return getClassLoader(); } } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/EntityManagerTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000002727411714611271032765 0ustar ebourgebourg//$Id$ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.FlushModeType; import javax.persistence.PersistenceException; import javax.persistence.Query; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.ejb.HibernateEntityManagerFactory; import org.hibernate.stat.Statistics; /** * @author Gavin King */ public class EntityManagerTest extends TestCase { public Class[] getAnnotatedClasses() { return new Class[] { Item.class, Distributor.class, Wallet.class }; } public Map getCachedClasses() { Map result = new HashMap(); result.put( Item.class, "read-write" ); return result; } public Map getCachedCollections() { Map result = new HashMap(); result.put( Item.class.getName() + ".distributors", "read-write, RegionName" ); return result; } public void testEntityManager() { Item item = new Item( "Mouse", "Micro$oft mouse" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); em.getTransaction().begin(); Item item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult(); assertNotNull( item1 ); assertSame( item, item1 ); item.setDescr( "Micro$oft wireless mouse" ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); em.getTransaction().begin(); item1 = em.find( Item.class, "Mouse" ); assertSame( item, item1 ); em.getTransaction().commit(); assertTrue( em.contains( item ) ); item1 = em.find( Item.class, "Mouse" ); assertSame( item, item1 ); assertTrue( em.contains( item ) ); item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult(); assertNotNull( item1 ); assertSame( item, item1 ); assertTrue( em.contains( item ) ); em.getTransaction().begin(); assertTrue( em.contains( item ) ); em.remove( item ); em.remove( item ); //Second should be no-op em.getTransaction().commit(); em.close(); } public void testConfiguration() throws Exception { Item item = new Item( "Mouse", "Micro$oft mouse" ); Distributor res = new Distributor(); res.setName( "Bruce" ); item.setDistributors( new HashSet() ); item.getDistributors().add( res ); Statistics stats = ( ( HibernateEntityManagerFactory ) factory ).getSessionFactory().getStatistics(); stats.clear(); stats.setStatisticsEnabled( true ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); em.persist( res ); em.persist( item ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.close(); assertEquals( 1, stats.getSecondLevelCachePutCount() ); assertEquals( 0, stats.getSecondLevelCacheHitCount() ); em = getOrCreateEntityManager(); em.getTransaction().begin(); Item second = em.find( Item.class, item.getName() ); assertEquals( 1, second.getDistributors().size() ); assertEquals( 1, stats.getSecondLevelCacheHitCount() ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); second = em.find( Item.class, item.getName() ); assertEquals( 1, second.getDistributors().size() ); assertEquals( 3, stats.getSecondLevelCacheHitCount() ); em.remove( second ); em.remove( second.getDistributors().iterator().next() ); em.getTransaction().commit(); em.close(); stats.clear(); stats.setStatisticsEnabled( false ); } public void testContains() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Integer nonManagedObject = new Integer( 4 ); try { em.contains( nonManagedObject ); fail( "Should have raised an exception" ); } catch ( IllegalArgumentException iae ) { //success if ( em.getTransaction() != null ) { em.getTransaction().rollback(); } } finally { em.close(); } em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item = new Item(); item.setDescr( "Mine" ); item.setName( "Juggy" ); em.persist( item ); em.getTransaction().commit(); em.getTransaction().begin(); item = em.getReference( Item.class, item.getName() ); assertTrue( em.contains( item ) ); em.remove( item ); em.getTransaction().commit(); em.close(); } public void testClear() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.flush(); em.clear(); assertFalse( em.contains( w ) ); em.getTransaction().rollback(); em.close(); } public void testFlushMode() throws Exception { EntityManager em = getOrCreateEntityManager(); em.setFlushMode( FlushModeType.COMMIT ); assertEquals( FlushModeType.COMMIT, em.getFlushMode() ); ( ( HibernateEntityManager ) em ).getSession().setFlushMode( FlushMode.ALWAYS ); assertNull( em.getFlushMode() ); em.close(); } public void testPersistNoneGenerator() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); em.getTransaction().commit(); em.getTransaction().begin(); Wallet wallet = em.find( Wallet.class, w.getSerial() ); assertEquals( w.getBrand(), wallet.getBrand() ); em.remove( wallet ); em.getTransaction().commit(); em.close(); } public void testPersistExisting() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); em.persist( w ); w = new Wallet(); w.setBrand( "Lacoste" ); w.setModel( "Minimic" ); w.setSerial( "0100202002" ); try { em.persist( w ); } catch ( EntityExistsException eee ) { //success if ( em.getTransaction() != null ) { em.getTransaction().rollback(); } em.close(); return; } try { em.getTransaction().commit(); fail( "Should have raised an exception" ); } catch (PersistenceException pe) {} finally { em.close(); } } public void testSerializableException() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { Query query = em.createQuery( "SELECT p FETCH JOIN p.distributors FROM Item p" ); query.getSingleResult(); } catch ( IllegalArgumentException e ) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( e ); out.close(); byte[] serialized = stream.toByteArray(); stream.close(); ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream( byteIn ); IllegalArgumentException deserializedException = ( IllegalArgumentException ) in.readObject(); in.close(); byteIn.close(); assertNull( deserializedException.getCause().getCause() ); assertNull( e.getCause().getCause() ); } em.getTransaction().rollback(); em.close(); Exception e = new HibernateException( "Exception", new NullPointerException( "NPE" ) ); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( e ); out.close(); byte[] serialized = stream.toByteArray(); stream.close(); ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream( byteIn ); HibernateException deserializedException = ( HibernateException ) in.readObject(); in.close(); byteIn.close(); assertNotNull( "Arbitrary exceptions nullified", deserializedException.getCause() ); assertNotNull( e.getCause() ); } public void testIsOpen() throws Exception { EntityManager em = getOrCreateEntityManager(); assertTrue( em.isOpen() ); em.getTransaction().begin(); assertTrue( em.isOpen() ); em.getTransaction().rollback(); em.close(); assertFalse( em.isOpen() ); } //EJB-9 public void testGet() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Item item = ( Item ) em.getReference( Item.class, "nonexistentone" ); try { item.getDescr(); em.getTransaction().commit(); fail( "Object with wrong id should have failed" ); } catch ( EntityNotFoundException e ) { //success if ( em.getTransaction() != null ) { em.getTransaction().rollback(); } } finally { em.close(); } } public void testGetProperties() throws Exception { EntityManager em = getOrCreateEntityManager(); Map properties = em.getProperties(); assertNotNull( properties ); try { properties.put( "foo", "bar" ); fail(); } catch ( UnsupportedOperationException e ) { // success } assertTrue( properties.containsKey( AvailableSettings.FLUSH_MODE ) ); } public void testSetProperty() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Wallet wallet = new Wallet(); wallet.setSerial( "000" ); em.persist( wallet ); em.getTransaction().commit(); em.clear(); assertEquals( em.getProperties().get( AvailableSettings.FLUSH_MODE ), "AUTO" ); assertNotNull( "With default settings the entity should be persisted on commit.", em.find( Wallet.class, wallet.getSerial() ) ); em.getTransaction().begin(); wallet = em.merge( wallet ); em.remove( wallet ); em.getTransaction().commit(); em.clear(); assertNull( "The entity should have been removed.", em.find( Wallet.class, wallet.getSerial() ) ); em.setProperty( "org.hibernate.flushMode", "MANUAL" + "" ); em.getTransaction().begin(); wallet = new Wallet(); wallet.setSerial( "000" ); em.persist( wallet ); em.getTransaction().commit(); em.clear(); assertNull( "With a flush mode of manual the entity should not have been persisted.", em.find( Wallet.class, wallet.getSerial() ) ); assertEquals( "MANUAL", em.getProperties().get( AvailableSettings.FLUSH_MODE ) ); em.close(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Wallet.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000153011714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Wallet implements Serializable { private String serial; private String model; private Date marketEntrance; private String brand; @Id public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Date getMarketEntrance() { return marketEntrance; } public void setMarketEntrance(Date marketEntrance) { this.marketEntrance = marketEntrance; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/connection/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/connection/DataSourceInjectionTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000337011714611271032754 0ustar ebourgebourg//$Id$ /* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.connection; import java.io.File; import javax.persistence.EntityManagerFactory; import junit.framework.TestCase; import org.hibernate.ejb.HibernatePersistence; /** * @author Emmanuel Bernard */ public class DataSourceInjectionTest extends TestCase { public void testDatasourceInjection() throws Exception { File current = new File("."); File sub = new File(current, "puroot"); sub.mkdir(); PersistenceUnitInfoImpl info = new PersistenceUnitInfoImpl( sub.toURI().toURL(), new String[]{} ); try { new HibernatePersistence().createContainerEntityManagerFactory( info, null ); fail( "FakeDatasource should have been used" ); } catch (FakeDataSourceException fde) { //success } finally { sub.delete(); } } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/connection/FakeDataSource.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000231211714611271032747 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.connection; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; /** * @author Emmanuel Bernard */ public class FakeDataSource implements DataSource { public Connection getConnection() throws SQLException { throw new FakeDataSourceException( "connection" ); } public Connection getConnection(String username, String password) throws SQLException { throw new FakeDataSourceException( "connection with password" ); } public PrintWriter getLogWriter() throws SQLException { throw new FakeDataSourceException( "getLogWriter" ); } public void setLogWriter(PrintWriter out) throws SQLException { throw new FakeDataSourceException( "setLogWriter" ); } public void setLoginTimeout(int seconds) throws SQLException { throw new FakeDataSourceException( "setLoginTimeout" ); } public int getLoginTimeout() throws SQLException { throw new FakeDataSourceException( "getLoginTimeout" ); } public T unwrap(Class tClass) throws SQLException { throw new UnsupportedOperationException("not yet supported"); } public boolean isWrapperFor(Class aClass) throws SQLException { return false; } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/connection/FakeDataSourceException.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000034211714611271032750 0ustar ebourgebourg//$Id$ package org.hibernate.ejb.test.connection; /** * @author Emmanuel Bernard */ public class FakeDataSourceException extends RuntimeException { public FakeDataSourceException(String message) { super( message ); } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/connection/PersistenceUnitInfoImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000715411714611271032760 0ustar ebourgebourg//$Id$ /* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.test.connection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.persistence.SharedCacheMode; import javax.persistence.ValidationMode; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.sql.DataSource; import org.hibernate.cfg.Environment; import org.hibernate.ejb.HibernatePersistence; import org.hibernate.ejb.test.Distributor; import org.hibernate.ejb.test.Item; import org.hibernate.ejb.test.xml.Light; import org.hibernate.ejb.test.xml.Lighter; /** * @author Emmanuel Bernard */ public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { private Properties properties = new Properties(); private List mappingFiles; private URL puRoot; public PersistenceUnitInfoImpl(URL puRoot, String[] mappingFiles) { this.mappingFiles = new ArrayList( mappingFiles.length ); this.mappingFiles.addAll( Arrays.asList( mappingFiles ) ); this.puRoot = puRoot; } public String getPersistenceUnitName() { return "persistenceinfo"; } public String getPersistenceProviderClassName() { return HibernatePersistence.class.getName(); } public DataSource getJtaDataSource() { return new FakeDataSource(); } public DataSource getNonJtaDataSource() { return null; } public List getMappingFileNames() { return mappingFiles; } public List getJarFileUrls() { return new ArrayList(); } public List getManagedClassNames() { List classes = new ArrayList(); classes.add( Item.class.getName() ); classes.add( Distributor.class.getName() ); classes.add( Light.class.getName() ); classes.add( Lighter.class.getName() ); return classes; } public Properties getProperties() { properties.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); return properties; } public String getPersistenceXMLSchemaVersion() { return null; } public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } public PersistenceUnitTransactionType getTransactionType() { return null; } public URL getPersistenceUnitRootUrl() { return puRoot; } public boolean excludeUnlistedClasses() { return true; } public SharedCacheMode getSharedCacheMode() { return null; } public ValidationMode getValidationMode() { return null; } public void addTransformer(ClassTransformer transformer) { } public ClassLoader getNewTempClassLoader() { return Thread.currentThread().getContextClassLoader(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/mapping/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000755000175000017500000000000012143273450032747 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/mapping/Phone.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000215711714611271032756 0ustar ebourgebourgpackage org.hibernate.ejb.test.mapping; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityResult; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SqlResultSetMapping; import javax.persistence.Table; /** * @author Emmanuel Bernard */ @Entity @Table(name = "PHONE") public class Phone implements java.io.Serializable { private Integer id; private String brandName; private float price; public Phone() { } @Id @Column(name="ID") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="BRANDNAME") public String getBrandName() { return brandName; } public void setBrandName(String bName) { this.brandName = bName; } @Column(name="PRICE") public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/mapping/QuotingTest.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test0000644000175000017500000000071211714611271032751 0ustar ebourgebourgpackage org.hibernate.ejb.test.mapping; import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class QuotingTest extends TestCase { public void testQuote() { // the configuration was failing } @Override public String[] getEjb3DD() { return new String[] { "org/hibernate/ejb/test/mapping/orm.xml" }; } @Override protected Class[] getAnnotatedClasses() { return new Class[] { Phone.class }; } } libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/java/NoPackageEntity.java0000644000175000017500000000020111714611271032440 0ustar ebourgebourg//$Id$ /** * @author Emmanuel Bernard */ public class NoPackageEntity { private Integer id; private String name; } libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/0000755000175000017500000000000011714611271027272 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/0000755000175000017500000000000011714611271032060 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000011714611271032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000011714611271032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000011714611271032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000011714611271032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000011714611271032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/ejb/test/pack/defaultpar_1_0/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000755000175000017500000000000012143273450032647 5ustar ebourgebourg././@LongLink0000000000000000000000000000023200000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/hibernate/ejb/test/pack/defaultpar_1_0/Mouse1.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/org/0000644000175000017500000000067011714611271032654 0ustar ebourgebourg ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META0000755000175000017500000000000012143273450032527 5ustar ebourgebourg././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META0000644000175000017500000000233311714611271032532 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar.Lighter ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META-INF/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar_1_0/META0000644000175000017500000000272411714611271032536 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar_1_0 libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/space par/0000755000175000017500000000000011714611271031130 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/space par/META-INF/0000755000175000017500000000000012143273450032270 5ustar ebourgebourg././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/space par/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/space par/META-INF/0000644000175000017500000000224311714611271032273 0ustar ebourgebourg libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/0000755000175000017500000000000011714611271031421 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/0000755000175000017500000000000011714611271032210 5ustar ebourgebourg././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000755000175000017500000000000011714611271033040 5ustar ebourgebourg././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000755000175000017500000000000011714611271033040 5ustar ebourgebourg././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000755000175000017500000000000011714611271033040 5ustar ebourgebourg././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000755000175000017500000000000011714611271033040 5ustar ebourgebourg././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/ejb/test/pack/defaultpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000755000175000017500000000000012143273450033040 5ustar ebourgebourg././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibernate/ejb/test/pack/defaultpar/Mouse.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/org/hibe0000644000175000017500000000066311714611271033047 0ustar ebourgebourg ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF0000755000175000017500000000000012143273450032502 5ustar ebourgebourg././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF0000644000175000017500000000241311714611271032504 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar.Lighter CALLBACK ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/defaultpar/META-INF0000644000175000017500000000246011714611271032506 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/0000755000175000017500000000000011714611271031601 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/0000755000175000017500000000000011714611271032370 5ustar ebourgebourg././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000755000175000017500000000000011714611271033053 5ustar ebourgebourg././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000755000175000017500000000000011714611271033053 5ustar ebourgebourg././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000755000175000017500000000000011714611271033053 5ustar ebourgebourg././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000755000175000017500000000000011714611271033053 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000755000175000017500000000000012143273450033053 5ustar ebourgebourg././@LongLink0000000000000000000000000000022600000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hibernate/ejb/test/pack/explodedpar/Elephant.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/org/hib0000644000175000017500000000064211714611271033057 0ustar ebourgebourg ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/META-IN0000755000175000017500000000000012143273450032554 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explodedpar/META-IN0000644000175000017500000000226411714611271032562 0ustar ebourgebourg libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/0000755000175000017500000000000011714611271031255 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/0000755000175000017500000000000011714611271032044 5ustar ebourgebourg././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000755000175000017500000000000011714611271033056 5ustar ebourgebourg././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000755000175000017500000000000011714611271033056 5ustar ebourgebourg././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000755000175000017500000000000011714611271033056 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000755000175000017500000000000011714611271033056 5ustar ebourgebourg././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/ejb/test/pack/cfgxmlpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000755000175000017500000000000012143273450033056 5ustar ebourgebourg././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hibernate/ejb/test/pack/cfgxmlpar/hibernate.cfg.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/org/hiber0000644000175000017500000000342011714611271033057 0ustar ebourgebourg ${db.dialect} ${jdbc.driver} ${jdbc.user} ${jdbc.pass} ${jdbc.url} ${jdbc.isolation} true hibernate.test true 0 3 create-drop true org.hibernate.cache.HashtableCacheProvider libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/META-INF/0000755000175000017500000000000012143273450032415 5ustar ebourgebourg././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/cfgxmlpar/META-INF/0000644000175000017500000000131411714611271032416 0ustar ebourgebourg org.hibernate.ejb.HibernatePersistence libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/0000755000175000017500000000000011714611271031616 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-IN0000755000175000017500000000000012143273450032571 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-IN0000644000175000017500000000607411714611271032602 0ustar ebourgebourg ${basedir}/target/packages/externaljar.jar org.hibernate.ejb.test.Cat org.hibernate.ejb.test.Kitten org.hibernate.ejb.test.Distributor org.hibernate.ejb.test.Item true ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-INF/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/explicitpar/META-IN0000644000175000017500000000113511714611271032573 0ustar ebourgebourg org.hibernate.ejb.test.pack.various libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/0000755000175000017500000000000011714611271032115 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/0000755000175000017500000000000011714611271032704 5ustar ebourgebourg././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000755000175000017500000000000011714611271033054 5ustar ebourgebourg././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000755000175000017500000000000011714611271033054 5ustar ebourgebourg././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000755000175000017500000000000011714611271033054 5ustar ebourgebourg././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000755000175000017500000000000011714611271033054 5ustar ebourgebourg././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/ejb/test/pack/excludehbmpar/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000755000175000017500000000000012143273450033054 5ustar ebourgebourg././@LongLink0000000000000000000000000000022700000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/hibernate/ejb/test/pack/excludehbmpar/Mouse.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/org/h0000644000175000017500000000066611714611271033066 0ustar ebourgebourg ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-0000755000175000017500000000000012143273450032641 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-0000644000175000017500000000247211714611271032650 0ustar ebourgebourg META-INF/orm2.xml ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-INF/orm2.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/excludehbmpar/META-0000644000175000017500000000121111714611271032636 0ustar ebourgebourg org.hibernate.ejb.test.xml libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/externaljar/0000755000175000017500000000000011714611271031611 5ustar ebourgebourg././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/externaljar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/externaljar/META-IN0000755000175000017500000000000012143273450032564 5ustar ebourgebourg././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/externaljar/META-INF/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/externaljar/META-IN0000644000175000017500000000105611714611271032570 0ustar ebourgebourg org.hibernate.ejb.test.pack.various libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/0000755000175000017500000000000011714611271030063 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/0000755000175000017500000000000011714611271031112 5ustar ebourgebourg././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000011714611271032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000012143273450032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/org/hibernate/ejb/test/pack/war/Mouse.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000644000175000017500000000065511714611271032500 0ustar ebourgebourg ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000755000175000017500000000000012143273450032470 5ustar ebourgebourg././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000644000175000017500000000233111714611271032471 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar.Lighter ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes/META-INF/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/war/WEB-INF/classes0000644000175000017500000000242411714611271032474 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/0000755000175000017500000000000012143273450031772 5ustar ebourgebourg././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/overridenpar.propertieslibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/overri0000644000175000017500000000033411714611271033223 0ustar ebourgebourghibernate.connection.driver_class ${jdbc.driver} hibernate.connection.url ${jdbc.url} hibernate.connection.username ${jdbc.user} hibernate.connection.password ${jdbc.pass} hibernate.connection.isolation ${jdbc.isolation}././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/META-INF/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/META-I0000755000175000017500000000000012143273450032627 5ustar ebourgebourg././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/META-INF/persistence.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/bundles/overridenpar/META-I0000644000175000017500000000141411714611271032631 0ustar ebourgebourg java:/unreachableDS libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/0000755000175000017500000000000012143273450027650 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/log4j.properties0000644000175000017500000000227711714611271033015 0ustar ebourgebourglog4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=warn, stdout log4j.logger.org.hibernate=debug #log4j.logger.org.hibernate=debug log4j.logger.org.hibernate.ejb=debug log4j.logger.org.hibernate.ejb.packaging=debug log4j.logger.org.hibernate.reflection=debug #log4j.logger.org.hibernate.engine.Cascades=debug #log4j.logger.org.hibernate.hql=debug ### log just the SQL log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### #log4j.logger.org.hibernate.type=info log4j.logger.org.hibernate.type=trace ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/hibernate.propertieslibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/hibernate.propert0000644000175000017500000000330311714611271033225 0ustar ebourgebourg################################################################################ # Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved. # # # # This copyrighted material is made available to anyone wishing to use, modify,# # copy, or redistribute it subject to the terms and conditions of the GNU # # Lesser General Public License, v. 2.1. This program is distributed in the # # hope that it will be useful, but WITHOUT A WARRANTY; without even the implied# # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # Lesser General Public License for more details. You should have received a # # copy of the GNU Lesser General Public License, v.2.1 along with this # # distribution; if not, write to the Free Software Foundation, Inc., # # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # # # Red Hat Author(s): Steve Ebersole # ################################################################################ hibernate.dialect ${db.dialect} hibernate.connection.driver_class ${jdbc.driver} hibernate.connection.url ${jdbc.url} hibernate.connection.username ${jdbc.user} hibernate.connection.password ${jdbc.pass} hibernate.connection.isolation ${jdbc.isolation} hibernate.connection.pool_size 5 hibernate.show_sql true hibernate.format_sql true hibernate.max_fetch_depth 5 hibernate.cache.region_prefix hibernate.test hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider hibernate.jdbc.batch_size 0 libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/0000755000175000017500000000000011714611271030437 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/0000755000175000017500000000000011714611271032400 5ustar ebourgebourg././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000011714611271033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/ejb3configuration/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/ejb3configuration/hibernate.cfg.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000056711714611271033073 0ustar ebourgebourg ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/sequences/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/sequences/orm3.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000404511714611271033066 0ustar ebourgebourg ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/sequences/orm2.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000201011714611271033054 0ustar ebourgebourg ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/sequences/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000224311714611271033064 0ustar ebourgebourg MY_SCHEMA MY_CATALOG PROPERTY org.hibernate.ejb.test.xml.sequences ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/orm3.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000447111714611271033071 0ustar ebourgebourg ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/orm2.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000177611714611271033076 0ustar ebourgebourg ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/xml/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000222611714611271033065 0ustar ebourgebourg MY_SCHEMA MY_CATALOG PROPERTY org.hibernate.ejb.test.xml ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/ops/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/ops/Employer.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000200411714611271033057 0ustar ebourgebourg ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/ops/Node.hbm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000233411714611271033065 0ustar ebourgebourg ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/jee/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/jee/valid-orm-2.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000454011714611271033066 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/jee/invalid-orm-1.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000500311714611271033061 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar_1_0 ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/jee/valid-orm-1.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000462411714611271033071 0ustar ebourgebourg org.hibernate.ejb.test.pack.defaultpar_1_0 ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/hibernate.cfg.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000323711714611271033070 0ustar ebourgebourg org.hibernate.dialect.HSQLDialect org.hsqldb.jdbcDriver sa jdbc:hsqldb:. true hibernate.test true 0 3 create-drop true org.hibernate.cache.HashtableCacheProvider ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/mapping/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000755000175000017500000000000012143273450033061 5ustar ebourgebourg././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb/test/mapping/orm.xmllibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/test/resources/org/hibernate/ejb0000644000175000017500000000047411714611271033070 0ustar ebourgebourg libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/0000755000175000017500000000000011714611271025603 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/0000755000175000017500000000000011714611271026524 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/0000755000175000017500000000000011714611271027313 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/0000755000175000017500000000000011714611271031254 5ustar ebourgebourglibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/engine/0000755000175000017500000000000012143273450032521 5ustar ebourgebourg././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadeStyle.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/engine/E0000644000175000017500000000337711714611271032642 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.engine; /** * Becasue CascadeStyle is not opened and package protected, * I need to subclass and override the persist alias * * Note that This class has to be triggered by EJB3PersistEventListener at class loading time * * TODO get rid of it for 3.3 * * @author Emmanuel Bernard */ public abstract class EJB3CascadeStyle extends CascadeStyle { /** * cascade using EJB3CascadingAction */ public static final CascadeStyle PERSIST_EJB3 = new CascadeStyle() { public boolean doCascade(CascadingAction action) { return action==EJB3CascadingAction.PERSIST_SKIPLAZY || action==CascadingAction.PERSIST_ON_FLUSH; } public String toString() { return "STYLE_PERSIST_SKIPLAZY"; } }; static { STYLES.put( "persist", PERSIST_EJB3 ); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadingAction.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/engine/E0000644000175000017500000000462511714611271032637 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.engine; import java.util.Map; import java.util.Iterator; import org.hibernate.event.EventSource; import org.hibernate.HibernateException; import org.hibernate.type.CollectionType; import org.slf4j.LoggerFactory; import org.slf4j.Logger; /** * Because of CascadingAction constructor visibility * I need a packaged friendly subclass * TODO Get rid of it for 3.3 * @author Emmanuel Bernard */ public abstract class EJB3CascadingAction extends CascadingAction { private static Logger log = LoggerFactory.getLogger( CascadingAction.class ); /** * @see org.hibernate.Session#persist(Object) */ public static final CascadingAction PERSIST_SKIPLAZY = new CascadingAction() { public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { log.trace( "cascading to persist: {}", entityName ); session.persist( entityName, child, (Map) anything ); } public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // persists don't cascade to uninitialized collections return CascadingAction.getLoadedElementsIterator( session, collectionType, collection ); } public boolean deleteOrphans() { return false; } public boolean performOnLazyProperty() { return false; } public String toString() { return "ACTION_PERSIST_SKIPLAZY"; } }; } libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/0000755000175000017500000000000012143273450032014 5ustar ebourgebourg././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EventListenerConfigurator.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Even0000644000175000017500000002562211714611271032643 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.ejb.event.CallbackHandlerConsumer; import org.hibernate.ejb.event.EJB3AutoFlushEventListener; import org.hibernate.ejb.event.EJB3DeleteEventListener; import org.hibernate.ejb.event.EJB3FlushEntityEventListener; import org.hibernate.ejb.event.EJB3FlushEventListener; import org.hibernate.ejb.event.EJB3MergeEventListener; import org.hibernate.ejb.event.EJB3PersistEventListener; import org.hibernate.ejb.event.EJB3PersistOnFlushEventListener; import org.hibernate.ejb.event.EJB3PostDeleteEventListener; import org.hibernate.ejb.event.EJB3PostInsertEventListener; import org.hibernate.ejb.event.EJB3PostLoadEventListener; import org.hibernate.ejb.event.EJB3PostUpdateEventListener; import org.hibernate.ejb.event.EJB3SaveEventListener; import org.hibernate.ejb.event.EJB3SaveOrUpdateEventListener; import org.hibernate.ejb.event.EntityCallbackHandler; import org.hibernate.event.AutoFlushEventListener; import org.hibernate.event.DeleteEventListener; import org.hibernate.event.EventListeners; import org.hibernate.event.FlushEntityEventListener; import org.hibernate.event.FlushEventListener; import org.hibernate.event.MergeEventListener; import org.hibernate.event.PersistEventListener; import org.hibernate.event.PostDeleteEventListener; import org.hibernate.event.PostInsertEventListener; import org.hibernate.event.PostLoadEventListener; import org.hibernate.event.PostUpdateEventListener; import org.hibernate.event.PreDeleteEventListener; import org.hibernate.event.PreInsertEventListener; import org.hibernate.event.PreLoadEventListener; import org.hibernate.event.PreUpdateEventListener; import org.hibernate.event.SaveOrUpdateEventListener; import org.hibernate.event.def.DefaultPostLoadEventListener; import org.hibernate.event.def.DefaultPreLoadEventListener; import org.hibernate.mapping.PersistentClass; import org.hibernate.secure.JACCPreDeleteEventListener; import org.hibernate.secure.JACCPreInsertEventListener; import org.hibernate.secure.JACCPreLoadEventListener; import org.hibernate.secure.JACCPreUpdateEventListener; import org.hibernate.secure.JACCSecurityListener; /** * @author Emmanuel Bernard */ public class EventListenerConfigurator { private static final Object[] READER_METHOD_ARGS = new Object[0]; private Ejb3Configuration configuration; private boolean isSecurity; public EventListenerConfigurator(Ejb3Configuration configuration) { this.configuration = configuration; EventListeners listenerConfig = configuration.getEventListeners(); //Action event //EJB3-specific ops listeners listenerConfig.setFlushEventListeners( new FlushEventListener[] { EJB3FlushEventListener.INSTANCE } ); //EJB3-specific ops listeners listenerConfig.setAutoFlushEventListeners( new AutoFlushEventListener[] { EJB3AutoFlushEventListener.INSTANCE } ); listenerConfig.setDeleteEventListeners( new DeleteEventListener[] { new EJB3DeleteEventListener() } ); listenerConfig.setFlushEntityEventListeners( new FlushEntityEventListener[] { new EJB3FlushEntityEventListener() } ); listenerConfig.setMergeEventListeners( new MergeEventListener[] { new EJB3MergeEventListener() } ); listenerConfig.setPersistEventListeners( new PersistEventListener[] { new EJB3PersistEventListener() } ); listenerConfig.setPersistOnFlushEventListeners( new PersistEventListener[] { new EJB3PersistOnFlushEventListener() } ); listenerConfig.setSaveEventListeners( new SaveOrUpdateEventListener[] { new EJB3SaveEventListener() } ); listenerConfig.setSaveOrUpdateEventListeners( new SaveOrUpdateEventListener[] { new EJB3SaveOrUpdateEventListener() } ); //Pre events listenerConfig.setPreInsertEventListeners( new PreInsertEventListener[] { new JACCPreInsertEventListener(), } ); listenerConfig.setPreUpdateEventListeners( new PreUpdateEventListener[] { new JACCPreUpdateEventListener(), } ); listenerConfig.setPreDeleteEventListeners( new PreDeleteEventListener[] { new JACCPreDeleteEventListener() } ); //Add the default Hibernate Core PreLoadEventListener //TODO shouldn't we read the value from getPreLoadEventListeners and add JACC? //probably a better thing to do as it allows cfg.xml config but this is a big change and need more thoughts listenerConfig.setPreLoadEventListeners( new PreLoadEventListener[] { new DefaultPreLoadEventListener(), new JACCPreLoadEventListener() } ); //post events listenerConfig.setPostDeleteEventListeners( new PostDeleteEventListener[] { new EJB3PostDeleteEventListener() } ); listenerConfig.setPostInsertEventListeners( new PostInsertEventListener[] { new EJB3PostInsertEventListener() } ); //Add the default Hibernate Core PostLoadEventListener //TODO shouldn't we read the value from getPostLoadEventListeners //probably a better thing to do as it allows cfg.xml config but this is a big change and need more thoughts listenerConfig.setPostLoadEventListeners( new PostLoadEventListener[] { new EJB3PostLoadEventListener(), new DefaultPostLoadEventListener() } ); EJB3PostUpdateEventListener postUpdateEventListener = new EJB3PostUpdateEventListener(); listenerConfig.setPostUpdateEventListeners( new PostUpdateEventListener[] { postUpdateEventListener } ); // EJB-288 - registration of post collection listeners. Commented out due to problem // of duplicated callbacks. See Jira. // listenerConfig.setPostCollectionRecreateEventListeners( // new PostCollectionRecreateEventListener[] { postUpdateEventListener }); // // listenerConfig.setPostCollectionRemoveEventListeners( // new PostCollectionRemoveEventListener[] { postUpdateEventListener }); // // listenerConfig.setPostCollectionUpdateEventListeners( // new PostCollectionUpdateEventListener[] { postUpdateEventListener }); } public void setProperties(Properties properties) { if ( properties.containsKey( AvailableSettings.JACC_ENABLED ) ) { isSecurity = true; } //override events if needed Enumeration enumeration = properties.propertyNames(); while ( enumeration.hasMoreElements() ) { String name = (String) enumeration.nextElement(); if ( name.startsWith( AvailableSettings.EVENT_LISTENER_PREFIX ) ) { String type = name.substring( AvailableSettings.EVENT_LISTENER_PREFIX.length() + 1 ); StringTokenizer st = new StringTokenizer( properties.getProperty( name ), " ,", false ); List listeners = new ArrayList(); while ( st.hasMoreElements() ) { listeners.add( (String) st.nextElement() ); } configuration.setListeners( type, listeners.toArray( new String[listeners.size()] ) ); } } } @SuppressWarnings("unchecked") public void configure() { //TODO exclude pure hbm file classes? //TODO move it to each event listener initialize()? EntityCallbackHandler callbackHandler = new EntityCallbackHandler(); configuration.buildMappings(); //needed to get all the classes Iterator classes = configuration.getClassMappings(); ReflectionManager reflectionManager = configuration.getHibernateConfiguration().getReflectionManager(); while ( classes.hasNext() ) { PersistentClass clazz = (PersistentClass) classes.next(); if ( clazz.getClassName() != null ) { //we can have non java class persisted by hibernate try { callbackHandler.add( reflectionManager.classForName( clazz.getClassName(), this.getClass() ), reflectionManager ); } catch (ClassNotFoundException e) { throw new MappingException( "entity class not found: " + clazz.getNodeName(), e ); } } } EventListeners listenerConfig = configuration.getEventListeners(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo( listenerConfig.getClass(), Object.class ); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); try { for (int i = 0, max = pds.length; i < max; i++) { final Object listeners = pds[i].getReadMethod().invoke( listenerConfig, READER_METHOD_ARGS ); if ( listeners == null ) { throw new HibernateException( "Listener [" + pds[i].getName() + "] was null" ); } if ( listeners instanceof Object[] ) { int securityListenersNbr = 0; Object[] listenersArray = (Object[]) listeners; for (Object listener : listenersArray) { if ( listener != null && listener instanceof CallbackHandlerConsumer ) { ( (CallbackHandlerConsumer) listener ).setCallbackHandler( callbackHandler ); } if ( listener != null && listener instanceof JACCSecurityListener ) { if ( !isSecurity ) { securityListenersNbr++; } } } if ( !isSecurity ) { Class clazz = pds[i].getReadMethod().getReturnType().getComponentType(); Object newArray = Array.newInstance( clazz, listenersArray.length - securityListenersNbr ); int index = 0; for (Object listener : listenersArray) { if ( !( listener != null && listener instanceof JACCSecurityListener ) ) { Array.set( newArray, index++, listener ); } } pds[i].getWriteMethod().invoke( listenerConfig, newArray ); } } } } catch (HibernateException e) { throw e; } catch (Throwable t) { throw new HibernateException( "Unable to validate listener config", t ); } } catch (Exception t) { throw new HibernateException( "Unable to copy listeners", t ); } finally { if ( beanInfo != null ) { // release the jdk internal caches everytime to ensure this // plays nicely with destroyable class-loaders Introspector.flushFromCaches( listenerConfig.getClass() ); } } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/transaction/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/tran0000755000175000017500000000000012143273450032701 5ustar ebourgebourg././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/transaction/JoinableCMTTransaction.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/tran0000644000175000017500000000737511714611271032717 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.transaction; import javax.transaction.SystemException; import javax.transaction.Transaction; import org.hibernate.HibernateException; import org.hibernate.TransactionException; import org.hibernate.jdbc.JDBCContext; import org.hibernate.transaction.CMTTransaction; import org.hibernate.transaction.TransactionFactory; import org.hibernate.util.JTAHelper; /** * Implements a joinable transaction. Until the transaction is marked for joined, the TM.isTransactionInProgress() * must return false * * @author Emmanuel Bernard */ public class JoinableCMTTransaction extends CMTTransaction { private JoinStatus status; public JoinableCMTTransaction(JDBCContext jdbcContext, TransactionFactory.Context transactionContext) { super( jdbcContext, transactionContext ); //status = JoinStatus.MARKED_FOR_JOINED; //tryJoiningTransaction(); } public boolean isTransactionInProgress( JDBCContext jdbcContext, TransactionFactory.Context transactionContext) { try { return status == JoinStatus.JOINED && isTransactionInProgress( transactionContext.getFactory().getTransactionManager().getTransaction() ); } catch (SystemException se) { throw new TransactionException( "Unable to check transaction status", se ); } } private boolean isTransactionInProgress() { try { Transaction transaction = transactionContext.getFactory().getTransactionManager().getTransaction(); return isTransactionInProgress(transaction); } catch (SystemException se) { throw new TransactionException( "Unable to check transaction status", se ); } } private boolean isTransactionInProgress(Transaction tx) throws SystemException { return JTAHelper.isTransactionInProgress(tx) && ! JTAHelper.isRollback( tx.getStatus() ); } void tryJoiningTransaction() { if ( status == JoinStatus.MARKED_FOR_JOINED ) { if ( isTransactionInProgress() ) { status = JoinStatus.JOINED; } else { status = JoinStatus.NOT_JOINED; } } } @Override public void begin() throws HibernateException { super.begin(); status = JoinStatus.JOINED; } @Override public void commit() throws HibernateException { /* this method is not supposed to be called * it breaks the flushBeforeCompletion flag optimizeation * regarding flushing skip. * In its current form, it will generate too much flush() calls */ super.commit(); } public JoinStatus getStatus() { return status; } public void resetStatus() { status = JoinStatus.NOT_JOINED; } public void markForJoined() { if ( status != JoinStatus.JOINED ) status = JoinStatus.MARKED_FOR_JOINED; } public static enum JoinStatus { NOT_JOINED, MARKED_FOR_JOINED, JOINED } } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/transaction/JoinableCMTTransactionFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/tran0000644000175000017500000000416411714611271032710 0ustar ebourgebourg/* * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.transaction; import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.jdbc.JDBCContext; import org.hibernate.transaction.CMTTransactionFactory; /** * A transaction is in progress if the underlying JTA tx is in progress and if the Tx is marked as * MARKED_FOR_JOINED * * @author Emmanuel Bernard */ public class JoinableCMTTransactionFactory extends CMTTransactionFactory { public Transaction createTransaction( JDBCContext jdbcContext, Context transactionContext) throws HibernateException { return new JoinableCMTTransaction( jdbcContext, transactionContext ); } @Override public boolean isTransactionInProgress( JDBCContext jdbcContext, Context transactionContext, Transaction transaction) { if ( transaction == null ) { return false; //should not happen though } JoinableCMTTransaction joinableCMTTransaction = ( (JoinableCMTTransaction) transaction ); joinableCMTTransaction.tryJoiningTransaction(); return joinableCMTTransaction.isTransactionInProgress( jdbcContext, transactionContext ); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032676 5ustar ebourgebourg././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/OrderImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000345311714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import javax.persistence.criteria.Order; import javax.persistence.criteria.Expression; /** * Represents an ORDER BY fragment. * * @author Steve Ebersole */ public class OrderImpl implements Order, Serializable { private final Expression expression; private boolean ascending; public OrderImpl(Expression expression) { this( expression, true ); } public OrderImpl(Expression expression, boolean ascending) { this.expression = expression; this.ascending = ascending; } public Order reverse() { ascending = !ascending; return this; } public boolean isAscending() { return ascending; } public Expression getExpression() { return expression; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/AbstractNode.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000343011714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; /** * All nodes in a criteria query tree will generally need access to the {@link CriteriaBuilderImpl} from which they * come. This base class provides convenient, consistent support for that. * * @author Steve Ebersole */ public class AbstractNode implements Serializable { private final CriteriaBuilderImpl criteriaBuilder; public AbstractNode(CriteriaBuilderImpl criteriaBuilder) { this.criteriaBuilder = criteriaBuilder; } /** * Provides protected access to the underlying {@link CriteriaBuilderImpl}. * * @return The underlying {@link CriteriaBuilderImpl} instance. */ protected CriteriaBuilderImpl criteriaBuilder() { return criteriaBuilder; } } ././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/IllegalDereferenceException.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000310611714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; /** * Represents an illegal attempt to dereference from a {@link #getPathSource() path source} which * cannot be dereferenced. * * @author Steve Ebersole */ public class IllegalDereferenceException extends RuntimeException { private final PathSource pathSource; public IllegalDereferenceException(PathSource pathSource) { super( "Illegal attempt to dereference path source [" + pathSource.getPathIdentifier() + "]" ); this.pathSource = pathSource; } public PathSource getPathSource() { return pathSource; } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CollectionJoinImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000275111714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.CollectionJoin; /** * Specialization of {@link JoinImplementor} for {@link java.util.Collection} typed attribute joins * * @author Steve Ebersole */ public interface CollectionJoinImplementor extends JoinImplementor, CollectionJoin { /** * {@inheritDoc} *

* Refined return type */ public CollectionJoinImplementor correlateTo(CriteriaSubqueryImpl subquery); } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/PathSource.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000310511714611271032677 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.Path; /** * Implementation contract for things which can be the source (parent, left-hand-side, etc) of a path * * @author Steve Ebersole */ public interface PathSource extends Path { public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext); /** * Get the string representation of this path as a navigation from one of the * queries identification variables * * @return The path's identifier. */ public String getPathIdentifier(); } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032676 5ustar ebourgebourg././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/RootImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000540511714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; /** * TODO : javadoc * * @author Steve Ebersole */ public class RootImpl extends AbstractFromImpl implements Root, Serializable { private final EntityType entityType; public RootImpl( CriteriaBuilderImpl criteriaBuilder, EntityType entityType) { super( criteriaBuilder, entityType.getJavaType() ); this.entityType = entityType; } public EntityType getEntityType() { return entityType; } public EntityType getModel() { return getEntityType(); } @Override protected FromImplementor createCorrelationDelegate() { return new RootImpl( criteriaBuilder(), getEntityType() ); } @Override public RootImpl correlateTo(CriteriaSubqueryImpl subquery) { return (RootImpl) super.correlateTo( subquery ); } @Override protected boolean canBeJoinSource() { return true; } public String renderTableExpression(CriteriaQueryCompiler.RenderingContext renderingContext) { prepareAlias( renderingContext ); return getModel().getName() + " as " + getAlias(); } @Override public String getPathIdentifier() { return getAlias(); } @Override public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { prepareAlias( renderingContext ); return getAlias(); } @Override public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/MapAttributeJoin.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000676411714611271032715 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.Map; import javax.persistence.criteria.Expression; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Path; import javax.persistence.metamodel.MapAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.MapJoinImplementor; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.expression.MapEntryExpression; /** * TODO : javadoc * * @author Steve Ebersole */ public class MapAttributeJoin extends PluralAttributeJoinSupport, V> implements MapJoinImplementor, Serializable { public MapAttributeJoin( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, MapAttribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); } @Override public MapAttribute getAttribute() { return (MapAttribute) super.getAttribute(); } @Override public MapAttribute getModel() { return getAttribute(); } @Override public final MapAttributeJoin correlateTo(CriteriaSubqueryImpl subquery) { return (MapAttributeJoin) super.correlateTo( subquery ); } @Override protected FromImplementor createCorrelationDelegate() { return new MapAttributeJoin( criteriaBuilder(), getJavaType(), (PathImplementor) getParentPath(), getAttribute(), getJoinType() ); } /** * {@inheritDoc} */ public Path value() { return this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression> entry() { return new MapEntryExpression( criteriaBuilder(), Map.Entry.class, this, getAttribute() ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Path key() { final MapKeyHelpers.MapKeySource mapKeySource = new MapKeyHelpers.MapKeySource( criteriaBuilder(), getAttribute().getJavaType(), this, getAttribute() ); final MapKeyHelpers.MapKeyAttribute mapKeyAttribute = new MapKeyHelpers.MapKeyAttribute( criteriaBuilder(), getAttribute() ); return new MapKeyHelpers.MapKeyPath( criteriaBuilder(), mapKeySource, mapKeyAttribute ); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/AbstractPathImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000002072511714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Path; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.SingularAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.expression.PathTypeExpression; /** * Convenience base class for various {@link Path} implementors. * * @author Steve Ebersole */ public abstract class AbstractPathImpl extends ExpressionImpl implements Path, PathImplementor, Serializable { private final PathSource pathSource; private final Expression> typeExpression; private Map attributePathRegistry; /** * Constructs a basic path instance. * * @param criteriaBuilder The criteria builder * @param javaType The java type of this path * @param pathSource The source (or origin) from which this path originates */ @SuppressWarnings({ "unchecked" }) public AbstractPathImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource) { super( criteriaBuilder, javaType ); this.pathSource = pathSource; this.typeExpression = new PathTypeExpression( criteriaBuilder(), getJavaType() ); } public PathSource getPathSource() { return pathSource; } /** * {@inheritDoc} */ public PathSource getParentPath() { return getPathSource(); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression> type() { return typeExpression; } /** * {@inheritDoc} */ public String getPathIdentifier() { return getPathSource().getPathIdentifier() + "." + getAttribute().getName(); } protected abstract boolean canBeDereferenced(); protected final RuntimeException illegalDereference() { String message = "Illegal attempt to dereference path source"; PathSource source = getPathSource(); if ( source != null ) { message += " [" + getPathSource().getPathIdentifier() + "]"; } return new IllegalArgumentException(message); } protected final RuntimeException unknownAttribute(String attributeName) { String message = "Unable to resolve attribute [" + attributeName + "] against path"; PathSource source = getPathSource(); if ( source != null ) { message += " [" + source.getPathIdentifier() + "]"; } return new IllegalArgumentException(message); } protected final Path resolveCachedAttributePath(String attributeName) { return attributePathRegistry == null ? null : attributePathRegistry.get( attributeName ); } protected final void registerAttributePath(String attributeName, Path path) { if ( attributePathRegistry == null ) { attributePathRegistry = new HashMap(); } attributePathRegistry.put( attributeName, path ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Path get(SingularAttribute attribute) { if ( ! canBeDereferenced() ) { throw illegalDereference(); } SingularAttributePath path = (SingularAttributePath) resolveCachedAttributePath( attribute.getName() ); if ( path == null ) { path = new SingularAttributePath( criteriaBuilder(), attribute.getJavaType(), this, attribute ); registerAttributePath( attribute.getName(), path ); } return path; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public > Expression get(PluralAttribute attribute) { if ( ! canBeDereferenced() ) { throw illegalDereference(); } PluralAttributePath path = (PluralAttributePath) resolveCachedAttributePath( attribute.getName() ); if ( path == null ) { path = new PluralAttributePath( criteriaBuilder(), this, attribute ); registerAttributePath( attribute.getName(), path ); } return path; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public > Expression get(MapAttribute attribute) { if ( ! canBeDereferenced() ) { throw illegalDereference(); } PluralAttributePath path = (PluralAttributePath) resolveCachedAttributePath( attribute.getName() ); if ( path == null ) { path = new PluralAttributePath( criteriaBuilder(), this, attribute ); registerAttributePath( attribute.getName(), path ); } return path; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Path get(String attributeName) { if ( ! canBeDereferenced() ) { throw illegalDereference(); } final Attribute attribute = locateAttribute( attributeName ); if ( attribute.isCollection() ) { final PluralAttribute pluralAttribute = (PluralAttribute) attribute; if ( PluralAttribute.CollectionType.MAP.equals( pluralAttribute.getCollectionType() ) ) { return (PluralAttributePath) this.>get( (MapAttribute) pluralAttribute ); } else { return (PluralAttributePath) this.get( (PluralAttribute) pluralAttribute ); } } else { return get( (SingularAttribute) attribute ); } } /** * Get the attribute by name from the underlying model. This allows subclasses to * define exactly how the attribute is derived. * * @param attributeName The name of the attribute to locate * * @return The attribute; should never return null. * * @throws IllegalArgumentException If no such attribute exists */ protected final Attribute locateAttribute(String attributeName) { final Attribute attribute = locateAttributeInternal( attributeName ); if ( attribute == null ) { throw unknownAttribute( attributeName ); } return attribute; } /** * Get the attribute by name from the underlying model. This allows subclasses to * define exactly how the attribute is derived. Called from {@link #locateAttribute} * which also applies nullness checking for proper error reporting. * * @param attributeName The name of the attribute to locate * * @return The attribute; may be null. * * @throws IllegalArgumentException If no such attribute exists */ protected abstract Attribute locateAttributeInternal(String attributeName); /** * {@inheritDoc} */ public void registerParameters(ParameterRegistry registry) { // none to register } public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { // Make sure we delegate up to our source (eventually up to the path root) to // prepare the path properly. PathSource source = getPathSource(); if ( source != null ) { source.prepareAlias( renderingContext ); } } /** * {@inheritDoc} */ public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { PathSource source = getPathSource(); if ( source != null ) { source.prepareAlias( renderingContext ); return source.getPathIdentifier() + "." + getAttribute().getName(); } else { return getAttribute().getName(); } } /** * {@inheritDoc} */ public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/SetAttributeJoin.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000507411714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.Set; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.SetAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.SetJoinImplementor; /** * TODO : javadoc * * @author Steve Ebersole */ public class SetAttributeJoin extends PluralAttributeJoinSupport,E> implements SetJoinImplementor, Serializable { public SetAttributeJoin( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, SetAttribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); } @Override public SetAttribute getAttribute() { return (SetAttribute) super.getAttribute(); } @Override public SetAttribute getModel() { return getAttribute(); } @Override public final SetAttributeJoin correlateTo(CriteriaSubqueryImpl subquery) { return (SetAttributeJoin) super.correlateTo( subquery ); } @Override protected FromImplementor createCorrelationDelegate() { return new SetAttributeJoin( criteriaBuilder(), getJavaType(), (PathImplementor) getParentPath(), getAttribute(), getJoinType() ); } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/AbstractFromImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000004644611714611271032716 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import javax.persistence.criteria.CollectionJoin; import javax.persistence.criteria.Fetch; import javax.persistence.criteria.From; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.MapJoin; import javax.persistence.criteria.SetJoin; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.CollectionAttribute; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.Type; import org.hibernate.ejb.criteria.BasicPathUsageException; import org.hibernate.ejb.criteria.CollectionJoinImplementor; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.JoinImplementor; import org.hibernate.ejb.criteria.ListJoinImplementor; import org.hibernate.ejb.criteria.MapJoinImplementor; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.SetJoinImplementor; /** * Convenience base class for various {@link javax.persistence.criteria.From} implementors. * * @author Steve Ebersole */ public abstract class AbstractFromImpl extends AbstractPathImpl implements From, FromImplementor, Serializable { public static final JoinType DEFAULT_JOIN_TYPE = JoinType.INNER; private Set> joins; private Set> fetches; public AbstractFromImpl(CriteriaBuilderImpl criteriaBuilder, Class javaType) { this( criteriaBuilder, javaType, null ); } public AbstractFromImpl(CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource) { super( criteriaBuilder, javaType, pathSource ); } @Override @SuppressWarnings({ "unchecked" }) public PathSource getPathSource() { return super.getPathSource(); } @Override public String getPathIdentifier() { return getAlias(); } /** * {@inheritDoc} */ @Override protected boolean canBeDereferenced() { return true; } /** * {@inheritDoc} */ public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { if ( getAlias() == null ) { if ( isCorrelated() ) { setAlias( getCorrelationParent().getAlias() ); } else { setAlias( renderingContext.generateAlias() ); } } } @Override public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { prepareAlias( renderingContext ); return getAlias(); } @Override public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return renderProjection( renderingContext ); } /** * {@inheritDoc} */ public Attribute getAttribute() { return null; } /** * {@inheritDoc} */ public From getParent() { return null; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) protected Attribute locateAttributeInternal(String name) { return (Attribute) locateManagedType().getAttribute( name ); } @SuppressWarnings({ "unchecked" }) protected ManagedType locateManagedType() { // by default, this should be the model return (ManagedType) getModel(); } // CORRELATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMPL NOTE : another means from handling correlations is to create a series of // specialized From implementations that represent the correlation roots. While // that may be cleaner code-wise, it is certainly means creating a lot of "extra" // classes since we'd need one for each Subquery#correlate method private FromImplementor correlationParent; private JoinScope joinScope = new BasicJoinScope(); /** * Helper contract used to define who/what keeps track of joins and fetches made from this FROM. */ public static interface JoinScope extends Serializable { public void addJoin(Join join); public void addFetch(Fetch fetch); } protected class BasicJoinScope implements JoinScope { public void addJoin(Join join) { if ( joins == null ) { joins = new LinkedHashSet>(); } joins.add( join ); } public void addFetch(Fetch fetch) { if ( fetches == null ) { fetches = new LinkedHashSet>(); } fetches.add( fetch ); } } protected class CorrelationJoinScope implements JoinScope { public void addJoin(Join join) { if ( joins == null ) { joins = new LinkedHashSet>(); } joins.add( join ); } public void addFetch(Fetch fetch) { throw new UnsupportedOperationException( "Cannot define fetch from a subquery correlation" ); } } /** * {@inheritDoc} */ public boolean isCorrelated() { return getCorrelationParent() != null; } /** * {@inheritDoc} */ public FromImplementor getCorrelationParent() { return correlationParent; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public FromImplementor correlateTo(CriteriaSubqueryImpl subquery) { final FromImplementor correlationDelegate = createCorrelationDelegate(); correlationDelegate.prepareCorrelationDelegate( this ); return correlationDelegate; } protected abstract FromImplementor createCorrelationDelegate(); public void prepareCorrelationDelegate(FromImplementor parent) { this.joinScope = new CorrelationJoinScope(); this.correlationParent = parent; } @Override public String getAlias() { return isCorrelated() ? getCorrelationParent().getAlias() : super.getAlias(); } // JOINS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ protected abstract boolean canBeJoinSource(); private RuntimeException illegalJoin() { return new IllegalArgumentException( "Collection of values [" + getPathIdentifier() + "] cannot be source of a join" ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Set> getJoins() { return joins == null ? Collections.EMPTY_SET : joins; } /** * {@inheritDoc} */ public Join join(SingularAttribute singularAttribute) { return join( singularAttribute, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ public Join join(SingularAttribute attribute, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } Join join = constructJoin( attribute, jt ); joinScope.addJoin( join ); return join; } private JoinImplementor constructJoin(SingularAttribute attribute, JoinType jt) { if ( Type.PersistenceType.BASIC.equals( attribute.getType().getPersistenceType() ) ) { throw new BasicPathUsageException( "Cannot join to attribute of basic type", attribute ); } // TODO : runtime check that the attribute in fact belongs to this From's model/bindable if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } final Class attributeType = attribute.getBindableJavaType(); return new SingularAttributeJoin( criteriaBuilder(), attributeType, this, attribute, jt ); } /** * {@inheritDoc} */ public CollectionJoin join(CollectionAttribute collection) { return join( collection, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ public CollectionJoin join(CollectionAttribute collection, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } final CollectionJoin join = constructJoin( collection, jt ); joinScope.addJoin( join ); return join; } private CollectionJoinImplementor constructJoin(CollectionAttribute collection, JoinType jt) { if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } // TODO : runtime check that the attribute in fact belongs to this From's model/bindable final Class attributeType = collection.getBindableJavaType(); return new CollectionAttributeJoin( criteriaBuilder(), attributeType, this, collection, jt ); } /** * {@inheritDoc} */ public SetJoin join(SetAttribute set) { return join( set, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ public SetJoin join(SetAttribute set, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } final SetJoin join = constructJoin( set, jt ); joinScope.addJoin( join ); return join; } private SetJoinImplementor constructJoin(SetAttribute set, JoinType jt) { if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } // TODO : runtime check that the attribute in fact belongs to this From's model/bindable final Class attributeType = set.getBindableJavaType(); return new SetAttributeJoin( criteriaBuilder(), attributeType, this, set, jt ); } /** * {@inheritDoc} */ public ListJoin join(ListAttribute list) { return join( list, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ public ListJoin join(ListAttribute list, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } final ListJoin join = constructJoin( list, jt ); joinScope.addJoin( join ); return join; } private ListJoinImplementor constructJoin(ListAttribute list, JoinType jt) { if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } // TODO : runtime check that the attribute in fact belongs to this From's model/bindable final Class attributeType = list.getBindableJavaType(); return new ListAttributeJoin( criteriaBuilder(), attributeType, this, list, jt ); } /** * {@inheritDoc} */ public MapJoin join(MapAttribute map) { return join( map, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ public MapJoin join(MapAttribute map, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } final MapJoin join = constructJoin( map, jt ); joinScope.addJoin( join ); return join; } private MapJoinImplementor constructJoin(MapAttribute map, JoinType jt) { if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } // TODO : runtime check that the attribute in fact belongs to this From's model/bindable final Class attributeType = map.getBindableJavaType(); return new MapAttributeJoin( criteriaBuilder(), attributeType, this, map, jt ); } /** * {@inheritDoc} */ public Join join(String attributeName) { return join( attributeName, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Join join(String attributeName, JoinType jt) { if ( ! canBeJoinSource() ) { throw illegalJoin(); } if ( jt.equals( JoinType.RIGHT ) ) { throw new UnsupportedOperationException( "RIGHT JOIN not supported" ); } final Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( attribute.isCollection() ) { final PluralAttribute pluralAttribute = ( PluralAttribute ) attribute; if ( PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { return (Join) join( (CollectionAttribute) attribute, jt ); } else if ( PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { return (Join) join( (ListAttribute) attribute, jt ); } else if ( PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { return (Join) join( (SetAttribute) attribute, jt ); } else { return (Join) join( (MapAttribute) attribute, jt ); } } else { return (Join) join( (SingularAttribute)attribute, jt ); } } /** * {@inheritDoc} */ public CollectionJoin joinCollection(String attributeName) { return joinCollection( attributeName, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public CollectionJoin joinCollection(String attributeName, JoinType jt) { final Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( ! attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a collection" ); } final PluralAttribute pluralAttribute = ( PluralAttribute ) attribute; if ( ! PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a collection" ); } return (CollectionJoin) join( (CollectionAttribute) attribute, jt ); } /** * {@inheritDoc} */ public SetJoin joinSet(String attributeName) { return joinSet( attributeName, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public SetJoin joinSet(String attributeName, JoinType jt) { final Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( ! attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a set" ); } final PluralAttribute pluralAttribute = ( PluralAttribute ) attribute; if ( ! PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a set" ); } return (SetJoin) join( (SetAttribute) attribute, jt ); } /** * {@inheritDoc} */ public ListJoin joinList(String attributeName) { return joinList( attributeName, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ListJoin joinList(String attributeName, JoinType jt) { final Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( ! attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a list" ); } final PluralAttribute pluralAttribute = ( PluralAttribute ) attribute; if ( ! PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a list" ); } return (ListJoin) join( (ListAttribute) attribute, jt ); } /** * {@inheritDoc} */ public MapJoin joinMap(String attributeName) { return joinMap( attributeName, DEFAULT_JOIN_TYPE ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public MapJoin joinMap(String attributeName, JoinType jt) { final Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( ! attribute.isCollection() ) { throw new IllegalArgumentException( "Requested attribute was not a map" ); } final PluralAttribute pluralAttribute = ( PluralAttribute ) attribute; if ( ! PluralAttribute.CollectionType.MAP.equals( pluralAttribute.getCollectionType() ) ) { throw new IllegalArgumentException( "Requested attribute was not a map" ); } return (MapJoin) join( (MapAttribute) attribute, jt ); } // FETCHES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ protected boolean canBeFetchSource() { // the conditions should be the same... return canBeJoinSource(); } private RuntimeException illegalFetch() { return new IllegalArgumentException( "Collection of values [" + getPathIdentifier() + "] cannot be source of a fetch" ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Set> getFetches() { return fetches == null ? Collections.EMPTY_SET : fetches; } public Fetch fetch(SingularAttribute singularAttribute) { return fetch( singularAttribute, DEFAULT_JOIN_TYPE ); } public Fetch fetch(SingularAttribute attribute, JoinType jt) { if ( ! canBeFetchSource() ) { throw illegalFetch(); } Fetch fetch = constructJoin( attribute, jt ); joinScope.addFetch( fetch ); return fetch; } public Fetch fetch(PluralAttribute pluralAttribute) { return fetch( pluralAttribute, DEFAULT_JOIN_TYPE ); } public Fetch fetch(PluralAttribute pluralAttribute, JoinType jt) { if ( ! canBeFetchSource() ) { throw illegalFetch(); } final Fetch fetch; // TODO : combine Fetch and Join hierarchies (JoinImplementor extends Join,Fetch???) if ( PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { fetch = constructJoin( (CollectionAttribute) pluralAttribute, jt ); } else if ( PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { fetch = constructJoin( (ListAttribute) pluralAttribute, jt ); } else if ( PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { fetch = constructJoin( (SetAttribute) pluralAttribute, jt ); } else { fetch = constructJoin( (MapAttribute) pluralAttribute, jt ); } joinScope.addFetch( fetch ); return fetch; } public Fetch fetch(String attributeName) { return fetch( attributeName, DEFAULT_JOIN_TYPE ); } @SuppressWarnings({ "unchecked" }) public Fetch fetch(String attributeName, JoinType jt) { if ( ! canBeFetchSource() ) { throw illegalFetch(); } Attribute attribute = (Attribute) locateAttribute( attributeName ); if ( attribute.isCollection() ) { return (Fetch) fetch( (PluralAttribute) attribute, jt ); } else { return (Fetch) fetch( (SingularAttribute) attribute, jt ); } } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/AbstractJoinImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000623111714611271032702 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import javax.persistence.criteria.From; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.Attribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.JoinImplementor; import org.hibernate.ejb.criteria.PathSource; /** * TODO : javadoc * * @author Steve Ebersole */ public abstract class AbstractJoinImpl extends AbstractFromImpl implements JoinImplementor, Serializable { private final Attribute joinAttribute; private final JoinType joinType; public AbstractJoinImpl( CriteriaBuilderImpl criteriaBuilder, PathSource pathSource, Attribute joinAttribute, JoinType joinType) { this( criteriaBuilder, joinAttribute.getJavaType(), pathSource, joinAttribute, joinType ); } public AbstractJoinImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, Attribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource ); this.joinAttribute = joinAttribute; this.joinType = joinType; } /** * {@inheritDoc} */ public Attribute getAttribute() { return joinAttribute; } /** * {@inheritDoc} */ public JoinType getJoinType() { return joinType; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public From getParent() { // this cast should be ok by virtue of our constructors... return (From) getPathSource(); } public String renderTableExpression(CriteriaQueryCompiler.RenderingContext renderingContext) { prepareAlias( renderingContext ); ( (FromImplementor) getParent() ).prepareAlias( renderingContext ); return getParent().getAlias() + '.' + getAttribute().getName() + " as " + getAlias(); } public JoinImplementor correlateTo(CriteriaSubqueryImpl subquery) { return (JoinImplementor) super.correlateTo( subquery ); } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/PluralAttributeJoinSupport.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000537411714611271032711 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.PluralJoin; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.Type; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.PathSource; /** * Support for defining joins to plural attributes (JPA requires typing based on * the specific collection type so we cannot really implement all support in a * single class) * * @author Steve Ebersole */ public abstract class PluralAttributeJoinSupport extends AbstractJoinImpl implements PluralJoin { public PluralAttributeJoinSupport( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, Attribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); } @Override public PluralAttribute getAttribute() { return (PluralAttribute) super.getAttribute(); } public PluralAttribute getModel() { return getAttribute(); } @Override protected ManagedType locateManagedType() { return isBasicCollection() ? null : (ManagedType) getAttribute().getElementType(); } public boolean isBasicCollection() { return Type.PersistenceType.BASIC.equals( getAttribute().getElementType().getPersistenceType() ); } @Override protected boolean canBeDereferenced() { return !isBasicCollection(); } @Override protected boolean canBeJoinSource() { return !isBasicCollection(); } } ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/CollectionAttributeJoin.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000522111714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.Collection; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.CollectionAttribute; import org.hibernate.ejb.criteria.CollectionJoinImplementor; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathSource; /** * TODO : javadoc * * @author Steve Ebersole */ public class CollectionAttributeJoin extends PluralAttributeJoinSupport,E> implements CollectionJoinImplementor, Serializable { public CollectionAttributeJoin( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, CollectionAttribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); } public final CollectionAttributeJoin correlateTo(CriteriaSubqueryImpl subquery) { return (CollectionAttributeJoin) super.correlateTo( subquery ); } @Override public CollectionAttribute getAttribute() { return (CollectionAttribute) super.getAttribute(); } @Override public CollectionAttribute getModel() { return getAttribute(); } @Override protected FromImplementor createCorrelationDelegate() { return new CollectionAttributeJoin( criteriaBuilder(), getJavaType(), (PathImplementor) getParentPath(), getAttribute(), getJoinType() ); } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/MapKeyHelpers.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001770111714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.lang.reflect.Member; import java.util.Map; import javax.persistence.criteria.Join; import javax.persistence.criteria.MapJoin; import javax.persistence.criteria.Path; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.Type; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.MapJoinImplementor; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.persister.collection.CollectionPersister; /** * {@link MapJoin#key} poses a number of implementation difficulties in terms of the type signatures * amongst the {@link Path}, {@link Join} and {@link Attribute} reference at play. The implementations found here * provide that bridge. * * @author Steve Ebersole */ public class MapKeyHelpers { /** * Models a path to a map key. This is the actual return used from {@link MapJoin#key} * * @param The type of the map key. */ public static class MapKeyPath extends AbstractPathImpl implements PathImplementor, Serializable { private final MapKeyAttribute mapKeyAttribute; public MapKeyPath( CriteriaBuilderImpl criteriaBuilder, MapKeySource source, MapKeyAttribute mapKeyAttribute) { super( criteriaBuilder, mapKeyAttribute.getJavaType(), source ); this.mapKeyAttribute = mapKeyAttribute; } @Override public MapKeySource getPathSource() { return (MapKeySource) super.getPathSource(); } public MapKeyAttribute getAttribute() { return mapKeyAttribute; } private boolean isBasicTypeKey() { return Attribute.PersistentAttributeType.BASIC == mapKeyAttribute.getPersistentAttributeType(); } @Override protected boolean canBeDereferenced() { return ! isBasicTypeKey(); } @Override protected Attribute locateAttributeInternal(String attributeName) { if ( ! canBeDereferenced() ) { throw new IllegalArgumentException( "Map key [" + getPathSource().getPathIdentifier() + "] cannot be dereferenced" ); } throw new UnsupportedOperationException( "Not yet supported!" ); } public Bindable getModel() { return mapKeyAttribute; } } /** * Defines a {@link Path} for the map which can then be used to represent the source of the * map key "attribute". * * @param The map key type * @param The map value type */ public static class MapKeySource extends AbstractPathImpl> implements PathImplementor>, Serializable { private final MapAttribute mapAttribute; private final MapJoinImplementor mapJoin; public MapKeySource( CriteriaBuilderImpl criteriaBuilder, Class> javaType, MapJoinImplementor mapJoin, MapAttribute attribute) { super( criteriaBuilder, javaType, null ); this.mapJoin = mapJoin; this.mapAttribute = attribute; } public MapAttribute getAttribute() { return mapAttribute; } @SuppressWarnings({ "unchecked" }) public Bindable> getModel() { // TODO : ok??? the attribute is in fact bindable, but its type signature is different return (Bindable>) mapAttribute; } @Override public PathImplementor getParentPath() { return (PathImplementor) mapJoin.getParentPath(); } @Override protected boolean canBeDereferenced() { return false; } @Override protected Attribute locateAttributeInternal(String attributeName) { throw new IllegalArgumentException( "Map [" + mapJoin.getPathIdentifier() + "] cannot be dereferenced" ); } } /** * Disallow instantiation */ private MapKeyHelpers() { } /** * Defines an {@link javax.persistence.metamodel.Attribute} modelling of a map-key. * * @param The type of the map key */ public static class MapKeyAttribute implements SingularAttribute,K>, Bindable, Serializable { private final MapAttribute attribute; private final CollectionPersister mapPersister; private final org.hibernate.type.Type mapKeyType; private final Type jpaType; private final BindableType jpaBindableType; private final Class jpaBinableJavaType; private final PersistentAttributeType persistentAttributeType; public MapKeyAttribute(CriteriaBuilderImpl criteriaBuilder, MapAttribute attribute) { this.attribute = attribute; this.jpaType = attribute.getKeyType(); this.jpaBinableJavaType = attribute.getKeyJavaType(); this.jpaBindableType = Type.PersistenceType .ENTITY.equals( jpaType.getPersistenceType() ) ? BindableType.ENTITY_TYPE : BindableType.SINGULAR_ATTRIBUTE; String guessedRoleName = determineRole( attribute ); SessionFactoryImplementor sfi = (SessionFactoryImplementor) criteriaBuilder.getEntityManagerFactory().getSessionFactory(); mapPersister = sfi.getCollectionPersister( guessedRoleName ); if ( mapPersister == null ) { throw new IllegalStateException( "Could not locate collection persister [" + guessedRoleName + "]" ); } mapKeyType = mapPersister.getIndexType(); if ( mapKeyType == null ) { throw new IllegalStateException( "Could not determine map-key type [" + guessedRoleName + "]" ); } this.persistentAttributeType = mapKeyType.isEntityType() ? PersistentAttributeType.MANY_TO_ONE : mapKeyType.isComponentType() ? PersistentAttributeType.EMBEDDED : PersistentAttributeType.BASIC; } private String determineRole(MapAttribute attribute) { return attribute.getDeclaringType().getJavaType().getName() + '.' + attribute.getName(); } /** * {@inheritDoc} */ public String getName() { // TODO : ??? return "map-key"; } /** * {@inheritDoc} */ public PersistentAttributeType getPersistentAttributeType() { return persistentAttributeType; } /** * {@inheritDoc} */ public ManagedType> getDeclaringType() { // TODO : ??? return null; } /** * {@inheritDoc} */ public Class getJavaType() { return attribute.getKeyJavaType(); } /** * {@inheritDoc} */ public Member getJavaMember() { // TODO : ??? return null; } /** * {@inheritDoc} */ public boolean isAssociation() { return mapKeyType.isEntityType(); } /** * {@inheritDoc} */ public boolean isCollection() { return false; } public boolean isId() { return false; } public boolean isVersion() { return false; } public boolean isOptional() { return false; } public Type getType() { return jpaType; } public BindableType getBindableType() { return jpaBindableType; } public Class getBindableJavaType() { return jpaBinableJavaType; } } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/SingularAttributeJoin.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000544011714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.SingularAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.PathSource; /** * TODO : javadoc * * @author Steve Ebersole */ public class SingularAttributeJoin extends AbstractJoinImpl { private final Bindable model; @SuppressWarnings({ "unchecked" }) public SingularAttributeJoin( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, SingularAttribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); this.model = (Bindable) ( Attribute.PersistentAttributeType.EMBEDDED == joinAttribute.getPersistentAttributeType() ? joinAttribute : criteriaBuilder.getEntityManagerFactory().getMetamodel().managedType( javaType ) ); } @Override public SingularAttribute getAttribute() { return (SingularAttribute) super.getAttribute(); } @Override public SingularAttributeJoin correlateTo(CriteriaSubqueryImpl subquery) { return (SingularAttributeJoin) super.correlateTo( subquery ); } @Override protected FromImplementor createCorrelationDelegate() { return new SingularAttributeJoin( criteriaBuilder(), getJavaType(), getPathSource(), getAttribute(), getJoinType() ); } @Override protected boolean canBeJoinSource() { return true; } public Bindable getModel() { return model; } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/SingularAttributePath.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000660411714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.EmbeddableType; import javax.persistence.metamodel.IdentifiableType; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.SingularAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.PathSource; /** * Models a path for a {@link SingularAttribute} generally obtained from a * {@link javax.persistence.criteria.Path#get(SingularAttribute)} call * * @author Steve Ebersole */ public class SingularAttributePath extends AbstractPathImpl implements Serializable { private final SingularAttribute attribute; private final ManagedType managedType; @SuppressWarnings({ "unchecked" }) public SingularAttributePath( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, SingularAttribute attribute) { super( criteriaBuilder, javaType, pathSource ); this.attribute = attribute; this.managedType = resolveManagedType( attribute ); } private ManagedType resolveManagedType(SingularAttribute attribute) { if ( Attribute.PersistentAttributeType.BASIC == attribute.getPersistentAttributeType() ) { return null; } else if ( Attribute.PersistentAttributeType.EMBEDDED == attribute.getPersistentAttributeType() ) { return (EmbeddableType) attribute.getType(); } else { return (IdentifiableType) attribute.getType(); // return criteriaBuilder.getEntityManagerFactory() // .getMetamodel() // .managedType( javaType ); } } /** * {@inheritDoc} */ public SingularAttribute getAttribute() { return attribute; } /** * {@inheritDoc} */ public Bindable getModel() { return getAttribute(); } /** * {@inheritDoc} */ @Override protected boolean canBeDereferenced() { return managedType != null; } @Override protected Attribute locateAttributeInternal(String attributeName) { final Attribute attribute = managedType.getAttribute( attributeName ); // ManagedType.getAttribute should throw exception rather than return // null, but just to be safe... if ( attribute == null ) { throw new IllegalArgumentException( "Could not resolve attribute named " + attributeName ); } return attribute; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/PluralAttributePath.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000635711714611271032713 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Bindable; import javax.persistence.metamodel.PluralAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.persister.collection.CollectionPersister; /** * Models a path for a {@link PluralAttribute} generally obtained from a * {@link javax.persistence.criteria.Path#get} call * * @author Steve Ebersole */ public class PluralAttributePath extends AbstractPathImpl implements Serializable { private final PluralAttribute attribute; private final CollectionPersister persister; public PluralAttributePath( CriteriaBuilderImpl criteriaBuilder, PathSource source, PluralAttribute attribute) { super( criteriaBuilder, attribute.getJavaType(), source ); this.attribute = attribute; this.persister = resolvePersister( criteriaBuilder, attribute ); } private static CollectionPersister resolvePersister(CriteriaBuilderImpl criteriaBuilder, PluralAttribute attribute) { SessionFactoryImplementor sfi = (SessionFactoryImplementor) criteriaBuilder.getEntityManagerFactory().getSessionFactory(); return sfi.getCollectionPersister( resolveRole( attribute ) ); } private static String resolveRole(PluralAttribute attribute) { return attribute.getDeclaringType().getJavaType().getName() + '.' + attribute.getName(); } public PluralAttribute getAttribute() { return attribute; } @SuppressWarnings({ "UnusedDeclaration" }) public CollectionPersister getPersister() { return persister; } @Override protected boolean canBeDereferenced() { // cannot be dereferenced return false; } @Override protected Attribute locateAttributeInternal(String attributeName) { throw new IllegalArgumentException( "Plural attribute paths cannot be further dereferenced" ); } public Bindable getModel() { // the issue here is the parameterized type; X is the collection // type (Map, Set, etc) while the "bindable" for a collection is the // elements. // // TODO : throw exception instead? return null; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/path/ListAttributeJoin.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000551511714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.path; import java.io.Serializable; import java.util.List; import javax.persistence.criteria.Expression; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.ListAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.ListJoinImplementor; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.expression.ListIndexExpression; /** * TODO : javadoc * * @author Steve Ebersole */ public class ListAttributeJoin extends PluralAttributeJoinSupport,E> implements ListJoinImplementor, Serializable { public ListAttributeJoin( CriteriaBuilderImpl criteriaBuilder, Class javaType, PathSource pathSource, ListAttribute joinAttribute, JoinType joinType) { super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType ); } /** * {@inheritDoc} */ public Expression index() { return new ListIndexExpression( criteriaBuilder(), this, getAttribute() ); } @Override public ListAttribute getAttribute() { return (ListAttribute) super.getAttribute(); } @Override public ListAttribute getModel() { return getAttribute(); } @Override public final ListAttributeJoin correlateTo(CriteriaSubqueryImpl subquery) { return (ListAttributeJoin) super.correlateTo( subquery ); } @Override protected FromImplementor createCorrelationDelegate() { return new ListAttributeJoin( criteriaBuilder(), getJavaType(), (PathImplementor) getParentPath(), getAttribute(), getJoinType() ); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/QueryStructure.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000003056011714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import java.util.Arrays; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.Collections; import java.util.LinkedHashSet; import java.util.ArrayList; import java.util.Collection; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.Root; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Expression; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Selection; import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Fetch; import javax.persistence.criteria.JoinType; import javax.persistence.metamodel.EntityType; import org.hibernate.ejb.criteria.path.RootImpl; /** * Models basic query structure. Used as a delegate in implementing both * {@link org.hibernate.criterion.CriteriaQuery} and * {@link javax.persistence.criteria.Subquery}. *

* Note the ORDER BY specs are neglected here. That's because it is not valid * for a subquery to define an ORDER BY clause. So we just handle them on the * root query directly... * * @author Steve Ebersole */ public class QueryStructure implements Serializable { private final AbstractQuery owner; private final CriteriaBuilderImpl criteriaBuilder; private final boolean isSubQuery; public QueryStructure(AbstractQuery owner, CriteriaBuilderImpl criteriaBuilder) { this.owner = owner; this.criteriaBuilder = criteriaBuilder; this.isSubQuery = Subquery.class.isInstance( owner ); } private boolean distinct; private Selection selection; private Set> roots = new LinkedHashSet>(); private Set correlationRoots; private Predicate restriction; private List> groupings = Collections.emptyList(); private Predicate having; private List> subqueries; // PARAMETERS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Set> getParameters() { final Set> parameters = new LinkedHashSet>(); final ParameterRegistry registry = new ParameterRegistry() { public void registerParameter(ParameterExpression parameter) { parameters.add( parameter ); } }; ParameterContainer.Helper.possibleParameter(selection, registry); ParameterContainer.Helper.possibleParameter(restriction, registry); ParameterContainer.Helper.possibleParameter(having, registry); if ( subqueries != null ) { for ( Subquery subquery : subqueries ) { ParameterContainer.Helper.possibleParameter(subquery, registry); } } // both group-by and having expressions can (though unlikely) contain parameters... ParameterContainer.Helper.possibleParameter(having, registry); if ( groupings != null ) { for ( Expression grouping : groupings ) { ParameterContainer.Helper.possibleParameter(grouping, registry); } } return parameters; } // SELECTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public boolean isDistinct() { return distinct; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public Selection getSelection() { return selection; } public void setSelection(Selection selection) { this.selection = selection; } // ROOTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Set> getRoots() { return roots; } public Root from(Class entityClass) { EntityType entityType = criteriaBuilder.getEntityManagerFactory() .getMetamodel() .entity( entityClass ); if ( entityType == null ) { throw new IllegalArgumentException( entityClass + " is not an entity" ); } return from( entityType ); } public Root from(EntityType entityType) { RootImpl root = new RootImpl( criteriaBuilder, entityType ); roots.add( root ); return root; } // CORRELATION ROOTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public void addCorrelationRoot(FromImplementor fromImplementor) { if ( !isSubQuery ) { throw new IllegalStateException( "Query is not identified as sub-query" ); } if ( correlationRoots == null ) { correlationRoots = new HashSet(); } correlationRoots.add( fromImplementor ); } public Set> collectCorrelatedJoins() { if ( !isSubQuery ) { throw new IllegalStateException( "Query is not identified as sub-query" ); } final Set> correlatedJoins; if ( correlationRoots != null ) { correlatedJoins = new HashSet>(); for ( FromImplementor correlationRoot : correlationRoots ) { correlatedJoins.addAll( correlationRoot.getJoins() ); } } else { correlatedJoins = Collections.emptySet(); } return correlatedJoins; } // RESTRICTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Predicate getRestriction() { return restriction; } public void setRestriction(Predicate restriction) { this.restriction = restriction; } // GROUPINGS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public List> getGroupings() { return groupings; } public void setGroupings(List> groupings) { this.groupings = groupings; } public void setGroupings(Expression... groupings) { if ( groupings != null && groupings.length > 0 ) { this.groupings = Arrays.asList( groupings ); } else { this.groupings = Collections.emptyList(); } } public Predicate getHaving() { return having; } public void setHaving(Predicate having) { this.having = having; } // SUB-QUERIES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public List> getSubqueries() { return subqueries; } public List> internalGetSubqueries() { if ( subqueries == null ) { subqueries = new ArrayList>(); } return subqueries; } public Subquery subquery(Class subqueryType) { CriteriaSubqueryImpl subquery = new CriteriaSubqueryImpl( criteriaBuilder, subqueryType, owner ); internalGetSubqueries().add( subquery ); return subquery; } @SuppressWarnings({ "unchecked" }) public void render(StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext) { jpaqlQuery.append( "select " ); if ( isDistinct() ) { jpaqlQuery.append( "distinct " ); } if ( getSelection() == null ) { jpaqlQuery.append( locateImplicitSelection().renderProjection( renderingContext ) ); } else { jpaqlQuery.append( ( (Renderable) getSelection() ).renderProjection( renderingContext ) ); } renderFromClause( jpaqlQuery, renderingContext ); if ( getRestriction() != null) { jpaqlQuery.append( " where " ) .append( ( (Renderable) getRestriction() ).render( renderingContext ) ); } if ( ! getGroupings().isEmpty() ) { jpaqlQuery.append( " group by " ); String sep = ""; for ( Expression grouping : getGroupings() ) { jpaqlQuery.append( sep ) .append( ( (Renderable) grouping ).render( renderingContext ) ); sep = ", "; } if ( getHaving() != null ) { jpaqlQuery.append( " having " ) .append( ( (Renderable) getHaving() ).render( renderingContext ) ); } } } private FromImplementor locateImplicitSelection() { FromImplementor implicitSelection = null; if ( ! isSubQuery ) { // we should have only a single root (query validation should have checked this...) implicitSelection = (FromImplementor) getRoots().iterator().next(); } else { // we should only have a single "root" which can act as the implicit selection final Set> correlatedJoins = collectCorrelatedJoins(); if ( correlatedJoins != null ) { if ( correlatedJoins.size() == 1 ) { implicitSelection = (FromImplementor) correlatedJoins.iterator().next(); } } } if ( implicitSelection == null ) { throw new IllegalStateException( "No explicit selection and an implicit one cold not be determined" ); } return implicitSelection; } @SuppressWarnings({ "unchecked" }) private void renderFromClause(StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext) { jpaqlQuery.append( " from " ); String sep = ""; for ( Root root : getRoots() ) { ( (FromImplementor) root ).prepareAlias( renderingContext ); jpaqlQuery.append( sep ); jpaqlQuery.append( ( (FromImplementor) root ).renderTableExpression( renderingContext ) ); sep = ", "; } for ( Root root : getRoots() ) { renderJoins( jpaqlQuery, renderingContext, root.getJoins() ); renderFetches( jpaqlQuery, renderingContext, root.getFetches() ); } if ( isSubQuery ) { if ( correlationRoots != null ) { for ( FromImplementor correlationRoot : correlationRoots ) { final FromImplementor correlationParent = correlationRoot.getCorrelationParent(); correlationParent.prepareAlias( renderingContext ); final String correlationRootAlias = correlationParent.getAlias(); for ( Join correlationJoin : correlationRoot.getJoins() ) { final JoinImplementor correlationJoinImpl = (JoinImplementor) correlationJoin; // IMPL NOTE: reuse the sep from above! jpaqlQuery.append( sep ); correlationJoinImpl.prepareAlias( renderingContext ); jpaqlQuery.append( correlationRootAlias ) .append( '.' ) .append( correlationJoinImpl.getAttribute().getName() ) .append( " as " ) .append( correlationJoinImpl.getAlias() ); sep = ", "; renderJoins( jpaqlQuery, renderingContext, correlationJoinImpl.getJoins() ); } } } } } @SuppressWarnings({ "unchecked" }) private void renderJoins( StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext, Collection> joins) { if ( joins == null ) { return; } for ( Join join : joins ) { ( (FromImplementor) join ).prepareAlias( renderingContext ); jpaqlQuery.append( renderJoinType( join.getJoinType() ) ) .append( ( (FromImplementor) join ).renderTableExpression( renderingContext ) ); renderJoins( jpaqlQuery, renderingContext, join.getJoins() ); renderFetches( jpaqlQuery, renderingContext, join.getFetches() ); } } private String renderJoinType(JoinType joinType) { switch ( joinType ) { case INNER: { return " inner join "; } case LEFT: { return " left join "; } case RIGHT: { return " right join "; } } throw new IllegalStateException( "Unknown join type " + joinType ); } @SuppressWarnings({ "unchecked" }) private void renderFetches( StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext, Collection fetches) { if ( fetches == null ) { return; } for ( Fetch fetch : fetches ) { ( (FromImplementor) fetch ).prepareAlias( renderingContext ); jpaqlQuery.append( renderJoinType( fetch.getJoinType() ) ) .append( "fetch " ) .append( ( (FromImplementor) fetch ).renderTableExpression( renderingContext ) ); renderFetches( jpaqlQuery, renderingContext, fetch.getFetches() ); } } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/SetJoinImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000270611714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.SetJoin; /** * Specialization of {@link JoinImplementor} for {@link java.util.Set} typed attribute joins * * @author Steve Ebersole */ public interface SetJoinImplementor extends JoinImplementor, SetJoin { /** * {@inheritDoc} *

* Refined return type */ public SetJoinImplementor correlateTo(CriteriaSubqueryImpl subquery); } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/BasicPathUsageException.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000414311714611271032702 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.metamodel.Attribute; /** * Represents an incorrect usage of a basic path. Generally this means an attempt to * de-reference a basic attribute path. * * @author Steve Ebersole */ public class BasicPathUsageException extends RuntimeException { private final Attribute attribute; /** * Construct the usage exception. * * @param message An error message describing the incorrect usage. * @param attribute The basic attribute involved. */ public BasicPathUsageException(String message, Attribute attribute) { super( message ); this.attribute = attribute; } /** * Construct the usage exception. * * @param message An error message describing the incorrect usage. * @param cause An underlying cause. * @param attribute The basic attribute involved. */ public BasicPathUsageException(String message, Throwable cause, Attribute attribute) { super( message, cause ); this.attribute = attribute; } public Attribute getAttribute() { return attribute; } } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/ParameterRegistry.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000324411714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.ParameterExpression; /** * A registry for parameters. In criteria queries, parameters must be actively seeked out as expressions and predicates * are added to the {@link org.hibernate.criterion.CriteriaQuery}; this contract allows the various subcomponents to * register any parameters they contain. * * @author Steve Ebersole */ public interface ParameterRegistry { /** * Registers the given parameter with this regitry. * * @param parameter The parameter to register. */ public void registerParameter(ParameterExpression parameter); } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/ParameterContainer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000355011714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.Selection; /** * Contract for query components capable of eirther being a parameter or containing parameters. * * @author Steve Ebersole */ public interface ParameterContainer { /** * Register any parameters contained within this query component with the given registry. * * @param registry The parameter registry with which to register. */ public void registerParameters(ParameterRegistry registry); /** * Helper to deal with potential parameter container nodes. */ public static class Helper { public static void possibleParameter(Selection selection, ParameterRegistry registry) { if ( ParameterContainer.class.isInstance( selection ) ) { ( (ParameterContainer) selection ).registerParameters( registry ); } } } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/PathImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000277011714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.Path; import javax.persistence.metamodel.Attribute; /** * Implementation contract for the JPA {@link Path} interface. * * @author Steve Ebersole */ public interface PathImplementor extends ExpressionImplementor, Path, PathSource, Renderable { /** * Retrieve reference to the attribute this path represents. * * @return The metamodel attribute. */ public Attribute getAttribute(); } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryCompiler.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000003640211714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import javax.persistence.TypedQuery; import javax.persistence.Parameter; import javax.persistence.TemporalType; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.ejb.HibernateEntityManagerImplementor; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.type.Type; import org.hibernate.type.TypeFactory; import org.hibernate.util.StringHelper; /** * Compiles a JPA criteria query into an executable {@link TypedQuery}. Its single contract is the {@link #compile} * method. *

* NOTE : This is a temporary implementation which simply translates the criteria query into a JPAQL query string. A * better, long-term solution is being implemented as part of refactoring the JPAQL/HQL translator. * * @author Steve Ebersole */ public class CriteriaQueryCompiler implements Serializable { private static final Logger log = LoggerFactory.getLogger( CriteriaQueryCompiler.class ); /** * Used to describe implicit (not defined in criteria query) parameters. */ public static interface ImplicitParameterBinding { /** * Retrieve the generated name of the implicit parameter. * * @return The parameter name. */ public String getParameterName(); /** * Get the java type of the "thing" that led to the implicit parameter. Used from * {@link org.hibernate.ejb.HibernateEntityManagerImplementor.Options#getNamedParameterExplicitTypes()} * in determining "guessed type" overriding. * * @return The java type */ public Class getJavaType(); /** * Bind the implicit parameter's value to the JPA query. * * @param typedQuery The JPA query. */ public void bind(TypedQuery typedQuery); } /** * Used to provide a context and services to the rendering. */ public static interface RenderingContext { /** * Generate a correlation name. * * @return The generated correlation name */ public String generateAlias(); /** * Register parameters explicitly encountered in the criteria query. * * @param criteriaQueryParameter The parameter expression * * @return The JPA-QL parameter name */ public String registerExplicitParameter(ParameterExpression criteriaQueryParameter); /** * Register a parameter that was not part of the criteria query (at least not as a parameter). * * @param literal The literal value * @param javaType The java type as whcih to handle the literal value. * * @return The JPA-QL parameter name */ public String registerLiteralParameterBinding(Object literal, Class javaType); /** * Given a java type, determine the proper cast type name. * * @param javaType The java type. * * @return The cast type name. */ public String getCastType(Class javaType); } public static interface RenderedCriteriaQuery { public String getQueryString(); public List getValueHandlers(); public HibernateEntityManagerImplementor.Options.ResultMetadataValidator getResultMetadataValidator(); } private final HibernateEntityManagerImplementor entityManager; public CriteriaQueryCompiler(HibernateEntityManagerImplementor entityManager) { this.entityManager = entityManager; } public TypedQuery compile(CriteriaQuery criteriaQuery) { CriteriaQueryImpl criteriaQueryImpl = ( CriteriaQueryImpl ) criteriaQuery; criteriaQueryImpl.validate(); final Map,String> explicitParameterMapping = new HashMap,String>(); final Map> explicitParameterNameMapping = new HashMap>(); final List implicitParameterBindings = new ArrayList(); final Map implicitParameterTypes = new HashMap(); RenderingContext renderingContext = new RenderingContext() { private int aliasCount = 0; private int explicitParameterCount = 0; public String generateAlias() { return "generatedAlias" + aliasCount++; } public String generateParameterName() { return "param" + explicitParameterCount++; } public String registerExplicitParameter(ParameterExpression criteriaQueryParameter) { final String jpaqlParameterName; if ( explicitParameterMapping.containsKey( criteriaQueryParameter ) ) { jpaqlParameterName = explicitParameterMapping.get( criteriaQueryParameter ); } else { jpaqlParameterName = generateParameterName(); explicitParameterMapping.put( criteriaQueryParameter, jpaqlParameterName ); } if ( StringHelper.isNotEmpty( criteriaQueryParameter.getName() ) ) { explicitParameterNameMapping.put( criteriaQueryParameter.getName(), criteriaQueryParameter ); } return jpaqlParameterName; } public String registerLiteralParameterBinding(final Object literal, final Class javaType) { final String parameterName = generateParameterName(); final ImplicitParameterBinding binding = new CriteriaQueryCompiler.ImplicitParameterBinding() { public String getParameterName() { return parameterName; } public Class getJavaType() { return javaType; } public void bind(TypedQuery typedQuery) { typedQuery.setParameter( parameterName, literal ); } }; implicitParameterBindings.add( binding ); implicitParameterTypes.put( parameterName, javaType ); return parameterName; } public String getCastType(Class javaType) { SessionFactoryImplementor factory = ( SessionFactoryImplementor ) entityManager.getFactory().getSessionFactory(); Type hibernateType = factory.getTypeResolver().heuristicType( javaType.getName() ); if ( hibernateType == null ) { throw new IllegalArgumentException( "Could not convert java type [" + javaType.getName() + "] to Hibernate type" ); } return hibernateType.getName(); } }; final RenderedCriteriaQuery renderedCriteriaQuery = criteriaQueryImpl.render( renderingContext ); log.debug( "Rendered criteria query -> {}", renderedCriteriaQuery.getQueryString() ); TypedQuery jpaqlQuery = entityManager.createQuery( renderedCriteriaQuery.getQueryString(), criteriaQuery.getResultType(), criteriaQuery.getSelection(), new HibernateEntityManagerImplementor.Options() { public List getValueHandlers() { return renderedCriteriaQuery.getValueHandlers(); } public Map getNamedParameterExplicitTypes() { return implicitParameterTypes; } public ResultMetadataValidator getResultMetadataValidator() { return renderedCriteriaQuery.getResultMetadataValidator(); } } ); for ( ImplicitParameterBinding implicitParameterBinding : implicitParameterBindings ) { implicitParameterBinding.bind( jpaqlQuery ); } return wrap( jpaqlQuery, explicitParameterMapping, explicitParameterNameMapping ); } private TypedQuery wrap( final TypedQuery jpaqlQuery, final Map, String> explicitParameterMapping, final Map> explicitParameterNameMapping) { return new TypedQuery() { public List getResultList() { return jpaqlQuery.getResultList(); } public X getSingleResult() { return jpaqlQuery.getSingleResult(); } public int getMaxResults() { return jpaqlQuery.getMaxResults(); } public TypedQuery setMaxResults(int i) { jpaqlQuery.setMaxResults( i ); return this; } public int getFirstResult() { return jpaqlQuery.getFirstResult(); } public TypedQuery setFirstResult(int i) { jpaqlQuery.setFirstResult( i ); return this; } public Map getHints() { return jpaqlQuery.getHints(); } public TypedQuery setHint(String name, Object value) { jpaqlQuery.setHint( name, value); return this; } public FlushModeType getFlushMode() { return jpaqlQuery.getFlushMode(); } public TypedQuery setFlushMode(FlushModeType flushModeType) { jpaqlQuery.setFlushMode( flushModeType ); return this; } public LockModeType getLockMode() { return jpaqlQuery.getLockMode(); } public TypedQuery setLockMode(LockModeType lockModeType) { jpaqlQuery.setLockMode( lockModeType ); return this; } @SuppressWarnings({ "unchecked" }) public Set getParameters() { return explicitParameterMapping.keySet(); } public boolean isBound(Parameter param) { return jpaqlQuery.isBound( param ); } @SuppressWarnings({ "unchecked" }) public T getParameterValue(Parameter param) { return ( T ) jpaqlQuery.getParameterValue( mapToNamedParameter( param ) ); } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(Parameter param, T t) { jpaqlQuery.setParameter( mapToNamedParameter( param ), t ); return this; } @SuppressWarnings({ "RedundantCast" }) private Parameter mapToNamedParameter(Parameter criteriaParameter) { return jpaqlQuery.getParameter( explicitParameterMapping.get( (ParameterExpression) criteriaParameter ) ); } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(Parameter param, Calendar calendar, TemporalType temporalType) { jpaqlQuery.setParameter( mapToNamedParameter( param ), calendar, temporalType ); return this; } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(Parameter param, Date date, TemporalType temporalType) { jpaqlQuery.setParameter( mapToNamedParameter( param ), date, temporalType ); return this; } public T unwrap(Class cls) { return jpaqlQuery.unwrap( cls ); } @SuppressWarnings({ "unchecked" }) public Object getParameterValue(String name) { return getParameterValue( resolveExplicitCriteriaParameterName( name ) ); } private Parameter resolveExplicitCriteriaParameterName(String name) { Parameter parameter = explicitParameterNameMapping.get( name ); if ( parameter == null ) { throw new IllegalArgumentException( "Named parameter [" + name + "] not encountered" ); } return parameter; } public Parameter getParameter(String name) { return mapToNamedParameter( resolveExplicitCriteriaParameterName( name ) ); } @SuppressWarnings({ "unchecked" }) public Parameter getParameter(String name, Class type) { Parameter parameter = resolveExplicitCriteriaParameterName( name ); if ( type.isAssignableFrom( parameter.getParameterType() ) ) { return (Parameter) parameter; } throw new IllegalArgumentException( "Named parameter [" + name + "] type is not assignanle to request type [" + type.getName() + "]" ); } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(String name, Object value) { setParameter( resolveExplicitCriteriaParameterName( name, value ), value ); return this; } private Parameter resolveExplicitCriteriaParameterName(String name, Object value) { Parameter parameter = resolveExplicitCriteriaParameterName( name ); // todo : is null valid? if ( value != null ) { if ( ! parameter.getParameterType().isInstance( value ) ) { throw new IllegalArgumentException( "Named parameter [" + name + "] type mismatch; expecting [" + parameter.getParameterType().getName() + "], found [" + value.getClass().getName() + "]" ); } } return parameter; } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(String name, Calendar calendar, TemporalType temporalType) { Parameter parameter = resolveExplicitCriteriaParameterName( name ); if ( ! Calendar.class.isAssignableFrom( parameter.getParameterType() ) ) { throw new IllegalArgumentException( "Named parameter [" + name + "] type mismatch; expecting [" + Calendar.class.getName() + "], found [" + parameter.getParameterType().getName() + "]" ); } setParameter( parameter, calendar, temporalType ); return this; } @SuppressWarnings({ "unchecked" }) public TypedQuery setParameter(String name, Date date, TemporalType temporalType) { Parameter parameter = resolveExplicitCriteriaParameterName( name ); if ( ! Date.class.isAssignableFrom( parameter.getParameterType() ) ) { throw new IllegalArgumentException( "Named parameter [" + name + "] type mismatch; expecting [" + Date.class.getName() + "], found [" + parameter.getParameterType().getName() + "]" ); } setParameter( parameter, date, temporalType ); return this; } // unsupported stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public int executeUpdate() { throw new IllegalArgumentException( "Criteria queries do not support update queries" ); } public TypedQuery setParameter(int i, Object o) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } public TypedQuery setParameter(int i, Calendar calendar, TemporalType temporalType) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } public TypedQuery setParameter(int i, Date date, TemporalType temporalType) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } public Object getParameterValue(int position) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } public Parameter getParameter(int position) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } public Parameter getParameter(int position, Class type) { throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" ); } }; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/JoinImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000304411714611271032701 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.Fetch; import javax.persistence.criteria.Join; /** * Consolidates the {@link Join} and {@link Fetch} hierarchies since that is how we implement them. * This allows us to treat them polymorphically. * * @author Steve Ebersole */ public interface JoinImplementor extends Join, Fetch, FromImplementor { /** * {@inheritDoc} *

* Refined return type */ public JoinImplementor correlateTo(CriteriaSubqueryImpl subquery); } ././@LongLink0000000000000000000000000000020000000000000011555 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000002511411714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Order; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Selection; import javax.persistence.Tuple; import javax.persistence.criteria.Subquery; import javax.persistence.metamodel.EntityType; import org.hibernate.ejb.HibernateEntityManagerImplementor; import org.hibernate.type.Type; /** * The Hibernate implementation of the JPA {@link CriteriaQuery} contract. Mostly a set of delegation to its * internal {@link QueryStructure}. * * @author Steve Ebersole */ public class CriteriaQueryImpl extends AbstractNode implements CriteriaQuery, Serializable { private final Class returnType; private final QueryStructure queryStructure; private List orderSpecs = Collections.emptyList(); public CriteriaQueryImpl( CriteriaBuilderImpl criteriaBuilder, Class returnType) { super( criteriaBuilder ); this.returnType = returnType; this.queryStructure = new QueryStructure( this, criteriaBuilder ); } /** * {@inheritDoc} */ public Class getResultType() { return returnType; } // SELECTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public CriteriaQuery distinct(boolean applyDistinction) { queryStructure.setDistinct( applyDistinction ); return this; } /** * {@inheritDoc} */ public boolean isDistinct() { return queryStructure.isDistinct(); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Selection getSelection() { return ( Selection ) queryStructure.getSelection(); } public void applySelection(Selection selection) { queryStructure.setSelection( selection ); } /** * {@inheritDoc} */ public CriteriaQuery select(Selection selection) { applySelection( selection ); return this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public CriteriaQuery multiselect(Selection... selections) { return multiselect( Arrays.asList( selections ) ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public CriteriaQuery multiselect(List> selections) { final Selection selection; if ( Tuple.class.isAssignableFrom( getResultType() ) ) { selection = ( Selection ) criteriaBuilder().tuple( selections ); } else if ( getResultType().isArray() ) { selection = ( Selection ) criteriaBuilder().array( ( Class ) getResultType(), selections ); } else if ( Object.class.equals( getResultType() ) ) { switch ( selections.size() ) { case 0: { throw new IllegalArgumentException( "empty selections passed to criteria query typed as Object" ); } case 1: { selection = ( Selection ) selections.get( 0 ); break; } default: { selection = ( Selection ) criteriaBuilder().array( selections ); } } } else { selection = criteriaBuilder().construct( getResultType(), selections ); } applySelection( selection ); return this; } // ROOTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Set> getRoots() { return queryStructure.getRoots(); } /** * {@inheritDoc} */ public Root from(EntityType entityType) { return queryStructure.from( entityType ); } /** * {@inheritDoc} */ public Root from(Class entityClass) { return queryStructure.from( entityClass ); } // RESTRICTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Predicate getRestriction() { return queryStructure.getRestriction(); } /** * {@inheritDoc} */ public CriteriaQuery where(Expression expression) { queryStructure.setRestriction( criteriaBuilder().wrap( expression ) ); return this; } /** * {@inheritDoc} */ public CriteriaQuery where(Predicate... predicates) { // TODO : assuming this should be a conjuntion, but the spec does not say specifically... queryStructure.setRestriction( criteriaBuilder().and( predicates ) ); return this; } // GROUPING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public List> getGroupList() { return queryStructure.getGroupings(); } /** * {@inheritDoc} */ public CriteriaQuery groupBy(Expression... groupings) { queryStructure.setGroupings( groupings ); return this; } public CriteriaQuery groupBy(List> groupings) { queryStructure.setGroupings( groupings ); return this; } /** * {@inheritDoc} */ public Predicate getGroupRestriction() { return queryStructure.getHaving(); } /** * {@inheritDoc} */ public CriteriaQuery having(Expression expression) { queryStructure.setHaving( criteriaBuilder().wrap( expression ) ); return this; } /** * {@inheritDoc} */ public CriteriaQuery having(Predicate... predicates) { queryStructure.setHaving( criteriaBuilder().and( predicates ) ); return this; } // ORDERING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public List getOrderList() { return orderSpecs; } /** * {@inheritDoc} */ public CriteriaQuery orderBy(Order... orders) { if ( orders != null && orders.length > 0 ) { orderSpecs = Arrays.asList( orders ); } else { orderSpecs = Collections.emptyList(); } return this; } /** * {@inheritDoc} */ public CriteriaQuery orderBy(List orders) { orderSpecs = orders; return this; } /** * {@inheritDoc} */ public Set> getParameters() { return queryStructure.getParameters(); } /** * {@inheritDoc} */ public Subquery subquery(Class subqueryType) { return queryStructure.subquery( subqueryType ); } public void validate() { // getRoots() is explicitly supposed to return empty if none defined, no need to check for null if ( getRoots().isEmpty() ) { throw new IllegalStateException( "No criteria query roots were specified" ); } // if there is not an explicit selection, there is an *implicit* selection of the root entity provided only // a single query root was defined. if ( getSelection() == null && !hasImplicitSelection() ) { throw new IllegalStateException( "No explicit selection and an implicit one cold not be determined" ); } } /** * If no explicit selection was defined, we have a condition called an implicit selection if the query specified * a single {@link Root} and the java type of that {@link Root root's} model is the same as this criteria's * {@link #getResultType() result type}. * * @return True if there is an explicit selection; false otherwise. */ private boolean hasImplicitSelection() { if ( getRoots().size() != 1 ) { return false; } Root root = getRoots().iterator().next(); if ( root.getModel().getJavaType() != returnType ) { return false; } // if we get here, the query defined no selection but defined a single root of the same type as the // criteria query return, so we use that as the implicit selection // // todo : should we put an implicit marker in the selection to this fact to make later processing easier? return true; } public CriteriaQueryCompiler.RenderedCriteriaQuery render(CriteriaQueryCompiler.RenderingContext renderingContext) { final StringBuilder jpaqlQuery = new StringBuilder(); queryStructure.render( jpaqlQuery, renderingContext ); if ( ! getOrderList().isEmpty() ) { jpaqlQuery.append( " order by " ); String sep = ""; for ( Order orderSpec : getOrderList() ) { jpaqlQuery.append( sep ) .append( ( ( Renderable ) orderSpec.getExpression() ).render( renderingContext ) ) .append( orderSpec.isAscending() ? " asc" : " desc" ); sep = ", "; } } return new CriteriaQueryCompiler.RenderedCriteriaQuery() { public String getQueryString() { return jpaqlQuery.toString(); } @SuppressWarnings({ "unchecked" }) public List getValueHandlers() { SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection(); return selection == null ? null : selection.getValueHandlers(); } public HibernateEntityManagerImplementor.Options.ResultMetadataValidator getResultMetadataValidator() { return new HibernateEntityManagerImplementor.Options.ResultMetadataValidator() { public void validate(Type[] returnTypes) { SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection(); if ( selection != null ) { if ( selection.isCompoundSelection() ) { if ( returnTypes.length != selection.getCompoundSelectionItems().size() ) { throw new IllegalStateException( "Number of return values [" + returnTypes.length + "] did not match expected [" + selection.getCompoundSelectionItems().size() + "]" ); } } else { if ( returnTypes.length > 1 ) { throw new IllegalStateException( "Number of return values [" + returnTypes.length + "] did not match expected [1]" ); } } } } }; } }; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/MapJoinImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000271411714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.MapJoin; /** * Specialization of {@link JoinImplementor} for {@link java.util.Map} typed attribute joins * * @author Steve Ebersole */ public interface MapJoinImplementor extends JoinImplementor, MapJoin { /** * {@inheritDoc} *

* Refined return type */ public MapJoinImplementor correlateTo(CriteriaSubqueryImpl subquery); } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/ValueHandlerFactory.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000002512211714611271032702 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; /** * Helper for generically dealing with literal values. * * @author Steve Ebersole */ public class ValueHandlerFactory { private ValueHandlerFactory() { } public static interface ValueHandler { public T convert(Object value); public String render(T value); } public static abstract class BaseValueHandler implements ValueHandler, Serializable { public String render(T value) { return value.toString(); } } public static class NoOpValueHandler extends BaseValueHandler { @SuppressWarnings({ "unchecked" }) public T convert(Object value) { return (T) value; } } public static boolean isCharacter(Class type) { return String.class.isAssignableFrom( type ) || Character.class.isAssignableFrom( type ) || Character.TYPE.equals( type ); } public static boolean isCharacter(Object value) { return String.class.isInstance( value ) || Character.class.isInstance( value ) || Character.TYPE.isInstance( value ); } public static boolean isNumeric(Class type) { return Number.class.isAssignableFrom( type ) || Byte.TYPE.equals( type ) || Short.TYPE.equals( type ) || Integer.TYPE.equals( type ) || Long.TYPE.equals( type ) || Float.TYPE.equals( type ) || Double.TYPE.equals( type ); } public static boolean isNumeric(Object value) { return Number.class.isInstance( value ) || Byte.TYPE.isInstance( value ) || Short.TYPE.isInstance( value ) || Integer.TYPE.isInstance( value ) || Long.TYPE.isInstance( value ) || Float.TYPE.isInstance( value ) || Double.TYPE.isInstance( value ); } public static class ByteValueHandler extends BaseValueHandler implements Serializable { public static final ByteValueHandler INSTANCE = new ByteValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Byte convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Byte.valueOf( ( (Number) value ).byteValue() ); } else if ( String.class.isInstance( value ) ) { return Byte.valueOf( ( (String) value ) ); } throw unknownConversion( value, Byte.class ); } } public static class ShortValueHandler extends BaseValueHandler implements Serializable { public static final ShortValueHandler INSTANCE = new ShortValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Short convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Short.valueOf( ( (Number) value ).shortValue() ); } else if ( String.class.isInstance( value ) ) { return Short.valueOf( ( (String) value ) ); } throw unknownConversion( value, Short.class ); } } public static class IntegerValueHandler extends BaseValueHandler implements Serializable { public static final IntegerValueHandler INSTANCE = new IntegerValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Integer convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Integer.valueOf( ( (Number) value ).intValue() ); } else if ( String.class.isInstance( value ) ) { return Integer.valueOf( ( (String) value ) ); } throw unknownConversion( value, Integer.class ); } } public static class LongValueHandler extends BaseValueHandler implements Serializable { public static final LongValueHandler INSTANCE = new LongValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Long convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Long.valueOf( ( (Number) value ).longValue() ); } else if ( String.class.isInstance( value ) ) { return Long.valueOf( ( (String) value ) ); } throw unknownConversion( value, Long.class ); } @Override public String render(Long value) { return value.toString() + 'L'; } } public static class FloatValueHandler extends BaseValueHandler implements Serializable { public static final FloatValueHandler INSTANCE = new FloatValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Float convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Float.valueOf( ( (Number) value ).floatValue() ); } else if ( String.class.isInstance( value ) ) { return Float.valueOf( ( (String) value ) ); } throw unknownConversion( value, Float.class ); } @Override public String render(Float value) { return value.toString() + 'F'; } } public static class DoubleValueHandler extends BaseValueHandler implements Serializable { public static final DoubleValueHandler INSTANCE = new DoubleValueHandler(); @SuppressWarnings({ "UnnecessaryBoxing" }) public Double convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return Double.valueOf( ( (Number) value ).doubleValue() ); } else if ( String.class.isInstance( value ) ) { return Double.valueOf( ( (String) value ) ); } throw unknownConversion( value, Double.class ); } @Override public String render(Double value) { return value.toString() + 'D'; } } public static class BigIntegerValueHandler extends BaseValueHandler implements Serializable { public static final BigIntegerValueHandler INSTANCE = new BigIntegerValueHandler(); public BigInteger convert(Object value) { if ( value == null ) { return null; } if ( Number.class.isInstance( value ) ) { return BigInteger.valueOf( ( (Number) value ).longValue() ); } else if ( String.class.isInstance( value ) ) { return new BigInteger( (String) value ); } throw unknownConversion( value, BigInteger.class ); } @Override public String render(BigInteger value) { return value.toString() + "BI"; } } public static class BigDecimalValueHandler extends BaseValueHandler implements Serializable { public static final BigDecimalValueHandler INSTANCE = new BigDecimalValueHandler(); public BigDecimal convert(Object value) { if ( value == null ) { return null; } if ( BigInteger.class.isInstance( value ) ) { return new BigDecimal( (BigInteger) value ); } else if ( Number.class.isInstance( value ) ) { return BigDecimal.valueOf( ( (Number) value ).doubleValue() ); } else if ( String.class.isInstance( value ) ) { return new BigDecimal( (String) value ); } throw unknownConversion( value, BigDecimal.class ); } @Override public String render(BigDecimal value) { return value.toString() + "BD"; } } public static class StringValueHandler extends BaseValueHandler implements Serializable { public static final StringValueHandler INSTANCE = new StringValueHandler(); public String convert(Object value) { return value == null ? null : value.toString(); } } private static IllegalArgumentException unknownConversion(Object value, Class type) { return new IllegalArgumentException( "Unaware how to convert value [" + value + " : " + typeName( value ) + "] to requested type [" + type.getName() + "]" ); } private static String typeName(Object value) { return value == null ? "???" : value.getClass().getName(); } /** * Convert the given value into the specified target type. * * @param value The value to convert * @param targetType The type to which it should be converted * * @return The converted value. */ @SuppressWarnings({ "unchecked" }) public static T convert(Object value, Class targetType) { if ( value == null ) { return null; } if ( targetType.equals( value.getClass() ) ) { return (T) value; } ValueHandler valueHandler = determineAppropriateHandler( targetType ); if ( valueHandler == null ) { throw unknownConversion( value, targetType ); } return valueHandler.convert( value ); } /** * Determine the appropriate {@link ValueHandlerFactory.ValueHandler} strategy for converting a value * to the given target type * * @param targetType The target type (to which we want to convert values). * @param parameterized type for the target type. * @return The conversion */ @SuppressWarnings({ "unchecked" }) public static ValueHandler determineAppropriateHandler(Class targetType) { if ( String.class.equals( targetType ) ) { return (ValueHandler) StringValueHandler.INSTANCE; } if ( Byte.class.equals( targetType ) || Byte.TYPE.equals( targetType ) ) { return (ValueHandler) ByteValueHandler.INSTANCE; } if ( Short.class.equals( targetType ) || Short.TYPE.equals( targetType ) ) { return (ValueHandler) ShortValueHandler.INSTANCE; } if ( Integer.class.equals( targetType ) || Integer.TYPE.equals( targetType ) ) { return (ValueHandler) IntegerValueHandler.INSTANCE; } if ( Long.class.equals( targetType ) || Long.TYPE.equals( targetType ) ) { return (ValueHandler) LongValueHandler.INSTANCE; } if ( Float.class.equals( targetType ) || Float.TYPE.equals( targetType ) ) { return (ValueHandler) FloatValueHandler.INSTANCE; } if ( Double.class.equals( targetType ) || Double.TYPE.equals( targetType ) ) { return (ValueHandler) DoubleValueHandler.INSTANCE; } if ( BigInteger.class.equals( targetType ) ) { return (ValueHandler) BigIntegerValueHandler.INSTANCE; } if ( BigDecimal.class.equals( targetType ) ) { return (ValueHandler) BigDecimalValueHandler.INSTANCE; } return null; } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/ExpressionImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000511611714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.criteria.Expression; /** * TODO : javadoc * * @author Steve Ebersole */ public interface ExpressionImplementor extends SelectionImplementor, Expression, Renderable { /** * See {@link javax.persistence.criteria.CriteriaBuilder#toLong} * * @return this but as a long */ public ExpressionImplementor asLong(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toInteger} * * @return this but as an integer */ public ExpressionImplementor asInteger(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toFloat} * * @return this but as a float */ public ExpressionImplementor asFloat(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toDouble} * * @return this but as a double */ public ExpressionImplementor asDouble(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toBigDecimal} * * @return this but as a {@link BigDecimal} */ public ExpressionImplementor asBigDecimal(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toBigInteger} * * @return this but as a {@link BigInteger} */ public ExpressionImplementor asBigInteger(); /** * See {@link javax.persistence.criteria.CriteriaBuilder#toString} * * @return this but as a string */ public ExpressionImplementor asString(); } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/ListJoinImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000271311714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.criteria.ListJoin; /** * Specialization of {@link JoinImplementor} for {@link java.util.List} typed attribute joins * * @author Steve Ebersole */ public interface ListJoinImplementor extends JoinImplementor, ListJoin { /** * {@inheritDoc} *

* Refined return type */ public ListJoinImplementor correlateTo(CriteriaSubqueryImpl subquery); } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/SelectionImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000252511714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.util.List; import javax.persistence.criteria.Selection; /** * TODO : javadoc * * @author Steve Ebersole */ public interface SelectionImplementor extends TupleElementImplementor, Selection { public List getValueHandlers(); } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/Renderable.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000247011714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; /** * TODO : javadoc * * @author Steve Ebersole */ public interface Renderable { public String render(CriteriaQueryCompiler.RenderingContext renderingContext); public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext); } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/TupleElementImplementor.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000243511714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.TupleElement; /** * TODO : javadoc * * @author Steve Ebersole */ public interface TupleElementImplementor extends TupleElement { public ValueHandlerFactory.ValueHandler getValueHandler(); } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaSubqueryImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001725611714611271032713 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import java.io.Serializable; import java.util.List; import java.util.Set; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CollectionJoin; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Join; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.MapJoin; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import javax.persistence.criteria.Subquery; import javax.persistence.metamodel.EntityType; import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.path.RootImpl; /** * The Hibernate implementation of the JPA {@link Subquery} contract. Mostlty a set of delegation to its internal * {@link QueryStructure}. * * @author Steve Ebersole */ public class CriteriaSubqueryImpl extends ExpressionImpl implements Subquery, Serializable { private final AbstractQuery parent; private final QueryStructure queryStructure; public CriteriaSubqueryImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, AbstractQuery parent) { super( criteriaBuilder, javaType); this.parent = parent; this.queryStructure = new QueryStructure( this, criteriaBuilder ); } /** * {@inheritDoc} */ public AbstractQuery getParent() { return parent; } /** * {@inheritDoc} */ public void registerParameters(ParameterRegistry registry) { for ( ParameterExpression param : queryStructure.getParameters() ) { registry.registerParameter( param ); } } /** * {@inheritDoc} */ public Class getResultType() { return getJavaType(); } // ROOTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Set> getRoots() { return queryStructure.getRoots(); } /** * {@inheritDoc} */ public Root from(EntityType entityType) { return queryStructure.from( entityType ); } /** * {@inheritDoc} */ public Root from(Class entityClass) { return queryStructure.from( entityClass ); } // SELECTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Subquery distinct(boolean applyDistinction) { queryStructure.setDistinct( applyDistinction ); return this; } public boolean isDistinct() { return queryStructure.isDistinct(); } public Expression getSelection() { return (Expression) queryStructure.getSelection(); } public Subquery select(Expression expression) { queryStructure.setSelection( expression ); return this; } // RESTRICTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Predicate getRestriction() { return queryStructure.getRestriction(); } /** * {@inheritDoc} */ public Subquery where(Expression expression) { queryStructure.setRestriction( criteriaBuilder().wrap( expression ) ); return this; } /** * {@inheritDoc} */ public Subquery where(Predicate... predicates) { // TODO : assuming this should be a conjuntion, but the spec does not say specifically... queryStructure.setRestriction( criteriaBuilder().and( predicates ) ); return this; } // GROUPING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public List> getGroupList() { return queryStructure.getGroupings(); } /** * {@inheritDoc} */ public Subquery groupBy(Expression... groupings) { queryStructure.setGroupings( groupings ); return this; } /** * {@inheritDoc} */ public Subquery groupBy(List> groupings) { queryStructure.setGroupings( groupings ); return this; } /** * {@inheritDoc} */ public Predicate getGroupRestriction() { return queryStructure.getHaving(); } /** * {@inheritDoc} */ public Subquery having(Expression expression) { queryStructure.setHaving( criteriaBuilder().wrap( expression ) ); return this; } /** * {@inheritDoc} */ public Subquery having(Predicate... predicates) { queryStructure.setHaving( criteriaBuilder().and( predicates ) ); return this; } // CORRELATIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Set> getCorrelatedJoins() { return queryStructure.collectCorrelatedJoins(); } /** * {@inheritDoc} */ public Root correlate(Root source) { final RootImpl correlation = ( ( RootImpl ) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public Join correlate(Join source) { final JoinImplementor correlation = ( (JoinImplementor) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public CollectionJoin correlate(CollectionJoin source) { final CollectionJoinImplementor correlation = ( (CollectionJoinImplementor) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public SetJoin correlate(SetJoin source) { final SetJoinImplementor correlation = ( (SetJoinImplementor) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public ListJoin correlate(ListJoin source) { final ListJoinImplementor correlation = ( (ListJoinImplementor) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public MapJoin correlate(MapJoin source) { final MapJoinImplementor correlation = ( (MapJoinImplementor) source ).correlateTo( this ); queryStructure.addCorrelationRoot( correlation ); return correlation; } /** * {@inheritDoc} */ public Subquery subquery(Class subqueryType) { return queryStructure.subquery( subqueryType ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder subqueryBuffer = new StringBuilder( "(" ); queryStructure.render( subqueryBuffer, renderingContext ); subqueryBuffer.append( ')' ); return subqueryBuffer.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { throw new IllegalStateException( "Subquery cannot occur in select clause" ); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032676 5ustar ebourgebourg././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/InPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001464511714611271032712 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Subquery; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.expression.LiteralExpression; /** * Models an [NOT] IN restriction * * @author Steve Ebersole */ public class InPredicate extends AbstractSimplePredicate implements CriteriaBuilderImpl.In, Serializable { private final Expression expression; private final List> values; /** * Constructs an IN predicate against a given expression with an empty list of values. * * @param criteriaBuilder The query builder from which this originates. * @param expression The expression. */ public InPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression) { this( criteriaBuilder, expression, new ArrayList>() ); } /** * Constructs an IN predicate against a given expression with the given list of expression values. * * @param criteriaBuilder The query builder from which this originates. * @param expression The expression. * @param values The value list. */ public InPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, Expression... values) { this( criteriaBuilder, expression, Arrays.asList( values ) ); } /** * Constructs an IN predicate against a given expression with the given list of expression values. * * @param criteriaBuilder The query builder from which this originates. * @param expression The expression. * @param values The value list. */ public InPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, List> values) { super( criteriaBuilder ); this.expression = expression; this.values = values; } /** * Constructs an IN predicate against a given expression with the given given literal value list. * * @param criteriaBuilder The query builder from which this originates. * @param expression The expression. * @param values The value list. */ public InPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, T... values) { this( criteriaBuilder, expression, Arrays.asList( values ) ); } /** * Constructs an IN predicate against a given expression with the given literal value list. * * @param criteriaBuilder The query builder from which this originates. * @param expression The expression. * @param values The value list. */ public InPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, Collection values) { super( criteriaBuilder ); this.expression = expression; this.values = new ArrayList>( values.size() ); ValueHandlerFactory.ValueHandler valueHandler = ValueHandlerFactory.isNumeric( expression.getJavaType() ) ? ValueHandlerFactory.determineAppropriateHandler( (Class) expression.getJavaType() ) : new ValueHandlerFactory.NoOpValueHandler(); for ( T value : values ) { this.values.add( new LiteralExpression( criteriaBuilder, valueHandler.convert( value ) ) ); } } @SuppressWarnings("unchecked") public Expression getExpression() { return ( Expression ) expression; } public Expression getExpressionInternal() { return expression; } public List> getValues() { return values; } public InPredicate value(T value) { return value( new LiteralExpression( criteriaBuilder(), value ) ); } public InPredicate value(Expression value) { values.add( value ); return this; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getExpressionInternal(), registry ); for ( Expression value : getValues() ) { Helper.possibleParameter(value, registry); } } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder buffer = new StringBuilder(); buffer.append( ( (Renderable) getExpression() ).render( renderingContext ) ); if ( isNegated() ) { buffer.append( " not" ); } buffer.append( " in " ); // subquery expressions are already wrapped in parenthesis, so we only need to // render the parenthesis here if the values represent an explicit value list boolean isInSubqueryPredicate = getValues().size() == 1 && Subquery.class.isInstance( getValues().get( 0 ) ); if ( isInSubqueryPredicate ) { buffer.append( ( (Renderable) getValues().get(0) ).render( renderingContext ) ); } else { buffer.append( '(' ); String sep = ""; for ( Expression value : getValues() ) { buffer.append( sep ) .append( ( (Renderable) value ).render( renderingContext ) ); sep = ", "; } buffer.append( ')' ); } return buffer.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/ComparisonPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001274411714611271032710 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.expression.BinaryOperatorExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression; /** * Models a basic relational comparison predicate. * * @author Steve Ebersole */ public class ComparisonPredicate extends AbstractSimplePredicate implements BinaryOperatorExpression, Serializable { private final ComparisonOperator comparisonOperator; private final Expression leftHandSide; private final Expression rightHandSide; public ComparisonPredicate( CriteriaBuilderImpl criteriaBuilder, ComparisonOperator comparisonOperator, Expression leftHandSide, Expression rightHandSide) { super( criteriaBuilder ); this.comparisonOperator = comparisonOperator; this.leftHandSide = leftHandSide; this.rightHandSide = rightHandSide; } @SuppressWarnings({ "unchecked" }) public ComparisonPredicate( CriteriaBuilderImpl criteriaBuilder, ComparisonOperator comparisonOperator, Expression leftHandSide, Object rightHandSide) { super( criteriaBuilder ); this.comparisonOperator = comparisonOperator; this.leftHandSide = leftHandSide; if ( ValueHandlerFactory.isNumeric( leftHandSide.getJavaType() ) ) { this.rightHandSide = new LiteralExpression( criteriaBuilder, ValueHandlerFactory.convert( rightHandSide, (Class) leftHandSide.getJavaType() ) ); } else { this.rightHandSide = new LiteralExpression( criteriaBuilder, rightHandSide ); } } @SuppressWarnings( {"unchecked"}) public ComparisonPredicate( CriteriaBuilderImpl criteriaBuilder, ComparisonOperator comparisonOperator, Expression leftHandSide, Number rightHandSide) { super( criteriaBuilder ); this.comparisonOperator = comparisonOperator; this.leftHandSide = leftHandSide; Class type = leftHandSide.getJavaType(); if ( Number.class.equals( type ) ) { this.rightHandSide = new LiteralExpression( criteriaBuilder, rightHandSide ); } else { N converted = (N) ValueHandlerFactory.convert( rightHandSide, type ); this.rightHandSide = new LiteralExpression( criteriaBuilder, converted ); } } public ComparisonOperator getComparisonOperator() { return isNegated() ? comparisonOperator.negated() : comparisonOperator; } public Expression getLeftHandOperand() { return leftHandSide; } public Expression getRightHandOperand() { return rightHandSide; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getLeftHandOperand(), registry ); Helper.possibleParameter( getRightHandOperand(), registry ); } /** * Defines the comparison operators. We could also get away with * only 3 and use negation... */ public static enum ComparisonOperator { EQUAL { public ComparisonOperator negated() { return NOT_EQUAL; } public String rendered() { return "="; } }, NOT_EQUAL { public ComparisonOperator negated() { return EQUAL; } public String rendered() { return "<>"; } }, LESS_THAN { public ComparisonOperator negated() { return GREATER_THAN_OR_EQUAL; } public String rendered() { return "<"; } }, LESS_THAN_OR_EQUAL { public ComparisonOperator negated() { return GREATER_THAN; } public String rendered() { return "<="; } }, GREATER_THAN { public ComparisonOperator negated() { return LESS_THAN_OR_EQUAL; } public String rendered() { return ">"; } }, GREATER_THAN_OR_EQUAL { public ComparisonOperator negated() { return LESS_THAN; } public String rendered() { return ">="; } }; public abstract ComparisonOperator negated(); public abstract String rendered(); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( (Renderable) getLeftHandOperand() ).render( renderingContext ) + getComparisonOperator().rendered() + ( (Renderable) getRightHandOperand() ).render( renderingContext ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/MemberOfPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000606211714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.Collection; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.path.PluralAttributePath; /** * Models an [NOT] MEMBER OF restriction * * @author Steve Ebersole */ public class MemberOfPredicate> extends AbstractSimplePredicate implements Serializable { private final Expression elementExpression; private final PluralAttributePath collectionPath; public MemberOfPredicate( CriteriaBuilderImpl criteriaBuilder, Expression elementExpression, PluralAttributePath collectionPath) { super( criteriaBuilder ); this.elementExpression = elementExpression; this.collectionPath = collectionPath; } public MemberOfPredicate( CriteriaBuilderImpl criteriaBuilder, E element, PluralAttributePath collectionPath) { this( criteriaBuilder, new LiteralExpression( criteriaBuilder, element ), collectionPath ); } public PluralAttributePath getCollectionPath() { return collectionPath; } public Expression getElementExpression() { return elementExpression; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getCollectionPath(), registry ); Helper.possibleParameter( getElementExpression(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( (Renderable) elementExpression ).render( renderingContext ) + ( isNegated() ? " not" : "" ) + " member of " + getCollectionPath().render( renderingContext ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/IsEmptyPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000462611714611271032710 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.Collection; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression; import org.hibernate.ejb.criteria.path.PluralAttributePath; /** * Models an IS [NOT] EMPTY restriction * * @author Steve Ebersole */ public class IsEmptyPredicate extends AbstractSimplePredicate implements UnaryOperatorExpression, Serializable { private final PluralAttributePath collectionPath; public IsEmptyPredicate( CriteriaBuilderImpl criteriaBuilder, PluralAttributePath collectionPath) { super( criteriaBuilder ); this.collectionPath = collectionPath; } public PluralAttributePath getOperand() { return collectionPath; } public void registerParameters(ParameterRegistry registry) { // nothing to do } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { final String operator = isNegated() ? " is not empty" : " is empty"; return getOperand().render( renderingContext ) + operator; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/BetweenPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000641611714611271032707 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models a BETWEEN {@link javax.persistence.criteria.Predicate}. * * @author Steve Ebersole */ public class BetweenPredicate extends AbstractSimplePredicate implements Serializable { private final Expression expression; private final Expression lowerBound; private final Expression upperBound; public BetweenPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, Y lowerBound, Y upperBound) { this( criteriaBuilder, expression, criteriaBuilder.literal( lowerBound ), criteriaBuilder.literal( upperBound ) ); } public BetweenPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, Expression lowerBound, Expression upperBound) { super( criteriaBuilder ); this.expression = expression; this.lowerBound = lowerBound; this.upperBound = upperBound; } public Expression getExpression() { return expression; } public Expression getLowerBound() { return lowerBound; } public Expression getUpperBound() { return upperBound; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getExpression(), registry ); Helper.possibleParameter( getLowerBound(), registry ); Helper.possibleParameter( getUpperBound(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { final String operator = isNegated() ? " not between " : " between "; return ( (Renderable) getExpression() ).render( renderingContext ) + operator + ( (Renderable) getLowerBound() ).render( renderingContext ) + " and " + ( (Renderable) getUpperBound() ).render( renderingContext ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/LikePredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001104411714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.expression.LiteralExpression; /** * Models a SQL LIKE expression. * * @author Steve Ebersole */ public class LikePredicate extends AbstractSimplePredicate implements Serializable { private final Expression matchExpression; private final Expression pattern; private final Expression escapeCharacter; public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, Expression pattern) { this( criteriaBuilder, matchExpression, pattern, null ); } public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, String pattern) { this( criteriaBuilder, matchExpression, new LiteralExpression( criteriaBuilder, pattern) ); } public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, Expression pattern, Expression escapeCharacter) { super( criteriaBuilder ); this.matchExpression = matchExpression; this.pattern = pattern; this.escapeCharacter = escapeCharacter; } public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, Expression pattern, char escapeCharacter) { this( criteriaBuilder, matchExpression, pattern, new LiteralExpression( criteriaBuilder, escapeCharacter ) ); } public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, String pattern, char escapeCharacter) { this( criteriaBuilder, matchExpression, new LiteralExpression( criteriaBuilder, pattern ), new LiteralExpression( criteriaBuilder, escapeCharacter ) ); } public LikePredicate( CriteriaBuilderImpl criteriaBuilder, Expression matchExpression, String pattern, Expression escapeCharacter) { this( criteriaBuilder, matchExpression, new LiteralExpression( criteriaBuilder, pattern ), escapeCharacter ); } public Expression getEscapeCharacter() { return escapeCharacter; } public Expression getMatchExpression() { return matchExpression; } public Expression getPattern() { return pattern; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getEscapeCharacter(), registry ); Helper.possibleParameter( getMatchExpression(), registry ); Helper.possibleParameter( getPattern(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { final String operator = isNegated() ? " not like " : " like "; StringBuilder buffer = new StringBuilder(); buffer.append( ( (Renderable) getMatchExpression() ).render( renderingContext ) ) .append( operator ) .append( ( (Renderable) getPattern() ).render( renderingContext ) ); if ( escapeCharacter != null ) { buffer.append( " escape " ) .append( ( (Renderable) getEscapeCharacter() ).render( renderingContext ) ); } return buffer.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/ExplicitTruthValueCheck.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000600411714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * ANSI-SQL defines TRUE, FALSE and UNKNOWN as truth values. These * truth values are used to explicitly check the result of a boolean expression (the syntax is like * a > b IS TRUE. IS TRUE is the assumed default. *

* JPA defines support for only IS TRUE and IS FALSE, not IS UNKNOWN (a > NULL * is an example where the result would be UNKNOWN. * * @author Steve Ebersole */ public class ExplicitTruthValueCheck extends AbstractSimplePredicate implements Serializable { // TODO : given that JPA supports only TRUE and FALSE, can this be handled just with negation? private final Expression booleanExpression; private final TruthValue truthValue; public ExplicitTruthValueCheck(CriteriaBuilderImpl criteriaBuilder, Expression booleanExpression, TruthValue truthValue) { super( criteriaBuilder ); this.booleanExpression = booleanExpression; this.truthValue = truthValue; } public Expression getBooleanExpression() { return booleanExpression; } public TruthValue getTruthValue() { return truthValue; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getBooleanExpression(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( (Renderable) getBooleanExpression() ).render( renderingContext ) + " = " + ( getTruthValue() == TruthValue.TRUE ? "true" : "false" ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/ExistsPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000431011714611271032676 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Subquery; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models an EXISTS() predicate * * @author Steve Ebersole */ public class ExistsPredicate extends AbstractSimplePredicate implements Serializable { private final Subquery subquery; public ExistsPredicate(CriteriaBuilderImpl criteriaBuilder, Subquery subquery) { super( criteriaBuilder ); this.subquery = subquery; } public Subquery getSubquery() { return subquery; } public void registerParameters(ParameterRegistry registry) { // nothing to do here } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( isNegated() ? "not " : "" ) + "exists " + ( (Renderable) getSubquery() ).render( renderingContext ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000023000000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/BooleanStaticAssertionPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000434311714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; /** * Predicate used to assert a static boolean condition. * * @author Steve Ebersole */ public class BooleanStaticAssertionPredicate extends AbstractSimplePredicate implements Serializable { private final Boolean assertedValue; public BooleanStaticAssertionPredicate( CriteriaBuilderImpl criteriaBuilder, Boolean assertedValue) { super( criteriaBuilder ); this.assertedValue = assertedValue; } public Boolean getAssertedValue() { return assertedValue; } /** * {@inheritDoc} */ public void registerParameters(ParameterRegistry registry) { // nada } /** * {@inheritDoc} */ public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { boolean isTrue = getAssertedValue(); if ( isNegated() ) { isTrue = !isTrue; } return isTrue ? "1=1" : "0=1"; } /** * {@inheritDoc} */ public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } }././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/CompoundPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001274111714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.Renderable; /** * A compound {@link Predicate predicate} is a grouping of other {@link Predicate predicates} in order to convert * either a conjunction (logical AND) or a disjunction (logical OR). * * @author Steve Ebersole */ public class CompoundPredicate extends AbstractPredicateImpl implements Serializable { private BooleanOperator operator; private final List> expressions = new ArrayList>(); /** * Constructs an empty conjunction or disjunction. * * @param criteriaBuilder The query builder from which this originates. * @param operator Indicates whether this predicate will function * as a conjunction or disjunction. */ public CompoundPredicate(CriteriaBuilderImpl criteriaBuilder, BooleanOperator operator) { super( criteriaBuilder ); this.operator = operator; } /** * Constructs a conjunction or disjunction over the given expressions. * * @param criteriaBuilder The query builder from which this originates. * @param operator Indicates whether this predicate will function * as a conjunction or disjunction. * @param expressions The expressions to be grouped. */ public CompoundPredicate( CriteriaBuilderImpl criteriaBuilder, BooleanOperator operator, Expression... expressions) { this( criteriaBuilder, operator ); applyExpressions( expressions ); } /** * Constructs a conjunction or disjunction over the given expressions. * * @param criteriaBuilder The query builder from which this originates. * @param operator Indicates whether this predicate will function * as a conjunction or disjunction. * @param expressions The expressions to be grouped. */ public CompoundPredicate( CriteriaBuilderImpl criteriaBuilder, BooleanOperator operator, List> expressions) { this( criteriaBuilder, operator ); applyExpressions( expressions ); } private void applyExpressions(Expression... expressions) { applyExpressions( Arrays.asList( expressions ) ); } private void applyExpressions(List> expressions) { this.expressions.clear(); this.expressions.addAll( expressions ); } public BooleanOperator getOperator() { return operator; } public List> getExpressions() { return expressions; } public void registerParameters(ParameterRegistry registry) { for ( Expression expression : getExpressions() ) { Helper.possibleParameter( expression, registry ); } } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { if ( getExpressions().size() == 0 ) { boolean implicitTrue = getOperator() == BooleanOperator.AND; if ( isNegated() ) { implicitTrue = !implicitTrue; } return implicitTrue ? "1=1" // true : "0=1"; // false } if ( getExpressions().size() == 1 ) { return ( (Renderable) getExpressions().get( 0 ) ).render( renderingContext ); } final StringBuilder buffer = new StringBuilder(); String sep = ""; for ( Expression expression : getExpressions() ) { buffer.append( sep ) .append( "( " ) .append( ( (Renderable) expression ).render( renderingContext ) ) .append( " )" ); sep = operatorTextWithSeparator(); } return buffer.toString(); } private String operatorTextWithSeparator() { return getOperator() == BooleanOperator.AND ? " and " : " or "; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } /** * Create negation of compound predicate by using logic rules: * 1. not (x || y) is (not x && not y) * 2. not (x && y) is (not x || not y) */ @Override public Predicate not() { toggleOperator(); for ( Expression expr : this.getExpressions() ) { if ( Predicate.class.isInstance( expr ) ) { ( (Predicate) expr ).not(); } } return this; } private void toggleOperator() { if ( this.operator == BooleanOperator.AND ) { this.operator = BooleanOperator.OR; } else { this.operator = BooleanOperator.AND; } } } ././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/BooleanAssertionPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000535211714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.Renderable; /** * Predicate to assert the explicit value of a boolean expression:

    *
  • x = true
  • *
  • x = false
  • *
  • x <> true
  • *
  • x <> false
  • *
* * @author Steve Ebersole */ public class BooleanAssertionPredicate extends AbstractSimplePredicate implements Serializable { private final Expression expression; private final Boolean assertedValue; public BooleanAssertionPredicate( CriteriaBuilderImpl criteriaBuilder, Expression expression, Boolean assertedValue) { super( criteriaBuilder ); this.expression = expression; this.assertedValue = assertedValue; } public Expression getExpression() { return expression; } public Boolean getAssertedValue() { return assertedValue; } /** * {@inheritDoc} */ public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( expression, registry ); } /** * {@inheritDoc} */ public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { final String operator = isNegated() ? " <> " : " = "; final String assertionLiteral = assertedValue ? "true" : "false"; return ( (Renderable) expression ).render( renderingContext ) + operator + assertionLiteral; } /** * {@inheritDoc} */ public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000024000000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/ImplicitNumericExpressionTypeDeterminer.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000474011714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.math.BigDecimal; import java.math.BigInteger; import org.hibernate.ejb.criteria.expression.BinaryArithmeticOperation.Operation; /** * @author Steve Ebersole */ public class ImplicitNumericExpressionTypeDeterminer { /** * Determine the appropriate runtime result type for a numeric expression according to * section "6.5.7.1 Result Types of Expressions" of the JPA spec. *

* Note that it is expected that the caveats about quotient handling have already been handled. * * @param types The argument/expression types * * @return The appropriate numeric result type. */ public static Class determineResultType(Class... types) { Class result = Number.class; for ( Class type : types ) { if ( Double.class.equals( type ) ) { result = Double.class; } else if ( Float.class.equals( type ) ) { result = Float.class; } else if ( BigDecimal.class.equals( type ) ) { result = BigDecimal.class; } else if ( BigInteger.class.equals( type ) ) { result = BigInteger.class; } else if ( Long.class.equals( type ) ) { result = Long.class; } else if ( isIntegralType( type ) ) { result = Integer.class; } } return result; } private static boolean isIntegralType(Class type) { return Integer.class.equals( type ) || Short.class.equals( type ); } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/AbstractSimplePredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000343711714611271032707 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.List; import java.util.Collections; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; /** * TODO : javadoc * * @author Steve Ebersole */ public abstract class AbstractSimplePredicate extends AbstractPredicateImpl implements Serializable { private static final List> NO_EXPRESSIONS = Collections.emptyList(); public AbstractSimplePredicate(CriteriaBuilderImpl criteriaBuilder) { super( criteriaBuilder ); } public BooleanOperator getOperator() { return BooleanOperator.AND; } public final List> getExpressions() { return NO_EXPRESSIONS; } } ././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/AbstractPredicateImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000444611714611271032710 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import java.util.List; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Selection; import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; /** * Basic template support for {@link Predicate} implementors providing * expression handling, negation and conjunction/disjunction handling. * * @author Steve Ebersole */ public abstract class AbstractPredicateImpl extends ExpressionImpl implements Predicate, Serializable { private boolean negated; protected AbstractPredicateImpl(CriteriaBuilderImpl criteriaBuilder) { super( criteriaBuilder, Boolean.class ); } public boolean isNegated() { return negated; } public Predicate not() { negated = !negated; return this; } // Selection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public final boolean isCompoundSelection() { // Should always be false for predicates return super.isCompoundSelection(); } @Override public final List> getCompoundSelectionItems() { // Should never have sub selection items for predicates return super.getCompoundSelectionItems(); } } ././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/NullnessPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000562211714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression; /** * Defines a {@link javax.persistence.criteria.Predicate} for checking the * nullness state of an expression, aka an IS [NOT] NULL predicate. *

* The NOT NULL form can be built by calling the constructor and then * calling {@link #not}. * * @author Steve Ebersole */ public class NullnessPredicate extends AbstractSimplePredicate implements UnaryOperatorExpression, Serializable { private final Expression operand; /** * Constructs the affirmitive form of nullness checking (IS NULL). To * construct the negative form (IS NOT NULL) call {@link #not} on the * constructed instance. * * @param criteriaBuilder The query builder from whcih this originates. * @param operand The expression to check. */ public NullnessPredicate(CriteriaBuilderImpl criteriaBuilder, Expression operand) { super( criteriaBuilder ); this.operand = operand; } public Expression getOperand() { return operand; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getOperand(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( (Renderable) operand ).render( renderingContext ) + check(); } private String check() { return isNegated() ? " is not null" : " is null"; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/BooleanExpressionPredicate.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000467611714611271032715 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; import java.io.Serializable; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Defines a {@link Predicate} used to wrap an {@link Expression Expression<Boolean>}. * * @author Steve Ebersole */ public class BooleanExpressionPredicate extends AbstractSimplePredicate implements Serializable { private final Expression expression; public BooleanExpressionPredicate(CriteriaBuilderImpl criteriaBuilder, Expression expression) { super( criteriaBuilder ); this.expression = expression; } /** * Get the boolean expression defining the predicate. * * @return The underlying boolean expression. */ public Expression getExpression() { return expression; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter(expression, registry); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return ( (Renderable) getExpression() ).render( renderingContext ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/predicate/TruthValue.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000334611714611271032706 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.predicate; /** * Models what ANSI-SQL terms a truth value. Specifically, ANSI-SQL defines TRUE, FALSE and * UNKNOWN as truth values. These truth values are used to explicitly check the result of a * boolean expression (the syntax is like a > b IS TRUE. IS TRUE is the assumed default. *

* JPA defines support for only IS TRUE and IS FALSE, not IS UNKNOWN (a > NULL * is an example where the result would be UNKNOWN). All 3 are provided here for completness. * * @author Steve Ebersole */ public enum TruthValue { TRUE, FALSE, UNKNOWN } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaBuilderImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000012425111714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria; import javax.persistence.Tuple; import javax.persistence.criteria.CompoundSelection; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Order; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Selection; import javax.persistence.criteria.Subquery; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.ejb.EntityManagerFactoryImpl; import org.hibernate.ejb.criteria.expression.BinaryArithmeticOperation; import org.hibernate.ejb.criteria.expression.CoalesceExpression; import org.hibernate.ejb.criteria.expression.CompoundSelectionImpl; import org.hibernate.ejb.criteria.expression.ConcatExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.NullLiteralExpression; import org.hibernate.ejb.criteria.expression.NullifExpression; import org.hibernate.ejb.criteria.expression.ParameterExpressionImpl; import org.hibernate.ejb.criteria.expression.SearchedCaseExpression; import org.hibernate.ejb.criteria.expression.SimpleCaseExpression; import org.hibernate.ejb.criteria.expression.SizeOfCollectionExpression; import org.hibernate.ejb.criteria.expression.SubqueryComparisonModifierExpression; import org.hibernate.ejb.criteria.expression.UnaryArithmeticOperation; import org.hibernate.ejb.criteria.expression.function.AbsFunction; import org.hibernate.ejb.criteria.expression.function.AggregationFunction; import org.hibernate.ejb.criteria.expression.function.BasicFunctionExpression; import org.hibernate.ejb.criteria.expression.function.CurrentDateFunction; import org.hibernate.ejb.criteria.expression.function.CurrentTimeFunction; import org.hibernate.ejb.criteria.expression.function.CurrentTimestampFunction; import org.hibernate.ejb.criteria.expression.function.LengthFunction; import org.hibernate.ejb.criteria.expression.function.LocateFunction; import org.hibernate.ejb.criteria.expression.function.LowerFunction; import org.hibernate.ejb.criteria.expression.function.ParameterizedFunctionExpression; import org.hibernate.ejb.criteria.expression.function.SqrtFunction; import org.hibernate.ejb.criteria.expression.function.SubstringFunction; import org.hibernate.ejb.criteria.expression.function.TrimFunction; import org.hibernate.ejb.criteria.expression.function.UpperFunction; import org.hibernate.ejb.criteria.path.PluralAttributePath; import org.hibernate.ejb.criteria.predicate.BetweenPredicate; import org.hibernate.ejb.criteria.predicate.BooleanAssertionPredicate; import org.hibernate.ejb.criteria.predicate.BooleanExpressionPredicate; import org.hibernate.ejb.criteria.predicate.BooleanStaticAssertionPredicate; import org.hibernate.ejb.criteria.predicate.ComparisonPredicate; import org.hibernate.ejb.criteria.predicate.CompoundPredicate; import org.hibernate.ejb.criteria.predicate.ExistsPredicate; import org.hibernate.ejb.criteria.predicate.InPredicate; import org.hibernate.ejb.criteria.predicate.IsEmptyPredicate; import org.hibernate.ejb.criteria.predicate.LikePredicate; import org.hibernate.ejb.criteria.predicate.MemberOfPredicate; import org.hibernate.ejb.criteria.predicate.NullnessPredicate; import static org.hibernate.ejb.criteria.predicate.ComparisonPredicate.ComparisonOperator; /** * Hibernate implementation of the JPA {@link CriteriaBuilder} contract. * * @author Steve Ebersole */ public class CriteriaBuilderImpl implements CriteriaBuilder, Serializable { private final EntityManagerFactoryImpl entityManagerFactory; public CriteriaBuilderImpl(EntityManagerFactoryImpl entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } /** * Provides protected access to the underlying {@link EntityManagerFactoryImpl}. * * @return The underlying {@link EntityManagerFactoryImpl} */ public EntityManagerFactoryImpl getEntityManagerFactory() { return entityManagerFactory; } /** * {@inheritDoc} */ public CriteriaQuery createQuery() { return new CriteriaQueryImpl( this, Object.class ); } /** * {@inheritDoc} */ public CriteriaQuery createQuery(Class resultClass) { return new CriteriaQueryImpl( this, resultClass ); } /** * {@inheritDoc} */ public CriteriaQuery createTupleQuery() { return new CriteriaQueryImpl( this, Tuple.class ); } /** * Package-protected method to centralize checking of criteria query * multiselects as defined by the * {@link CriteriaQuery#multiselect(List)} method. * * @param selections The selection varargs to check * * @throws IllegalArgumentException If, as per * {@link CriteriaQuery#multiselect(List)} documentation, * "An argument to the multiselect method must not be a tuple- * or array-valued compound selection item." */ void checkMultiselect(List> selections) { for ( Selection selection : selections ) { if ( selection.isCompoundSelection() ) { if ( selection.getJavaType().isArray() ) { throw new IllegalArgumentException( "multiselect selections cannot contain " + "compound array-valued elements" ); } if ( Tuple.class.isAssignableFrom( selection.getJavaType() ) ) { throw new IllegalArgumentException( "multiselect selections cannot contain " + "compound tuple-valued elements" ); } } } } /** * {@inheritDoc} */ public CompoundSelection tuple(Selection... selections) { return tuple( Arrays.asList( selections ) ); } /** * Version of {@link #tuple(Selection[])} taking a list. * * @param selections List of selections. * * @return The tuple compound selection */ public CompoundSelection tuple(List> selections) { checkMultiselect( selections ); return new CompoundSelectionImpl( this, Tuple.class, selections ); } /** * {@inheritDoc} */ public CompoundSelection array(Selection... selections) { return array( Arrays.asList( selections ) ); } /** * Version of {@link #array(Selection[])} taking a list of selections. * * @param selections List of selections. * * @return The array compound selection */ public CompoundSelection array(List> selections) { return array( Object[].class, selections ); } /** * Version of {@link #array(Selection[])} taking a list of selections, * as well as the type of array. * * @param type The type of array * @param selections List of selections. * * @return The array compound selection */ public CompoundSelection array(Class type, List> selections) { checkMultiselect( selections ); return new CompoundSelectionImpl( this, type, selections ); } /** * {@inheritDoc} */ public CompoundSelection construct(Class result, Selection... selections) { return construct( result, Arrays.asList( selections ) ); } /** * Version of {@link #construct(Class,Selection[])} taking the * to-be-constructed type as well as a list of selections. * * @param result The result class to be constructed. * @param selections The selections to use in the constructor call. * * @return The view compound selection. */ public CompoundSelection construct(Class result, List> selections) { checkMultiselect( selections ); return new CompoundSelectionImpl( this, result, selections ); } // ordering ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Order asc(Expression x) { return new OrderImpl( x, true ); } /** * {@inheritDoc} */ public Order desc(Expression x) { return new OrderImpl( x, false ); } // predicates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Predicate wrap(Expression expression) { if ( Predicate.class.isInstance( expression ) ) { return ( (Predicate) expression ); } else if ( PathImplementor.class.isInstance( expression ) ) { return new BooleanAssertionPredicate( this, expression, Boolean.TRUE ); } else { return new BooleanExpressionPredicate( this, expression ); } } /** * {@inheritDoc} */ public Predicate not(Expression expression) { return wrap( expression ).not(); } /** * {@inheritDoc} */ public Predicate and(Expression x, Expression y) { return new CompoundPredicate( this, Predicate.BooleanOperator.AND, x, y ); } /** * {@inheritDoc} */ public Predicate or(Expression x, Expression y) { return new CompoundPredicate( this, Predicate.BooleanOperator.OR, x, y ); } /** * {@inheritDoc} */ public Predicate and(Predicate... restrictions) { return new CompoundPredicate( this, Predicate.BooleanOperator.AND, restrictions ); } /** * {@inheritDoc} */ public Predicate or(Predicate... restrictions) { return new CompoundPredicate( this, Predicate.BooleanOperator.OR, restrictions ); } /** * {@inheritDoc} */ public Predicate conjunction() { return new CompoundPredicate( this, Predicate.BooleanOperator.AND ); } /** * {@inheritDoc} */ public Predicate disjunction() { return new CompoundPredicate( this, Predicate.BooleanOperator.OR ); } /** * {@inheritDoc} */ public Predicate isTrue(Expression expression) { if ( CompoundPredicate.class.isInstance( expression ) ) { final CompoundPredicate predicate = (CompoundPredicate) expression; if ( predicate.getExpressions().size() == 0 ) { return new BooleanStaticAssertionPredicate( this, predicate.getOperator() == Predicate.BooleanOperator.AND ); } return predicate; } else if ( Predicate.class.isInstance( expression ) ) { return (Predicate) expression; } return new BooleanAssertionPredicate( this, expression, Boolean.TRUE ); } /** * {@inheritDoc} */ public Predicate isFalse(Expression expression) { if ( CompoundPredicate.class.isInstance( expression ) ) { final CompoundPredicate predicate = (CompoundPredicate) expression; if ( predicate.getExpressions().size() == 0 ) { return new BooleanStaticAssertionPredicate( this, predicate.getOperator() == Predicate.BooleanOperator.OR ); } predicate.not(); return predicate; } else if ( Predicate.class.isInstance( expression ) ) { final Predicate predicate = (Predicate) expression; predicate.not(); return predicate; } return new BooleanAssertionPredicate( this, expression, Boolean.FALSE ); } /**s * {@inheritDoc} */ public Predicate isNull(Expression x) { return new NullnessPredicate( this, x ); } /** * {@inheritDoc} */ public Predicate isNotNull(Expression x) { return isNull( x ).not(); } /** * {@inheritDoc} */ public Predicate equal(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate notEqual(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.NOT_EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate equal(Expression x, Object y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate notEqual(Expression x, Object y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.NOT_EQUAL, x, y ); } /** * {@inheritDoc} */ public > Predicate greaterThan(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN, x, y ); } /** * {@inheritDoc} */ public > Predicate lessThan( Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN, x, y ); } /** * {@inheritDoc} */ public > Predicate greaterThanOrEqualTo( Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public > Predicate lessThanOrEqualTo( Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public > Predicate greaterThan( Expression x, Y y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN, x, y ); } /** * {@inheritDoc} */ public > Predicate lessThan( Expression x, Y y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN, x, y ); } /** * {@inheritDoc} */ public > Predicate greaterThanOrEqualTo( Expression x, Y y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public> Predicate lessThanOrEqualTo( Expression x, Y y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate gt(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN, x, y ); } /** * {@inheritDoc} */ public Predicate lt(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN, x, y ); } /** * {@inheritDoc} */ public Predicate ge(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate le(Expression x, Expression y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate gt(Expression x, Number y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN, x, y ); } /** * {@inheritDoc} */ public Predicate lt(Expression x, Number y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN, x, y ); } /** * {@inheritDoc} */ public Predicate ge(Expression x, Number y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.GREATER_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public Predicate le(Expression x, Number y) { //noinspection SuspiciousNameCombination return new ComparisonPredicate( this, ComparisonOperator.LESS_THAN_OR_EQUAL, x, y ); } /** * {@inheritDoc} */ public > Predicate between( Expression expression, Y lowerBound, Y upperBound) { return new BetweenPredicate( this, expression, lowerBound, upperBound ); } /** * {@inheritDoc} */ public > Predicate between( Expression expression, Expression lowerBound, Expression upperBound) { return new BetweenPredicate( this, expression, lowerBound, upperBound ); } /** * {@inheritDoc} */ public In in(Expression expression) { return new InPredicate( this, expression ); } public In in(Expression expression, Expression... values) { return new InPredicate( this, expression, values ); } public In in(Expression expression, T... values) { return new InPredicate( this, expression, values ); } public In in(Expression expression, Collection values) { return new InPredicate( this, expression, values ); } public Predicate like(Expression matchExpression, Expression pattern) { return new LikePredicate( this, matchExpression, pattern ); } public Predicate like(Expression matchExpression, Expression pattern, Expression escapeCharacter) { return new LikePredicate( this, matchExpression, pattern, escapeCharacter ); } public Predicate like(Expression matchExpression, Expression pattern, char escapeCharacter) { return new LikePredicate( this, matchExpression, pattern, escapeCharacter ); } public Predicate like(Expression matchExpression, String pattern) { return new LikePredicate( this, matchExpression, pattern ); } public Predicate like(Expression matchExpression, String pattern, Expression escapeCharacter) { return new LikePredicate( this, matchExpression, pattern, escapeCharacter ); } public Predicate like(Expression matchExpression, String pattern, char escapeCharacter) { return new LikePredicate( this, matchExpression, pattern, escapeCharacter ); } public Predicate notLike(Expression matchExpression, Expression pattern) { return like( matchExpression, pattern ).not(); } public Predicate notLike(Expression matchExpression, Expression pattern, Expression escapeCharacter) { return like( matchExpression, pattern, escapeCharacter ).not(); } public Predicate notLike(Expression matchExpression, Expression pattern, char escapeCharacter) { return like( matchExpression, pattern, escapeCharacter ).not(); } public Predicate notLike(Expression matchExpression, String pattern) { return like( matchExpression, pattern ).not(); } public Predicate notLike(Expression matchExpression, String pattern, Expression escapeCharacter) { return like( matchExpression, pattern, escapeCharacter ).not(); } public Predicate notLike(Expression matchExpression, String pattern, char escapeCharacter) { return like( matchExpression, pattern, escapeCharacter ).not(); } // parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public ParameterExpression parameter(Class paramClass) { return new ParameterExpressionImpl( this, paramClass ); } /** * {@inheritDoc} */ public ParameterExpression parameter(Class paramClass, String name) { return new ParameterExpressionImpl( this, paramClass, name ); } /** * {@inheritDoc} */ public Expression literal(T value) { if ( value == null ) { throw new IllegalArgumentException( "literal value cannot be null" ); } return new LiteralExpression( this, value ); } /** * {@inheritDoc} */ public Expression nullLiteral(Class resultClass) { return new NullLiteralExpression( this, resultClass ); } // aggregate functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Expression avg(Expression x) { return new AggregationFunction.AVG( this, x ); } /** * {@inheritDoc} */ public Expression sum(Expression x) { return new AggregationFunction.SUM( this, x ); } /** * {@inheritDoc} */ public Expression sumAsLong(Expression x) { return new AggregationFunction.SUM( this, x, Long.class ); } /** * {@inheritDoc} */ public Expression sumAsDouble(Expression x) { return new AggregationFunction.SUM( this, x, Double.class ); } /** * {@inheritDoc} */ public Expression max(Expression x) { return new AggregationFunction.MAX( this, x ); } /** * {@inheritDoc} */ public Expression min(Expression x) { return new AggregationFunction.MIN( this, x ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public > Expression greatest(Expression x) { return new AggregationFunction.GREATEST( this, x ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public > Expression least(Expression x) { return new AggregationFunction.LEAST( this, x ); } /** * {@inheritDoc} */ public Expression count(Expression x) { return new AggregationFunction.COUNT( this, x, false ); } /** * {@inheritDoc} */ public Expression countDistinct(Expression x) { return new AggregationFunction.COUNT( this, x, true ); } // other functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Expression function(String name, Class returnType, Expression... arguments) { return new ParameterizedFunctionExpression( this, returnType, name, arguments ); } /** * Create a reference to a function taking no params. * * @param name The function name. * @param returnType The return type. * * @return The function expression */ public Expression function(String name, Class returnType) { return new BasicFunctionExpression( this, returnType, name ); } /** * {@inheritDoc} */ public Expression abs(Expression expression) { return new AbsFunction( this, expression ); } /** * {@inheritDoc} */ public Expression sqrt(Expression expression) { return new SqrtFunction( this, expression ); } public Expression currentDate() { return new CurrentDateFunction( this ); } public Expression currentTimestamp() { return new CurrentTimestampFunction( this ); } public Expression currentTime() { return new CurrentTimeFunction( this ); } public Expression substring(Expression value, Expression start) { return new SubstringFunction( this, value, start ); } public Expression substring(Expression value, int start) { return new SubstringFunction( this, value, start ); } public Expression substring(Expression value, Expression start, Expression length) { return new SubstringFunction( this, value, start, length ); } public Expression substring(Expression value, int start, int length) { return new SubstringFunction( this, value, start, length ); } public Expression trim(Expression trimSource ) { return new TrimFunction( this, trimSource ); } public Expression trim(Trimspec trimspec, Expression trimSource) { return new TrimFunction( this, trimspec, trimSource ); } public Expression trim(Expression trimCharacter, Expression trimSource) { return new TrimFunction( this, trimCharacter, trimSource ); } public Expression trim(Trimspec trimspec, Expression trimCharacter, Expression trimSource) { return new TrimFunction( this, trimspec, trimCharacter, trimSource ); } public Expression trim(char trimCharacter, Expression trimSource) { return new TrimFunction( this, trimCharacter, trimSource ); } public Expression trim(Trimspec trimspec, char trimCharacter, Expression trimSource) { return new TrimFunction( this, trimspec, trimCharacter, trimSource ); } public Expression lower(Expression value) { return new LowerFunction( this, value ); } public Expression upper(Expression value) { return new UpperFunction( this, value ); } public Expression length(Expression value) { return new LengthFunction( this, value ); } public Expression locate(Expression string, Expression pattern) { return new LocateFunction( this, pattern, string ); } public Expression locate(Expression string, Expression pattern, Expression start) { return new LocateFunction( this, pattern, string, start ); } public Expression locate(Expression string, String pattern) { return new LocateFunction( this, pattern, string ); } public Expression locate(Expression string, String pattern, int start) { return new LocateFunction( this, pattern, string, start ); } // arithmetic operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public Expression neg(Expression expression) { return new UnaryArithmeticOperation( this, UnaryArithmeticOperation.Operation.UNARY_MINUS, expression ); } @SuppressWarnings({ "unchecked" }) public Expression sum(Expression expression1, Expression expression2) { if ( expression1 == null || expression2 == null ) { throw new IllegalArgumentException( "arguments to sum() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression1.getJavaType(), expression2.getJavaType() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.ADD, expression1, expression2 ); } @SuppressWarnings({ "unchecked" }) public Expression prod(Expression expression1, Expression expression2) { if ( expression1 == null || expression2 == null ) { throw new IllegalArgumentException( "arguments to prod() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression1.getJavaType(), expression2.getJavaType() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.MULTIPLY, expression1, expression2 ); } @SuppressWarnings({ "unchecked" }) public Expression diff(Expression expression1, Expression expression2) { if ( expression1 == null || expression2 == null ) { throw new IllegalArgumentException( "arguments to diff() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression1.getJavaType(), expression2.getJavaType() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.SUBTRACT, expression1, expression2 ); } @SuppressWarnings({ "unchecked" }) public Expression sum(Expression expression, N n) { if ( expression == null || n == null ) { throw new IllegalArgumentException( "arguments to sum() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression.getJavaType(), n.getClass() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.ADD, expression, n ); } @SuppressWarnings({ "unchecked" }) public Expression prod(Expression expression, N n) { if ( expression == null || n == null ) { throw new IllegalArgumentException( "arguments to prod() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression.getJavaType(), n.getClass() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.MULTIPLY, expression, n ); } @SuppressWarnings({ "unchecked" }) public Expression diff(Expression expression, N n) { if ( expression == null || n == null ) { throw new IllegalArgumentException( "arguments to diff() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression.getJavaType(), n.getClass() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.SUBTRACT, expression, n ); } @SuppressWarnings({ "unchecked" }) public Expression sum(N n, Expression expression) { if ( expression == null || n == null ) { throw new IllegalArgumentException( "arguments to sum() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( n.getClass(), expression.getJavaType() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.ADD, n, expression ); } @SuppressWarnings({ "unchecked" }) public Expression prod(N n, Expression expression) { if ( n == null || expression == null ) { throw new IllegalArgumentException( "arguments to prod() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( n.getClass(), expression.getJavaType() ); return (BinaryArithmeticOperation) new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.MULTIPLY, n, expression ); } @SuppressWarnings({ "unchecked" }) public Expression diff(N n, Expression expression) { if ( n == null || expression == null ) { throw new IllegalArgumentException( "arguments to diff() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( n.getClass(), expression.getJavaType() ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.SUBTRACT, n, expression ); } @SuppressWarnings( {"unchecked"}) public Expression quot(Expression expression1, Expression expression2) { if ( expression1 == null || expression2 == null ) { throw new IllegalArgumentException( "arguments to quot() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression1.getJavaType(), expression2.getJavaType(), true ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.DIVIDE, expression1, expression2 ); } @SuppressWarnings( {"unchecked"}) public Expression quot(Expression expression, Number number) { if ( expression == null || number == null ) { throw new IllegalArgumentException( "arguments to quot() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( expression.getJavaType(), number.getClass(), true ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.DIVIDE, expression, number ); } @SuppressWarnings( {"unchecked"}) public Expression quot(Number number, Expression expression) { if ( expression == null || number == null ) { throw new IllegalArgumentException( "arguments to quot() cannot be null" ); } final Class resultType = BinaryArithmeticOperation.determineResultType( number.getClass(), expression.getJavaType(), true ); return new BinaryArithmeticOperation( this, resultType, BinaryArithmeticOperation.Operation.DIVIDE, number, expression ); } public Expression mod(Expression expression1, Expression expression2) { if ( expression1 == null || expression2 == null ) { throw new IllegalArgumentException( "arguments to mod() cannot be null" ); } return new BinaryArithmeticOperation( this, Integer.class, BinaryArithmeticOperation.Operation.MOD, expression1, expression2 ); } public Expression mod(Expression expression, Integer integer) { if ( expression == null || integer == null ) { throw new IllegalArgumentException( "arguments to mod() cannot be null" ); } return new BinaryArithmeticOperation( this, Integer.class, BinaryArithmeticOperation.Operation.MOD, expression, integer ); } public Expression mod(Integer integer, Expression expression) { if ( integer == null || expression == null ) { throw new IllegalArgumentException( "arguments to mod() cannot be null" ); } return new BinaryArithmeticOperation( this, Integer.class, BinaryArithmeticOperation.Operation.MOD, integer, expression ); } // casting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public ExpressionImplementor toLong(Expression expression) { return ( (ExpressionImplementor) expression ).asLong(); } /** * {@inheritDoc} */ public ExpressionImplementor toInteger(Expression expression) { return ( (ExpressionImplementor) expression ).asInteger(); } /** * {@inheritDoc} */ public ExpressionImplementor toFloat(Expression expression) { return ( (ExpressionImplementor) expression ).asFloat(); } /** * {@inheritDoc} */ public ExpressionImplementor toDouble(Expression expression) { return ( (ExpressionImplementor) expression ).asDouble(); } /** * {@inheritDoc} */ public ExpressionImplementor toBigDecimal(Expression expression) { return ( (ExpressionImplementor) expression ).asBigDecimal(); } /** * {@inheritDoc} */ public ExpressionImplementor toBigInteger(Expression expression) { return ( (ExpressionImplementor) expression ).asBigInteger(); } /** * {@inheritDoc} */ public ExpressionImplementor toString(Expression characterExpression) { return ( (ExpressionImplementor) characterExpression ).asString(); } // subqueries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Predicate exists(Subquery subquery) { return new ExistsPredicate( this, subquery ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression all(Subquery subquery) { return new SubqueryComparisonModifierExpression( this, (Class) subquery.getJavaType(), subquery, SubqueryComparisonModifierExpression.Modifier.ALL ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression some(Subquery subquery) { return new SubqueryComparisonModifierExpression( this, (Class) subquery.getJavaType(), subquery, SubqueryComparisonModifierExpression.Modifier.SOME ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression any(Subquery subquery) { return new SubqueryComparisonModifierExpression( this, (Class) subquery.getJavaType(), subquery, SubqueryComparisonModifierExpression.Modifier.ANY ); } // miscellaneous expressions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ @SuppressWarnings({ "RedundantCast" }) public Expression coalesce(Expression exp1, Expression exp2) { return coalesce( (Class) null, exp1, exp2 ); } public Expression coalesce(Class type, Expression exp1, Expression exp2) { return new CoalesceExpression( this, type ).value( exp1 ).value( exp2 ); } /** * {@inheritDoc} */ @SuppressWarnings({ "RedundantCast" }) public Expression coalesce(Expression exp1, Y exp2) { return coalesce( (Class) null, exp1, exp2 ); } public Expression coalesce(Class type, Expression exp1, Y exp2) { return new CoalesceExpression( this, type ).value( exp1 ).value( exp2 ); } /** * {@inheritDoc} */ public Coalesce coalesce() { return coalesce( (Class)null ); } public Coalesce coalesce(Class type) { return new CoalesceExpression( this, type ); } /** * {@inheritDoc} */ public Expression concat(Expression string1, Expression string2) { return new ConcatExpression( this, string1, string2 ); } /** * {@inheritDoc} */ public Expression concat(Expression string1, String string2) { return new ConcatExpression( this, string1, string2 ); } /** * {@inheritDoc} */ public Expression concat(String string1, Expression string2) { return new ConcatExpression( this, string1, string2 ); } /** * {@inheritDoc} */ public Expression nullif(Expression exp1, Expression exp2) { return nullif( null, exp1, exp2 ); } public Expression nullif(Class type, Expression exp1, Expression exp2) { return new NullifExpression( this, type, exp1, exp2 ); } /** * {@inheritDoc} */ public Expression nullif(Expression exp1, Y exp2) { return nullif( null, exp1, exp2 ); } public Expression nullif(Class type, Expression exp1, Y exp2) { return new NullifExpression( this, type, exp1, exp2 ); } /** * {@inheritDoc} */ public SimpleCase selectCase(Expression expression) { return selectCase( (Class)null, expression ); } public SimpleCase selectCase(Class type, Expression expression) { return new SimpleCaseExpression( this, type, expression ); } /** * {@inheritDoc} */ public Case selectCase() { return selectCase( (Class)null ); } public Case selectCase(Class type) { return new SearchedCaseExpression( this, type ); } /** * {@inheritDoc} */ public > Expression size(C c) { int size = c == null ? 0 : c.size(); return new LiteralExpression(this, Integer.class, size); } /** * {@inheritDoc} */ public > Expression size(Expression exp) { if ( LiteralExpression.class.isInstance(exp) ) { return size( ( (LiteralExpression) exp ).getLiteral() ); } else if ( PluralAttributePath.class.isInstance(exp) ) { return new SizeOfCollectionExpression(this, (PluralAttributePath) exp ); } // TODO : what other specific types? any? throw new IllegalArgumentException("unknown collection expression type [" + exp.getClass().getName() + "]" ); } /** * {@inheritDoc} */ public > Expression> values(M map) { return new LiteralExpression>( this, map.values() ); } /** * {@inheritDoc} */ public > Expression> keys(M map) { return new LiteralExpression>( this, map.keySet() ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public > Predicate isEmpty(Expression collectionExpression) { if ( PluralAttributePath.class.isInstance(collectionExpression) ) { return new IsEmptyPredicate( this, (PluralAttributePath) collectionExpression ); } // TODO : what other specific types? any? throw new IllegalArgumentException( "unknown collection expression type [" + collectionExpression.getClass().getName() + "]" ); } /** * {@inheritDoc} */ public > Predicate isNotEmpty(Expression collectionExpression) { return isEmpty( collectionExpression ).not(); } /** * {@inheritDoc} */ public > Predicate isMember(E e, Expression collectionExpression) { if ( ! PluralAttributePath.class.isInstance( collectionExpression ) ) { throw new IllegalArgumentException( "unknown collection expression type [" + collectionExpression.getClass().getName() + "]" ); } return new MemberOfPredicate( this, e, (PluralAttributePath)collectionExpression ); } /** * {@inheritDoc} */ public > Predicate isNotMember(E e, Expression cExpression) { return isMember(e, cExpression).not(); } /** * {@inheritDoc} */ public > Predicate isMember(Expression elementExpression, Expression collectionExpression) { if ( ! PluralAttributePath.class.isInstance( collectionExpression ) ) { throw new IllegalArgumentException( "unknown collection expression type [" + collectionExpression.getClass().getName() + "]" ); } return new MemberOfPredicate( this, elementExpression, (PluralAttributePath)collectionExpression ); } /** * {@inheritDoc} */ public > Predicate isNotMember(Expression eExpression, Expression cExpression) { return isMember(eExpression, cExpression).not(); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032676 5ustar ebourgebourg././@LongLink0000000000000000000000000000021600000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/SimpleCaseExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001201111714611271032673 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.Expression; import javax.persistence.criteria.CriteriaBuilder.SimpleCase; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models what ANSI SQL terms a simple case statement. This is a CASE expression in the form
 * CASE [expression]
 *     WHEN [firstCondition] THEN [firstResult]
 *     WHEN [secondCondition] THEN [secondResult]
 *     ELSE [defaultResult]
 * END
 * 
* * @author Steve Ebersole */ public class SimpleCaseExpression extends ExpressionImpl implements SimpleCase, Serializable { private Class javaType; private final Expression expression; private List whenClauses = new ArrayList(); private Expression otherwiseResult; public class WhenClause { private final C condition; private final Expression result; public WhenClause(C condition, Expression result) { this.condition = condition; this.result = result; } public C getCondition() { return condition; } public Expression getResult() { return result; } } public SimpleCaseExpression( CriteriaBuilderImpl criteriaBuilder, Class javaType, Expression expression) { super( criteriaBuilder, javaType); this.javaType = javaType; this.expression = expression; } @SuppressWarnings({ "unchecked" }) public Expression getExpression() { return (Expression) expression; } public SimpleCase when(C condition, R result) { return when( condition, buildLiteral(result) ); } @SuppressWarnings({ "unchecked" }) private LiteralExpression buildLiteral(R result) { final Class type = result != null ? (Class) result.getClass() : getJavaType(); return new LiteralExpression( criteriaBuilder(), type, result ); } public SimpleCase when(C condition, Expression result) { WhenClause whenClause = new WhenClause( condition, result ); whenClauses.add( whenClause ); adjustJavaType( result ); return this; } @SuppressWarnings({ "unchecked" }) private void adjustJavaType(Expression exp) { if ( javaType == null ) { javaType = (Class) exp.getJavaType(); } } public Expression otherwise(R result) { return otherwise( buildLiteral(result) ); } public Expression otherwise(Expression result) { this.otherwiseResult = result; adjustJavaType( result ); return this; } public Expression getOtherwiseResult() { return otherwiseResult; } public List getWhenClauses() { return whenClauses; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getExpression(), registry ); for ( WhenClause whenClause : getWhenClauses() ) { Helper.possibleParameter( whenClause.getResult(), registry ); } Helper.possibleParameter( getOtherwiseResult(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder caseExpr = new StringBuilder(); caseExpr.append( "case " ) .append( ( (Renderable) getExpression() ).render( renderingContext ) ) .append( ' ' ); for ( WhenClause whenClause : getWhenClauses() ) { caseExpr.append( ( (Renderable) whenClause.getCondition() ).render( renderingContext ) ) .append( " then " ) .append( ( (Renderable) whenClause.getResult() ).render( renderingContext ) ); } caseExpr.append( " else " ) .append( ( (Renderable) getOtherwiseResult() ).render( renderingContext ) ) .append( " end" ); return caseExpr.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/NullLiteralExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000355711714611271032712 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; /** * Represents a NULLliteral expression. * * @author Steve Ebersole */ public class NullLiteralExpression extends ExpressionImpl implements Serializable { public NullLiteralExpression(CriteriaBuilderImpl criteriaBuilder, Class type) { super( criteriaBuilder, type ); } public void registerParameters(ParameterRegistry registry) { // nothing to do } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return "null"; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } }././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/PathTypeExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000404411714611271032702 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; /** * Used to construct the result of {@link javax.persistence.criteria.Path#type()} * * @author Steve Ebersole */ public class PathTypeExpression extends ExpressionImpl implements Serializable { public PathTypeExpression(CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType ); } public void registerParameters(ParameterRegistry registry) { // nothing to do } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { // todo : is it valid for this to get rendered into the query itself? throw new IllegalArgumentException( "Unexpected call on EntityTypeExpression#render" ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/SearchedCaseExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001153711714611271032707 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.Expression; import javax.persistence.criteria.CriteriaBuilder.Case; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models what ANSI SQL terms a searched case expression. This is a CASE expression * in the form
 * CASE
 *     WHEN [firstCondition] THEN [firstResult]
 *     WHEN [secondCondition] THEN [secondResult]
 *     ELSE [defaultResult]
 * END
 * 
* * @author Steve Ebersole */ public class SearchedCaseExpression extends ExpressionImpl implements Case, Serializable { private Class javaType; // overrides the javaType kept on tuple-impl so that we can adjust it private List whenClauses = new ArrayList(); private Expression otherwiseResult; public class WhenClause { private final Expression condition; private final Expression result; public WhenClause(Expression condition, Expression result) { this.condition = condition; this.result = result; } public Expression getCondition() { return condition; } public Expression getResult() { return result; } } public SearchedCaseExpression( CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType); this.javaType = javaType; } public Case when(Expression condition, R result) { return when( condition, buildLiteral(result) ); } @SuppressWarnings({ "unchecked" }) private LiteralExpression buildLiteral(R result) { final Class type = result != null ? (Class) result.getClass() : getJavaType(); return new LiteralExpression( criteriaBuilder(), type, result ); } public Case when(Expression condition, Expression result) { WhenClause whenClause = new WhenClause( condition, result ); whenClauses.add( whenClause ); adjustJavaType( result ); return this; } @SuppressWarnings({ "unchecked" }) private void adjustJavaType(Expression exp) { if ( javaType == null ) { javaType = (Class) exp.getJavaType(); } } public Expression otherwise(R result) { return otherwise( buildLiteral(result) ); } public Expression otherwise(Expression result) { this.otherwiseResult = result; adjustJavaType( result ); return this; } public Expression getOtherwiseResult() { return otherwiseResult; } public List getWhenClauses() { return whenClauses; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getOtherwiseResult(), registry ); for ( WhenClause whenClause : getWhenClauses() ) { Helper.possibleParameter( whenClause.getCondition(), registry ); Helper.possibleParameter( whenClause.getResult(), registry ); } } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder caseStatement = new StringBuilder( "case" ); for ( WhenClause whenClause : getWhenClauses() ) { caseStatement.append( " when " ) .append( ( (Renderable) whenClause.getCondition() ).render( renderingContext ) ) .append( " then " ) .append( ( (Renderable) whenClause.getResult() ).render( renderingContext ) ); } caseStatement.append( " else " ) .append( ( (Renderable) getOtherwiseResult() ).render( renderingContext ) ) .append( " end" ); return caseStatement.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000022200000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/BinaryOperatorExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000304311714611271032700 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import javax.persistence.criteria.Expression; /** * Contract for operators with two operands. * * @author Steve Ebersole */ public interface BinaryOperatorExpression extends Expression { /** * Get the right-hand operand. * * @return The right-hand operand. */ public Expression getRightHandOperand(); /** * Get the left-hand operand. * * @return The left-hand operand. */ public Expression getLeftHandOperand(); } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/CoalesceExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000642111714611271032703 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.Expression; import javax.persistence.criteria.CriteriaBuilder.Coalesce; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models an ANSI SQL COALESCE expression. COALESCE is a specialized CASE statement. * * @author Steve Ebersole */ public class CoalesceExpression extends ExpressionImpl implements Coalesce, Serializable { private final List> expressions; private Class javaType; public CoalesceExpression(CriteriaBuilderImpl criteriaBuilder) { this( criteriaBuilder, null ); } public CoalesceExpression( CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType ); this.javaType = javaType; this.expressions = new ArrayList>(); } @Override public Class getJavaType() { return javaType; } public Coalesce value(T value) { return value( new LiteralExpression( criteriaBuilder(), value ) ); } @SuppressWarnings({ "unchecked" }) public Coalesce value(Expression value) { expressions.add( value ); if ( javaType == null ) { javaType = (Class) value.getJavaType(); } return this; } public List> getExpressions() { return expressions; } public void registerParameters(ParameterRegistry registry) { for ( Expression expression : getExpressions() ) { Helper.possibleParameter(expression, registry); } } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder buffer = new StringBuilder( "coalesce(" ); String sep = ""; for ( Expression expression : getExpressions() ) { buffer.append( sep ) .append( ( (Renderable) expression ).render( renderingContext ) ); sep = ", "; } return buffer.append( ")" ).toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021200000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/NullifExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000654311714611271032710 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; /** * Models an ANSI SQL NULLIF expression. NULLIF is a specialized CASE statement. * * @author Steve Ebersole */ public class NullifExpression extends ExpressionImpl implements Serializable { private final Expression primaryExpression; private final Expression secondaryExpression; public NullifExpression( CriteriaBuilderImpl criteriaBuilder, Class javaType, Expression primaryExpression, Expression secondaryExpression) { super( criteriaBuilder, (Class)determineType(javaType, primaryExpression) ); this.primaryExpression = primaryExpression; this.secondaryExpression = secondaryExpression; } public NullifExpression( CriteriaBuilderImpl criteriaBuilder, Class javaType, Expression primaryExpression, Object secondaryExpression) { super( criteriaBuilder, (Class)determineType(javaType, primaryExpression) ); this.primaryExpression = primaryExpression; this.secondaryExpression = new LiteralExpression( criteriaBuilder, secondaryExpression ); } private static Class determineType(Class javaType, Expression primaryExpression) { return javaType != null ? javaType : primaryExpression.getJavaType(); } public Expression getPrimaryExpression() { return primaryExpression; } public Expression getSecondaryExpression() { return secondaryExpression; } public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getPrimaryExpression(), registry ); Helper.possibleParameter( getSecondaryExpression(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return "nullif(" + ( (Renderable) getPrimaryExpression() ).render( renderingContext ) + ',' + ( (Renderable) getSecondaryExpression() ).render( renderingContext ) + ")"; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/SelectionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000442411714611271032704 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.Collections; import java.util.List; import javax.persistence.criteria.Selection; import org.hibernate.ejb.criteria.ParameterContainer; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.SelectionImplementor; import org.hibernate.ejb.criteria.ValueHandlerFactory; /** * The Hibernate implementation of the JPA {@link Selection} * contract. * * @author Steve Ebersole */ public abstract class SelectionImpl extends AbstractTupleElement implements SelectionImplementor, ParameterContainer, Serializable { public SelectionImpl(CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType ); } public Selection alias(String alias) { setAlias( alias ); return this; } public boolean isCompoundSelection() { return false; } public List getValueHandlers() { return getValueHandler() == null ? null : Collections.singletonList( (ValueHandlerFactory.ValueHandler) getValueHandler() ); } public List> getCompoundSelectionItems() { throw new IllegalStateException( "Not a compound selection" ); } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/ExpressionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001021711714611271032701 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.ExpressionImplementor; import org.hibernate.ejb.criteria.expression.function.CastFunction; /** * Models an expression in the criteria query language. * * @author Steve Ebersole */ public abstract class ExpressionImpl extends SelectionImpl implements ExpressionImplementor, Serializable { public ExpressionImpl(CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public Expression as(Class type) { return type.equals( getJavaType() ) ? (Expression) this : new CastFunction( criteriaBuilder(), type, this ); } /** * {@inheritDoc} */ public Predicate isNull() { return criteriaBuilder().isNull( this ); } /** * {@inheritDoc} */ public Predicate isNotNull() { return criteriaBuilder().isNotNull( this ); } /** * {@inheritDoc} */ public Predicate in(Object... values) { return criteriaBuilder().in( this, values ); } /** * {@inheritDoc} */ public Predicate in(Expression... values) { return criteriaBuilder().in( this, values ); } /** * {@inheritDoc} */ public Predicate in(Collection values) { return criteriaBuilder().in( this, values.toArray() ); } /** * {@inheritDoc} */ public Predicate in(Expression> values) { return criteriaBuilder().in( this, values ); } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asLong() { resetJavaType( Long.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asInteger() { resetJavaType( Integer.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asFloat() { resetJavaType( Float.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asDouble() { resetJavaType( Double.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asBigDecimal() { resetJavaType( BigDecimal.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asBigInteger() { resetJavaType( BigInteger.class ); return (ExpressionImplementor) this; } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked" }) public ExpressionImplementor asString() { resetJavaType( String.class ); return (ExpressionImplementor) this; } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/ListIndexExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000453311714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.metamodel.ListAttribute; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.PathImplementor; /** * An expression for referring to the index of a list. * * @author Steve Ebersole */ public class ListIndexExpression extends ExpressionImpl implements Serializable { private final PathImplementor origin; private final ListAttribute listAttribute; public ListIndexExpression( CriteriaBuilderImpl criteriaBuilder, PathImplementor origin, ListAttribute listAttribute) { super( criteriaBuilder, Integer.class ); this.origin = origin; this.listAttribute = listAttribute; } public ListAttribute getListAttribute() { return listAttribute; } public void registerParameters(ParameterRegistry registry) { // nothing to do } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return "index(" + origin.getPathIdentifier() + '.' + getListAttribute().getName() + ")"; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/LiteralExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000701011714611271032676 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.TypedQuery; import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; /** * Represents a literal expression. * * @author Steve Ebersole */ public class LiteralExpression extends ExpressionImpl implements Serializable { private Object literal; @SuppressWarnings({ "unchecked" }) public LiteralExpression(CriteriaBuilderImpl criteriaBuilder, T literal) { this( criteriaBuilder, (Class) determineClass( literal ), literal ); } private static Class determineClass(Object literal) { return literal == null ? null : literal.getClass(); } public LiteralExpression(CriteriaBuilderImpl criteriaBuilder, Class type, T literal) { super( criteriaBuilder, type ); this.literal = literal; } @SuppressWarnings({ "unchecked" }) public T getLiteral() { return (T) literal; } public void registerParameters(ParameterRegistry registry) { // nothing to do } @SuppressWarnings({ "unchecked" }) public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { if ( ValueHandlerFactory.isNumeric( literal ) ) { return ValueHandlerFactory.determineAppropriateHandler( (Class) literal.getClass() ).render( literal ); } // else... final String parameterName = renderingContext.registerLiteralParameterBinding( getLiteral(), getJavaType() ); return ':' + parameterName; } @SuppressWarnings({ "unchecked" }) public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { // some drivers/servers do not like parameters in the select clause final ValueHandlerFactory.ValueHandler handler = ValueHandlerFactory.determineAppropriateHandler( literal.getClass() ); if ( ValueHandlerFactory.isCharacter( literal ) ) { return '\'' + handler.render( literal ) + '\''; } else { return handler.render( literal ); } } @Override @SuppressWarnings({ "unchecked" }) protected void resetJavaType(Class targetType) { super.resetJavaType( targetType ); ValueHandlerFactory.ValueHandler valueHandler = getValueHandler(); if ( valueHandler == null ) { valueHandler = ValueHandlerFactory.determineAppropriateHandler( targetType ); forceConversion( valueHandler ); } if ( valueHandler != null ) { literal = valueHandler.convert( literal ); } } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/UnaryOperatorExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000266511714611271032711 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.criteria.Expression; /** * Contract for operators with a single operand. * * @author Steve Ebersole */ public interface UnaryOperatorExpression extends Expression, Serializable { /** * Get the operand. * * @return The operand. */ public Expression getOperand(); } ././@LongLink0000000000000000000000000000021700000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/CompoundSelectionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000744011714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Tuple; import javax.persistence.criteria.CompoundSelection; import javax.persistence.criteria.Selection; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.TupleElementImplementor; import org.hibernate.ejb.criteria.ValueHandlerFactory; /** * The Hibernate implementation of the JPA {@link CompoundSelection} * contract. * * @author Steve Ebersole */ public class CompoundSelectionImpl extends SelectionImpl implements CompoundSelection, Renderable, Serializable { private final boolean isConstructor; private List> selectionItems; public CompoundSelectionImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, List> selectionItems) { super( criteriaBuilder, javaType ); this.isConstructor = !javaType.isArray() && !Tuple.class.isAssignableFrom( javaType ); this.selectionItems = selectionItems; } @Override public boolean isCompoundSelection() { return true; } @Override public List> getCompoundSelectionItems() { return selectionItems; } @Override public List getValueHandlers() { if ( isConstructor ) { return null; } boolean foundHandlers = false; ArrayList valueHandlers = new ArrayList(); for ( Selection selection : getCompoundSelectionItems() ) { ValueHandlerFactory.ValueHandler valueHandler = ( (TupleElementImplementor) selection ).getValueHandler(); valueHandlers.add( valueHandler ); foundHandlers = foundHandlers || valueHandler != null; } return foundHandlers ? null : valueHandlers; } public void registerParameters(ParameterRegistry registry) { for ( Selection selectionItem : getCompoundSelectionItems() ) { Helper.possibleParameter(selectionItem, registry); } } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { StringBuilder buff = new StringBuilder(); if ( isConstructor ) { buff.append( "new " ).append( getJavaType().getName() ).append( '(' ); } String sep = ""; for ( Selection selection : selectionItems ) { buff.append( sep ) .append( ( (Renderable) selection ).renderProjection( renderingContext ) ); sep = ", "; } if ( isConstructor ) { buff.append( ')' ); } return buff.toString(); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000022300000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/BinaryArithmeticOperation.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000001644011714611271032705 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.criteria.Expression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.predicate.ImplicitNumericExpressionTypeDeterminer; /** * Models standard arithmetc operations with two operands. * * @author Steve Ebersole */ public class BinaryArithmeticOperation extends ExpressionImpl implements BinaryOperatorExpression, Serializable { public static enum Operation { ADD { String apply(String lhs, String rhs) { return applyPrimitive( lhs, '+', rhs ); } }, SUBTRACT { String apply(String lhs, String rhs) { return applyPrimitive( lhs, '-', rhs ); } }, MULTIPLY { String apply(String lhs, String rhs) { return applyPrimitive( lhs, '*', rhs ); } }, DIVIDE { String apply(String lhs, String rhs) { return applyPrimitive( lhs, '/', rhs ); } }, QUOT { String apply(String lhs, String rhs) { return applyPrimitive( lhs, '/', rhs ); } }, MOD { String apply(String lhs, String rhs) { // return lhs + " % " + rhs; return "mod(" + lhs + "," + rhs + ")"; } }; abstract String apply(String lhs, String rhs); private static final char LEFT_PAREN = '('; private static final char RIGHT_PAREN = ')'; private static String applyPrimitive(String lhs, char operator, String rhs) { return new StringBuffer( lhs.length() + rhs.length() + 3 ) .append( LEFT_PAREN ) .append( lhs ) .append( operator ) .append( rhs ) .append( RIGHT_PAREN ) .toString(); } } private final Operation operator; private final Expression rhs; private final Expression lhs; public static Class determineResultType( Class argument1Type, Class argument2Type ) { return determineResultType( argument1Type, argument2Type, false ); } public static Class determineResultType( Class argument1Type, Class argument2Type, boolean isQuotientOperation ) { if ( isQuotientOperation ) { return Number.class; } return ImplicitNumericExpressionTypeDeterminer.determineResultType( argument1Type, argument2Type ); } /** * Helper for determining the appropriate operation return type based on one of the operands as an expression. * * @param defaultType The default return type to use if we cannot determine the java type of 'expression' operand. * @param expression The operand. * * @return The appropriate return type. */ public static Class determineReturnType( Class defaultType, Expression expression) { return expression == null || expression.getJavaType() == null ? defaultType : expression.getJavaType(); } /** * Helper for determining the appropriate operation return type based on one of the operands as a literal. * * @param defaultType The default return type to use if we cannot determine the java type of 'numberLiteral' operand. * @param numberLiteral The operand. * * @return The appropriate return type. */ public static Class determineReturnType( Class defaultType, Number numberLiteral) { return numberLiteral == null ? defaultType : numberLiteral.getClass(); } /** * Creates an arithmethic operation based on 2 expressions. * * @param criteriaBuilder The builder for query components. * @param resultType The operation result type * @param operator The operator (type of operation). * @param lhs The left-hand operand. * @param rhs The right-hand operand */ public BinaryArithmeticOperation( CriteriaBuilderImpl criteriaBuilder, Class resultType, Operation operator, Expression lhs, Expression rhs) { super( criteriaBuilder, resultType ); this.operator = operator; this.lhs = lhs; this.rhs = rhs; } /** * Creates an arithmethic operation based on an expression and a literal. * * @param criteriaBuilder The builder for query components. * @param javaType The operation result type * @param operator The operator (type of operation). * @param lhs The left-hand operand * @param rhs The right-hand operand (the literal) */ public BinaryArithmeticOperation( CriteriaBuilderImpl criteriaBuilder, Class javaType, Operation operator, Expression lhs, N rhs) { super( criteriaBuilder, javaType ); this.operator = operator; this.lhs = lhs; this.rhs = new LiteralExpression( criteriaBuilder, rhs ); } /** * Creates an arithmetic operation based on an expression and a literal. * * @param criteriaBuilder The builder for query components. * @param javaType The operation result type * @param operator The operator (type of operation). * @param lhs The left-hand operand (the literal) * @param rhs The right-hand operand */ public BinaryArithmeticOperation( CriteriaBuilderImpl criteriaBuilder, Class javaType, Operation operator, N lhs, Expression rhs) { super( criteriaBuilder, javaType ); this.operator = operator; this.lhs = new LiteralExpression( criteriaBuilder, lhs ); this.rhs = rhs; } public Operation getOperator() { return operator; } /** * {@inheritDoc} */ public Expression getRightHandOperand() { return rhs; } /** * {@inheritDoc} */ public Expression getLeftHandOperand() { return lhs; } /** * {@inheritDoc} */ public void registerParameters(ParameterRegistry registry) { Helper.possibleParameter( getRightHandOperand(), registry ); Helper.possibleParameter( getLeftHandOperand(), registry ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { return getOperator().apply( ( (Renderable) getLeftHandOperand() ).render( renderingContext ), ( (Renderable) getRightHandOperand() ).render( renderingContext ) ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000021400000000000011562 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/MapEntryExpression.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000535411714611271032707 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import java.util.Map; import javax.persistence.criteria.Expression; import javax.persistence.metamodel.MapAttribute; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.Renderable; /** * TODO : javadoc * * @author Steve Ebersole */ public class MapEntryExpression extends ExpressionImpl> implements Expression>, Serializable { private final PathImplementor origin; private final MapAttribute attribute; public MapEntryExpression( CriteriaBuilderImpl criteriaBuilder, Class> javaType, PathImplementor origin, MapAttribute attribute) { super( criteriaBuilder, javaType); this.origin = origin; this.attribute = attribute; } public MapAttribute getAttribute() { return attribute; } public void registerParameters(ParameterRegistry registry) { // none to register } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { // don't think this is valid outside of select clause... throw new IllegalStateException( "illegal reference to map entry outside of select clause." ); } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return "entry(" + path( renderingContext ) + ")"; } private String path(CriteriaQueryCompiler.RenderingContext renderingContext) { return origin.getPathIdentifier() + '.' + ( (Renderable) getAttribute() ).renderProjection( renderingContext ); } } ././@LongLink0000000000000000000000000000022100000000000011560 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/ParameterExpressionImpl.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000552711714611271032711 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression; import java.io.Serializable; import javax.persistence.criteria.ParameterExpression; import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaQueryCompiler; /** * Defines a parameter specification, or the information about a parameter (where it occurs, what is * its type, etc). * * @author Steve Ebersole */ public class ParameterExpressionImpl extends ExpressionImpl implements ParameterExpression, Serializable { private final String name; private final Integer position; public ParameterExpressionImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, String name) { super( criteriaBuilder, javaType ); this.name = name; this.position = null; } public ParameterExpressionImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType, Integer position) { super( criteriaBuilder, javaType ); this.name = null; this.position = position; } public ParameterExpressionImpl( CriteriaBuilderImpl criteriaBuilder, Class javaType) { super( criteriaBuilder, javaType ); this.name = null; this.position = null; } public String getName() { return name; } public Integer getPosition() { return position; } public Class getParameterType() { return getJavaType(); } public void registerParameters(ParameterRegistry registry) { registry.registerParameter( this ); } public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { final String jpaqlParamName = renderingContext.registerExplicitParameter( this ); return ':' + jpaqlParamName; } public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { return render( renderingContext ); } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/function/libhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000755000175000017500000000000012143273450032676 5ustar ebourgebourg././@LongLink0000000000000000000000000000022600000000000011565 Lustar rootrootlibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/expression/function/CurrentTimeFunction.javalibhibernate3-java-3.6.10.Final/project/hibernate-entitymanager/src/main/java/org/hibernate/ejb/crit0000644000175000017500000000310011714611271032672 0ustar ebourgebourg/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by * third-party contributors as indicated by either @author tags or express * copyright attribution statements applied by the authors. All * third-party contributions are distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ejb.criteria.expression.function; import java.io.Serializable; import java.sql.Time; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; /** * Models the ANSI SQL CURRENT_TIME function. * * @author Steve Ebersole */ public class CurrentTimeFunction extends BasicFunctionExpression